text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Increase request buffer as workaround for stackoverflow in asyncio
|
from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
docs = article_service.all()
return req.Response(text=docs.to_json())
def keywords(req):
"""
Retrieve articles by keywords
"""
#AsyncIO buffer problem
req.transport.set_write_buffer_limits=4096
words = req.match_dict['keywords']
docs = article_service.keywords(words)
headers = {'Content-Type': 'application/json'}
body = docs.to_json().encode()
return req.Response(body=body, headers=headers)
app = Application()
app.router.add_route('/', index)
app.router.add_route('/articles', articles)
app.router.add_route('/articles/keywords/{keywords}', keywords)
#Some bugs require us to dial to MongoDB just before server is listening
host = 'mongodb://aws-ap-southeast-1-portal.0.dblayer.com/news'
connect(db='news',host=host, port=15501, username='azzuwan', password='Reddoor74', alias='default', connect=False)
app.run(debug=True)
|
from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
docs = article_service.all()
return req.Response(text=docs.to_json())
def keywords(req):
"""
Retrieve articles by keywords
"""
words = req.match_dict['keywords']
docs = article_service.keywords(words)
headers = {'Content-Type': 'application/json'}
body = docs.to_json().encode()
return req.Response(body=body, headers=headers)
app = Application()
app.router.add_route('/', index)
app.router.add_route('/articles', articles)
app.router.add_route('/articles/keywords/{keywords}', keywords)
#Some bugs require us to dial to MongoDB just before server is listening
host = 'mongodb://aws-ap-southeast-1-portal.0.dblayer.com/news'
connect(db='news',host=host, port=15501, username='azzuwan', password='Reddoor74', alias='default', connect=False)
app.run(debug=True)
|
Add test that validates method call
|
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
def test_invalid_method_pattern_call(self):
with self.assertRaises(AttributeError):
twenty_brl = self.twenty_euro.batman()
if __name__ == '__main__':
unittest.main()
|
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
if __name__ == '__main__':
unittest.main()
|
Use bigrams in Markov chain generator
|
"""Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
attribution = [
"salad master",
"esquire",
"the one and only",
"startup enthusiast",
"boba king",
"not-dictator",
"normal citizen",
"ping-pong expert"
]
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
def generate_phrase(phrases, cache, max_length=40):
seed_phrase = []
while len(seed_phrase) < 2:
seed_phrase = random.choice(phrases).split()
w1, = seed_phrase[:1]
chosen = [w1]
while w1 in cache and len(chosen)<max_length:
w1 = random.choice(cache[w1])
chosen.append(w1)
return ' '.join(chosen)
def on_message(bot, channel, user, message):
return '> {} ~ Brian Chu, {}'.format(generate_phrase(phrases, cache),
random.choice(attribution))
|
"""Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def generate_phrase(phrases, cache):
seed_phrase = []
while len(seed_phrase) < 3:
seed_phrase = random.choice(phrases).split()
w1, w2 = seed_phrase[:2]
chosen = [w1, w2]
while "{}|{}".format(w1, w2) in cache:
choice = random.choice(cache["{}|{}".format(w1, w2)])
w1, w2 = w2, choice
chosen.append(choice)
return ' '.join(chosen)
def on_message(bot, channel, user, message):
return '> {} ~brian'.format(generate_phrase(phrases, cache))
|
Correct Balance update logic upon transaction
|
package devopsdistilled.operp.server.data.service.account.impl;
import java.util.Date;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import devopsdistilled.operp.server.data.entity.account.PaidTransaction;
import devopsdistilled.operp.server.data.repo.account.PaidTransactionRepository;
import devopsdistilled.operp.server.data.service.account.PaidTransactionService;
import devopsdistilled.operp.server.data.service.account.PayableAccountService;
@Service
public class PaidTransactionServiceImpl extends
TransactionServiceImpl<PaidTransaction, PaidTransactionRepository>
implements PaidTransactionService {
private static final long serialVersionUID = 8946536638729817665L;
@Inject
private PaidTransactionRepository repo;
@Inject
private PayableAccountService payableAccountService;
@Override
protected PaidTransactionRepository getRepo() {
return repo;
}
@Override
@Transactional
public <S extends PaidTransaction> S save(S transaction) {
transaction.setTransactionDate(new Date());
transaction = super.save(transaction);
Double initBalance = transaction.getAccount().getBalance();
Double afterTranBalance = initBalance - transaction.getAmount();
transaction.getAccount().setBalance(afterTranBalance);
payableAccountService.save(transaction.getAccount());
return transaction;
}
}
|
package devopsdistilled.operp.server.data.service.account.impl;
import java.util.Date;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import devopsdistilled.operp.server.data.entity.account.PaidTransaction;
import devopsdistilled.operp.server.data.repo.account.PaidTransactionRepository;
import devopsdistilled.operp.server.data.service.account.PaidTransactionService;
import devopsdistilled.operp.server.data.service.account.PayableAccountService;
@Service
public class PaidTransactionServiceImpl extends
TransactionServiceImpl<PaidTransaction, PaidTransactionRepository>
implements PaidTransactionService {
private static final long serialVersionUID = 8946536638729817665L;
@Inject
private PaidTransactionRepository repo;
@Inject
private PayableAccountService payableAccountService;
@Override
protected PaidTransactionRepository getRepo() {
return repo;
}
@Override
@Transactional
public <S extends PaidTransaction> S save(S transaction) {
transaction.setTransactionDate(new Date());
transaction = super.save(transaction);
Double initBalance = transaction.getAccount().getBalance();
Double afterTranBalance = initBalance + transaction.getAmount();
transaction.getAccount().setBalance(afterTranBalance);
payableAccountService.save(transaction.getAccount());
return transaction;
}
}
|
Put event handler in separate func
|
package main
import (
"errors"
"sdl"
)
const (
defaultWidth, defaultHeight = 1024, 768
gameName = "gogame"
)
var (
quitting = errors.New("quitting")
)
func eventHandler(e interface{}) error {
switch v := e.(type) {
case sdl.QuitEvent:
return quitting
case sdl.KeyEvent:
if v.Type == sdl.KeyUp {
switch v.KeyCode {
case 'q':
return quitting
}
}
}
return nil
}
func main() {
ctx, err := sdl.NewContext(gameName, defaultWidth, defaultHeight)
if err != nil {
panic(err)
}
defer ctx.Close()
for {
err = sdl.HandleEvents(eventHandler)
if err == quitting {
return
}
ctx.Render()
sdl.Delay(1)
}
}
|
package main
import (
"errors"
"sdl"
)
const (
defaultWidth, defaultHeight = 1024, 768
gameName = "gogame"
)
func main() {
ctx, err := sdl.NewContext(gameName, defaultWidth, defaultHeight)
if err != nil {
panic(err)
}
defer ctx.Close()
quit := errors.New("quitting")
for {
err = sdl.HandleEvents(func(e interface{}) error {
switch v := e.(type) {
case sdl.QuitEvent:
return quit
case sdl.KeyEvent:
if v.Type == sdl.KeyUp && v.KeyCode == 'q' {
return quit
}
}
return nil
})
if err == quit {
return
}
ctx.Render()
sdl.Delay(1)
}
}
|
Handle zero-padding for millisecond component
Fixes tests for 1 and 12 milliseconds.
|
(function (millisecondsToISO8601Duration) {
'use strict';
millisecondsToISO8601Duration.iso8601duration = function(milliseconds) {
var offset = Math.floor(milliseconds);
var milliseconds = offset % 1000;
offset = Math.floor(offset / 1000);
var seconds = offset % 60;
offset = Math.floor(offset / 60);
var minutes = offset % 60;
offset = Math.floor(offset / 60);
var hours = offset % 24;
var days = Math.floor(offset / 24);
var parts = ['P'];
if (days) {
parts.push(days + 'D');
}
if (hours || minutes || seconds || milliseconds) {
parts.push('T');
if (hours) {
parts.push(hours + 'H');
}
if (minutes) {
parts.push(minutes + 'M');
}
if (seconds || milliseconds) {
parts.push(seconds);
if (milliseconds) {
milliseconds = milliseconds.toString();
while (milliseconds.length < 3) {
milliseconds = '0' + milliseconds;
}
parts.push('.' + milliseconds);
}
parts.push('S');
}
}
return parts.join('')
};
})(typeof exports === 'undefined' ? millisecondsToISO8601Duration = {} : exports);
|
(function (millisecondsToISO8601Duration) {
'use strict';
millisecondsToISO8601Duration.iso8601duration = function(milliseconds) {
var offset = Math.floor(milliseconds);
var milliseconds = offset % 1000;
offset = Math.floor(offset / 1000);
var seconds = offset % 60;
offset = Math.floor(offset / 60);
var minutes = offset % 60;
offset = Math.floor(offset / 60);
var hours = offset % 24;
var days = Math.floor(offset / 24);
var parts = ['P'];
if (days) {
parts.push(days + 'D');
}
if (hours || minutes || seconds || milliseconds) {
parts.push('T');
if (hours) {
parts.push(hours + 'H');
}
if (minutes) {
parts.push(minutes + 'M');
}
if (seconds || milliseconds) {
parts.push(seconds);
if (milliseconds) {
parts.push('.' + milliseconds);
}
parts.push('S');
}
}
return parts.join('')
};
})(typeof exports === 'undefined' ? millisecondsToISO8601Duration = {} : exports);
|
Disable ant trails for now, too expensive
|
// Global planners
var room_counter = require("planners_global_room_counter");
// Local planners
var construction = require("planners_local_construction");
var towers = require("planners_local_towers");
var family_planner = require("planners_local_family_planner");
var ant_trail = require("planners_local_ant_trail");
// Selected planners to run
var global_planners = [room_counter];
var local_planners = [construction, towers, family_planner];
module.exports.run = function() {
for(var i in global_planners)
global_planners[i].run();
for(var name in Game.rooms) {
var room = Game.rooms[name];
if(room.controller && room.controller.my) {
for(var j in local_planners)
local_planners[j].run(room);
}
}
};
|
// Global planners
var room_counter = require("planners_global_room_counter");
// Local planners
var construction = require("planners_local_construction");
var towers = require("planners_local_towers");
var family_planner = require("planners_local_family_planner");
var ant_trail = require("planners_local_ant_trail");
// Selected planners to run
var global_planners = [room_counter];
var local_planners = [construction, towers, family_planner, ant_trail];
module.exports.run = function() {
for(var i in global_planners)
global_planners[i].run();
for(var name in Game.rooms) {
var room = Game.rooms[name];
if(room.controller && room.controller.my) {
for(var j in local_planners)
local_planners[j].run(room);
}
}
};
|
Add comment explaining why we disable ip_forward
|
# coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __init__(self, name, **params):
super(PaxNode, self).__init__(name, **params)
def config(self, **params):
super(PaxNode, self).config(**params)
# Setup iptable rules to drop incoming packets on each interface:
# Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets
# to prevent the OS from handling them and responding.
for intf in self.intfList():
self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
# Disable ip_forward because otherwise, even with the above iptables rules, the OS
# will still forward packets that have a different IP on the other interfaces, which
# is not the behaviour we want from an ideal node that only processes packets through Pax.
self.cmd("sysctl -w net.ipv4.ip_forward=0")
def terminate(self):
# Remove iptables rules
for intf in self.intfList():
self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name)
super(PaxNode, self).terminate()
|
# coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __init__(self, name, **params):
super(PaxNode, self).__init__(name, **params)
def config(self, **params):
super(PaxNode, self).config(**params)
# Setup iptable rules to drop incoming packets on each interface:
# Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets
# to prevent the OS from handling them and responding.
for intf in self.intfList():
self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
# Disable ip_forward because otherwise this still happens, even with the above iptables rules
self.cmd("sysctl -w net.ipv4.ip_forward=0")
def terminate(self):
# Remove iptables rules
for intf in self.intfList():
self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name)
super(PaxNode, self).terminate()
|
Remove specific path for Travis
|
'use strict';
/**
* This file contains the variables used in other gulp files
* which defines tasks
* By design, we only put there very generic config values
* which are used in several places to keep good readability
* of the tasks
*/
const path = require('path');
const gutil = require('gulp-util');
<% if (framework === 'angular1') { -%>
exports.ngModule = 'app';
<% } -%>
/**
* The main paths of your project handle these with care
*/
exports.paths = {
src: 'src',
dist: 'dist',
tmp: '.tmp',
e2e: 'e2e'
};
exports.path = {};
for (let pathName in exports.paths) {
exports.path[pathName] = function pathJoin() {
const pathValue = exports.paths[pathName];
const funcArgs = Array.prototype.slice.call(arguments);
const joinArgs = [pathValue].concat(funcArgs);
return path.join.apply(this, joinArgs);
}
}
/**
* Common implementation for an error handler of a Gulp plugin
*/
exports.errorHandler = function (title) {
return function (err) {
gutil.log(gutil.colors.red(`[${title}]`), err.toString());
this.emit('end');
};
};
|
'use strict';
/**
* This file contains the variables used in other gulp files
* which defines tasks
* By design, we only put there very generic config values
* which are used in several places to keep good readability
* of the tasks
*/
const path = require('path');
const gutil = require('gulp-util');
<% if (framework === 'angular1') { -%>
exports.ngModule = 'app';
<% } -%>
/**
* The main paths of your project handle these with care
*/
exports.paths = {
src: 'src',
dist: 'dist',
tmp: '.tmp',
e2e: 'e2e'
};
exports.path = {};
for (let pathName in exports.paths) {
exports.path[pathName] = function pathJoin() {
const pathValue = exports.paths[pathName];
const funcArgs = Array.prototype.slice.call(arguments);
const joinArgs = [pathValue].concat(funcArgs);
return path.join.apply(this, joinArgs);
}
}
if (process.env.CI === 'true') {
exports.paths = {
src: 'testGulpTasks/fixture/src',
dist: 'testGulpTasks/build/dist',
tmp: 'testGulpTasks/build/.tmp',
e2e: 'testGulpTasks/fixture/e2e'
};
}
/**
* Common implementation for an error handler of a Gulp plugin
*/
exports.errorHandler = function (title) {
return function (err) {
gutil.log(gutil.colors.red(`[${title}]`), err.toString());
this.emit('end');
};
};
|
Fix domains test after pull & npm install
|
'use strict';
let nock = require('nock');
let cmd = require('../../../commands/domains');
let expect = require('chai').expect;
describe('domains', function() {
beforeEach(() => cli.mockConsole());
it('shows the domains', function() {
let api = nock('https://api.heroku.com:443')
.get('/apps/myapp/domains')
.reply(200, [
{"cname": "myapp.com", "hostname": "myapp.com", "kind": "custom"},
{"cname": null, "hostname": "myapp.herokuapp.com", "kind": "heroku"},
]);
return cmd.run({app: 'myapp', flags: {}})
.then(() => expect(cli.stdout).to.equal(`=== myapp Heroku Domain
myapp.herokuapp.com
=== myapp Custom Domains
Domain Name DNS Target
βββββββββββ ββββββββββ
myapp.com myapp.com
`))
.then(() => api.done());
});
});
|
'use strict';
let nock = require('nock');
let cmd = require('../../../commands/domains');
let expect = require('chai').expect;
describe('domains', function() {
beforeEach(() => cli.mockConsole());
it('shows the domains', function() {
let api = nock('https://api.heroku.com:443')
.get('/apps/myapp/domains')
.reply(200, [
{"cname": "myapp.com", "hostname": "myapp.com", "kind": "custom"},
{"cname": null, "hostname": "myapp.herokuapp.com", "kind": "heroku"},
]);
return cmd.run({app: 'myapp', flags: {}})
.then(() => expect(cli.stdout).to.equal(`=== myapp Heroku Domain
myapp.herokuapp.com
=== myapp Custom Domains
Domain Name DNS Target
βββββββββββ ββββββββββ
myapp.com myapp.com
`))
.then(() => api.done());
});
});
|
Add State to Artifact struct to support the new packer api (v0.7.2)
|
package softlayer
import (
"fmt"
"log"
)
// Artifact represents a Softlayer image as the result of a Packer build.
type Artifact struct {
imageName string
imageId string
datacenterName string
client *SoftlayerClient
}
// BuilderId returns the builder Id.
func (*Artifact) BuilderId() string {
return BuilderId
}
// Destroy destroys the Softlayer image represented by the artifact.
func (self *Artifact) Destroy() error {
log.Printf("Destroying image: %s", self.String())
err := self.client.destroyImage(self.imageId)
return err
}
// Files returns the files represented by the artifact.
func (*Artifact) Files() []string {
return nil
}
// Id returns the Softlayer image ID.
func (self *Artifact) Id() string {
return self.imageId
}
func (self *Artifact) State(name string) interface{} {
return nil
}
// String returns the string representation of the artifact.
func (self *Artifact) String() string {
return fmt.Sprintf("%s::%s (%s)", self.datacenterName, self.imageId, self.imageName)
}
|
package softlayer
import (
"fmt"
"log"
)
// Artifact represents a Softlayer image as the result of a Packer build.
type Artifact struct {
imageName string
imageId string
datacenterName string
client *SoftlayerClient
}
// BuilderId returns the builder Id.
func (*Artifact) BuilderId() string {
return BuilderId
}
// Destroy destroys the Softlayer image represented by the artifact.
func (self *Artifact) Destroy() error {
log.Printf("Destroying image: %s", self.String())
err := self.client.destroyImage(self.imageId)
return err
}
// Files returns the files represented by the artifact.
func (*Artifact) Files() []string {
return nil
}
// Id returns the Softlayer image ID.
func (self *Artifact) Id() string {
return self.imageId
}
// String returns the string representation of the artifact.
func (self *Artifact) String() string {
return fmt.Sprintf("%s::%s (%s)", self.datacenterName, self.imageId, self.imageName)
}
|
Include missing argument in router query string method
|
class GelatoRouter extends Backbone.Router {
execute(callback, args, name) {
if (this.page) {
this.page.remove();
}
this.trigger('navigate:before', args, name);
callback && callback.apply(this, args);
this.trigger('navigate:after', args, name);
}
getQueryString(name) {
const location = window.location;
let query = '';
if (location.hash.length) {
query = location.hash.substring(location.hash.indexOf('?') + 1);
} else {
query = location.search.substring(1);
}
const params = query.split('&');
for (let i = 0; i < params.length; i++) {
const pair = params[i].split('=');
if (pair[0] === name) {
return pair[1];
}
}
return null;
}
isRunning() {
return Backbone.History.started;
}
start(options) {
return Backbone.history.start(options);
}
}
Gelato = Gelato || {};
Gelato.Router = GelatoRouter;
|
class GelatoRouter extends Backbone.Router {
execute(callback, args, name) {
if (this.page) {
this.page.remove();
}
this.trigger('navigate:before', args, name);
callback && callback.apply(this, args);
this.trigger('navigate:after', args, name);
}
getQueryString() {
const location = window.location;
let query = '';
if (location.hash.length) {
query = location.hash.substring(location.hash.indexOf('?') + 1);
} else {
query = location.search.substring(1);
}
const params = query.split('&');
for (let i = 0; i < params.length; i++) {
const pair = params[i].split('=');
if (pair[0] === name) {
return pair[1];
}
}
return null;
}
isRunning() {
return Backbone.History.started;
}
start(options) {
return Backbone.history.start(options);
}
}
Gelato = Gelato || {};
Gelato.Router = GelatoRouter;
|
Make sure encoding closes correctly
|
package io.appium.android.bootstrap.utils;
import java.nio.charset.Charset;
import io.appium.android.bootstrap.Logger;
public class UnicodeEncoder {
private static final Charset M_UTF7 = Charset.forName("x-IMAP-mailbox-name");
private static final Charset ASCII = Charset.forName("US-ASCII");
public static String encode(final String text) {
byte[] encoded = text.getBytes(M_UTF7);
String ret = new String(encoded, ASCII);
if (ret.charAt(ret.length()-1) != text.charAt(text.length()-1) && !ret.endsWith("-")) {
// in some cases there is a problem and the closing tag is not added
// to the encoded text (for instance, with `ΓΌ`)
Logger.debug("Closing tag missing. Adding.");
ret = ret + "-";
}
return ret;
}
public static boolean needsEncoding(final String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
int cp = Character.codePointAt(chars, i);
if (cp > 0x7F || cp == '&') {
// Selenium uses a Unicode PUA to cover certain special characters
// see https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/Keys.java
// these should juse be passed through as is.
return !(cp >= 0xE000 && cp <= 0xE040);
}
}
return false;
}
}
|
package io.appium.android.bootstrap.utils;
import java.nio.charset.Charset;
public class UnicodeEncoder {
private static final Charset M_UTF7 = Charset.forName("x-IMAP-mailbox-name");
private static final Charset ASCII = Charset.forName("US-ASCII");
public static String encode(final String text) {
byte[] encoded = text.getBytes(M_UTF7);
return new String(encoded, ASCII);
}
public static boolean needsEncoding(final String text) {
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
int cp = Character.codePointAt(chars, i);
if (cp > 0x7F || cp == '&') {
// Selenium uses a Unicode PUA to cover certain special characters
// see https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/Keys.java
// these should juse be passed through as is.
return !(cp >= 0xE000 && cp <= 0xE040);
}
}
return false;
}
}
|
Fix module name in JSDoc
|
'use strict';
/**
* Uniformly distributed pseudorandom numbers.
*
* @module @stdlib/math/base/random/randu
*
* @example
* var randu = require( '@stdlib/math/base/random/randu' );
*
* var v = randu();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/math/base/random/randu' ).factory;
*
* var randu = factory({
* 'name': 'minstd',
* 'seed': 12345
* });
*
* var v = randu();
* // returns <number>
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var randu = require( './uniform.js' );
var factory = require( './factory.js' );
// METHODS //
setReadOnly( randu, 'factory', factory );
// EXPORTS //
module.exports = randu;
|
'use strict';
/**
* Uniformly distributed pseudorandom numbers.
*
* @module @stdlib/math/base/random/uniform
*
* @example
* var randu = require( '@stdlib/math/base/random/randu' );
*
* var v = randu();
* // returns <number>
*
* @example
* var factory = require( '@stdlib/math/base/random/randu' ).factory;
*
* var randu = factory({
* 'name': 'minstd',
* 'seed': 12345
* });
*
* var v = randu();
* // returns <number>
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var randu = require( './uniform.js' );
var factory = require( './factory.js' );
// METHODS //
setReadOnly( randu, 'factory', factory );
// EXPORTS //
module.exports = randu;
|
Increase keepalive to 24 hrs.
|
'use strict';
let mqtt = require('mqtt');
let mqttClient;
module.exports = {
connect: function (options, callback) {
mqttClient = mqtt.connect(options.url, {
keepalive: 86400,
clientId: options.machineCode,
username: options.user,
password: options.pass,
reconnectPeriod: 1000
});
mqttClient.on('connect', function () {
console.log('MQTT Client connected to server.');
mqttClient.subscribe(options.machineCode);
console.log(`MQTT Client subscribed to ${options.machineCode}`);
});
mqttClient.on('offline', function() {
console.log('MQTT Client went offline.');
});
mqttClient.on('reconnect', function() {
console.log('MQTT Client reconnecting to server.');
});
callback();
},
getClient: function (callback) {
callback(null, mqttClient);
}
};
|
'use strict';
let mqtt = require('mqtt');
let mqttClient;
module.exports = {
connect: function (options, callback) {
mqttClient = mqtt.connect(options.url, {
keepalive: 300,
clientId: options.machineCode,
username: options.user,
password: options.pass,
reconnectPeriod: 1000
});
mqttClient.on('connect', function () {
console.log('MQTT Client connected to server.');
mqttClient.subscribe(options.machineCode);
console.log(`MQTT Client subscribed to ${options.machineCode}`);
});
mqttClient.on('offline', function() {
console.log('MQTT Client went offline.');
});
mqttClient.on('reconnect', function() {
console.log('MQTT Client reconnecting to server.');
});
callback();
},
getClient: function (callback) {
callback(null, mqttClient);
}
};
|
Remove django requirement to prevent version conflicts when using pip
|
#!/usr/bin/env python
from setuptools import setup,find_packages
METADATA = dict(
name='django-socialregistration',
version='0.4.3',
author='Alen Mujezinovic',
author_email='alen@caffeinehit.com',
description='Django application enabling registration through a variety of APIs',
long_description=open('README.rst').read(),
url='http://github.com/flashingpumpkin/django-socialregistration',
keywords='django facebook twitter oauth openid registration',
install_requires=['oauth2', 'python-openid'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Environment :: Web Environment',
'Topic :: Internet',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=find_packages(),
package_data={'socialregistration': ['templates/socialregistration/*.html'], }
)
if __name__ == '__main__':
setup(**METADATA)
|
#!/usr/bin/env python
from setuptools import setup,find_packages
METADATA = dict(
name='django-socialregistration',
version='0.4.3',
author='Alen Mujezinovic',
author_email='alen@caffeinehit.com',
description='Django application enabling registration through a variety of APIs',
long_description=open('README.rst').read(),
url='http://github.com/flashingpumpkin/django-socialregistration',
keywords='django facebook twitter oauth openid registration',
install_requires=['django', 'oauth2', 'python-openid'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'Environment :: Web Environment',
'Topic :: Internet',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
],
packages=find_packages(),
package_data={'socialregistration': ['templates/socialregistration/*.html'], }
)
if __name__ == '__main__':
setup(**METADATA)
|
Use ActivityCompat instead of reinventing the wheel
|
package net.redwarp.library.testapplication;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
public class DetailActivity extends AppCompatActivity {
@Bind(R.id.text) TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ButterKnife.bind(this);
if (getActionBar() != null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
long userId = getIntent().getLongExtra(MainActivity.EXTRA_USER_ID, -1);
if (userId != -1) {
RandomUser user = TestApplication.getDatabaseHelper().getWithId(RandomUser.class, userId);
if (user != null) {
mTextView.setText(user.name);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
ActivityCompat.finishAfterTransition(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package net.redwarp.library.testapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
public class DetailActivity extends AppCompatActivity {
@Bind(R.id.text) TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ButterKnife.bind(this);
if (getActionBar() != null) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
long userId = getIntent().getLongExtra(MainActivity.EXTRA_USER_ID, -1);
if (userId != -1) {
RandomUser user = TestApplication.getDatabaseHelper().getWithId(RandomUser.class, userId);
if (user != null) {
mTextView.setText(user.name);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAfterTransition();
} else {
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
Refactor str_to_num to be more concise
Functionally nothing has changed. We just need not try twice nor
define the variable _ twice.
|
# -*- coding: utf-8 -*-
def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
if not exact_match:
return int(i)
elif str(int(i)) == i:
return int(i)
elif str(float(i)) == i:
return float(i)
else:
pass
except ValueError:
pass
return i
def set_defaults(kwargs, defaults):
for k, v in defaults.items():
if k not in kwargs:
kwargs[k] = v
|
# -*- coding: utf-8 -*-
def str_to_num(i, exact_match=True):
"""
Attempts to convert a str to either an int or float
"""
# TODO: Cleanup -- this is really ugly
if not isinstance(i, str):
return i
try:
_ = int(i)
if not exact_match:
return _
elif str(_) == i:
return _
else:
pass
except ValueError:
pass
try:
_ = float(i)
if not exact_match:
return _
elif str(_) == i:
return _
else:
pass
except ValueError:
pass
return i
def set_defaults(kwargs, defaults):
for k, v in defaults.items():
if k not in kwargs:
kwargs[k] = v
|
Fix zoom levels for example.
|
var playlist = WaveformPlaylist.init({
samplesPerPixel: 3000,
zoomLevels: [500, 1000, 3000, 5000],
mono: true,
waveHeight: 100,
container: document.getElementById("playlist"),
state: 'cursor',
waveOutlineColor: '#E0EFF1',
colors: {
waveOutlineColor: '#E0EFF1',
timeColor: 'grey',
fadeColor: 'black'
},
controls: {
show: true, //whether or not to include the track controls
width: 200 //width of controls in pixels
}
});
playlist.load([
{
"src": "media/audio/Vocals30.mp3",
"name": "Vocals",
"states": {
"shift": false
}
},
{
"src": "media/audio/BassDrums30.mp3",
"name": "Drums",
"start": 30
}
]).then(function() {
//can do stuff with the playlist.
});
|
var playlist = WaveformPlaylist.init({
samplesPerPixel: 3000,
mono: true,
waveHeight: 100,
container: document.getElementById("playlist"),
state: 'cursor',
waveOutlineColor: '#E0EFF1',
colors: {
waveOutlineColor: '#E0EFF1',
timeColor: 'grey',
fadeColor: 'black'
},
controls: {
show: true, //whether or not to include the track controls
width: 200 //width of controls in pixels
}
});
playlist.load([
{
"src": "media/audio/Vocals30.mp3",
"name": "Vocals",
"states": {
"shift": false
}
},
{
"src": "media/audio/BassDrums30.mp3",
"name": "Drums",
"start": 30
}
]).then(function() {
//can do stuff with the playlist.
});
|
Use css class instead of direct formatting
In order to preserve the hover effect on the table, use a css class to
highlight table rows with active projects.
|
name: Dashboard - Highlight active projects (Compact View only)
description: See https://github.com/quincunx/testrail-ui-scripts
author: Christian Schuerer-Waldheim <csw@gmx.at>
version: 1.0
includes: ^dashboard
excludes:
js:
$(document).ready(
function() {
// Check if Compact View is being displayed
if ($('span.content-header-icon:nth-child(1) > a:nth-child(1) > img:nth-child(1)').attr('src').indexOf("Inactive") >= 0) {
console.log("TestRail UI Script - Dashboard - Highlight active projects: Only Compact View is supported");
} else {
$('#content-inner > table > tbody > tr').each(function() {
var $project = $(this);
var run_count = 0;
$project.children('td:nth-child(3)').each(function() { run_count = $(this).children('strong:nth-child(3)').html(); });
if (run_count > 0) { $project.addClass("project-active"); }
});
}
}
);
css:
.project-active{
background:#FFCC33
}
|
name: Dashboard - Highlight active projects (Compact View only)
description: See https://github.com/quincunx/testrail-ui-scripts
author: Christian Schuerer-Waldheim <csw@gmx.at>
version: 1.0
includes: ^dashboard
excludes:
js:
$(document).ready(
function() {
// Check if Compact View is being displayed
if ($('span.content-header-icon:nth-child(1) > a:nth-child(1) > img:nth-child(1)').attr('src').indexOf("Inactive") >= 0) {
console.log("TestRail UI Script - Dashboard - Highlight active projects: Only Compact View is supported");
} else {
$('#content-inner > table > tbody > tr').each(function() {
var $project = $(this);
var run_count = 0;
$project.children('td:nth-child(3)').each(function() { run_count = $(this).children('strong:nth-child(3)').html(); });
if (run_count > 0) { $project.css("background-color", "#D1E6FD"); }
});
}
}
);
|
Mark all scripts as 0o755
This gives execute permission for everyone even if Atom is installed as root:
https://github.com/atom/atom/issues/19367
|
#!/usr/bin/env node
var cp = require('child_process')
var fs = require('fs')
var path = require('path')
var script = path.join(__dirname, 'postinstall')
if (process.platform === 'win32') {
script += '.cmd'
} else {
script += '.sh'
}
// Make sure all the scripts have the necessary permissions when we execute them
// (npm does not preserve permissions when publishing packages on Windows,
// so this is especially needed to allow apm to be published successfully on Windows)
fs.chmodSync(script, 0o755)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), 0o755)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), 0o755)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), 0o755)
var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true })
child.stderr.pipe(process.stderr)
child.stdout.pipe(process.stdout)
|
#!/usr/bin/env node
var cp = require('child_process')
var fs = require('fs')
var path = require('path')
var script = path.join(__dirname, 'postinstall')
if (process.platform === 'win32') {
script += '.cmd'
} else {
script += '.sh'
}
// Read + execute permission
fs.chmodSync(script, fs.constants.S_IRUSR | fs.constants.S_IXUSR)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'apm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'npm'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
fs.chmodSync(path.join(__dirname, '..', 'bin', 'python-interceptor.sh'), fs.constants.S_IRUSR | fs.constants.S_IXUSR)
var child = cp.spawn(script, [], { stdio: ['pipe', 'pipe', 'pipe'], shell: true })
child.stderr.pipe(process.stderr)
child.stdout.pipe(process.stdout)
|
Update muteConsole & restoreConsole functions
|
const fs = require('fs');
export const makeAsyncCallback = (callbackValue) => {
let promiseResolve;
const promise = new Promise((resolve) => {
promiseResolve = resolve;
});
const func = jest.fn(
callbackValue
? () => promiseResolve(callbackValue)
: (...args) => promiseResolve(args.length === 1 ? args[0] : args),
);
return { promise, func };
};
export const loadPDF = (path) => {
const raw = fs.readFileSync(path);
const arrayBuffer = raw.buffer;
return {
raw,
arrayBuffer,
get blob() {
return new Blob([arrayBuffer], { type: 'application/pdf' });
},
get data() {
return new Uint8Array(raw);
},
get dataURI() {
return `data:application/pdf;base64,${raw.toString('base64')}`;
},
get file() {
return new File([arrayBuffer], { type: 'application/pdf' });
},
};
};
export const muteConsole = () => {
jest.spyOn(global.console, 'log').mockImplementation(() => {});
jest.spyOn(global.console, 'error').mockImplementation(() => {});
jest.spyOn(global.console, 'warn').mockImplementation(() => {});
};
export const restoreConsole = () => {
global.console.log.mockClear();
global.console.error.mockClear();
global.console.warn.mockClear();
};
|
const fs = require('fs');
export const makeAsyncCallback = (callbackValue) => {
let promiseResolve;
const promise = new Promise((resolve) => {
promiseResolve = resolve;
});
const func = jest.fn(
callbackValue
? () => promiseResolve(callbackValue)
: (...args) => promiseResolve(args.length === 1 ? args[0] : args),
);
return { promise, func };
};
export const loadPDF = (path) => {
const raw = fs.readFileSync(path);
const arrayBuffer = raw.buffer;
return {
raw,
arrayBuffer,
get blob() {
return new Blob([arrayBuffer], { type: 'application/pdf' });
},
get data() {
return new Uint8Array(raw);
},
get dataURI() {
return `data:application/pdf;base64,${raw.toString('base64')}`;
},
get file() {
return new File([arrayBuffer], { type: 'application/pdf' });
},
};
};
export const muteConsole = () => {
global.consoleBackup = global.console;
global.console = {
log: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
};
};
export const restoreConsole = () => {
global.console = global.consoleBackup;
};
|
Fix code for review comments
|
"""Functions to retrieve pending list and invoke Graph Sync."""
import f8a_jobs.defaults as configuration
import requests
import traceback
import logging
from urllib.parse import urljoin
logger = logging.getLogger(__name__)
def _api_call(url, params=None):
params = params or {}
try:
logger.info("API Call for url: %s, params: %s" % (url, params))
r = requests.get(url, params=params)
r.raise_for_status()
result = {"data": r.json()}
except requests.exceptions.HTTPError:
logger.error(traceback.format_exc())
result = {"error": "Failed to retrieve data from Data Model Importer backend"}
return result
def fetch_pending(params=None):
params = params or {}
"""Invoke Pending Graph Sync APIs for given parameters."""
url = urljoin(configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/pending")
return _api_call(url, params)
def invoke_sync(params=None):
params = params or {}
"""Invoke Graph Sync APIs to sync for given parameters."""
url = urljoin(configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/sync_all")
return _api_call(url, params)
|
"""Functions to retrieve pending list and invoke Graph Sync."""
import f8a_jobs.defaults as configuration
import requests
import traceback
import logging
logger = logging.getLogger(__name__)
def _api_call(url, params={}):
try:
logger.info("API Call for url: %s, params: %s" % (url, params))
r = requests.get(url, params=params)
if r is None:
logger.error("Returned response is: %s" % r)
raise Exception("Empty response found")
result = {"data": r.json()}
except Exception:
logger.error(traceback.format_exc())
result = {"error": "Failed to retrieve data from Data Model Importer backend"}
return result
def fetch_pending(params={}):
"""Invoke Pending Graph Sync APIs for given parameters."""
url = "%s%s" % (configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/pending")
return _api_call(url, params)
def invoke_sync(params={}):
"""Invoke Graph Sync APIs to sync for given parameters."""
url = "%s%s" % (configuration.DATA_IMPORTER_ENDPOINT, "/api/v1/sync_all")
return _api_call(url, params)
|
Add example of using sorting options for calcs
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { push } from 'connected-react-router';
import { selectors } from '@openchemistry/redux'
import { calculations, molecules } from '@openchemistry/redux'
import { isNil } from 'lodash-es';
import Calculations from '../components/calculations';
class CalculationsContainer extends Component {
componentDidMount() {
const options = { limit: 25, offset: 0, sort: '_id', sortdir: -1 }
this.props.dispatch(molecules.loadMolecules(options));
this.props.dispatch(calculations.loadCalculations(options));
}
onOpen = (id) => {
this.props.dispatch(push(`/calculations/${id}?mo=homo`));
}
render() {
const { calculations, molecules } = this.props;
if (isNil(calculations)) {
return null;
}
return (
<Calculations calculations={calculations} molecules={molecules} onOpen={this.onOpen} />
);
}
}
CalculationsContainer.propTypes = {
}
CalculationsContainer.defaultProps = {
}
function mapStateToProps(state, ownProps) {
let calculations = selectors.calculations.getCalculations(state);
let molecules = selectors.molecules.getMoleculesById(state);
return { calculations, molecules };
}
export default connect(mapStateToProps)(CalculationsContainer)
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import { push } from 'connected-react-router';
import { selectors } from '@openchemistry/redux'
import { calculations, molecules } from '@openchemistry/redux'
import { isNil } from 'lodash-es';
import Calculations from '../components/calculations';
class CalculationsContainer extends Component {
componentDidMount() {
this.props.dispatch(molecules.loadMolecules());
this.props.dispatch(calculations.loadCalculations());
}
onOpen = (id) => {
this.props.dispatch(push(`/calculations/${id}?mo=homo`));
}
render() {
const { calculations, molecules } = this.props;
if (isNil(calculations)) {
return null;
}
return (
<Calculations calculations={calculations} molecules={molecules} onOpen={this.onOpen} />
);
}
}
CalculationsContainer.propTypes = {
}
CalculationsContainer.defaultProps = {
}
function mapStateToProps(state, ownProps) {
let calculations = selectors.calculations.getCalculations(state);
let molecules = selectors.molecules.getMoleculesById(state);
return { calculations, molecules };
}
export default connect(mapStateToProps)(CalculationsContainer)
|
Fix selector not using get
|
import { takeLatest } from 'redux-saga';
import { call, put, select, take } from 'redux-saga/effects';
import { NOT_CONNECTED, CREATING_ACCOUNT, CONNECTED_CREATING_ACCOUNT } from '../messages';
import * as libs from '../libs';
import * as actions from '../actions';
import * as types from '../types';
import * as deps from '../dependencies';
export function* createAccountSaga({ name, email, password }) {
if (yield select(deps.selectors.getIsConnected)) {
try {
yield put(actions.createAccountStatusChanged(CREATING_ACCOUNT));
const userId = yield call(libs.createAccount, name, email, password);
yield put(actions.createAccountSucceed(userId));
yield put(actions.loginRequested(email, password));
} catch (error) {
yield put(actions.createAccountFailed(error));
}
} else {
yield put(actions.createAccountStatusChanged(NOT_CONNECTED));
yield take(deps.types.CONNECTION_SUCCEED);
yield put(actions.createAccountStatusChanged(CONNECTED_CREATING_ACCOUNT));
yield call(createAccountSaga, { name, email, password });
}
}
export default function* createAccountSagas() {
yield [
takeLatest(types.CREATE_ACCOUNT_REQUESTED, createAccountSaga),
];
}
|
import { takeLatest } from 'redux-saga';
import { call, put, select, take } from 'redux-saga/effects';
import { NOT_CONNECTED, CREATING_ACCOUNT, CONNECTED_CREATING_ACCOUNT } from '../messages';
import * as libs from '../libs';
import * as actions from '../actions';
import * as types from '../types';
import * as deps from '../dependencies';
export function* createAccountSaga({ name, email, password }) {
if (yield select(deps.selectors.isConnected)) {
try {
yield put(actions.createAccountStatusChanged(CREATING_ACCOUNT));
const userId = yield call(libs.createAccount, name, email, password);
yield put(actions.createAccountSucceed(userId));
yield put(actions.loginRequested(email, password));
} catch (error) {
yield put(actions.createAccountFailed(error));
}
} else {
yield put(actions.createAccountStatusChanged(NOT_CONNECTED));
yield take(deps.types.CONNECTION_SUCCEED);
yield put(actions.createAccountStatusChanged(CONNECTED_CREATING_ACCOUNT));
yield call(createAccountSaga, { name, email, password });
}
}
export default function* createAccountSagas() {
yield [
takeLatest(types.CREATE_ACCOUNT_REQUESTED, createAccountSaga),
];
}
|
Make wedding page home page.
|
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import App from './components/App';
import BlogContainer from './containers/blog-container';
import PostEditorContainer from './containers/post-editor-container';
import Test from './components/Test';
import ScgSearchHelper from './components/scg-search-helper';
import Wedding from './components/wedding';
export default function getRouter(store) {
const history = syncHistoryWithStore(browserHistory, store);
return (
<Router history={history}>
<Route path="/" component={Wedding} />
<Route path="blog" component={App}>
<IndexRoute component={BlogContainer} />
<Route path="test(/:number)" component={Test} />
<Route path="editor(/:postId)" component={PostEditorContainer} />
</Route>
<Route path="scg" component={ScgSearchHelper} />
</Router>
);
}
|
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import App from './components/App';
import BlogContainer from './containers/blog-container';
import PostEditorContainer from './containers/post-editor-container';
import Test from './components/Test';
import ScgSearchHelper from './components/scg-search-helper';
import Wedding from './components/wedding';
export default function getRouter(store) {
const history = syncHistoryWithStore(browserHistory, store);
return (
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={BlogContainer} />
<Route path="test(/:number)" component={Test} />
<Route path="editor(/:postId)" component={PostEditorContainer} />
</Route>
<Route path="scg" component={ScgSearchHelper} />
<Route path="wedding" component={Wedding} />
</Router>
);
}
|
Fix issue where tar command would fail if there were too many command line arguments
Signed-off-by: Dan Weinberg <5ed7700fd0f25639b4f8f8b3c1bd72b4eff8b781@cloudcredo.com>
|
// +build !windows
package commands
import (
"io"
"log"
"os"
"os/exec"
)
func tarStreamFrom(workDir string, paths []string) (io.ReadCloser, error) {
var archive io.ReadCloser
var writer io.WriteCloser
if tarPath, err := exec.LookPath("tar"); err == nil {
tarCmd := exec.Command(tarPath, []string{"-czf", "-", "-T", "-"}...)
tarCmd.Dir = workDir
tarCmd.Stderr = os.Stderr
archive, err = tarCmd.StdoutPipe()
if err != nil {
log.Fatalln("could not create tar pipe:", err)
}
writer, err = tarCmd.StdinPipe()
if err != nil {
log.Fatalln("could not create tar stdin pipe:", err)
}
err = tarCmd.Start()
if err != nil {
log.Fatalln("could not run tar:", err)
}
go func() {
for _, s := range paths {
io.WriteString(writer, s+"\n")
}
writer.Close()
}()
} else {
return nativeTarGZStreamFrom(workDir, paths)
}
return archive, nil
}
|
// +build !windows
package commands
import (
"io"
"log"
"os"
"os/exec"
)
func tarStreamFrom(workDir string, paths []string) (io.ReadCloser, error) {
var archive io.ReadCloser
if tarPath, err := exec.LookPath("tar"); err == nil {
tarCmd := exec.Command(tarPath, append([]string{"-czf", "-"}, paths...)...)
tarCmd.Dir = workDir
tarCmd.Stderr = os.Stderr
archive, err = tarCmd.StdoutPipe()
if err != nil {
log.Fatalln("could not create tar pipe:", err)
}
err = tarCmd.Start()
if err != nil {
log.Fatalln("could not run tar:", err)
}
} else {
return nativeTarGZStreamFrom(workDir, paths)
}
return archive, nil
}
|
Add filters module to deps
|
'use strict';
var angular = require('angular');
// angular modules
require('angular-ui-router');
require('angular-animate');
require('angular-moment');
require('angular-loading-bar');
require('./templates');
require('./controllers/_index');
require('./services/_index');
require('./directives/_index');
require('./components/_index');
require('./filters/_index');
// create and bootstrap application
angular.element(document).ready(function() {
var requires = [
'ui.router',
'ngAnimate',
'angularMoment',
'angular-loading-bar',
'templates',
'app.controllers',
'app.services',
'app.directives',
'app.filters',
'ui.bootstrap.datetimepicker',
'wu.masonry'
];
// mount on window for testing
window.app = angular.module('app', requires);
angular.module('app').constant('AppSettings', require('./constants'));
angular.module('app').config(require('./routes'));
angular.module('app').run(require('./on_run'));
angular.bootstrap(document, ['app']);
});
|
'use strict';
var angular = require('angular');
// angular modules
require('angular-ui-router');
require('angular-animate');
require('angular-moment');
require('angular-loading-bar');
require('./templates');
require('./controllers/_index');
require('./services/_index');
require('./directives/_index');
require('./components/_index');
// create and bootstrap application
angular.element(document).ready(function() {
var requires = [
'ui.router',
'ngAnimate',
'angularMoment',
'angular-loading-bar',
'templates',
'app.controllers',
'app.services',
'app.directives',
'ui.bootstrap.datetimepicker',
'wu.masonry'
];
// mount on window for testing
window.app = angular.module('app', requires);
angular.module('app').constant('AppSettings', require('./constants'));
angular.module('app').config(require('./routes'));
angular.module('app').run(require('./on_run'));
angular.bootstrap(document, ['app']);
});
|
Fix AppView test to render activity indicator
|
/*eslint-disable max-nested-callbacks*/
import React from 'react';
import {shallow} from 'enzyme';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import {ActivityIndicator} from 'react-native';
import AppView from '../AppView';
describe('<AppView />', () => {
describe('isReady', () => {
it('should render a <ActivityIndicator /> if not ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={false}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(1);
});
it('should not render a <ActivityIndicator /> if ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={true}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(0);
});
});
});
|
/*eslint-disable max-nested-callbacks*/
import React from 'react';
import {shallow} from 'enzyme';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import Spinner from 'react-native-gifted-spinner';
import AppView from '../AppView';
describe('<AppView />', () => {
describe('isReady', () => {
it('should render a <Spinner /> if not ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={false}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(Spinner)).to.have.lengthOf(1);
});
it('should not render a <Spinner /> if ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={true}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(Spinner)).to.have.lengthOf(0);
});
});
});
|
Remove unnecessary set time to calendar.
|
package bj.pranie.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by noon on 03.02.17.
*/
public class TimeUtil {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw");
private static Calendar calendar = Calendar.getInstance(timeZone);
public static String getTime() {
return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE);
}
public static Calendar getCalendar(){
return (Calendar) calendar.clone();
}
public static boolean isPast(String time, String date) {
Calendar now = TimeUtil.getCalendar();
Calendar calendar = TimeUtil.getCalendar();
try {
calendar.setTime(format.parse(date + " " + time));
} catch (ParseException e) {
e.printStackTrace();
return false;
}
if (now.before(calendar)) {
return false;
} else {
return true;
}
}
}
|
package bj.pranie.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* Created by noon on 03.02.17.
*/
public class TimeUtil {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
private static TimeZone timeZone = TimeZone.getTimeZone("Europe/Warsaw");
private static Calendar calendar = Calendar.getInstance(timeZone);
public static String getTime() {
return calendar.get(Calendar.HOUR_OF_DAY) + ":"+ calendar.get(Calendar.MINUTE);
}
public static Calendar getCalendar(){
return (Calendar) calendar.clone();
}
public static boolean isPast(String time, String date) {
Calendar now = TimeUtil.getCalendar();
now.setTime(new Date());
Calendar calendar = TimeUtil.getCalendar();
try {
calendar.setTime(format.parse(date + " " + time));
} catch (ParseException e) {
e.printStackTrace();
return false;
}
if (now.before(calendar)) {
return false;
} else {
return true;
}
}
}
|
Use define as it seems to work correctly?
|
define([
'angular',
'app',
'moment',
'app/controllers/default',
'app/controllers/manageTeamOwnership',
'app/controllers/projectStream',
'app/controllers/teamDashboard',
'app/directives/count',
'app/directives/timeSince'
], function(angular, app, moment){
'use strict';
app.config(function(
$httpProvider, $interpolateProvider, $provide
) {
// compatiblity with Django templates
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
// add in Django csrf support
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$provide.value('config', window.SentryConfig);
$provide.value('selectedTeam', window.SentryConfig.selectedTeam);
$provide.value('selectedProject', window.SentryConfig.selectedProject);
});
moment.lang(window.SentryConfig.lang);
angular.bootstrap(document, ['app']);
});
|
require([
'angular',
'app',
'moment',
'app/controllers/default',
'app/controllers/loginSudo',
'app/controllers/manageTeamOwnership',
'app/controllers/projectStream',
'app/controllers/teamDashboard',
'app/directives/count',
'app/directives/timeSince'
], function(angular, app, moment){
'use strict';
app.config(function(
$httpProvider, $interpolateProvider, $provide
) {
// compatiblity with Django templates
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
// add in Django csrf support
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$provide.value('config', window.SentryConfig);
$provide.value('selectedTeam', window.SentryConfig.selectedTeam);
$provide.value('selectedProject', window.SentryConfig.selectedProject);
});
moment.lang(window.SentryConfig.lang);
angular.bootstrap(document, ['app']);
});
|
Update to new location of require config
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
jasmine : {
src : 'src/**/*.js',
options : {
specs : 'spec/**/*.js',
template: require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfigFile: 'lib/requirejs/main.js'
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/**/*.js',
'spec/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('test', ['jshint', 'jasmine']);
grunt.registerTask('default', ['test']);
};
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
jasmine : {
src : 'src/**/*.js',
options : {
specs : 'spec/**/*.js',
template: require('grunt-template-jasmine-requirejs'),
templateOptions: {
requireConfigFile: 'lib/main.js'
}
}
},
jshint: {
all: [
'Gruntfile.js',
'src/**/*.js',
'spec/**/*.js'
],
options: {
jshintrc: '.jshintrc'
}
}
});
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('test', ['jshint', 'jasmine']);
grunt.registerTask('default', ['test']);
};
|
Use requests.session instead of requests.Session
|
import re
import requests
import lxml.html
def grab_cloudflare(url, *args, **kwargs):
sess = requests.session()
sess.headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"}
safe_eval = lambda s: eval(s, {"__builtins__": {}}) if "#" not in s and "__" not in s else ""
page = sess.get(url, *args, **kwargs).content
if "a = document.getElementById('jschl-answer');" in page:
# Cloudflare anti-bots is on
html = lxml.html.fromstring(page)
challenge = html.find(".//input[@name='jschl_vc']").attrib["value"]
script = html.findall(".//script")[-1].text_content()
domain_parts = url.split("/")
domain = domain_parts[2]
math = re.search(r"a\.value = (\d.+?);", script).group(1)
answer = str(safe_eval(math) + len(domain))
data = {"jschl_vc": challenge, "jschl_answer": answer}
get_url = domain_parts[0] + '//' + domain + "/cdn-cgi/l/chk_jschl"
return sess.get(get_url, params=data, headers={"Referer": url}, *args, **kwargs).content
else:
return page
|
import re
import requests
import lxml.html
def grab_cloudflare(url, *args, **kwargs):
sess = requests.Session()
sess.headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"}
safe_eval = lambda s: eval(s, {"__builtins__": {}}) if "#" not in s and "__" not in s else ""
page = sess.get(url, *args, **kwargs).content
if "a = document.getElementById('jschl-answer');" in page:
# Cloudflare anti-bots is on
html = lxml.html.fromstring(page)
challenge = html.find(".//input[@name='jschl_vc']").attrib["value"]
script = html.findall(".//script")[-1].text_content()
domain_parts = url.split("/")
domain = domain_parts[2]
math = re.search(r"a\.value = (\d.+?);", script).group(1)
answer = str(safe_eval(math) + len(domain))
data = {"jschl_vc": challenge, "jschl_answer": answer}
get_url = domain_parts[0] + '//' + domain + "/cdn-cgi/l/chk_jschl"
return sess.get(get_url, params=data, headers={"Referer": url}, *args, **kwargs).content
else:
return page
|
Add related et related_owner methods
|
<?php
namespace Amenophis\Bundle\SocialBundle\Twig;
use Amenophis\Bundle\SocialBundle\Manager\SocialManager;
class SocialExtension extends \Twig_Extension
{
public function __construct(SocialManager $service)
{
$this->service = $service;
}
public function getFunctions()
{
return array(
'social_is' => new \Twig_Function_Method($this, 'social_is'),
'social_count' => new \Twig_Function_Method($this, 'social_count'),
'social_related' => new \Twig_Function_Method($this, 'social_related'),
'social_related_owner' => new \Twig_Function_Method($this, 'social_related_owner'),
);
}
public function social_is($type, $item)
{
return $this->service->is($type, $item);
}
public function social_count($type, $item)
{
return $this->service->count($type, $item);
}
public function social_related($type, $item)
{
return $this->service->related($type, $item);
}
public function social_related_owner($social_item)
{
return $this->service->related_owner($social_item);
}
public function getName()
{
return 'amenophis_social_extension';
}
}
|
<?php
namespace Amenophis\Bundle\SocialBundle\Twig;
use Amenophis\Bundle\SocialBundle\Service\SocialManager;
class SocialExtension extends \Twig_Extension
{
public function __construct(SocialManager $service)
{
$this->service = $service;
}
public function getFunctions()
{
return array(
'social_is' => new \Twig_Function_Method($this, 'social_is'),
'social_count' => new \Twig_Function_Method($this, 'social_count'),
);
}
public function social_is($type, $item)
{
return $this->service->is($type, $item);
}
public function social_count($type, $item)
{
return $this->service->count($type, $item);
}
public function getName()
{
return 'amenophis_social_extension';
}
}
|
Change of context for picture transformation
|
package com.williammora.openfeed.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.williammora.openfeed.R;
import com.williammora.openfeed.activities.StatusActivity;
import com.williammora.openfeed.adapters.viewholders.StatusViewHolder;
import twitter4j.Status;
public class StatusFragment extends Fragment {
private static final String SAVED_STATUS = "SAVED_STATUS";
private Status mStatus;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_status, container, false);
if (savedInstanceState != null) {
mStatus = (Status) savedInstanceState.getSerializable(SAVED_STATUS);
} else {
mStatus = (Status) getActivity().getIntent().getSerializableExtra(StatusActivity.EXTRA_STATUS);
}
StatusViewHolder viewHolder = new StatusViewHolder(view, view.getContext());
viewHolder.updateView(mStatus);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(SAVED_STATUS, mStatus);
super.onSaveInstanceState(outState);
}
}
|
package com.williammora.openfeed.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.williammora.openfeed.R;
import com.williammora.openfeed.activities.StatusActivity;
import com.williammora.openfeed.adapters.viewholders.StatusViewHolder;
import twitter4j.Status;
public class StatusFragment extends Fragment {
private static final String SAVED_STATUS = "SAVED_STATUS";
private Status mStatus;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_status, container, false);
if (savedInstanceState != null) {
mStatus = (Status) savedInstanceState.getSerializable(SAVED_STATUS);
} else {
mStatus = (Status) getActivity().getIntent().getSerializableExtra(StatusActivity.EXTRA_STATUS);
}
StatusViewHolder viewHolder = new StatusViewHolder(view, getActivity());
viewHolder.updateView(mStatus);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putSerializable(SAVED_STATUS, mStatus);
super.onSaveInstanceState(outState);
}
}
|
Increase the default timeout to 1s.
|
from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
Type = Gio.BusType
def __init__(self, type, timeout=1000):
self.con = Gio.bus_get_sync(type, None)
self.timeout = timeout
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.con = None
def SystemBus():
return Bus(Bus.Type.SYSTEM)
def SessionBus():
return Bus(Bus.Type.SESSION)
if __name__ == "__main__":
import sys
title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'
bus = SessionBus()
notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
# [""] is not required, but makes us compatible with Gnome 2030.
|
from gi.repository import Gio
from .proxy import ProxyMixin
from .bus_names import OwnMixin, WatchMixin
from .subscription import SubscriptionMixin
from .registration import RegistrationMixin
from .publication import PublicationMixin
class Bus(ProxyMixin, OwnMixin, WatchMixin, SubscriptionMixin, RegistrationMixin, PublicationMixin):
Type = Gio.BusType
def __init__(self, type, timeout=10):
self.con = Gio.bus_get_sync(type, None)
self.timeout = timeout
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.con = None
def SystemBus():
return Bus(Bus.Type.SYSTEM)
def SessionBus():
return Bus(Bus.Type.SESSION)
if __name__ == "__main__":
import sys
title = sys.argv[1] if len(sys.argv) >= 2 else "Hello World!"
message = sys.argv[2] if len(sys.argv) >= 3 else 'pydbus works :)'
bus = SessionBus()
notifications = bus.get('.Notifications') # org.freedesktop automatically prepended
notifications[""].Notify('test', 0, 'dialog-information', title, message, [], {}, 5000)
# [""] is not required, but makes us compatible with Gnome 2030.
|
Make sg label clicking act like a toggle
|
"use strict";
angular.module('arethusa.sg').directive('sgAncestors', [
'sg',
function(sg) {
return {
restrict: 'A',
scope: {
obj: '=sgAncestors'
},
link: function(scope, element, attrs) {
scope.requestGrammar = function(el) {
if (el.sections) {
if (sg.readerRequested === el) {
sg.readerRequested = false;
} else {
sg.readerRequested = el;
}
}
};
scope.$watchCollection('obj.ancestors', function(newVal, oldVal) {
scope.hierarchy = scope.obj.definingAttrs.concat(newVal);
});
},
templateUrl: './templates/arethusa.sg/ancestors.html'
};
}
]);
|
"use strict";
angular.module('arethusa.sg').directive('sgAncestors', [
'sg',
function(sg) {
return {
restrict: 'A',
scope: {
obj: '=sgAncestors'
},
link: function(scope, element, attrs) {
scope.requestGrammar = function(el) {
if (el.sections) {
sg.readerRequested = el;
}
};
scope.$watchCollection('obj.ancestors', function(newVal, oldVal) {
scope.hierarchy = scope.obj.definingAttrs.concat(newVal);
});
},
templateUrl: './templates/arethusa.sg/ancestors.html'
};
}
]);
|
Use `open` of props. and close hander call onHidePromoteModal action.
|
import React, { Component } from 'react';
import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import RaisedButton from 'material-ui/lib/raised-button';
// NOTE: For emit `onTouchTap` event.
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
export default class PromoteModal extends Component {
constructor(props) {
super(props);
this.state = { open: false };
}
handleOpen() {
this.setState({ open: true });
}
handleClose() {
this.props.onHidePromoteModal();
this.setState({ open: this.props.open });
}
render() {
const actions = [
<FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose.bind(this)} />,
<FlatButton label="Submit" primary={true} onTouchTap={this.handleClose.bind(this)} />
];
return (
<div>
<Dialog title="" actions={actions} modal={true} open={this.props.open} />
</div>
);
}
}
|
import React, { Component } from 'react';
import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import RaisedButton from 'material-ui/lib/raised-button';
// NOTE: For emit `onTouchTap` event.
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
export default class PromoteModal extends Component {
constructor(props) {
super(props);
this.state = { open: false };
}
handleOpen() {
this.setState({ open: true });
}
handleClose() {
this.setState({ open: false });
}
render() {
const actions = [
<FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose.bind(this)} />,
<FlatButton label="Submit" primary={true} onTouchTap={this.handleClose.bind(this)} />
];
return (
<div>
<RaisedButton label="Modal" onTouchTap={this.handleOpen.bind(this)} />
<Dialog title="" actions={actions} modal={true} open={this.state.open} />
</div>
);
}
}
|
Fix another I18n skeleton case typo
|
<?php
namespace Victoire\Bundle\I18nBundle\CacheWarmer;
use Sensio\Bundle\GeneratorBundle\Generator\Generator;
/**
*
* @author Florian Raux
*
*/
class I18nGenerator extends Generator
{
private $annotationReader;
protected $applicationLocales;
/**
*
* @param unknown $annotationReader
*/
public function __construct($annotationReader, $applicationLocales)
{
$this->annotationReader = $annotationReader;
$this->applicationLocales = $applicationLocales;
}
/**
* Warms up the cache.
*
* @return string
*/
public function generate()
{
$this->setSkeletonDirs(__DIR__."/Skeleton/");
return $this->render('I18n.php.twig', array('locales' => $this->applicationLocales));
}
}
|
<?php
namespace Victoire\Bundle\I18nBundle\CacheWarmer;
use Sensio\Bundle\GeneratorBundle\Generator\Generator;
/**
*
* @author Florian Raux
*
*/
class I18nGenerator extends Generator
{
private $annotationReader;
protected $applicationLocales;
/**
*
* @param unknown $annotationReader
*/
public function __construct($annotationReader, $applicationLocales)
{
$this->annotationReader = $annotationReader;
$this->applicationLocales = $applicationLocales;
}
/**
* Warms up the cache.
*
* @return string
*/
public function generate()
{
$this->setSkeletonDirs(__DIR__."/skeleton/");
return $this->render('I18n.php.twig', array('locales' => $this->applicationLocales));
}
}
|
Use auto generated hashcode and equals
|
package io.github.imsmobile.fahrplan.model;
import com.google.common.base.Objects;
public class FavoriteModelItem {
private final String from;
private final String to;
FavoriteModelItem(String from, String to) {
this.from = from;
this.to = to;
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
@Override
public String toString() {
return from + " \u279C " + to;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FavoriteModelItem that = (FavoriteModelItem) o;
if (from != null ? !from.equals(that.from) : that.from != null) return false;
return to != null ? to.equals(that.to) : that.to == null;
}
@Override
public int hashCode() {
int result = from != null ? from.hashCode() : 0;
result = 31 * result + (to != null ? to.hashCode() : 0);
return result;
}
}
|
package io.github.imsmobile.fahrplan.model;
import com.google.common.base.Objects;
public class FavoriteModelItem {
private final String from;
private final String to;
FavoriteModelItem(String from, String to) {
this.from = from;
this.to = to;
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
@Override
public String toString() {
return from + " \u279C " + to;
}
@Override
public boolean equals(Object obj) {
return obj instanceof FavoriteModelItem && Objects.equal(((FavoriteModelItem) obj).getFrom().toLowerCase(), from.toLowerCase()) && Objects.equal(((FavoriteModelItem) obj).getTo().toLowerCase(), to.toLowerCase());
}
@Override
public int hashCode() {
return Objects.hashCode(to.toLowerCase(), from.toLowerCase());
}
}
|
Add isEnable method to the slot for render things
|
package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
private final int x;
private final int y;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isEnabled() {
return true;
}
}
|
package info.u_team.u_team_core.container;
import info.u_team.u_team_core.api.fluid.IFluidHandlerModifiable;
import net.minecraftforge.fluids.FluidStack;
public class FluidSlot {
private final IFluidHandlerModifiable fluidHandler;
private final int index;
private final int x;
private final int y;
public FluidSlot(IFluidHandlerModifiable fluidHandler, int index, int x, int y) {
this.fluidHandler = fluidHandler;
this.index = index;
this.x = x;
this.y = y;
}
public boolean isFluidValid(FluidStack stack) {
if (stack.isEmpty()) {
return false;
}
return fluidHandler.isFluidValid(index, stack);
}
public FluidStack getStack() {
return fluidHandler.getFluidInTank(index);
}
public void putStack(FluidStack stack) {
fluidHandler.setFluidInTank(index, stack);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
|
Replace google tts with voice rss.
|
<?php
namespace Mo\FlashCardsApiBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
/**
* Actions serving different resources.
*/
class ResourceController
{
/**
* Creates an audio/mpeg pronouncing the text parameter.
*
* @ApiDoc(
* statusCodes={
* 200="On success"
* }
* )
*
* @param string $text
* @return Response
*/
public function textToSpeechAction($text)
{
$audio = file_get_contents('https://api.voicerss.org/?' . http_build_query(array(
'key' => '36b73c895a48485faedd7f6f8de71eb0',
'hl' => 'en-gb',
'src' => $text,
'c' => 'mp3',
'f' => '48khz_16bit_stereo'
)));
// build response
$response = new Response();
$response->setContent($audio);
$response->headers->set('Content-Type', 'audio/mpeg');
return $response;
}
}
|
<?php
namespace Mo\FlashCardsApiBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
/**
* Actions serving different resources.
*/
class ResourceController
{
/**
* Creates an audio/mpeg pronouncing the text parameter.
*
* @ApiDoc(
* statusCodes={
* 200="On success"
* }
* )
*
* @param string $text
* @return Response
*/
public function textToSpeechAction($text)
{
$audio = file_get_contents('http://translate.google.com/translate_tts?' . http_build_query(array(
'tl' => 'en',
'q' => $text
)));
// build response
$response = new Response();
$response->setContent($audio);
$response->headers->set('Content-Type', 'audio/mpeg');
return $response;
}
}
|
Return the point as a number.
|
'use strict';
angular.module('kanbanBoardApp')
.controller('BoardCtrl', ['$scope', 'Task', 'Project', 'Workspace', 'Tag', 'WORKSPACE_ID', 'PROJECT_ID', function ($scope, Task, Project, Workspace, Tag, WORKSPACE_ID, PROJECT_ID) {
$scope.tags = [];
var tagsLoaded = false;
$scope.tagsLoaded = function () {
return tagsLoaded;
};
$scope.loadTags = function () {
Workspace.get({path: 'tags'}, function (response) {
$scope.tags = response.data;
tagsLoaded = true;
});
};
$scope.getPointTags = function (tags) {
return tags.filter( function (tag) {
if (tag.name.match(/points/)) {
return tag;
}
});
};
$scope.tagPointValue = function (tag) {
return parseInt(tag.name.replace(/[^\d+]/g, ''));
}
}]);
|
'use strict';
angular.module('kanbanBoardApp')
.controller('BoardCtrl', ['$scope', 'Task', 'Project', 'Workspace', 'Tag', 'WORKSPACE_ID', 'PROJECT_ID', function ($scope, Task, Project, Workspace, Tag, WORKSPACE_ID, PROJECT_ID) {
$scope.tags = [];
var tagsLoaded = false;
$scope.tagsLoaded = function () {
return tagsLoaded;
};
$scope.loadTags = function () {
Workspace.get({path: 'tags'}, function (response) {
$scope.tags = response.data;
tagsLoaded = true;
});
};
$scope.getPointTags = function (tags) {
return tags.filter( function (tag) {
if (tag.name.match(/points/)) {
return tag;
}
});
};
$scope.tagPointValue = function (tag) {
return tag.name.replace(/[^\d+]/g, '');
}
}]);
|
Fix password complexity validation: length between 8 and 255
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.parallax.server.common.cloudsession.service.impl;
import com.parallax.server.common.cloudsession.service.PasswordValidationService;
import java.util.Arrays;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;
/**
*
* @author Michel
*/
public class PasswordValidationServiceImpl implements PasswordValidationService {
private final PasswordValidator validator;
public PasswordValidationServiceImpl() {
LengthRule r1 = new LengthRule(8, 255);
validator = new PasswordValidator(Arrays.asList((Rule) r1));
}
@Override
public boolean validatePassword(String password) {
PasswordData data = PasswordData.newInstance(password, null, null);
RuleResult result = validator.validate(data);
return result.isValid();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.parallax.server.common.cloudsession.service.impl;
import com.parallax.server.common.cloudsession.service.PasswordValidationService;
import java.util.Arrays;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;
/**
*
* @author Michel
*/
public class PasswordValidationServiceImpl implements PasswordValidationService {
private PasswordValidator validator;
public PasswordValidationServiceImpl() {
LengthRule r1 = new LengthRule(8);
validator = new PasswordValidator(Arrays.asList((Rule) r1));
}
@Override
public boolean validatePassword(String password) {
PasswordData data = PasswordData.newInstance(password, null, null);
RuleResult result = validator.validate(data);
return result.isValid();
}
}
|
Update tag to use for forked psutil
|
# 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 setuptools import setup
setup(
name="atsy",
version="0.0.1",
description="AreTheySlimYet",
long_description="A set of tools for measuring cross-browser, cross-platform memory usage.",
url="https://github.com/EricRahm/atsy",
author="Eric Rahm",
author_email="erahm@mozilla.com",
license="MPL 2.0",
classifiers=[
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"
],
packages=["atsy"],
install_requires=[
"selenium",
"marionette-client",
"psutil==3.5.0",
],
dependency_links=[
# We need to use a fork of psutil until USS calculations get integrated.
"git+ssh://git@github.com/ericrahm/psutil@release-3.5.0#egg=psutil-3.5.0"
],
)
|
# 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 setuptools import setup
setup(
name="atsy",
version="0.0.1",
description="AreTheySlimYet",
long_description="A set of tools for measuring cross-browser, cross-platform memory usage.",
url="https://github.com/EricRahm/atsy",
author="Eric Rahm",
author_email="erahm@mozilla.com",
license="MPL 2.0",
classifiers=[
"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)"
],
packages=["atsy"],
install_requires=[
"selenium",
"marionette-client",
"psutil==3.5.0",
],
dependency_links=[
# We need to use a fork of psutil until USS calculations get integrated.
"git+ssh://git@github.com/ericrahm/psutil@release-3.4.2-uss#egg=psutil-3.5.0"
],
)
|
Add SSH logs when provisioning with RedHat derivatives
Fixes #3507
Signed-off-by: KOBAYASHI Shinji <f11af612650f474cce319970f68085816c4c9a70@jp.fujitsu.com>
|
package provision
import (
"fmt"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/ssh"
)
type RedHatSSHCommander struct {
Driver drivers.Driver
}
func (sshCmder RedHatSSHCommander) SSHCommand(args string) (string, error) {
client, err := drivers.GetSSHClientFromDriver(sshCmder.Driver)
if err != nil {
return "", err
}
log.Debugf("About to run SSH command:\n%s", args)
// redhat needs "-t" for tty allocation on ssh therefore we check for the
// external client and add as needed.
// Note: CentOS 7.0 needs multiple "-tt" to force tty allocation when ssh has
// no local tty.
var output string
switch c := client.(type) {
case *ssh.ExternalClient:
c.BaseArgs = append(c.BaseArgs, "-tt")
output, err = c.Output(args)
case *ssh.NativeClient:
output, err = c.OutputWithPty(args)
}
log.Debugf("SSH cmd err, output: %v: %s", err, output)
if err != nil {
return "", fmt.Errorf(`Something went wrong running an SSH command!
command : %s
err : %v
output : %s
`, args, err, output)
}
return output, nil
}
|
package provision
import (
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/ssh"
)
type RedHatSSHCommander struct {
Driver drivers.Driver
}
func (sshCmder RedHatSSHCommander) SSHCommand(args string) (string, error) {
client, err := drivers.GetSSHClientFromDriver(sshCmder.Driver)
if err != nil {
return "", err
}
// redhat needs "-t" for tty allocation on ssh therefore we check for the
// external client and add as needed.
// Note: CentOS 7.0 needs multiple "-tt" to force tty allocation when ssh has
// no local tty.
switch c := client.(type) {
case *ssh.ExternalClient:
c.BaseArgs = append(c.BaseArgs, "-tt")
client = c
case *ssh.NativeClient:
return c.OutputWithPty(args)
}
return client.Output(args)
}
|
Add missing index.html in webpack target
|
const path = require('path');
const ls = require('ls');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const plugins = [];
const entry = {};
const filenamePrefix = process.env.DEV_SERVER ? 'contribs/gmf/apps/' : '';
for (const filename of ls('contribs/gmf/apps/*/index.html')) {
const name = path.basename(filename.path);
entry[name] = `./${filename.path}/js/Controller.js`;
plugins.push(
new HtmlWebpackPlugin({
template: filename.full,
chunksSortMode: 'manual',
filename: filenamePrefix + name + '/index.html',
chunks: ['commons', name]
})
);
}
module.exports = {
entry: entry,
optimization: {
splitChunks: {
chunks: 'all',
name: 'commons',
}
},
plugins: plugins,
};
if (!process.env.DEV_SERVER) {
Object.assign(module.exports, {
output: {
path: path.resolve(__dirname, '../.build/contribs-gmf-apps'),
},
});
}
|
const path = require('path');
const ls = require('ls');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const plugins = [];
const entry = {};
const filenamePrefix = process.env.DEV_SERVER ? 'contribs/gmf/apps/' : '';
for (const filename of ls('contribs/gmf/apps/*/index.html')) {
const name = path.basename(filename.path);
entry[name] = `./${filename.path}/js/Controller.js`;
plugins.push(
new HtmlWebpackPlugin({
template: filename.full,
chunksSortMode: 'manual',
filename: filenamePrefix + name,
chunks: ['commons', name]
})
);
}
module.exports = {
entry: entry,
optimization: {
splitChunks: {
chunks: 'all',
name: 'commons',
}
},
plugins: plugins,
};
if (!process.env.DEV_SERVER) {
Object.assign(module.exports, {
output: {
path: path.resolve(__dirname, '../.build/contribs-gmf-apps'),
},
});
}
|
Fix generated pages not showing publication on load
|
$(function () {
var initialTitle = document.title;
$(Z).on('Z:publicationchange', function (ev, publication) {
document.title = [publication.title, initialTitle].join(': ');
if (typeof history.replaceState === 'function') {
history.replaceState(publication, publication.title, Z.slugify(publication));
$(Z).trigger('Z:statechange');
}
});
// Check if document was loaded with a path
$(Z).on('Z:ready', function (ev, publications) {
var initialSlug = window.location.pathname.split('/').pop();
if (initialSlug !== '') {
for (var i=0, l=publications.length; i<l; i++) {
if (initialSlug === Z.slugify(publications[i])) {
$(Z).trigger('Z:publicationchange', publications[i]);
break;
}
}
}
});
});
|
$(function () {
var base = '/';
var initialTitle = document.title;
$(Z).on('Z:publicationchange', function (ev, publication) {
document.title = [publication.title, initialTitle].join(': ');
if (typeof history.replaceState === 'function') {
history.replaceState(publication, publication.title, Z.slugify(publication));
$(Z).trigger('Z:statechange');
}
});
// Check if document was loaded with a path
$(Z).on('Z:ready', function (ev, publications) {
var initialSlug = window.location.pathname.replace(base, '');
if (initialSlug.length !== '') {
for (var i=0, l=publications.length; i<l; i++) {
if (initialSlug === Z.slugify(publications[i])) {
$(Z).trigger('Z:publicationchange', publications[i]);
break;
}
}
}
});
});
|
Check for existence of isMounted
|
var Reflux = require('./index'),
_ = require('./utils');
module.exports = function(listenable,key){
return {
getInitialState: function(){
if (!_.isFunction(listenable.getInitialState)) {
return {};
} else if (key === undefined) {
return listenable.getInitialState();
} else {
return _.object([key],[listenable.getInitialState()]);
}
},
componentDidMount: function(){
_.extend(this,Reflux.ListenerMethods);
var me = this, cb = (key === undefined ? this.setState : function(v){
if (typeof me.isMounted === "undefined" || me.isMounted() === true) {
me.setState(_.object([key],[v]));
}
});
this.listenTo(listenable,cb);
},
componentWillUnmount: Reflux.ListenerMixin.componentWillUnmount
};
};
|
var Reflux = require('./index'),
_ = require('./utils');
module.exports = function(listenable,key){
return {
getInitialState: function(){
if (!_.isFunction(listenable.getInitialState)) {
return {};
} else if (key === undefined) {
return listenable.getInitialState();
} else {
return _.object([key],[listenable.getInitialState()]);
}
},
componentDidMount: function(){
_.extend(this,Reflux.ListenerMethods);
var me = this, cb = (key === undefined ? this.setState : function(v){
if (me.isMounted()) {
me.setState(_.object([key],[v]));
}
});
this.listenTo(listenable,cb);
},
componentWillUnmount: Reflux.ListenerMixin.componentWillUnmount
};
};
|
Update the client test to clean up before tests
|
package cloudwatch
import (
"os"
"testing"
)
func TestDefaultSessionConfig(t *testing.T) {
// Cleanup before the test
os.Unsetenv("AWS_DEFAULT_REGION")
os.Unsetenv("AWS_REGION")
cases := []struct {
expected string
export bool
exportVar string
exportVal string
}{
{
expected: "us-east-1",
export: false,
exportVar: "",
exportVal: "",
},
{
expected: "ap-southeast-2",
export: true,
exportVar: "AWS_DEFAULT_REGION",
exportVal: "ap-southeast-2",
},
{
expected: "us-west-2",
export: true,
exportVar: "AWS_REGION",
exportVal: "us-west-2",
},
}
for _, c := range cases {
if c.export == true {
os.Setenv(c.exportVar, c.exportVal)
}
config := DefaultSessionConfig()
if *config.Region != c.expected {
t.Errorf("expected %q to be %q", *config.Region, c.expected)
}
if c.export == true {
os.Unsetenv(c.exportVar)
}
}
}
|
package cloudwatch
import (
"os"
"testing"
)
func TestDefaultSessionConfig(t *testing.T) {
cases := []struct {
expected string
export bool
exportVar string
exportVal string
}{
{
expected: "us-east-1",
export: false,
exportVar: "",
exportVal: "",
},
{
expected: "ap-southeast-1",
export: true,
exportVar: "AWS_DEFAULT_REGION",
exportVal: "ap-southeast-1",
},
{
expected: "us-west-2",
export: true,
exportVar: "AWS_REGION",
exportVal: "us-west-2",
},
}
for _, c := range cases {
if c.export == true {
os.Setenv(c.exportVar, c.exportVal)
}
config := DefaultSessionConfig()
if *config.Region != c.expected {
t.Errorf("expected %q to be %q", *config.Region, c.expected)
}
if c.export == true {
os.Unsetenv(c.exportVar)
}
}
}
|
Fix summary not showing up in console logs
|
'use strict';
const { protocolHandlers } = require('../../protocols');
const { rpcHandlers } = require('../../rpc');
// Build message of events of type `request` as:
// STATUS [ERROR] - PROTOCOL METHOD RPC /PATH COMMAND...
const getRequestMessage = function ({
protocol,
rpc,
method,
path,
error = 'SUCCESS',
commandpath,
summary,
}) {
const summaryA = error === 'SUCCESS' ? summary : commandpath;
const { title: protocolTitle } = protocolHandlers[protocol] || {};
const { title: rpcTitle } = rpcHandlers[rpc] || {};
const message = [
error,
'-',
protocolTitle,
method,
rpcTitle,
path,
summaryA,
].filter(val => val)
.join(' ');
return message;
};
module.exports = {
getRequestMessage,
};
|
'use strict';
const { protocolHandlers } = require('../../protocols');
const { rpcHandlers } = require('../../rpc');
// Build message of events of type `request` as:
// STATUS [ERROR] - PROTOCOL METHOD RPC /PATH COMMAND...
const getRequestMessage = function ({
protocol,
rpc,
method,
path,
error = 'SUCCESS',
commandpath,
summary,
}) {
const summaryA = error ? commandpath : summary;
const { title: protocolTitle } = protocolHandlers[protocol] || {};
const { title: rpcTitle } = rpcHandlers[rpc] || {};
const message = [
error,
'-',
protocolTitle,
method,
rpcTitle,
path,
summaryA,
].filter(val => val)
.join(' ');
return message;
};
module.exports = {
getRequestMessage,
};
|
Remove unnecessary setlocale call in templatetags
|
from __future__ import absolute_import
from json import dumps as json_dumps
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
from argonauts.serializers import JSONArgonautEncoder
register = template.Library()
@register.filter
def json(a):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter.
"""
kwargs = {}
if settings.DEBUG:
kwargs['indent'] = 4
kwargs['separators'] = (',', ': ')
json_str = json_dumps(a, cls=JSONArgonautEncoder, **kwargs)
# Escape all the XML/HTML special characters.
escapes = ['<', '>', '&']
for c in escapes:
json_str = json_str.replace(c, r'\u%04x' % ord(c))
# now it's safe to use mark_safe
return mark_safe(json_str)
json.is_safe = True
|
from __future__ import absolute_import
# `setlocale` is not threadsafe
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
from json import dumps as json_dumps
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
from argonauts.serializers import JSONArgonautEncoder
register = template.Library()
@register.filter
def json(a):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter.
"""
kwargs = {}
if settings.DEBUG:
kwargs['indent'] = 4
kwargs['separators'] = (',', ': ')
json_str = json_dumps(a, cls=JSONArgonautEncoder, **kwargs)
# Escape all the XML/HTML special characters.
escapes = ['<', '>', '&']
for c in escapes:
json_str = json_str.replace(c, r'\u%04x' % ord(c))
# now it's safe to use mark_safe
return mark_safe(json_str)
json.is_safe = True
|
Use isinstance check so library can be used for more types
|
# -*- coding: UTF-8 -*-
import collections
__version__ = '0.1.0'
def flatkeys(d, sep="."):
"""
Flatten a dictionary: build a new dictionary from a given one where all
non-dict values are left untouched but nested ``dict``s are recursively
merged in the new one with their keys prefixed by their parent key.
>>> flatkeys({1: 42, 'foo': 12})
{1: 42, 'foo': 12}
>>> flatkeys({1: 42, 'foo': 12, 'bar': {'qux': True}})
{1: 42, 'foo': 12, 'bar.qux': True}
>>> flatkeys({1: {2: {3: 4}}})
{'1.2.3': 4}
>>> flatkeys({1: {2: {3: 4}, 5: 6}})
{'1.2.3': 4, '1.5': 6}
"""
flat = {}
dicts = [("", d)]
while dicts:
prefix, d = dicts.pop()
for k, v in d.items():
k_s = str(k)
if isinstance(v, collections.Mapping):
dicts.append(("%s%s%s" % (prefix, k_s, sep), v))
else:
k_ = prefix + k_s if prefix else k
flat[k_] = v
return flat
|
# -*- coding: UTF-8 -*-
__version__ = '0.1.0'
def flatkeys(d, sep="."):
"""
Flatten a dictionary: build a new dictionary from a given one where all
non-dict values are left untouched but nested ``dict``s are recursively
merged in the new one with their keys prefixed by their parent key.
>>> flatkeys({1: 42, 'foo': 12})
{1: 42, 'foo': 12}
>>> flatkeys({1: 42, 'foo': 12, 'bar': {'qux': True}})
{1: 42, 'foo': 12, 'bar.qux': True}
>>> flatkeys({1: {2: {3: 4}}})
{'1.2.3': 4}
>>> flatkeys({1: {2: {3: 4}, 5: 6}})
{'1.2.3': 4, '1.5': 6}
"""
flat = {}
dicts = [("", d)]
while dicts:
prefix, d = dicts.pop()
for k, v in d.items():
k_s = str(k)
if type(v) is dict:
dicts.append(("%s%s%s" % (prefix, k_s, sep), v))
else:
k_ = prefix + k_s if prefix else k
flat[k_] = v
return flat
|
Add helper to get project name
|
// 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 {getPackageDir} from './paths'
import {join} from 'path'
export function exitOnPackageNotFound() {
if (getPackageDir())
return
process.stdout.write('No valid βpackage.jsonβ found.')
process.exit(1)
}
export function getProjectName() {
const PACKAGE_JSON = join(getPackageDir(), 'package.json')
return require(PACKAGE_JSON).name
}
export function pickNonFalsy(obj:Object):Object {
let result = {}
for (let prop in obj) {
if (obj[prop])
result[prop] = obj[prop]
}
return result
}
|
// 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 {getPackageDir} from './paths'
export function exitOnPackageNotFound() {
if (getPackageDir())
return
process.stdout.write('No valid βpackage.jsonβ found.')
process.exit(1)
}
export function pickNonFalsy(obj:Object):Object {
let result = {}
for (let prop in obj) {
if (obj[prop])
result[prop] = obj[prop]
}
return result
}
|
Add tests for eidos found_by annotation
|
import os
from indra.sources import eidos
from indra.statements import Influence
path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')
def test_process_json():
ep = eidos.process_json_file(test_json)
assert ep is not None
assert len(ep.statements) == 1
stmt = ep.statements[0]
assert isinstance(stmt, Influence)
assert stmt.subj_delta.get('polarity') == 1
assert stmt.obj_delta.get('polarity') == -1
assert stmt.subj_delta.get('adjectives') == ['large']
assert stmt.obj_delta.get('adjectives') == ['seriously']
assert(stmt.evidence[0].annotations['found_by'] == \
'causeEffect_ported_syntax_1_verb-${addlabel}')
print(stmt)
def test_process_text():
ep = eidos.process_text('The cost of fuel decreases water trucking.')
assert ep is not None
assert len(ep.statements) == 1
stmt = ep.statements[0]
assert isinstance(stmt, Influence)
assert stmt.subj.name == 'cost of fuel'
assert stmt.obj.name == 'water trucking'
assert stmt.obj_delta.get('polarity') == -1
assert(stmt.evidence[0].annotations['found_by'] == \
'ported_syntax_1_verb-Causal')
|
import os
from indra.sources import eidos
from indra.statements import Influence
path_this = os.path.dirname(os.path.abspath(__file__))
test_json = os.path.join(path_this, 'eidos_test.json')
def test_process_json():
ep = eidos.process_json_file(test_json)
assert ep is not None
assert len(ep.statements) == 1
stmt = ep.statements[0]
assert isinstance(stmt, Influence)
assert stmt.subj_delta.get('polarity') == 1
assert stmt.obj_delta.get('polarity') == -1
assert stmt.subj_delta.get('adjectives') == ['large']
assert stmt.obj_delta.get('adjectives') == ['seriously']
print(stmt)
def test_process_text():
ep = eidos.process_text('The cost of fuel decreases water trucking.')
assert ep is not None
assert len(ep.statements) == 1
stmt = ep.statements[0]
assert isinstance(stmt, Influence)
assert stmt.subj.name == 'cost of fuel'
assert stmt.obj.name == 'water trucking'
assert stmt.obj_delta.get('polarity') == -1
|
Reformat for easier copy and pasting (needed for usability with AWS Console).
|
from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
for i in range(3, n+1):
if sieve[i]:
markOff(i)
return [ i for i in range(1, n+1) if sieve[i] ]
def lambda_handler(event, context):
start = timer()
#print("Received event: " + json.dumps(event, indent=2))
maxPrime = int(event['queryStringParameters']['max'])
numLoops = int(event['queryStringParameters']['loops'])
print("looping " + str(numLoops) + " time(s)")
for loop in range (0, numLoops):
primes = eratosthenes(maxPrime)
print("Highest 3 primes: " + str(primes.pop()) + ", " + str(primes.pop()) + ", " + str(primes.pop()))
durationSeconds = timer() - start
return {"statusCode": 200, \
"headers": {"Content-Type": "application/json"}, \
"body": "{\"durationSeconds\": " + str(durationSeconds) + \
", \"max\": " + str(maxPrime) + ", \"loops\": " + str(numLoops) + "}"}
|
from __future__ import print_function
from timeit import default_timer as timer
import json
import datetime
print('Loading function')
def eratosthenes(n):
sieve = [ True for i in range(n+1) ]
def markOff(pv):
for i in range(pv+pv, n+1, pv):
sieve[i] = False
markOff(2)
for i in range(3, n+1):
if sieve[i]:
markOff(i)
return [ i for i in range(1, n+1) if sieve[i] ]
def lambda_handler(event, context):
start = timer()
#print("Received event: " + json.dumps(event, indent=2))
maxPrime = int(event['queryStringParameters']['max'])
numLoops = int(event['queryStringParameters']['loops'])
print("looping " + str(numLoops) + " time(s)")
for loop in range (0, numLoops):
primes = eratosthenes(maxPrime)
print("Highest 3 primes: " + str(primes.pop()) + ", " + str(primes.pop()) + ", " + str(primes.pop()))
durationSeconds = timer() - start
return {"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": "{\"durationSeconds\": " + str(durationSeconds) + ", \"max\": " + str(maxPrime) + ", \"loops\": " + str(numLoops) + "}"}
|
Make new test use contains assertion
|
import sys
from nose.tools import ok_
from _utils import (
_output_eq, IntegrationSpec, _dispatch, trap, expect_exit, assert_contains
)
class ShellCompletion(IntegrationSpec):
"""
Shell tab-completion behavior
"""
def no_input_means_just_task_names(self):
_output_eq('-c simple_ns_list --complete', "z_toplevel\na.b.subtask\n")
def no_input_with_no_tasks_yields_empty_response(self):
_output_eq('-c empty --complete', "")
@trap
def top_level_with_dash_means_core_options(self):
with expect_exit(0):
_dispatch('inv --complete -- -')
output = sys.stdout.getvalue()
# No point mirroring all core options, just spot check a few
for flag in ('--no-dedupe', '-d', '--debug', '-V', '--version'):
assert_contains(output, "{0}\n".format(flag))
|
import sys
from nose.tools import ok_
from _utils import _output_eq, IntegrationSpec, _dispatch, trap, expect_exit
class ShellCompletion(IntegrationSpec):
"""
Shell tab-completion behavior
"""
def no_input_means_just_task_names(self):
_output_eq('-c simple_ns_list --complete', "z_toplevel\na.b.subtask\n")
def no_input_with_no_tasks_yields_empty_response(self):
_output_eq('-c empty --complete', "")
@trap
def top_level_with_dash_means_core_options(self):
with expect_exit(0):
_dispatch('inv --complete -- -')
output = sys.stdout.getvalue()
# No point mirroring all core options, just spot check a few
for flag in ('--no-dedupe', '-d', '--debug', '-V', '--version'):
ok_(flag in output)
|
Revert "Wrap fact exports in quotes"
This reverts commit bf5b568b05066b3d31b3c7c1f56ef86d4c5c3dca.
Conflicts:
stack-builder/hiera_config.py
|
#!/usr/bin/env python
"""
stack-builder.hiera_config
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module will read metadata set during instance
launch and override any yaml under the /etc/puppet/data
directory (except data_mappings) that has a key matching
the metadata
"""
import yaml
import os
hiera_dir = '/etc/puppet/data'
metadata_path = '/root/config.yaml'
#debug
#metadata_path = './sample.json'
#hiera_dir = './openstack-installer/data/'
# Child processes cannot set environment variables, so
# create a bash file to set some exports for facter
def facter_config():
with open(metadata_path, 'r') as metadata:
meta = yaml.load(metadata.read())
print meta
with open('/root/fact_exports', 'w') as facts:
for key,value in meta.items():
# Things with spaces can't be exported
if ' ' not in str(value):
facts.write('FACTER_' + str(key) + '=' + str(value) + '\n')
#TODO
def hostname_config():
with open(metadata_path, 'r') as metadata:
meta = yaml.load(metadata.read())
with open('/root/openstack-installer/manifests/setup.pp', 'a') as facts:
for key,value in meta.items():
pass
facter_config()
|
#!/usr/bin/env python
"""
stack-builder.hiera_config
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module will read metadata set during instance
launch and override any yaml under the /etc/puppet/data
directory (except data_mappings) that has a key matching
the metadata
"""
import yaml
import os
hiera_dir = '/etc/puppet/data'
metadata_path = '/root/config.yaml'
#debug
#metadata_path = './sample.json'
#hiera_dir = './openstack-installer/data/'
# Child processes cannot set environment variables, so
# create a bash file to set some exports for facter
def facter_config():
with open(metadata_path, 'r') as metadata:
meta = yaml.load(metadata.read())
print meta
with open('/root/fact_exports', 'w') as facts:
for key,value in meta.items():
# Things with spaces can't be exported
if ' ' not in str(value):
facts.write('FACTER_' + str(key) + '="' + str(value) + '"\n')
#TODO
def hostname_config():
with open(metadata_path, 'r') as metadata:
meta = yaml.load(metadata.read())
with open('/root/openstack-installer/manifests/setup.pp', 'a') as facts:
for key,value in meta.items():
pass
facter_config()
|
Fix error when trying to run --remove-all
The error was as follows:
sudo hose --remove-all
/usr/local/share/npm/lib/node_modules/hose/index.js:32
if (!err) {
^
ReferenceError: err is not defined
at /usr/local/share/npm/lib/node_modules/hose/index.js:32:14
at Object.oncomplete (fs.js:107:15)
|
var program = require('commander');
var pkg = require('./package.json');
var settings = require('./settings.js');
program
.usage('[options] <domain>')
.version(pkg.version)
.option('-r, --remove', 'Removes the domain')
.option('-R, --remove-all', 'Wipes the blacklist')
.option('-H, --hosts <hosts>', 'The hosts file to use')
.option('--off', 'Turns off the hose')
.option('--list', 'Prints the blacklist')
.parse(process.argv);
if (program.hosts) {
settings.set('hosts', program.hosts);
}
var etc = require('./etc.js').bind(null, program.off);
var domains = program.args;
if (domains.length) {
if (program.remove) {
settings.remove(domains, etc);
} else {
settings.add(domains, etc);
}
} else if (program.remove) {
console.log('You must specify domain name(s) to remove.');
process.exit(1);
} else if (program.removeAll) {
settings.wipe(function (err) {
if (!err) {
console.log('Wiped out blacklist.')
}
etc(err);
});
} else if (program.list) {
Object.keys(settings.domains).forEach(function (domain) {
console.log(domain);
});
} else {
etc();
}
|
var program = require('commander');
var pkg = require('./package.json');
var settings = require('./settings.js');
program
.usage('[options] <domain>')
.version(pkg.version)
.option('-r, --remove', 'Removes the domain')
.option('-R, --remove-all', 'Wipes the blacklist')
.option('-H, --hosts <hosts>', 'The hosts file to use')
.option('--off', 'Turns off the hose')
.option('--list', 'Prints the blacklist')
.parse(process.argv);
if (program.hosts) {
settings.set('hosts', program.hosts);
}
var etc = require('./etc.js').bind(null, program.off);
var domains = program.args;
if (domains.length) {
if (program.remove) {
settings.remove(domains, etc);
} else {
settings.add(domains, etc);
}
} else if (program.remove) {
console.log('You must specify domain name(s) to remove.');
process.exit(1);
} else if (program.removeAll) {
settings.wipe(function (etc) {
if (!err) {
console.log('Wiped out blacklist.')
}
etc(err);
});
} else if (program.list) {
Object.keys(settings.domains).forEach(function (domain) {
console.log(domain);
});
} else {
etc();
}
|
Fix test for new memory limit
|
<?php
namespace SlmQueueTest\Options;
use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueTest\Util\ServiceManagerFactory;
use Zend\ServiceManager\ServiceManager;
class WorkerOptionsTest extends TestCase
{
/**
* @var ServiceManager
*/
protected $serviceManager;
public function setUp()
{
parent::setUp();
$this->serviceManager = ServiceManagerFactory::getServiceManager();
}
public function testCreateWorkerOptions()
{
/** @var $workerOptions \SlmQueue\Options\WorkerOptions */
$workerOptions = $this->serviceManager->get('SlmQueue\Options\WorkerOptions');
$this->assertInstanceOf('SlmQueue\Options\WorkerOptions', $workerOptions);
$this->assertEquals(100000, $workerOptions->getMaxRuns());
$this->assertEquals(104857600, $workerOptions->getMaxMemory());
}
}
|
<?php
namespace SlmQueueTest\Options;
use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueTest\Util\ServiceManagerFactory;
use Zend\ServiceManager\ServiceManager;
class WorkerOptionsTest extends TestCase
{
/**
* @var ServiceManager
*/
protected $serviceManager;
public function setUp()
{
parent::setUp();
$this->serviceManager = ServiceManagerFactory::getServiceManager();
}
public function testCreateWorkerOptions()
{
/** @var $workerOptions \SlmQueue\Options\WorkerOptions */
$workerOptions = $this->serviceManager->get('SlmQueue\Options\WorkerOptions');
$this->assertInstanceOf('SlmQueue\Options\WorkerOptions', $workerOptions);
$this->assertEquals(100000, $workerOptions->getMaxRuns());
$this->assertEquals(1024, $workerOptions->getMaxMemory());
}
}
|
FIX opt_out prevention for mailchimp export
|
##############################################################################
#
# Copyright (C) 2020 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
if force_create and partner_id.opt_out:
return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
|
##############################################################################
#
# Copyright (C) 2020 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models, fields, _
from odoo.exceptions import UserError
class ExportMailchimpWizard(models.TransientModel):
_inherit = "partner.export.mailchimp"
@api.multi
def get_mailing_contact_id(self, partner_id, force_create=False):
# Avoid exporting opt_out partner
if force_create:
partner = self.env["res.partner"].browse(partner_id)
if partner.opt_out:
return False
# Push the partner_id in mailing_contact creation
return super(
ExportMailchimpWizard, self.with_context(default_partner_id=partner_id)
).get_mailing_contact_id(partner_id, force_create)
|
:art: Enhance the main cli entry file
|
#!/usr/bin/env node
'use strict'
const command = process.argv[2] || ''
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
// Note: This is a trick to make multiple commander commands work with single executables
process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3))
let showHelp = command === '--help'
if (!showHelp && (!command || command === 'run')) {
require('./motion-run')
} else if (!showHelp && validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
motion alias for 'motion run'
motion run run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion
motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339)
`.trim())
process.exit(1)
}
|
#!/usr/bin/env node
'use strict'
import commander from 'commander'
const parameters = require('minimist')(process.argv.slice(2))
const command = parameters['_'][0]
const validCommands = ['new', 'build', 'update', 'init']
// TODO: Check for updates
// Note: This is a trick to make multiple commander commands work with single executables
process.argv = process.argv.slice(0, 2).concat(process.argv.slice(3))
if (!command || command === 'run') {
require('./motion-run')
} else if (validCommands.indexOf(command) !== -1) {
require(`./motion-${command}`)
} else {
console.error(`
Usage:
motion run your motion app
motion new [name] [template] start a new app
motion build build for production
motion update update motion
motion init add a motion config to an existing app (temporary, awaiting https://github.com/motion/motion/issues/339)
`.trim())
process.exit(1)
}
|
Fix typo in FXML file name
|
package com.gitrekt.resort.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
/**
* FXML Controller class for reports home screen.
*/
public class ReportsHomeScreenController implements Initializable {
@FXML
private Button backButton;
@FXML
private Button bookingPercentagesReportButton;
@FXML
private Button feedbackReportButton;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void onBackButtonClicked() {
ScreenManager.getInstance().switchToScreen(
"/fxml/StaffHomeScreen.fxml"
);
}
public void onBookingPercentagesReportButtonClicked() {
ScreenManager.getInstance().switchToScreen(
"/fxml/BookingsReportScreen.fxml"
);
}
public void onFeedbackReportButtonClicked() {
ScreenManager.getInstance().switchToScreen(
"/fxml/FeedbackReportScreen.fxml"
);
}
}
|
package com.gitrekt.resort.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
/**
* FXML Controller class for reports home screen.
*/
public class ReportsHomeScreenController implements Initializable {
@FXML
private Button backButton;
@FXML
private Button bookingPercentagesReportButton;
@FXML
private Button feedbackReportButton;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void onBackButtonClicked() {
ScreenManager.getInstance().switchToScreen(
"/fxml/StaffHomeScreen.fxml"
);
}
public void onBookingPercentagesReportButtonClicked() {
ScreenManager.getInstance().switchToScreen(
"/fxml/BookingReportScreen.fxml"
);
}
public void onFeedbackReportButtonClicked() {
ScreenManager.getInstance().switchToScreen(
"/fxml/FeedbackReportScreen.fxml"
);
}
}
|
Add test for as_bool bug
|
from nose2 import config
from nose2.compat import unittest
class TestConfigSession(unittest.TestCase):
def test_can_create_session(self):
config.Session()
class TestConfig(unittest.TestCase):
def setUp(self):
self.conf = config.Config([
('a', ' 1 '), ('b', ' x\n y '), ('c', '0')])
def test_as_int(self):
self.assertEqual(self.conf.as_int('a'), 1)
def test_as_str(self):
self.assertEqual(self.conf.as_str('a'), '1')
self.assertEqual(self.conf.as_str('b'), 'x\n y')
self.assertEqual(self.conf.as_str('missing', 'default'), 'default')
def test_as_bool(self):
self.assertEqual(self.conf.as_bool('a'), True)
self.assertEqual(self.conf.as_bool('c'), False)
def test_as_float(self):
self.assertAlmostEqual(self.conf.as_float('a'), 1.0)
def test_as_list(self):
self.assertEqual(self.conf.as_list('b'), ['x', 'y'])
|
from nose2 import config
from nose2.compat import unittest
class TestConfigSession(unittest.TestCase):
def test_can_create_session(self):
config.Session()
class TestConfig(unittest.TestCase):
def setUp(self):
self.conf = config.Config([('a', ' 1 '), ('b', ' x\n y ')])
def test_as_int(self):
self.assertEqual(self.conf.as_int('a'), 1)
def test_as_str(self):
self.assertEqual(self.conf.as_str('a'), '1')
self.assertEqual(self.conf.as_str('b'), 'x\n y')
self.assertEqual(self.conf.as_str('missing', 'default'), 'default')
def test_as_bool(self):
self.assertEqual(self.conf.as_bool('a'), True)
def test_as_float(self):
self.assertAlmostEqual(self.conf.as_float('a'), 1.0)
def test_as_list(self):
self.assertEqual(self.conf.as_list('b'), ['x', 'y'])
|
Use root locale when normalising
|
package net.squanchy.search.engines;
import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Pattern;
final class StringNormalizer {
private static final String ACCENTS_PATTERN_STRING = "\\p{M}";
private static final Pattern ACCENTS_PATTERN = Pattern.compile(ACCENTS_PATTERN_STRING);
private static final String EMPTY_STRING = "";
static String normalize(String text) {
String lowercasedText = lowercase(text);
return removeDiacritics(lowercasedText);
}
private static String lowercase(String text) {
return text.toLowerCase(Locale.ROOT);
}
private static String removeDiacritics(String text) {
String normalised = Normalizer.normalize(text, Normalizer.Form.NFD);
return ACCENTS_PATTERN.matcher(normalised).replaceAll(EMPTY_STRING);
}
}
|
package net.squanchy.search.engines;
import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Pattern;
final class StringNormalizer {
private static final String EMPTY_STRING = "";
private static final String ACCENTS_PATTERN_STRING = "\\p{M}";
private static final Pattern ACCENTS_PATTERN = Pattern.compile(ACCENTS_PATTERN_STRING);
static String normalize(String text) {
String lowercasedText = lowercase(text);
return removeDiacritics(lowercasedText);
}
private static String lowercase(String text) {
return text.toLowerCase(Locale.getDefault());
}
private static String removeDiacritics(String text) {
String normalised = Normalizer.normalize(text, Normalizer.Form.NFD);
return ACCENTS_PATTERN.matcher(normalised).replaceAll(EMPTY_STRING);
}
}
|
Update to work with the last version of twig
|
<?php
namespace Bundle\MarkdownBundle\Twig\Extension;
use Bundle\MarkdownBundle\Helper\MarkdownHelper;
class MarkdownTwigExtension extends \Twig_Extension
{
protected $helper;
function __construct(MarkdownHelper $helper)
{
$this->helper = $helper;
}
public function getFilters()
{
return array(
'markdown' => new \Twig_Filter_Method($this, 'markdown', array('is_safe' => array('html'))),
);
}
public function markdown($txt)
{
return $this->helper->transform($txt);
}
public function getName()
{
return 'markdown';
}
}
|
<?php
namespace Bundle\MarkdownBundle\Twig\Extension;
use Bundle\MarkdownBundle\Helper\MarkdownHelper;
class MarkdownTwigExtension extends \Twig_Extension
{
protected $helper;
function __construct(MarkdownHelper $helper)
{
$this->helper = $helper;
}
public function getFilters()
{
return array(
'markdown' => new \Twig_Filter_Method($this, 'markdown', array('is_escaper' => true)),
);
}
public function markdown($txt)
{
return $this->helper->transform($txt);
}
public function getName()
{
return 'markdown';
}
}
|
Use a shorter name for the Camel @RunWith so its easier to remember
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.spring;
import org.junit.runners.model.InitializationError;
/**
* The class {@link CamelSpringBootJUnit4ClassRunner} has been renamed to {@link CamelSpringBootRunner}
* which is a shorter and easier to remember name.
*
* @deprecated use {@link CamelSpringBootRunner}
*/
public class CamelSpringBootJUnit4ClassRunner extends CamelSpringBootRunner {
public CamelSpringBootJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
}
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.spring;
import org.junit.runners.model.InitializationError;
/**
* The class {@link CamelSpringBootJUnit4ClassRunner} has been renamed to {@link CamelSpringBootRunner}
* which is a shorter and easier to remember name.
*
* @deprecated use {@link CamelSpringBootRunner}
*/
public class CamelSpringBootJUnit4ClassRunner extends CamelSpringRunner {
public CamelSpringBootJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
}
|
Update trove classifiers with Apache License.
|
import os
import sys
from setuptools import setup
INSTALL_REQUIRES = ['requests >=1.0.3', 'boto >=2.1.1', 'six >=1.2.0', 'urllib3 >= 1.0.2']
if sys.version_info < (2, 7, 0):
INSTALL_REQUIRES.append('argparse>=1.1')
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="qds_sdk",
version="1.3.4",
author="Qubole",
author_email="dev@qubole.com",
description=("Python SDK for coding to the Qubole Data Service API"),
keywords="qubole sdk api",
url="https://github.com/qubole/qds-sdk-py",
packages=['qds_sdk'],
scripts=['bin/qds.py'],
install_requires=INSTALL_REQUIRES,
long_description=read('README.rst'),
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4"
]
)
|
import os
import sys
from setuptools import setup
INSTALL_REQUIRES = ['requests >=1.0.3', 'boto >=2.1.1', 'six >=1.2.0', 'urllib3 >= 1.0.2']
if sys.version_info < (2, 7, 0):
INSTALL_REQUIRES.append('argparse>=1.1')
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="qds_sdk",
version="1.3.4",
author="Qubole",
author_email="dev@qubole.com",
description=("Python SDK for coding to the Qubole Data Service API"),
keywords="qubole sdk api",
url="https://github.com/qubole/qds-sdk-py",
packages=['qds_sdk'],
scripts=['bin/qds.py'],
install_requires=INSTALL_REQUIRES,
long_description=read('README.rst'),
classifiers=[
"Environment :: Console",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4"
]
)
|
Revert "fixed the formatting such that the time has no "0" in front of it."
This reverts commit 0f167142d5329deed444e10cde11a42b634b899b.
|
var readline = require('readline');
var chalk = require('chalk');
function extractPhoneNumber(phoneString) {
return phoneString.split('@')[0];
}
function timeLeftMin(time) {
var timeLeft = Math.ceil((time - new Date()) / 1000 / 60);
if (timeLeft < 0) {
return "N.A.";
} else {
return timeLeft + ' min';
}
}
function currentTimeGreeting() {
var hours = new Date().getHours();
if (hours < 12) {
return "morning";
} else if (hours >= 12 && hours < 18) {
return "afternoon";
} else if (hours >= 18) {
return "evening";
} else {
return "";
}
}
function formatDate(date) {
return date.toDateString().substr(0, 3) + ', ' + date.toDateString().substr(4, 6);
}
function formatTime(date) {
var median = (date.getHours() < 12) ? "AM" : "PM";
return (formatDigit(date.getHours() % 12)) + ":" + formatDigit(date.getMinutes()) + " " + median;
}
function formatDigit(n) {
return n > 9 ? "" + n : "0" + n;
}
module.exports = {
getPhoneNum: extractPhoneNumber,
timeLeftMin: timeLeftMin,
formatTime: formatTime,
formatDate: formatDate,
currentTimeGreeting: currentTimeGreeting
};
|
var readline = require('readline');
var chalk = require('chalk');
function extractPhoneNumber(phoneString) {
return phoneString.split('@')[0];
}
function timeLeftMin(time) {
var timeLeft = Math.ceil((time - new Date()) / 1000 / 60);
if (timeLeft < 0) {
return "N.A.";
} else {
return timeLeft + ' min';
}
}
function currentTimeGreeting() {
var hours = new Date().getHours();
if (hours < 12) {
return "morning";
} else if (hours >= 12 && hours < 18) {
return "afternoon";
} else if (hours >= 18) {
return "evening";
} else {
return "";
}
}
function formatDate(date) {
return date.toDateString().substr(0, 3) + ', ' + date.toDateString().substr(4, 6);
}
function formatTime(date) {
var median = (date.getHours() < 12) ? "AM" : "PM";
}
function formatDigit(n) {
return n > 9 ? "" + n : n;
}
module.exports = {
getPhoneNum: extractPhoneNumber,
timeLeftMin: timeLeftMin,
formatTime: formatTime,
formatDate: formatDate,
currentTimeGreeting: currentTimeGreeting
};
|
Fix flag file paths again
|
<?php
// echo '<p>Hi I am some random ' . rand() .' output from the server.</p>';
// echo '<strong>Bitcoin is Enabled</strong>';
// echo "Data is";
$domvalue = $_GET['id'];
// Bitcoin controls
switch ($domvalue) {
case "bitcoin_restart":
echo "Bitcoin has been restarted";
shell_exec ('echo "1" > /home/linaro/restartflag');
break;
case "update-software":
echo "System Software is being updated";
shell_exec ('echo "2" > /home/linaro/updateflag');
break;
// Device Controls
case "device_shutdown":
echo "Device is being shut down";
shell_exec ('echo "2" > /home/linaro/restartflag');
break;
}
// Open the updateflag file. If it is written with a '1', then
// alert the user that a new software update is available.
// $fh = fopen("home/linaro/updateflag", "r");
// Read out the first line to see if it contains '1' as the sole entry
//if ($fh) {
// while (($line = fgets($fh)) !== false) {
// // process. In this case, there is only a single entry of '1'.
// // if preg_match(("/^1/$"), $line) {
// if preg_match(("/^1/$"), $line) {
// echo "Software updates are available");
// }
// }
//} else {
// echo "There was an error in opening the updateflag file";
//}
//fclose($fh);
?>
|
<?php
// echo '<p>Hi I am some random ' . rand() .' output from the server.</p>';
// echo '<strong>Bitcoin is Enabled</strong>';
// echo "Data is";
$domvalue = $_GET['id'];
// Bitcoin controls
switch ($domvalue) {
case "bitcoin_restart":
echo "Bitcoin has been restarted";
shell_exec ('echo "1" > btflags.txt');
break;
case "update-software":
echo "System Software is being updated";
shell_exec ('echo "2" > updateflag');
break;
// Device Controls
case "device_shutdown":
echo "Device is being shut down";
shell_exec ('echo "1" > devflags.txt');
break;
}
// Open the updateflag file. If it is written with a '1', then
// alert the user that a new software update is available.
// $fh = fopen("home/linaro/updateflag", "r");
// Read out the first line to see if it contains '1' as the sole entry
//if ($fh) {
// while (($line = fgets($fh)) !== false) {
// // process. In this case, there is only a single entry of '1'.
// // if preg_match(("/^1/$"), $line) {
// if preg_match(("/^1/$"), $line) {
// echo "Software updates are available");
// }
// }
//} else {
// echo "There was an error in opening the updateflag file";
//}
//fclose($fh);
?>
|
test: Fix doctypes impots in tests
|
module.exports = {
testURL: 'http://localhost/',
moduleFileExtensions: ['js', 'jsx', 'json', 'styl'],
setupFiles: ['<rootDir>/test/jestLib/setup.js'],
moduleDirectories: ['src', 'node_modules'],
moduleNameMapper: {
'^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client',
'^cozy-doctypes$': 'cozy-logger/dist/index.js',
'\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js',
// identity-obj-proxy module is installed by cozy-scripts
styles: 'identity-obj-proxy'
},
transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'],
globals: {
__ALLOW_HTTP__: false,
__TARGET__: 'browser',
__SENTRY_TOKEN__: 'token',
cozy: {}
}
}
|
module.exports = {
testURL: 'http://localhost/',
moduleFileExtensions: ['js', 'jsx', 'json', 'styl'],
setupFiles: ['<rootDir>/test/jestLib/setup.js'],
moduleDirectories: ['src', 'node_modules'],
moduleNameMapper: {
'^redux-cozy-client$': '<rootDir>/src/lib/redux-cozy-client',
'\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js',
// identity-obj-proxy module is installed by cozy-scripts
styles: 'identity-obj-proxy'
},
transformIgnorePatterns: ['node_modules/(?!cozy-ui|cozy-harvest-lib)'],
globals: {
__ALLOW_HTTP__: false,
__TARGET__: 'browser',
__SENTRY_TOKEN__: 'token',
cozy: {}
}
}
|
Make security util to work for mock dashboard server mode.
|
package org.slc.sli.util;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.slc.sli.security.SLIPrincipal;
/**
* Class, which allows user to access security context
* @author svankina
*
*/
public class SecurityUtil {
public static UserDetails getPrincipal() {
return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
public static String getToken() {
UserDetails user = getPrincipal();
if (user instanceof SLIPrincipal) {
return ((SLIPrincipal) user).getId();
} else {
// gets here in mock server mode
return user.getUsername();
}
}
}
|
package org.slc.sli.util;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.slc.sli.security.SLIPrincipal;
/**
* Class, which allows user to access security context
* @author svankina
*
*/
public class SecurityUtil {
public static UserDetails getPrincipal() {
return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
public static String getToken() {
UserDetails user = getPrincipal();
if (user instanceof SLIPrincipal) {
return ((SLIPrincipal) user).getId();
}
return null;
}
}
|
Remove old ref to AggregateError
- Leftover from converting the nodejs-common package to local functions
|
import Promise from 'bluebird';
import { logger } from './logging';
/**
* Do a promise returning function with retries.
*/
export function withRetries(promiseFn, maxRetries, delaySeconds, errMsg, expBackoff) {
let retryCount = 0;
function doIt() {
return promiseFn().catch(err => {
// If we've hit the max, just propagate the error
if (retryCount >= maxRetries) {
throw err;
}
// Calculate delay time in MS
let delayMs = expBackoff === true
? Math.pow(delaySeconds, retryCount) * 1000
: delaySeconds * 1000;
// Log, delay, and try again
retryCount++;
logger.log('debug', '', err);
logger.log('verbose', `${errMsg}. Retry ${retryCount} in ${delayMs}ms.`);
return Promise.delay(delayMs).then(doIt);
});
}
return doIt();
};
|
import Promise from 'bluebird';
import { logger } from './logging';
/**
* Do a promise returning function with retries.
*/
export function withRetries(promiseFn, maxRetries, delaySeconds, errMsg, expBackoff) {
let retryCount = 0;
function doIt() {
return promiseFn().catch(err => {
// If we've hit the max, just propagate the error
if (retryCount >= maxRetries) {
throw err;
}
// Calculate delay time in MS
let delayMs = expBackoff === true
? Math.pow(delaySeconds, retryCount) * 1000
: delaySeconds * 1000;
// Log, delay, and try again
retryCount++;
logger.log('debug', '', err);
if (err instanceof AggregateError) {
logger.log('debug', 'Inner errors:');
err.innerErrors.forEach(innerError => {
logger.log('debug', '', innerError);
});
}
logger.log('verbose', `${errMsg}. Retry ${retryCount} in ${delayMs}ms.`);
return Promise.delay(delayMs).then(doIt);
});
}
return doIt();
};
|
Fix needed trailing spaces in the license
|
/*
* -\-\-
* Spotify Apollo okhttp Client Module
* --
* Copyright (C) 2013 - 2015 Spotify AB
* --
* 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.spotify.apollo.http.client;
import org.mockserver.mock.action.ExpectationCallback;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;
public class SleepCallback implements ExpectationCallback {
@Override
public HttpResponse handle(final HttpRequest httpRequest) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
return HttpResponse.response().withStatusCode(500);
}
return HttpResponse.response().withStatusCode(200);
}
}
|
/*
* -\-\-
* Spotify Apollo okhttp Client Module
* --
* Copyright (C) 2013 - 2015 Spotify AB
* --
* 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.spotify.apollo.http.client;
import org.mockserver.mock.action.ExpectationCallback;
import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpResponse;
public class SleepCallback implements ExpectationCallback {
@Override
public HttpResponse handle(final HttpRequest httpRequest) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
return HttpResponse.response().withStatusCode(500);
}
return HttpResponse.response().withStatusCode(200);
}
}
|
Fix typo in godoc synopsis
|
/*
Simplistic asynchronous routines for the masses.
*/
package async
/*
Done types are used for shorthand definitions of the functions that are
passed into each Routine to show that the Routine has completed.
An example a Done function would be:
func ImDone(err error, args ...interface{}) {
if err != nil {
// Handle the error your Routine returned.
return
}
// There wasn't an error returned your Routine! Do what you want with
// the args.
}
*/
type Done func(error, ...interface{})
/*
Done types are used for shorthand definitions of the functions that are
actually ran when calling Parallel, Waterfall, etc.
An example of a Routine function would be:
func MyRoutine(done async.Done, args ...interface{}) {
// Do something in your routine and then call its done function.
done(nil, "arg1", "arg2", "arg3")
}
*/
type Routine func(Done, ...interface{})
|
/*
Simplistic ansynchronous routines for the masses.
*/
package async
/*
Done types are used for shorthand definitions of the functions that are
passed into each Routine to show that the Routine has completed.
An example a Done function would be:
func ImDone(err error, args ...interface{}) {
if err != nil {
// Handle the error your Routine returned.
return
}
// There wasn't an error returned your Routine! Do what you want with
// the args.
}
*/
type Done func(error, ...interface{})
/*
Done types are used for shorthand definitions of the functions that are
actually ran when calling Parallel, Waterfall, etc.
An example of a Routine function would be:
func MyRoutine(done async.Done, args ...interface{}) {
// Do something in your routine and then call its done function.
done(nil, "arg1", "arg2", "arg3")
}
*/
type Routine func(Done, ...interface{})
|
Increase lambda-k space to better differentiate bottlenecks from startup cost.
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:23:58 2015
@author: jensv
"""
import skin_core_scanner_simple as scss
reload(scss)
import equil_solver as es
reload(es)
import newcomb_simple as new
reload(new)
(lambda_a_mesh, k_a_mesh,
stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25],
epsilon=0.11, core_radius_norm=0.9,
transition_width_norm=0.033,
skin_width_norm=0.034,
method='lsoda',
max_step=1E-2, nsteps=1000)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:23:58 2015
@author: jensv
"""
import skin_core_scanner_simple as scss
reload(scss)
import equil_solver as es
reload(es)
import newcomb_simple as new
reload(new)
(lambda_a_mesh, k_a_mesh,
stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 10.], [0.01, 1.5, 10],
epsilon=0.11, core_radius_norm=0.9,
transition_width_norm=0.033,
skin_width_norm=0.034,
method='lsoda',
max_step=1E-2, nsteps=1000)
|
Initialize log using `name` and `version`
|
import { initLog } from 'roc';
import Dredd from 'dredd';
const { name, version } = require('../../package.json');
const log = initLog(name, version);
export default ({ context: { config: { settings } } }) => () => {
const port = process.env.PORT || settings.runtime.port;
const dredd = new Dredd({
server: `http://localhost:${port}`,
options: settings.test.dredd,
});
log.small.info('Testing API using dredd.\n');
return () => dredd.run((err, stats) => {
if (err) {
throw err;
}
if (stats.errors) {
log.large.error('One or more errors occured while running dredd');
return;
}
if (stats.failures) {
log.large.error('One or more dredd tests failed');
return;
}
log.small.success('Dredd tests passed');
});
};
|
import { initLog } from 'roc';
import Dredd from 'dredd';
const log = initLog();
export default ({ context: { config: { settings } } }) => () => {
const port = process.env.PORT || settings.runtime.port;
const dredd = new Dredd({
server: `http://localhost:${port}`,
options: settings.test.dredd,
});
log.small.info('Testing API using dredd.\n');
return () => dredd.run((err, stats) => {
if (err) {
throw err;
}
if (stats.errors) {
log.large.error('One or more errors occured while running dredd');
return;
}
if (stats.failures) {
log.large.error('One or more dredd tests failed');
return;
}
log.small.success('Dredd tests passed');
});
};
|
Initialize input for proper behavior
|
import Ember from 'ember';
import config from 'degenerator-ui/config/environment';
export default Ember.Controller.extend({
filesystem: Ember.inject.service(),
init() {
this._super(...arguments);
this.set('uploadFile', null);
},
actions:{
selectPhoto() {
this.get('filesystem').prompt().then((upload) => {
this.set('uploadFile', upload);
});
},
uploadImg(formValues){
if (!this.uploadFile) {
return alert('Yo! Upload a file!');
}
this.get('filesystem').fetch(`${config.DS.host}/uploads`, {
method: 'POST',
headers: {
accept: 'application/json',
},
body: {
...formValues,
uploadFile: this.get('uploadFile'),
},
}).then((res) => res.json())
.then((data) => {
this.store.push(data);
this.transitionToRoute('degenerator.main');
});
},
}
});
|
import Ember from 'ember';
import fetch from 'ember-network/fetch';
export default Ember.Service.extend({
prompt(){
return new Promise((resolve, reject) => {
const input = document.createElement('input');
input.setAttribute("type","file");
input.click();
Ember.$(input).change(() => {
if (input.files.length === 0) {
return reject();
}
return resolve(input.files);
});
})
},
fetch(url, options){
var data = new FormData();
for (var key in options.body) {
if (options.body.hasOwnProperty(key)) {
data.append(key, options.body[key]);
}
}
return fetch(url,{...options, body: data});
}
});
|
Correct PHPDoc type for float ttl
It can be null as the Lock instance accepts it.
|
<?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\Lock;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
/**
* Factory provides method to create locks.
*
* @author JΓ©rΓ©my DerussΓ© <jeremy@derusse.com>
*/
class Factory implements LoggerAwareInterface
{
use LoggerAwareTrait;
private $store;
public function __construct(StoreInterface $store)
{
$this->store = $store;
$this->logger = new NullLogger();
}
/**
* Creates a lock for the given resource.
*
* @param string $resource The resource to lock
* @param float|null $ttl Maximum expected lock duration in seconds
* @param bool $autoRelease Whether to automatically release the lock or not when the lock instance is destroyed
*
* @return Lock
*/
public function createLock($resource, $ttl = 300.0, $autoRelease = true)
{
$lock = new Lock(new Key($resource), $this->store, $ttl, $autoRelease);
$lock->setLogger($this->logger);
return $lock;
}
}
|
<?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\Lock;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
/**
* Factory provides method to create locks.
*
* @author JΓ©rΓ©my DerussΓ© <jeremy@derusse.com>
*/
class Factory implements LoggerAwareInterface
{
use LoggerAwareTrait;
private $store;
public function __construct(StoreInterface $store)
{
$this->store = $store;
$this->logger = new NullLogger();
}
/**
* Creates a lock for the given resource.
*
* @param string $resource The resource to lock
* @param float $ttl Maximum expected lock duration in seconds
* @param bool $autoRelease Whether to automatically release the lock or not when the lock instance is destroyed
*
* @return Lock
*/
public function createLock($resource, $ttl = 300.0, $autoRelease = true)
{
$lock = new Lock(new Key($resource), $this->store, $ttl, $autoRelease);
$lock->setLogger($this->logger);
return $lock;
}
}
|
Fix selector for tab selection
|
$(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.search-navigation a').map(function(i, el){
return $(el).attr('href').split('#').pop();
}),
$defaultTab = $('input[name=tab]'),
selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
}
if($searchForm.length){
$tabs.on('tabChanged', updateSearchForm);
}
function updateSearchForm(e, hash){
if(typeof hash !== 'undefined'){
var $defaultTab = $('input[name=tab]');
if($defaultTab.length === 0){
$defaultTab = $('<input type="hidden" name="tab">');
$searchForm.prepend($defaultTab);
}
$defaultTab.val(hash);
}
}
});
|
$(function() {
var $tabs = $('#search-results-tabs'),
$searchForm = $('.js-search-hash');
if($tabs.length > 0){
$tabs.tabs({ 'defaultTab' : getDefaultSearchTabIndex(), scrollOnload: true });
}
function getDefaultSearchTabIndex(){
var tabIds = $('.nav-tabs a').map(function(i, el){
return $(el).attr('href').split('#').pop();
}),
$defaultTab = $('input[name=tab]'),
selectedTab = $.inArray($defaultTab.val(), tabIds);
return selectedTab > -1 ? selectedTab : 0;
}
if($searchForm.length){
$tabs.on('tabChanged', updateSearchForm);
}
function updateSearchForm(e, hash){
if(typeof hash !== 'undefined'){
var $defaultTab = $('input[name=tab]');
if($defaultTab.length === 0){
$defaultTab = $('<input type="hidden" name="tab">');
$searchForm.prepend($defaultTab);
}
$defaultTab.val(hash);
}
}
});
|
[Java] Fix class used for logging
Change-Id: Ic689a8b5e9ed090330737386ed814fb020afc6ea
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
package itest.io.joynr.jeeintegration.preprocessor;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.joynr.messaging.RawMessagingPreprocessor;
public class TestRawMessagingProcessor extends RawMessagingPreprocessor {
private static final Logger logger = LoggerFactory.getLogger(TestRawMessagingProcessor.class);
@Override
public byte[] process(byte[] rawMessage, Map<String, Serializable> context) {
logger.info("raw message received: " + new String(rawMessage, StandardCharsets.UTF_8));
return rawMessage;
}
}
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
package itest.io.joynr.jeeintegration.preprocessor;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.joynr.messaging.RawMessagingPreprocessor;
public class TestRawMessagingProcessor extends RawMessagingPreprocessor {
private static final Logger logger = LoggerFactory.getLogger(RawMessagingPreprocessor.class);
@Override
public byte[] process(byte[] rawMessage, Map<String, Serializable> context) {
logger.info("raw message received: " + new String(rawMessage, StandardCharsets.UTF_8));
return rawMessage;
}
}
|
Use respond instead of create_response
|
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from ask import alexa
def lambda_handler(request_obj, context=None):
return alexa.route_request(request_obj)
@alexa.default
def default_handler(request):
logger.info('default_handler')
return alexa.respond('There were 42 accidents in 2016.')
@alexa.request("LaunchRequest")
def launch_request_handler(request):
logger.info('launch_request_handler')
return alexa.respond('You can ask me about car accidents.')
@alexa.request("SessionEndedRequest")
def session_ended_request_handler(request):
logger.info('session_ended_request_handler')
return alexa.respond('Goodbye.')
@alexa.intent('AMAZON.CancelIntent')
def cancel_intent_handler(request):
logger.info('cancel_intent_handler')
return alexa.respond('Okay.', end_session=True)
@alexa.intent('AMAZON.HelpIntent')
def help_intent_handler(request):
logger.info('help_intent_handler')
return alexa.respond('You can ask me about car accidents.')
@alexa.intent('AMAZON.StopIntent')
def stop_intent_handler(request):
logger.info('stop_intent_handler')
return alexa.respond('Okay.', end_session=True)
|
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from ask import alexa
def lambda_handler(request_obj, context=None):
return alexa.route_request(request_obj)
@alexa.default
def default_handler(request):
logger.info('default_handler')
return alexa.respond('There were 42 accidents in 2016.')
@alexa.request("LaunchRequest")
def launch_request_handler(request):
logger.info('launch_request_handler')
return alexa.create_response(message='You can ask me about car accidents.')
@alexa.request("SessionEndedRequest")
def session_ended_request_handler(request):
logger.info('session_ended_request_handler')
return alexa.create_response(message="Goodbye!")
@alexa.intent('AMAZON.CancelIntent')
def cancel_intent_handler(request):
logger.info('cancel_intent_handler')
return alexa.create_response(message='ok', end_session=True)
@alexa.intent('AMAZON.HelpIntent')
def help_intent_handler(request):
logger.info('help_intent_handler')
return alexa.create_response(message='You can ask me about car accidents.')
@alexa.intent('AMAZON.StopIntent')
def stop_intent_handler(request):
logger.info('stop_intent_handler')
return alexa.create_response(message='ok', end_session=True)
|
Hide a reader for now.
|
export default {
name: 'ArticleNav',
configure (config) {
config.addLabel('mode', 'Mode')
config.addViewMode({
name: 'open-manuscript',
viewName: 'manuscript',
commandGroup: 'switch-view',
icon: 'fa-align-left',
label: 'Manuscript'
})
config.addViewMode({
name: 'open-metadata',
viewName: 'metadata',
commandGroup: 'switch-view',
icon: 'fa-th-list',
label: 'Metadata'
})
// TODO: make reader great again
/*
config.addViewMode({
name: 'open-reader',
viewName: 'reader',
commandGroup: 'switch-view',
icon: 'fa-th-list',
label: 'Reader'
})
*/
}
}
|
export default {
name: 'ArticleNav',
configure (config) {
config.addLabel('mode', 'Mode')
config.addViewMode({
name: 'open-manuscript',
viewName: 'manuscript',
commandGroup: 'switch-view',
icon: 'fa-align-left',
label: 'Manuscript'
})
config.addViewMode({
name: 'open-metadata',
viewName: 'metadata',
commandGroup: 'switch-view',
icon: 'fa-th-list',
label: 'Metadata'
})
config.addViewMode({
name: 'open-reader',
viewName: 'reader',
commandGroup: 'switch-view',
icon: 'fa-th-list',
label: 'Reader'
})
}
}
|
Fix checking invokable $instead of $resource
|
<?php
namespace Colorium\App\Kernel;
use Colorium\App\Context;
use Colorium\App\Plugin;
use Colorium\Http\Response;
use Colorium\Runtime\Invokable;
class Execution extends Plugin
{
/**
* Handle context
*
* @param Context $context
* @param callable $chain
* @return Context
*/
public function handle(Context $context, callable $chain = null)
{
// expect valid invokable
if(!$context->invokable instanceof Invokable) {
throw new \RuntimeException('Context::invokable must be a valid Colorium\Runtime\Invokable instance');
}
// instanciate invokable class
$context->invokable->instanciate();
// add context as last params
$context->invokable->params[] = $context;
// execute resource
$content = $context->invokable->call();
if($content instanceof Response) {
$context->response = $content;
return $context;
}
$context->response->raw = true;
$context->response->content = $content;
return $context;
}
}
|
<?php
namespace Colorium\App\Kernel;
use Colorium\App\Context;
use Colorium\App\Plugin;
use Colorium\Http\Response;
use Colorium\Runtime\Invokable;
class Execution extends Plugin
{
/**
* Handle context
*
* @param Context $context
* @param callable $chain
* @return Context
*/
public function handle(Context $context, callable $chain = null)
{
// expect valid invokable
if(!$context->resource instanceof Invokable) {
throw new \RuntimeException('Context::invokable must be a valid Colorium\Runtime\Invokable instance');
}
// instanciate invokable class
$context->invokable->instanciate();
// add context as last params
$context->invokable->params[] = $context;
// execute resource
$content = $context->invokable->call();
if($content instanceof Response) {
$context->response = $content;
return $context;
}
$context->response->raw = true;
$context->response->content = $content;
return $context;
}
}
|
Update expanding progress tests to use enzyme.
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const enzyme = require('enzyme');
const ExpandingProgress = require('./expanding-progress');
describe('ExpandingProgress', function() {
const renderComponent = (options = {}) => enzyme.shallow(
<ExpandingProgress />
);
beforeEach(() => {
this.clock = sinon.useFakeTimers();
});
afterEach(() => {
this.clock.restore();
});
it('renders properly', () => {
const wrapper = renderComponent();
var expected = (
<div className="expanding-progress"></div>);
assert.compareJSX(wrapper, expected);
});
it('adds the active class after mounted', () => {
const wrapper = renderComponent();
// The class is set asynchronously fast forward until it should be applied.
this.clock.tick(1);
wrapper.update();
assert.equal(
wrapper.prop('className').includes('expanding-progress--active'),
true);
});
});
|
/* Copyright (C) 2017 Canonical Ltd. */
'use strict';
const React = require('react');
const ExpandingProgress = require('./expanding-progress');
const jsTestUtils = require('../../utils/component-test-utils');
const testUtils = require('react-dom/test-utils');
describe('ExpandingProgress', function() {
it('renders properly', () => {
var output = jsTestUtils.shallowRender(
<ExpandingProgress />);
var expected = (
<div className="expanding-progress"></div>);
assert.deepEqual(output, expected);
});
it('adds the active class after mounted', done => {
var component = testUtils.renderIntoDocument(
<ExpandingProgress />);
// The class is set asynchronously so loop over the value and continue When
// it changes.
setTimeout(() => {
if (component.state.active) {
assert.equal(component.state.active, true);
done();
}
});
});
});
|
Fix s3 upload file extra_args named paramether
|
import boto3
from boto3.s3.transfer import S3Transfer
from config import AWS_ACCESS_KEY, AWS_SECRET_KEY
def delete_s3_file(file_id):
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
return client.delete_object(
Bucket='dataviva',
Key=file_id
)
def upload_s3_file(file_path, bucket, file_id, extra_args={'ContentType': "html/text"}):
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
transfer = S3Transfer(client)
return transfer.upload_file(file_path, bucket, file_id, extra_args=extra_args)
|
import boto3
from boto3.s3.transfer import S3Transfer
from config import AWS_ACCESS_KEY, AWS_SECRET_KEY
def delete_s3_file(file_id):
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
return client.delete_object(
Bucket='dataviva',
Key=file_id
)
def upload_s3_file(file_path, bucket, file_id, extra_args={'ContentType': "html/text"}):
client = boto3.client(
's3',
aws_access_key_id=AWS_ACCESS_KEY,
aws_secret_access_key=AWS_SECRET_KEY
)
transfer = S3Transfer(client)
return transfer.upload_file(file_path, bucket, file_id, extra_args)
|
Add debug to prod settings
|
module.exports = {
port: 3000,
canvas: {
apiUrl: 'https://kth.instructure.com/api/v1'
},
logging: {
log: {
level: 'debug',
src: false
},
stdout: {
enabled: true
},
console: {
enabled: false
}
},
ldap: {
client: {
url: 'ldaps://ldap.ug.kth.se',
timeout: 300000,
connectTimeout: 3000,
maxConnections: 10,
idleTimeout: 300000,
checkInterval: 10000,
reconnect: true
}
},
azure: {
queueName: 'ug-canvas',
csvBlobName: 'lms-csv-prod',
msgBlobName: 'lms-msg-prod'
},
localFile: {
csvDir: '/tmp/'
}
}
|
module.exports = {
port: 3000,
canvas: {
apiUrl: 'https://kth.instructure.com/api/v1'
},
logging: {
log: {
level: 'info',
src: false
},
stdout: {
enabled: true
},
console: {
enabled: false
}
},
ldap: {
client: {
url: 'ldaps://ldap.ug.kth.se',
timeout: 300000,
connectTimeout: 3000,
maxConnections: 10,
idleTimeout: 300000,
checkInterval: 10000,
reconnect: true
}
},
azure: {
queueName: 'ug-canvas',
csvBlobName: 'lms-csv-prod',
msgBlobName: 'lms-msg-prod'
},
localFile: {
csvDir: '/tmp/'
}
}
|
Move deletion of installer folder to the end
|
<?php
namespace Installer\Handlers;
use Installer\Helpers\File;
final class CleanerHandler extends AbstractHandler implements HandlerInterface
{
public function execute()
{
$this->write('');
$this->writeHeader('Cleaning up <info>(also something you will forget)</info>.');
if($this->askConfirmation('Do you want to remove the \'paragonie/random_compat\' package?'))
{
exec(
escapeshellcmd(
sprintf(
'composer remove %s -d "%s" ',
escapeshellarg('paragonie/random_compat'),
escapeshellarg(__DIR__ . '/../../')
)
)
);
}
File::remove(File::INSTALLER);
$this->write('You are ready to rock!');
}
}
|
<?php
namespace Installer\Handlers;
use Installer\Helpers\File;
final class CleanerHandler extends AbstractHandler implements HandlerInterface
{
public function execute()
{
$this->write('');
$this->writeHeader('Cleaning up <info>(also something you will forget)</info>.');
File::remove(File::INSTALLER);
if($this->askConfirmation('Do you want to remove the \'paragonie/random_compat\' package?'))
{
exec(
escapeshellcmd(
sprintf(
'composer remove %s -d "%s" ',
escapeshellarg('paragonie/random_compat'),
escapeshellarg(__DIR__ . '/../../')
)
)
);
}
$this->write('You are ready to rock!');
}
}
|
Build closure for TRIPS ontology
|
import os
from indra.preassembler.hierarchy_manager import HierarchyManager
# Make a TRIPS ontology
_fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf')
trips_ontology = HierarchyManager(_fname, uri_as_name=False, build_closure=True)
trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/'
trips_ontology.initialize()
def trips_isa(concept1, concept2):
# Preprocess to make this more general
concept1 = concept1.lower().replace('ont::', '')
concept2 = concept2.lower().replace('ont::', '')
if concept1 == concept2:
return True
isa = trips_ontology.isa('http://trips.ihmc.us/concepts/', concept1,
'http://trips.ihmc.us/concepts/', concept2)
return isa
|
import os
from indra.preassembler.hierarchy_manager import HierarchyManager
# Make a TRIPS ontology
_fname = os.path.join(os.path.dirname(__file__), 'trips_ontology.rdf')
trips_ontology = HierarchyManager(_fname, uri_as_name=False)
trips_ontology.relations_prefix = 'http://trips.ihmc.us/relations/'
trips_ontology.initialize()
def trips_isa(concept1, concept2):
# Preprocess to make this more general
concept1 = concept1.lower().replace('ont::', '')
concept2 = concept2.lower().replace('ont::', '')
if concept1 == concept2:
return True
isa = trips_ontology.isa('http://trips.ihmc.us/concepts/', concept1,
'http://trips.ihmc.us/concepts/', concept2)
return isa
|
Add Api method for getting rooms of a hostel
|
<?php
namespace AppBundle\RestApi;
use Doctrine\DBAL\Connection;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
class HostelController extends FOSRestController implements ClassResourceInterface
{
public function cgetAction()
{
$db = $this->getConnection();
return $db->fetchAll("select * from hostel");
}
public function getAction($slug)
{
$db = $this->getConnection();
return $db->fetchAssoc("select * from hostel where slug = :slug", [
"slug" => $slug
]);
}
public function getRoomsAction($slug)
{
$db = $this->getConnection();
$sql = "select * from room where hostel_id = (select id from hostel where slug = :slug)";
return $db->fetchAll($sql, [
"slug" => $slug
]);
}
private function getConnection(): Connection
{
return $connection = $this->get("database_connection");
}
private function getRepository()
{
return $this->getDoctrine()->getRepository('AppBundle:Hostel');
}
}
|
<?php
namespace AppBundle\RestApi;
use Doctrine\DBAL\Connection;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
class HostelController extends FOSRestController implements ClassResourceInterface
{
public function cgetAction()
{
$db = $this->getConnection();
return $db->fetchAll("select * from hostel");
}
public function getAction($slug)
{
$db = $this->getConnection();
return $db->fetchAssoc("select * from hostel where slug = :slug", [
"slug" => $slug
]);
}
private function getConnection(): Connection
{
return $connection = $this->get("database_connection");
}
private function getRepository()
{
return $this->getDoctrine()->getRepository('AppBundle:Hostel');
}
}
|
Fix entry point for blacklist_requests
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "images_of",
version = "0.1.0",
author = "acimi-ursi",
description = "Tools for managing the ImagesOfNetwork on reddit",
url = "https://github.com/amici-ursi/ImagesOfNetwork",
packages = find_packages(),
install_requires = [
"click",
"praw==3.4",
"pytoml",
],
entry_points = {
"console_scripts": [
"ion_expand = images_of.entrypoints.expand:main",
"ion_setup_oauth = images_of.entrypoints.oauth:main",
"ion_bot = images_of.entrypoints.bot:main",
"ion_propagate = images_of.entrypoints.propagate:main",
"ion_invite_mods = images_of.entrypoints.invite_mods:main",
"ion_bulkmail = images_of.entrypoints.bulkmail:main",
"ion_audit_mods = images_of.entrypoints.audit_mods:main",
"ion_blacklist_requests = images_of.entrypoints.blacklist_requests:main",
],
},
data_files = [
('images_of', 'data/*.toml'),
],
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = "images_of",
version = "0.1.0",
author = "acimi-ursi",
description = "Tools for managing the ImagesOfNetwork on reddit",
url = "https://github.com/amici-ursi/ImagesOfNetwork",
packages = find_packages(),
install_requires = [
"click",
"praw==3.4",
"pytoml",
],
entry_points = {
"console_scripts": [
"ion_expand = images_of.entrypoints.expand:main",
"ion_setup_oauth = images_of.entrypoints.oauth:main",
"ion_bot = images_of.entrypoints.bot:main",
"ion_propagate = images_of.entrypoints.propagate:main",
"ion_invite_mods = images_of.entrypoints.invite_mods:main",
"ion_bulkmail = images_of.entrypoints.bulkmail:main",
"ion_audit_mods = images_of.entrypoints.audit_mods:main",
"ion_blacklist_requests = images_of.entrypoints.blacklist_requests.py:main",
],
},
data_files = [
('images_of', 'data/*.toml'),
],
)
|
Make sure the tests exit with status 1 when there are errors or failures
|
#!/usr/bin/python
import optparse
import sys
import unittest2
USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""
def main(sdk_path, test_path, third_party_path=None):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
if third_party_path:
sys.path.insert(0, third_party_path)
suite = unittest2.loader.TestLoader().discover(test_path,
pattern='*_test.py')
result = unittest2.TextTestRunner(verbosity=2).run(suite)
if len(result.errors) > 0 or len(result.failures) > 0:
sys.exit(1)
if __name__ == '__main__':
sys.dont_write_bytecode = True
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 2:
print 'Error: At least 2 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = args[1]
THIRD_PARTY_PATH = args[2] if len(args) > 2 else None
main(SDK_PATH, TEST_PATH, THIRD_PARTY_PATH)
|
#!/usr/bin/python
import optparse
import sys
import unittest2
USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""
def main(sdk_path, test_path, third_party_path=None):
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
if third_party_path:
sys.path.insert(0, third_party_path)
suite = unittest2.loader.TestLoader().discover(test_path,
pattern='*_test.py')
unittest2.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
sys.dont_write_bytecode = True
parser = optparse.OptionParser(USAGE)
options, args = parser.parse_args()
if len(args) < 2:
print 'Error: At least 2 arguments required.'
parser.print_help()
sys.exit(1)
SDK_PATH = args[0]
TEST_PATH = args[1]
THIRD_PARTY_PATH = args[2] if len(args) > 2 else None
main(SDK_PATH, TEST_PATH, THIRD_PARTY_PATH)
|
Add db from config to modals
|
from config import db
class User(db.Modal):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
asu_id = db.Column(db.Integer,nullable=False)
class_standing = db.Column(db.String(100), nullable=True)
email = db.Column(db.String(100))
phone_number = db.Column(db.String(100))
def __init__(self,name,asu_id,class_standing,email,phone_number):
self.name = name
self.asu_id = asu_id
self.class_standing = class_standing
self.email = email
self.phone_number = phone_number
def __repr__(self):
return "User's name: %s" % self.name
|
from app import db
class Users(db.Modal):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
asu_id = db.Column(db.Integer,nullable=False)
class_standing = db.Column(db.String(100), nullable=True)
email = db.Column(db.String(100))
phone_number = db.Column(db.String(100))
def __init__(self,name,asu_id,class_standing,email,phone_number):
self.name = name
self.asu_id = asu_id
self.class_standing = class_standing
self.email = email
self.phone_number = phone_number
def __repr__(self):
return "User's name: %s" % self.name
|
Rename REDUNDANT_PARENTHESIS rule to REDUNDANT_PARENTHESES
|
package com.sleekbyte.tailor.common;
import com.sleekbyte.tailor.listeners.BlankLineListener;
import com.sleekbyte.tailor.listeners.MultipleImportListener;
import com.sleekbyte.tailor.listeners.RedundantParenthesisListener;
import com.sleekbyte.tailor.listeners.SemicolonTerminatedListener;
import com.sleekbyte.tailor.listeners.UpperCamelCaseListener;
import com.sleekbyte.tailor.listeners.WhitespaceListener;
/**
* Enum for all rules implemented in Tailor.
*/
public enum Rules {
UPPER_CAMEL_CASE ("upperCamelCase", UpperCamelCaseListener.class.getName()),
SEMICOLON_TERMINATED ("semicolonTerminated", SemicolonTerminatedListener.class.getName()),
REDUNDANT_PARENTHESES ("redundantParentheses", RedundantParenthesisListener.class.getName()),
MULTIPLE_IMPORT ("multipleImports", MultipleImportListener.class.getName()),
BLANK_LINE_FUNCTION ("blankLinesAroundFunction", BlankLineListener.class.getName()),
WHITESPACE ("whitespace", WhitespaceListener.class.getName());
private String name;
private String className;
Rules(String name, String className) {
this.name = name;
this.className = className;
}
public String getName() {
return this.name;
}
public String getClassName() {
return this.className;
}
}
|
package com.sleekbyte.tailor.common;
import com.sleekbyte.tailor.listeners.BlankLineListener;
import com.sleekbyte.tailor.listeners.MultipleImportListener;
import com.sleekbyte.tailor.listeners.RedundantParenthesisListener;
import com.sleekbyte.tailor.listeners.SemicolonTerminatedListener;
import com.sleekbyte.tailor.listeners.UpperCamelCaseListener;
import com.sleekbyte.tailor.listeners.WhitespaceListener;
/**
* Enum for all rules implemented in Tailor.
*/
public enum Rules {
UPPER_CAMEL_CASE ("upperCamelCase", UpperCamelCaseListener.class.getName()),
SEMICOLON_TERMINATED ("semicolonTerminated", SemicolonTerminatedListener.class.getName()),
REDUNDANT_PARENTHESIS ("redundantParentheses", RedundantParenthesisListener.class.getName()),
MULTIPLE_IMPORT ("multipleImports", MultipleImportListener.class.getName()),
BLANK_LINE_FUNCTION ("blankLinesAroundFunction", BlankLineListener.class.getName()),
WHITESPACE ("whitespace", WhitespaceListener.class.getName());
private String name;
private String className;
Rules(String name, String className) {
this.name = name;
this.className = className;
}
public String getName() {
return this.name;
}
public String getClassName() {
return this.className;
}
}
|
Fix for Qt5 in plugins that use matplotlib
|
#
# Plot.py -- Plotting function for Ginga FITS viewer.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
# GUI imports
from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
from ginga.toolkit import toolkit
import matplotlib
if toolkit == 'qt4':
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg \
as FigureCanvas
elif toolkit == 'qt5':
# qt5 backend is not yet released in matplotlib stable
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg \
as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
|
#
# Plot.py -- Plotting function for Ginga FITS viewer.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
# GUI imports
from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from ginga.base.PlotBase import PlotBase, HistogramMixin, CutsMixin
class Plot(PlotBase):
def __init__(self, logger, width=300, height=300, dpi=100):
PlotBase.__init__(self, logger, FigureCanvas,
width=width, height=height, dpi=dpi)
class Histogram(Plot, HistogramMixin):
pass
class Cuts(Plot, CutsMixin):
pass
#END
|
Reset now deletes and recreates the demo db
|
<?php
namespace OParl\Server\Commands;
use Illuminate\Console\Command;
use OParl\Server\Model\Body;
use OParl\Server\Model\Consultation;
use OParl\Server\Model\File;
use OParl\Server\Model\Keyword;
use OParl\Server\Model\LegislativeTerm;
use OParl\Server\Model\Location;
use OParl\Server\Model\Meeting;
use OParl\Server\Model\Membership;
use OParl\Server\Model\Organization;
use OParl\Server\Model\Paper;
use OParl\Server\Model\Person;
use OParl\Server\Model\System;
/**
* Clear the server data
*
* @package OParl\Server\Commands
*/
class ResetCommand extends Command
{
protected $name = 'server:reset';
protected $description = "Reset the server's database";
public function handle()
{
$this->info('Reset demoserver database...');
unlink(config('database.connections.sqlite_demo.database'));
touch(config('database.connections.sqlite_demo.database'));
$this->call('migrate', ['--database' => 'sqlite_demo']);
}
}
|
<?php
namespace OParl\Server\Commands;
use Illuminate\Console\Command;
use OParl\Server\Model\Body;
use OParl\Server\Model\Consultation;
use OParl\Server\Model\File;
use OParl\Server\Model\Keyword;
use OParl\Server\Model\LegislativeTerm;
use OParl\Server\Model\Location;
use OParl\Server\Model\Meeting;
use OParl\Server\Model\Membership;
use OParl\Server\Model\Organization;
use OParl\Server\Model\Paper;
use OParl\Server\Model\Person;
use OParl\Server\Model\System;
/**
* Clear the server data
*
* @package OParl\Server\Commands
*/
class ResetCommand extends Command
{
protected $name = 'server:reset';
protected $description = "Reset the server's database";
public function handle()
{
$this->info('Removing all existing server data...');
System::truncate();
Body::truncate();
LegislativeTerm::truncate();
Person::truncate();
Organization::truncate();
Membership::truncate();
Meeting::truncate();
Consultation::truncate();
Paper::truncate();
Location::truncate();
File::truncate();
Keyword::truncate();
}
}
|
Add Undeclared Faker Instance to PhoneNumber Test in en_NG
|
<?php
namespace Faker\Test\Provider\ng_NG;
use Faker\Generator;
use Faker\Provider\en_NG\PhoneNumber;
use PHPUnit\Framework\TestCase;
class PhoneNumberTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
public function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumberReturnsPhoneNumberWithOrWithoutCountryCode()
{
$phoneNumber = $this->faker->phoneNumber();
$this->assertNotEmpty($phoneNumber);
$this->assertInternalType('string', $phoneNumber);
$this->assertRegExp('/^(0|(\+234))\s?[789][01]\d\s?(\d{3}\s?\d{4})/', $phoneNumber);
}
}
|
<?php
namespace Faker\Test\Provider\ng_NG;
use Faker\Generator;
use Faker\Provider\en_NG\PhoneNumber;
use PHPUnit\Framework\TestCase;
class PhoneNumberTest extends TestCase
{
public function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumberReturnsPhoneNumberWithOrWithoutCountryCode()
{
$phoneNumber = $this->faker->phoneNumber();
$this->assertNotEmpty($phoneNumber);
$this->assertInternalType('string', $phoneNumber);
$this->assertRegExp('/^(0|(\+234))\s?[789][01]\d\s?(\d{3}\s?\d{4})/', $phoneNumber);
}
}
|
Allow to run build from studio for cra.
|
'use strict';
const fs = require('fs');
const path = require('path');
const rekitCore = require('rekit-core');
const spawn = require('child_process').spawn;
function runBuild(io) {
const prjRoot = rekitCore.utils.getProjectRoot();
return new Promise((resolve) => {
const isCra = fs.existsSync(path.join(prjRoot, 'scripts/build.js'));
const child = spawn('node',
[
isCra ? `${prjRoot}/scripts/build.js` : `${prjRoot}/tools/build.js`
],
{
stdio: 'pipe',
cwd: prjRoot
}
);
child.stdout.pipe(process.stdout);
const handleOutput = (data) => {
// collect the data
const text = data.toString('utf8').replace(/ /g, ' ').split('\n');
const arr = [];
text.forEach(t => arr.push(t));
io.emit('output', {
type: 'build',
output: arr,
});
};
child.stdout.on('data', handleOutput);
child.stderr.on('data', handleOutput);
child.on('close', () => {
io.emit('build-finished', {});
resolve();
});
});
}
module.exports = runBuild;
|
'use strict';
const rekitCore = require('rekit-core');
const spawn = require('child_process').spawn;
function runBuild(io) {
const prjRoot = rekitCore.utils.getProjectRoot();
return new Promise((resolve) => {
const child = spawn('node',
[
`${prjRoot}/tools/build.js`
],
{
stdio: 'pipe',
cwd: prjRoot
}
);
child.stdout.pipe(process.stdout);
const handleOutput = (data) => {
// collect the data
const text = data.toString('utf8').replace(/ /g, ' ').split('\n');
const arr = [];
text.forEach(t => arr.push(t));
io.emit('output', {
type: 'build',
output: arr,
});
};
child.stdout.on('data', handleOutput);
child.stderr.on('data', handleOutput);
child.on('close', () => {
io.emit('build-finished', {});
resolve();
});
});
}
module.exports = runBuild;
|
Remove note about assets directory.
|
<?php
require('autoloader.php');
$headlinks = new NigeLib\Headlinks(
array(
'$jquery-ui' => array( 'assets/jquery/ui/jquery-ui.js' ),
'assets/jquery/ui/jquery-ui.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/themes/base/jquery-ui.css' ),
'assets/jquery/themes/base/jquery-ui.css' => array( 'assets/jquery/ui/jquery-ui.js' ),
'assets/test.1.2.3.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/ui/jquery-ui.js' ),
)
);
$headlinks->addFile( 'assets/moment.js' );
$headlinks->addFile( '$jquery-ui' );
$headlinks->addFile( 'assets/style.css' );
$headlinks->addFile( 'assets/test.1.2.3.js' );
?>
<!doctype html>
<html>
<head>
<?php echo $headlinks->getLinks(); ?>
</head>
<body>
<h1>This is a test</h1>
<a href='test_headlinks.php'>Load again</a>
</body>
</html>
|
<?php
// Note: The assets directory is not included in the git repo to keep the size
// down. However this serves to demonstrate the Headlinks class.
require('autoloader.php');
$headlinks = new NigeLib\Headlinks(
array(
'$jquery-ui' => array( 'assets/jquery/ui/jquery-ui.js' ),
'assets/jquery/ui/jquery-ui.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/themes/base/jquery-ui.css' ),
'assets/jquery/themes/base/jquery-ui.css' => array( 'assets/jquery/ui/jquery-ui.js' ),
'assets/test.1.2.3.js' => array( 'assets/jquery/jquery.js', 'assets/jquery/ui/jquery-ui.js' ),
)
);
$headlinks->addFile( 'assets/moment.js' );
$headlinks->addFile( '$jquery-ui' );
$headlinks->addFile( 'assets/style.css' );
$headlinks->addFile( 'assets/test.1.2.3.js' );
?>
<!doctype html>
<html>
<head>
<?php echo $headlinks->getLinks(); ?>
</head>
<body>
<h1>This is a test</h1>
<a href='test_headlinks.php'>Load again</a>
</body>
</html>
|
Test for String Object and value mutation of the same
|
var capitalize = require('../capitalize');
var chai = require('chai');
var expect = chai.expect;
describe('capitalize', function() {
it('capitalizes single words', function() {
expect(capitalize('express')).to.equal('Express');
expect(capitalize('cats')).to.equal('Cats');
});
it('makes the rest of the string lowercase', function() {
expect(capitalize('javaScript')).to.equal('Javascript');
});
it('leaves empty strings alone', function() {
expect(capitalize('')).to.equal('');
});
it('leaves strings with no words alone', function() {
expect(capitalize(' ')).to.equal(' ');
expect(capitalize('123')).to.equal('123');
});
it('capitalizes multiple-word strings', function() {
expect(capitalize('what is Express')).to.equal('What is express');
expect(capitalize('i love lamp')).to.equal('I love lamp');
});
it('leaves already-capitalized words alone', function() {
expect(capitalize('Express')).to.equal('Express');
expect(capitalize('Evan')).to.equal('Evan');
expect(capitalize('Catman')).to.equal('Catman');
});
it('capitalizes String objects without changing their values', function() {
var str = new String('who is JavaScript?');
expect(capitalize(str)).to.equal('Who is javascript?');
expect(str.valueOf()).to.equal('who is JavaScript?');
});
});
|
var capitalize = require('../capitalize');
var chai = require('chai');
var expect = chai.expect;
describe('capitalize', function() {
it('capitalizes single words', function() {
expect(capitalize('express')).to.equal('Express');
expect(capitalize('cats')).to.equal('Cats');
});
it('makes the rest of the string lowercase', function() {
expect(capitalize('javaScript')).to.equal('Javascript');
});
it('leaves empty strings alone', function() {
expect(capitalize('')).to.equal('');
});
it('leaves strings with no words alone', function() {
expect(capitalize(' ')).to.equal(' ');
expect(capitalize('123')).to.equal('123');
});
it('capitalizes multiple-word strings', function() {
expect(capitalize('what is Express')).to.equal('What is express');
expect(capitalize('i love lamp')).to.equal('I love lamp');
});
it('leaves already-capitalized words alone', function() {
expect(capitalize('Express')).to.equal('Express');
expect(capitalize('Evan')).to.equal('Evan');
expect(capitalize('Catman')).to.equal('Catman');
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.