text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix line continuation indent level. | """SOAP client."""
from __future__ import print_function
import requests
from rinse import ENVELOPE_XSD
from rinse.util import SCHEMA
from rinse.response import RinseResponse
class SoapClient(object):
"""Rinse SOAP client."""
__session = None
def __init__(self, url, debug=False, **kwargs):
"""Set base attributes."""
self.url = url
self.debug = debug
self.kwargs = kwargs
self.operations = {}
self.soap_schema = SCHEMA[ENVELOPE_XSD]
@property
def _session(self):
"""Cached instance of requests.Session."""
if self.__session is None:
self.__session = requests.Session()
return self.__session
@_session.setter
def _session(self, session):
"""Allow injecting your own instance of requests.Session."""
self.__session = session
def __call__(self, msg, action="", build_response=RinseResponse,
debug=False):
"""Post 'msg' to remote service."""
# generate HTTP request from msg
request = msg.request(self.url, action).prepare()
if debug or self.debug:
print('{} {}'.format(request.method, self.url))
print(
''.join(
'{}: {}\n'.format(name, val)
for name, val
in sorted(request.headers.items())
)
)
print(request.content)
# perform HTTP(s) POST
resp = self._session.send(request)
return build_response(resp)
| """SOAP client."""
from __future__ import print_function
import requests
from rinse import ENVELOPE_XSD
from rinse.util import SCHEMA
from rinse.response import RinseResponse
class SoapClient(object):
"""Rinse SOAP client."""
__session = None
def __init__(self, url, debug=False, **kwargs):
"""Set base attributes."""
self.url = url
self.debug = debug
self.kwargs = kwargs
self.operations = {}
self.soap_schema = SCHEMA[ENVELOPE_XSD]
@property
def _session(self):
"""Cached instance of requests.Session."""
if self.__session is None:
self.__session = requests.Session()
return self.__session
@_session.setter
def _session(self, session):
"""Allow injecting your own instance of requests.Session."""
self.__session = session
def __call__(self, msg, action="", build_response=RinseResponse,
debug=False):
"""Post 'msg' to remote service."""
# generate HTTP request from msg
request = msg.request(self.url, action).prepare()
if debug or self.debug:
print('{} {}'.format(request.method, self.url))
print(
''.join(
'{}: {}\n'.format(name, val)
for name, val
in sorted(request.headers.items())
)
)
print(request.content)
# perform HTTP(s) POST
resp = self._session.send(request)
return build_response(resp)
|
Enable node.js to support both http and https | const https = require("https"),
http = require("http"),
zlib = require("zlib"),
fs = require("fs"),
path = require("path"),
isURL = require("is-url");
var langdata = require('../common/langdata.json')
function getLanguageData(req, res, cb){
var lang = req.options.lang,
langfile = lang + '.traineddata.gz';
// langPath defaults to a URL where languages can be downloaded. If a custom path is specified
// and it is a local path, use that instead
var localPath = isURL(req.workerOptions.langPath) ?
lang + '.traineddata' :
path.join(req.workerOptions.langPath, lang + '.traineddata');
var fetchProtocol = req.workerOptions.langPath.startsWith('http://') ? http : https;
fs.readFile(localPath, function (err, data) {
if(!err) return cb(new Uint8Array(data));
fetchProtocol.get(req.workerOptions.langPath + langfile, stream => {
var received_bytes = 0;
stream.on('data', function(chunk) {
received_bytes += chunk.length;
res.progress({
status: 'downloading ' + langfile,
loaded: received_bytes,
progress: Math.min(1, received_bytes / langdata[lang])
});
});
var gunzip = zlib.createGunzip();
stream.pipe(gunzip).pipe(fs.createWriteStream(lang + '.traineddata'))
gunzip.on('end',() => {
getLanguageData(req, stream, cb)
});
});
});
}
module.exports = getLanguageData;
| const http = require("http"),
zlib = require("zlib"),
fs = require("fs"),
path = require("path"),
isURL = require("is-url");
var langdata = require('../common/langdata.json')
function getLanguageData(req, res, cb){
var lang = req.options.lang,
langfile = lang + '.traineddata.gz';
// langPath defaults to a URL where languages can be downloaded. If a custom path is specified
// and it is a local path, use that instead
var localPath = isURL(req.workerOptions.langPath) ?
lang + '.traineddata' :
path.join(req.workerOptions.langPath, lang + '.traineddata');
fs.readFile(localPath, function (err, data) {
if(!err) return cb(new Uint8Array(data));
http.get(req.workerOptions.langPath + langfile, stream => {
var received_bytes = 0;
stream.on('data', function(chunk) {
received_bytes += chunk.length;
res.progress({
status: 'downloading ' + langfile,
loaded: received_bytes,
progress: Math.min(1, received_bytes / langdata[lang])
});
});
var gunzip = zlib.createGunzip();
stream.pipe(gunzip).pipe(fs.createWriteStream(lang + '.traineddata'))
gunzip.on('end',() => {
getLanguageData(req, stream, cb)
});
});
});
}
module.exports = getLanguageData;
|
Add quotes so all params are strings | # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
subprocess.call(['webdriver-manager', 'update'], stdout=f, stderr=f)
cls.webdriver = subprocess.Popen(
['webdriver-manager', 'start'], stdout=f, stderr=f)
@classmethod
def tearDownClass(cls):
cls.webdriver.kill()
super(ProtractorTestCaseMixin, cls).tearDownClass()
def get_protractor_params(self):
"""A hook for adding params that protractor will receive."""
return {
'live_server_url': self.live_server_url
}
def test_run(self):
protractor_command = 'protractor {}'.format(self.protractor_conf)
protractor_command += ' --baseUrl {}'.format(self.live_server_url)
if self.specs:
protractor_command += ' --specs {}'.format(','.join(self.specs))
if self.suite:
protractor_command += ' --suite {}'.format(self.suite)
for key, value in self.get_protractor_params().items():
protractor_command += ' --params.{key}="{value}"'.format(
key=key, value=value
)
return_code = subprocess.call(protractor_command.split())
self.assertEqual(return_code, 0)
| # -*- coding: utf-8 -*-
import os
import subprocess
class ProtractorTestCaseMixin(object):
protractor_conf = 'protractor.conf.js'
suite = None
specs = None
@classmethod
def setUpClass(cls):
super(ProtractorTestCaseMixin, cls).setUpClass()
with open(os.devnull, 'wb') as f:
subprocess.call(['webdriver-manager', 'update'], stdout=f, stderr=f)
cls.webdriver = subprocess.Popen(
['webdriver-manager', 'start'], stdout=f, stderr=f)
@classmethod
def tearDownClass(cls):
cls.webdriver.kill()
super(ProtractorTestCaseMixin, cls).tearDownClass()
def get_protractor_params(self):
"""A hook for adding params that protractor will receive."""
return {
'live_server_url': self.live_server_url
}
def test_run(self):
protractor_command = 'protractor {}'.format(self.protractor_conf)
protractor_command += ' --baseUrl {}'.format(self.live_server_url)
if self.specs:
protractor_command += ' --specs {}'.format(','.join(self.specs))
if self.suite:
protractor_command += ' --suite {}'.format(self.suite)
for key, value in self.get_protractor_params().items():
protractor_command += ' --params.{key}={value}'.format(
key=key, value=value
)
return_code = subprocess.call(protractor_command.split())
self.assertEqual(return_code, 0)
|
Fix new route after new ember-data | (function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
record.destroyRecord();
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.destroyRecord();
return true;
} else {
transition.abort();
}
} else {
if (record.get('isDirty')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.rollback();
return true;
} else {
transition.abort();
}
} else {
return true;
}
}
}
},
model: function() {
return this.store.createRecord('post');
},
renderTemplate: function() {
this.render();
this.render('posts/_form_action_bar', {
into: 'application',
outlet: 'footer'
});
}
});
})();
| (function() {
"use strict";
App.PostsNewRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
var record = this.get('controller.content');
// Allow transition if nothing is entered
if (Ember.isEmpty(record.get('title')) &&
Ember.isEmpty(record.get('bodyMarkdown'))
) {
return true;
}
// Confirm transition if there are unsaved changes
if (record.get('isNew')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.deleteRecord();
return true;
} else {
transition.abort();
}
} else {
if (record.get('isDirty')) {
if (confirm("Are you sure you want to lose unsaved changes?")) {
record.rollback();
return true;
} else {
transition.abort();
}
} else {
return true;
}
}
}
},
model: function() {
return App.Post.createRecord();
},
renderTemplate: function() {
this.render();
this.render('posts/_form_action_bar', {
into: 'application',
outlet: 'footer'
});
}
});
})();
|
Use a fixed thumbnail size rather then a relative scale. | """An overview window showing thumbnails of the image set.
"""
from __future__ import division
import math
from PySide import QtCore, QtGui
class ThumbnailWidget(QtGui.QLabel):
ThumbnailSize = QtCore.QSize(128, 128)
def __init__(self, image):
super(ThumbnailWidget, self).__init__()
pixmap = image.getPixmap()
pixmap = pixmap.scaled(self.ThumbnailSize, QtCore.Qt.KeepAspectRatio)
self.setPixmap(pixmap)
class OverviewWindow(QtGui.QMainWindow):
def __init__(self, imageViewer):
super(OverviewWindow, self).__init__()
self.imageViewer = imageViewer
self.numcolumns = 4
self.setWindowTitle("Overview")
self.mainLayout = QtGui.QGridLayout()
self._populate()
centralWidget = QtGui.QWidget()
centralWidget.setLayout(self.mainLayout)
scrollArea = QtGui.QScrollArea()
scrollArea.setWidget(centralWidget)
scrollArea.setAlignment(QtCore.Qt.AlignCenter)
self.setCentralWidget(scrollArea)
def _populate(self):
"""Populate the mainLayout with thumbnail images.
"""
# FIXME: by now, implement only the initial setup of the image
# list. Must also support updating the list after changes in
# imageViewer.selection.
images = self.imageViewer.selection
ncol = self.numcolumns
c = 0
for i in images:
thumb = ThumbnailWidget(i)
self.mainLayout.addWidget(thumb, c // ncol, c % ncol)
c += 1
| """An overview window showing thumbnails of the image set.
"""
from __future__ import division
import math
from PySide import QtCore, QtGui
class ThumbnailWidget(QtGui.QLabel):
def __init__(self, image, scale):
super(ThumbnailWidget, self).__init__()
pixmap = image.getPixmap()
size = scale * pixmap.size()
pixmap = pixmap.scaled(size)
self.setPixmap(pixmap)
class OverviewWindow(QtGui.QMainWindow):
def __init__(self, imageViewer):
super(OverviewWindow, self).__init__()
self.imageViewer = imageViewer
self.numcolumns = 4
self.scaleFactor = self.imageViewer.scaleFactor / 5.0
self.setWindowTitle("Overview")
self.mainLayout = QtGui.QGridLayout()
self._populate()
centralWidget = QtGui.QWidget()
centralWidget.setLayout(self.mainLayout)
scrollArea = QtGui.QScrollArea()
scrollArea.setWidget(centralWidget)
scrollArea.setAlignment(QtCore.Qt.AlignCenter)
self.setCentralWidget(scrollArea)
def _populate(self):
"""Populate the mainLayout with thumbnail images.
"""
# FIXME: by now, implement only the initial setup of the image
# list. Must also support updating the list after changes in
# imageViewer.selection.
images = self.imageViewer.selection
ncol = self.numcolumns
c = 0
for i in images:
thumb = ThumbnailWidget(i, self.scaleFactor)
self.mainLayout.addWidget(thumb, c // ncol, c % ncol)
c += 1
|
Update avoider's use of BBCServices | var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = routes;
function routes(app, radiodan, bbcServices) {
var avoidPlayer = radiodan.player.get("avoider"),
mainPlayer = radiodan.player.get("main"),
announcePlayer = radiodan.player.get("announcer"),
Avoider = require("./avoider")(
bbcServices, mainPlayer, avoidPlayer
),
settings = require("./settings").create();
app.get("/", index);
app.get("/avoid", avoid);
return app;
function index(req, res) {
settings.get().then(function(settings) {
res.render(
__dirname+"/views/index",
{ settings: JSON.stringify(settings) }
);
}).then(null, utils.failedPromiseHandler(logger));
}
function avoid(req, res) {
bbcServices.ready.then(function() {
var radio1 = bbcServices.get("radio1").audioStreams[0].url,
radio4 = bbcServices.get("radio4").audioStreams[0].url;
mainPlayer.add({playlist: [radio1], clear: true})
.then(mainPlayer.play)
.then(function() {
avoidPlayer.add({playlist: [radio4], clear: true});
})
.then(function() {
setTimeout(Avoider.create("radio1").avoid, 5000);
});
res.redirect("./");
}, utils.failedPromiseHandler(logger));
}
}
| var utils = require("radiodan-client").utils,
logger = utils.logger(__filename);
module.exports = routes;
function routes(app, radiodan, bbcServices) {
var avoidPlayer = radiodan.player.get("avoider"),
mainPlayer = radiodan.player.get("main"),
announcePlayer = radiodan.player.get("announcer"),
Avoider = require("./avoider")(
bbcServices, mainPlayer, avoidPlayer
),
settings = require("./settings").create();
app.get("/", index);
app.get("/avoid", avoid);
return app;
function index(req, res) {
settings.get().then(function(settings) {
res.render(
__dirname+"/views/index",
{ settings: JSON.stringify(settings) }
);
}).then(null, utils.failedPromiseHandler(logger));
}
function avoid(req, res) {
bbcServices.ready.then(function() {
var radio1 = bbcServices.cache["radio1"].audioStream[0].url,
radio4 = bbcServices.cache["radio4/fm"].audioStream[0].url;
mainPlayer.add({playlist: [radio1], clear: true})
.then(mainPlayer.play)
.then(function() {
avoidPlayer.add({playlist: [radio4], clear: true});
})
.then(function() {
setTimeout(Avoider.create("radio1").avoid, 5000);
});
res.redirect("./");
}, utils.failedPromiseHandler(logger));
}
}
|
Improve naive bayes unit test. | import unittest
import numpy as np
import Orange
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = Orange.data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 4, (nrows, ncols))
x[:, 0] = 3
y = x[:, ncols // 2].reshape(nrows, 1)
continuous_table = Orange.data.Table(x, y)
table = Orange.data.discretization.DiscretizeTable(continuous_table)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.6)
| import unittest
import numpy as np
from Orange import data
import Orange.classification.naive_bayes as nb
from Orange.evaluation import scoring, testing
class NaiveBayesTest(unittest.TestCase):
def test_NaiveBayes(self):
nrows = 1000
ncols = 10
x = np.random.random_integers(1, 3, (nrows, ncols))
col = np.random.randint(ncols)
y = x[:nrows, col].reshape(nrows, 1) + 100
x1, x2 = np.split(x, 2)
y1, y2 = np.split(y, 2)
t = data.Table(x1, y1)
learn = nb.BayesLearner()
clf = learn(t)
z = clf(x2)
self.assertTrue((z.reshape((-1, 1)) == y2).all())
def test_BayesStorage(self):
nrows = 200
ncols = 10
x = np.random.random_integers(0, 5, (nrows, ncols))
x[:, 0] = np.ones(nrows) * 3
y = x[:, ncols / 2].reshape(nrows, 1)
table = data.Table(x, y)
bayes = nb.BayesStorageLearner()
results = testing.CrossValidation(table, [bayes], k=10)
ca = scoring.CA(results)
self.assertGreater(ca, 0.5)
|
Remove commented out debug print lines | # -*- coding: utf-8 -*-
from helpers import HTTPEventHandler
import looping
import buffer_event
class StatusClient(HTTPEventHandler):
def __init__(self, server, sock, address, request_parser):
HTTPEventHandler.__init__(self, server, sock, address, request_parser,
204, b'No content')
class StreamClient(HTTPEventHandler):
def __init__(self, server, source, sock, address, request_parser, content_type):
HTTPEventHandler.__init__(self, server, sock, address, request_parser,
200, b'OK', {b'Content-Length': None,
b'Content-Type': content_type})
self.source = source
def add_packet(self, packet):
self.output_buffer.add_buffer(packet)
def close(self):
self.server.remove_client(self)
HTTPEventHandler.close(self)
def flush_if_ready(self):
if self.output_buffer.ready:
self.output_buffer.flush()
def handle_event(self, eventmask):
if eventmask & looping.POLLOUT:
self.output_buffer.flush()
else:
print 'Unexpected eventmask %s' % (eventmask)
| # -*- coding: utf-8 -*-
from helpers import HTTPEventHandler
import looping
import buffer_event
class StatusClient(HTTPEventHandler):
def __init__(self, server, sock, address, request_parser):
HTTPEventHandler.__init__(self, server, sock, address, request_parser,
204, b'No content')
class StreamClient(HTTPEventHandler):
def __init__(self, server, source, sock, address, request_parser, content_type):
HTTPEventHandler.__init__(self, server, sock, address, request_parser,
200, b'OK', {b'Content-Length': None,
b'Content-Type': content_type})
self.source = source
def add_packet(self, packet):
self.output_buffer.add_buffer(packet)
def close(self):
self.server.remove_client(self)
HTTPEventHandler.close(self)
def flush_if_ready(self):
# print 'buffer is ready: %s' % (self.output_buffer.ready)
if self.output_buffer.ready:
self.output_buffer.flush()
def handle_event(self, eventmask):
if eventmask & looping.POLLOUT:
# print 'lol I can write, %d items in buffer' % (len(self.output_buffer.buffer_queue))
self.output_buffer.flush()
else:
print 'Unexpected eventmask %s' % (eventmask)
|
Fix bug when starting pmdr multiple times |
var Pomodoro = Backbone.Model.extend({
defaults: {
isStarted: false,
duration: 25 * 60,
remainingSeconds: null
},
initialize: function() {
this.listenTo(this, 'finished', this.finish);
},
start: function(duration){
if (duration) {
this.set('duration', duration);
}
this.set('isStarted', true);
this.set('remainingSeconds', this.get('duration'));
this.trigger('countedDown', this.get('remainingSeconds'));
var that = this;
clearInterval(this._interval);
this._interval = setInterval(function(){
that.set('remainingSeconds', that.get('remainingSeconds') - 1);
var remainingSeconds = that.get('remainingSeconds');
that.trigger('countedDown', remainingSeconds);
if (remainingSeconds <= 0){
that.trigger('finished');
}
}, 1000);
},
finish: function() {
clearInterval(this._interval);
this.stop();
},
stop: function() {
this.set('isStarted', false);
this.set('remainingSeconds', null);
},
onChange: function(callback) {
this.listenTo(this, 'countedDown', callback);
},
onFinish: function(callback) {
this.listenTo(this, 'finished', callback);
}
});
module.exports = Pomodoro;
|
var Pomodoro = Backbone.Model.extend({
defaults: {
isStarted: false,
duration: 25 * 60,
remainingSeconds: null
},
initialize: function() {
this.listenTo(this, 'finished', this.finish);
},
start: function(duration){
if (duration) {
this.set('duration', duration);
}
this.set('isStarted', true);
this.set('remainingSeconds', this.get('duration'));
var that = this;
this._interval = setInterval(function(){
that.set('remainingSeconds', that.get('remainingSeconds') - 1);
var remainingSeconds = that.get('remainingSeconds');
that.trigger('countedDown', remainingSeconds);
if (remainingSeconds === 0){
that.trigger('finished');
}
}, 1000);
},
finish: function() {
clearInterval(this._interval);
this.stop();
},
stop: function() {
this.set('isStarted', false);
this.set('remainingSeconds', null);
},
onChange: function(callback) {
this.listenTo(this, 'countedDown', callback);
},
onFinish: function(callback) {
this.listenTo(this, 'finished', callback);
}
});
module.exports = Pomodoro;
|
Fix PSR-4 fix for Composer deprecation
Composer:
Deprecation Notice: Class Sly\Sly\NotificationPusher\Adapter\ApnsAPI located in ./vendor/sly/notification-pusher/src/Sly/NotificationPusher/Adapter/ApnsAPI.php does not comply with psr-4 autoloading standard. It will not autoload anymore in Composer v2.0. in /vendor/composer/composer/src/Composer/Autoload/ClassMapGenerator.php:185
The namespace just needs to be updated. | <?php
/**
* Created by PhpStorm.
* User: seyfer
* Date: 09.08.17
* Time: 17:03
*/
namespace Sly\NotificationPusher\Adapter;
use Sly\NotificationPusher\Adapter\BaseAdapter;
use Sly\NotificationPusher\Model\PushInterface;
/**
* Class ApnsAPI
* @package Sly\Sly\NotificationPusher\Adapter
*
* todo: implement with edamov/pushok
*/
class ApnsAPI extends BaseAdapter
{
/**
* Push.
*
* @param \Sly\NotificationPusher\Model\PushInterface $push Push
*
* @return \Sly\NotificationPusher\Collection\DeviceCollection
*/
public function push(PushInterface $push)
{
// TODO: Implement push() method.
}
/**
* Supports.
*
* @param string $token Token
*
* @return boolean
*/
public function supports($token)
{
// TODO: Implement supports() method.
}
/**
* Get defined parameters.
*
* @return array
*/
public function getDefinedParameters()
{
// TODO: Implement getDefinedParameters() method.
}
/**
* Get default parameters.
*
* @return array
*/
public function getDefaultParameters()
{
// TODO: Implement getDefaultParameters() method.
}
/**
* Get required parameters.
*
* @return array
*/
public function getRequiredParameters()
{
// TODO: Implement getRequiredParameters() method.
}
}
| <?php
/**
* Created by PhpStorm.
* User: seyfer
* Date: 09.08.17
* Time: 17:03
*/
namespace Sly\Sly\NotificationPusher\Adapter;
use Sly\NotificationPusher\Adapter\BaseAdapter;
use Sly\NotificationPusher\Model\PushInterface;
/**
* Class ApnsAPI
* @package Sly\Sly\NotificationPusher\Adapter
*
* todo: implement with edamov/pushok
*/
class ApnsAPI extends BaseAdapter
{
/**
* Push.
*
* @param \Sly\NotificationPusher\Model\PushInterface $push Push
*
* @return \Sly\NotificationPusher\Collection\DeviceCollection
*/
public function push(PushInterface $push)
{
// TODO: Implement push() method.
}
/**
* Supports.
*
* @param string $token Token
*
* @return boolean
*/
public function supports($token)
{
// TODO: Implement supports() method.
}
/**
* Get defined parameters.
*
* @return array
*/
public function getDefinedParameters()
{
// TODO: Implement getDefinedParameters() method.
}
/**
* Get default parameters.
*
* @return array
*/
public function getDefaultParameters()
{
// TODO: Implement getDefaultParameters() method.
}
/**
* Get required parameters.
*
* @return array
*/
public function getRequiredParameters()
{
// TODO: Implement getRequiredParameters() method.
}
} |
Remove fake_button stuff from js | var bind_sortable = function() {
$('.sortable').sortable({
dropOnEmpty: true,
stop: function(evt, ui) {
var data = $(this).sortable('serialize', {attribute: 'data-sortable'});
$.ajax({
data: data,
type: 'PUT',
dataType: 'json',
url: '/admin/sidebar/sortable',
statusCode: {
200: function(data, textStatus, jqXHR) {
$('#sidebar-config').replaceWith(data.html);
bind_sortable();
},
500: function(jqXHR, textStatus, errorThrown) {
alert('Oups?');
}
}
});
},
});
$('.draggable').draggable({
connectToSortable: '.sortable',
helper: "clone",
revert: "invalid"
});
}
$(document).ready(function() {
bind_sortable();
});
| var bind_sortable = function() {
$('.sortable').sortable({
dropOnEmpty: true,
stop: function(evt, ui) {
var data = $(this).sortable('serialize', {attribute: 'data-sortable'});
$.ajax({
data: data,
type: 'PUT',
dataType: 'json',
url: '/admin/sidebar/sortable',
statusCode: {
200: function(data, textStatus, jqXHR) {
$('#sidebar-config').replaceWith(data.html);
bind_sortable();
},
500: function(jqXHR, textStatus, errorThrown) {
alert('Oups?');
}
}
});
},
});
$('.draggable').draggable({
connectToSortable: '.sortable',
helper: "clone",
revert: "invalid"
});
$('.fake_button').on('ajax:beforeSend', function(e, xhr, settings) {
console.log('BS befr');
settings.data = $(this).parents('.active').find('input').serializeArray();
console.log('BS after');
});
$('.fake_button').on('ajax:after', function(e, xhr, settings) {
console.log('after');
});
}
$(document).ready(function() {
bind_sortable();
});
|
Fix issue where first selection in detail pane after refresh would not be possible |
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
if (!rangy.initialized) rangy.init();
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
var e = rangy.createRange();
e.setStart(range.startContainer, range.startOffset);
e.setEnd(range.endContainer, range.endOffset);
// Move range start to include n more of words
e.moveStart('word', -numberWords);
// Move range end to include n more words
e.moveEnd('word', numberWords);
// Calculate what we just included and send that back
if (splitBeforeAfterOutput) {
var output = rangy.createRange();
output.setStart(e.startContainer, e.startOffset);
output.setEnd(range.startContainer, range.startOffset);
splitBeforeAfterOutput.before = output.text();
output.setStart(range.endContainer, range.endOffset);
output.setEnd(e.endContainer, e.endOffset);
splitBeforeAfterOutput.after = output.text();
}
return e;
}
};
});
|
define([
'rangy',
'rangy-text'
], function(
rangy,
rangyText
) {
return {
expandRangeByWords: function(range, numberWords, splitBeforeAfterOutput) {
if (!rangy.initialized) rangy.init();
var e = rangy.createRange();
e.setStart(range.startContainer, range.startOffset);
e.setEnd(range.endContainer, range.endOffset);
// Move range start to include n more of words
e.moveStart('word', -numberWords);
// Move range end to include n more words
e.moveEnd('word', numberWords);
// Calculate what we just included and send that back
if (splitBeforeAfterOutput) {
var output = rangy.createRange();
output.setStart(e.startContainer, e.startOffset);
output.setEnd(range.startContainer, range.startOffset);
splitBeforeAfterOutput.before = output.text();
output.setStart(range.endContainer, range.endOffset);
output.setEnd(e.endContainer, e.endOffset);
splitBeforeAfterOutput.after = output.text();
}
return e;
}
};
});
|
Save descriptor into field so can start parsing other elkements | package org.realityforge.arez.processor;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import org.realityforge.arez.annotations.Container;
final class ContainerDescriptorParser
{
private ContainerDescriptorParser()
{
}
static ContainerDescriptor parse( @Nonnull final Element element,
@Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils )
throws ArezProcessorException
{
final PackageElement packageElement = elementUtils.getPackageOf( element );
final TypeElement typeElement = (TypeElement) element;
if ( !element.getKind().isClass() )
{
throw new ArezProcessorException( "@Container target must be a class", element );
}
else if ( element.getModifiers().contains( Modifier.ABSTRACT ) )
{
throw new ArezProcessorException( "@Container target must not be abstract", element );
}
else if ( element.getModifiers().contains( Modifier.FINAL ) )
{
throw new ArezProcessorException( "@Container target must not be final", element );
}
final Container container = typeElement.getAnnotation( Container.class );
final String name =
container.name().equals( "<default>" ) ? typeElement.getSimpleName().toString() : container.name();
final ContainerDescriptor descriptor =
new ContainerDescriptor( name, container.singleton(), packageElement, typeElement );
return descriptor;
}
}
| package org.realityforge.arez.processor;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import org.realityforge.arez.annotations.Container;
final class ContainerDescriptorParser
{
private ContainerDescriptorParser()
{
}
static ContainerDescriptor parse( @Nonnull final Element element,
@Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils )
throws ArezProcessorException
{
final PackageElement packageElement = elementUtils.getPackageOf( element );
final TypeElement typeElement = (TypeElement) element;
if ( !element.getKind().isClass() )
{
throw new ArezProcessorException( "@Container target must be a class", element );
}
else if ( element.getModifiers().contains( Modifier.ABSTRACT ) )
{
throw new ArezProcessorException( "@Container target must not be abstract", element );
}
else if ( element.getModifiers().contains( Modifier.FINAL ) )
{
throw new ArezProcessorException( "@Container target must not be final", element );
}
final Container container = typeElement.getAnnotation( Container.class );
final String name =
container.name().equals( "<default>" ) ? typeElement.getSimpleName().toString() : container.name();
return new ContainerDescriptor( name, container.singleton(), packageElement, typeElement );
}
}
|
Fix typo in the script | #!/usr/bin/python
# vim : set fileencoding=utf-8 :
#
# mergeSegToCtm.py
#
# Enhance the CTM file by adding extra fields with the diarisation
# information
#
# First argument is the seg file
# Second argument is the ctm file
#
import sys
with open(sys.argv[1], 'r', encoding='iso-8859-1') as seg:
with open(sys.argv[2], 'r', encoding='iso-8859-1') as ctm:
# For each frame, we will create an entry in a dictionnary
# It will help the lookup later on
# We don't really care about memory issues here, should we?
frames = {}
for line in seg:
values = line.split()
start = int(values[2])
duration = int(values[3])
for i in range(start, start + duration):
frames[i] = values[4], values[5], values[7]
for line in ctm:
values = line.split()
# Use the same start format than in the .seg file
start = int(float(values[2])*100)
print(line.strip(), end="")
if start in frames:
print(" " + frames[start][0] + " " + frames[start][1] + " " + frames[start][2])
else:
print(" N/A N/A N/A")
| #!/usr/bin/python
# vim : set fileencoding=utf-8 :
#
# mergeSegToCtm.py
#
# Enhance the Bck file by adding extra fields with the diarisation
# information
#
import sys
with open(sys.argv[1], 'r', encoding='iso-8859-1') as seg:
with open(sys.argv[2], 'r', encoding='iso-8859-1') as ctm:
# For each frame, we will create an entry in a dictionnary
# It will help the lookup later on
# We don't really care about memory issues here, should we?
frames = {}
for line in seg:
values = line.split()
start = int(values[2])
duration = int(values[3])
for i in range(start, start + duration):
frames[i] = values[4], values[5], values[7]
for line in ctm:
values = line.split()
# Use the same start format than in the .seg file
start = int(float(values[2])*100)
print(line.strip(), end="")
if start in frames:
print(" " + frames[start][0] + " " + frames[start][1] + " " + frames[start][2])
else:
print(" N/A N/A N/A")
|
Use the Github API repo sorting.
The Github API can sort by pushed time, no need to do it manually.
http://developer.github.com/v3/repos/#list-user-repositories
This is both more efficient, Github does the sorting, but it also
fixes a bug. Because the list of results are paginated, if you have
more than a page's worth of repositories it will only sort that page.
This results in a false view of what has been recently pushed.
For a good example, try my github account "schwern" with and
without this patch. | var github = (function(){
function escapeHtml(str) {
return $('<div/>').text(str).html();
}
function render(target, repos){
var i = 0, fragment = '', t = $(target)[0];
for(i = 0; i < repos.length; i++) {
fragment += '<li><a href="'+repos[i].html_url+'">'+repos[i].name+'</a><p>'+escapeHtml(repos[i].description||'')+'</p></li>';
}
t.innerHTML = fragment;
}
return {
showRepos: function(options){
$.ajax({
url: "https://api.github.com/users/"+options.user+"/repos?sort=pushed;callback=?"
, type: 'jsonp'
, error: function (err) { $(options.target + ' li.loading').addClass('error').text("Error loading feed"); }
, success: function(data) {
var repos = [];
if (!data || !data.data) { return; }
for (var i = 0; i < data.data.length; i++) {
if (options.skip_forks && data.data[i].fork) { continue; }
repos.push(data.data[i]);
}
if (options.count) { repos.splice(options.count); }
render(options.target, repos);
}
});
}
};
})();
| var github = (function(){
function escapeHtml(str) {
return $('<div/>').text(str).html();
}
function render(target, repos){
var i = 0, fragment = '', t = $(target)[0];
for(i = 0; i < repos.length; i++) {
fragment += '<li><a href="'+repos[i].html_url+'">'+repos[i].name+'</a><p>'+escapeHtml(repos[i].description||'')+'</p></li>';
}
t.innerHTML = fragment;
}
return {
showRepos: function(options){
$.ajax({
url: "https://api.github.com/users/"+options.user+"/repos?callback=?"
, type: 'jsonp'
, error: function (err) { $(options.target + ' li.loading').addClass('error').text("Error loading feed"); }
, success: function(data) {
var repos = [];
if (!data || !data.data) { return; }
for (var i = 0; i < data.data.length; i++) {
if (options.skip_forks && data.data[i].fork) { continue; }
repos.push(data.data[i]);
}
repos.sort(function(a, b) {
var aDate = new Date(a.pushed_at).valueOf(),
bDate = new Date(b.pushed_at).valueOf();
if (aDate === bDate) { return 0; }
return aDate > bDate ? -1 : 1;
});
if (options.count) { repos.splice(options.count); }
render(options.target, repos);
}
});
}
};
})();
|
Change the logout form the verb GET to the verb POST (and only)
Signed-off-by: Henrique Vicente <[email protected]> | /*global angular */
(function () {
'use strict';
angular.module('auth', ['Facebook', 'config'])
.config(['FacebookProvider', 'config', function (FacebookProvider, config) {
FacebookProvider.init(config.facebook.id);
}])
.factory('userService', function ($http, $window, $rootScope, alert) {
var set = function (user) {
$rootScope.user = user;
};
(function () {
$http({ method: 'GET', url: '/api/me' }).then(
function (user) {
set(user.data);
},
function () {
alert.add('Error in retrieving user data.');
}
);
}());
return {
get: function () {
return $rootScope.user;
},
login: function () {
$window.location.href = '/auth/facebook';
},
logout: function () {
$http({ method: 'POST', url: '/logout' })
.success(function () {
set(undefined);
})
.error(function () {
alert.add('Error in logging out.', true);
});
}
};
});
}());
| /*global angular */
(function () {
'use strict';
angular.module('auth', ['Facebook', 'config'])
.config(['FacebookProvider', 'config', function (FacebookProvider, config) {
FacebookProvider.init(config.facebook.id);
}])
.factory('userService', function ($http, $window, $rootScope, alert) {
var set = function (user) {
$rootScope.user = user;
};
(function () {
$http({ method: 'GET', url: '/api/me' }).then(
function (user) {
set(user.data);
},
function () {
alert.add('Error in retrieving user data.');
}
);
}());
return {
get: function () {
return $rootScope.user;
},
login: function () {
$window.location.href = '/auth/facebook';
},
logout: function () {
$http({ method: 'GET', url: '/logout' })
.success(function () {
set(undefined);
})
.error(function () {
alert.add('Error in logging out.', true);
});
}
};
});
}());
|
DEV: Add long description for upload. | from __future__ import print_function
from setuptools import setup
from os.path import join, dirname, abspath
import sys
long_description = ''
if 'upload' in sys.argv or '--long-description' in sys.argv:
with open('README.rst') as f:
long_description = f.read()
def main():
reqs_file = join(dirname(abspath(__file__)), 'requirements.txt')
with open(reqs_file) as f:
requirements = [req.strip() for req in f.readlines()]
setup(
name='pgcontents',
version='0.2',
description="A Postgres-backed ContentsManager for IPython.",
long_description=long_description,
author="Scott Sanderson",
author_email="[email protected]",
packages=[
'pgcontents',
'pgcontents/alembic',
'pgcontents/alembic/versions',
'pgcontents/tests/',
'pgcontents/utils/',
],
license='Apache 2.0',
include_package_data=True,
zip_safe=False,
url="https://github.com/quantopian/pgcontents",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: IPython',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python',
'Topic :: Database',
],
install_requires=requirements,
scripts=[
'bin/pgcontents',
],
)
if __name__ == '__main__':
main()
| from __future__ import print_function
from setuptools import setup
from os.path import join, dirname, abspath
def main():
reqs_file = join(dirname(abspath(__file__)), 'requirements.txt')
with open(reqs_file) as f:
requirements = [req.strip() for req in f.readlines()]
setup(
name='pgcontents',
version='0.2',
description="A Postgres-backed ContentsManager for IPython.",
author="Scott Sanderson",
author_email="[email protected]",
packages=[
'pgcontents',
'pgcontents/alembic',
'pgcontents/alembic/versions',
'pgcontents/tests/',
'pgcontents/utils/',
],
license='Apache 2.0',
include_package_data=True,
zip_safe=False,
url="https://github.com/quantopian/pgcontents",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: IPython',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python',
'Topic :: Database',
],
install_requires=requirements,
scripts=[
'bin/pgcontents',
],
)
if __name__ == '__main__':
main()
|
Fix event listener test after propagation change | <?php
/*
* Copyright (c)
* Kirill chEbba Chebunin <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*/
namespace Che\EventBand\Tests;
use Che\EventBand\PublishEventListener;
use PHPUnit_Framework_TestCase as TestCase;
use Symfony\Component\EventDispatcher\Event;
/**
* Test for PublishEventListener
*
* @author Kirill chEbba Chebunin <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT
*/
class PublishEventListenerTest extends TestCase
{
/**
* @var \Che\EventBand\EventPublisher|\PHPUnit_Framework_MockObject_MockObject
*/
private $publisher;
protected function setUp()
{
$this->publisher = $this->getMock('Che\EventBand\EventPublisher');
}
/**
* @test __invoke publishes event
*/
public function eventPublish()
{
$listener = new PublishEventListener($this->publisher);
$event = new Event();
$this->publisher
->expects($this->once())
->method('publishEvent')
->with($event);
$listener($event);
}
/**
* @test __invoke stop propagation
*/
public function stopPropagation()
{
$listener = new PublishEventListener($this->publisher, false);
$event = new Event();
$listener($event);
$this->assertTrue($event->isPropagationStopped());
}
}
| <?php
/*
* Copyright (c)
* Kirill chEbba Chebunin <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this package in the file LICENSE.
*/
namespace Che\EventBand\Tests;
use Che\EventBand\PublishEventListener;
use PHPUnit_Framework_TestCase as TestCase;
use Symfony\Component\EventDispatcher\Event;
/**
* Test for PublishEventListener
*
* @author Kirill chEbba Chebunin <[email protected]>
* @license http://opensource.org/licenses/mit-license.php MIT
*/
class PublishEventListenerTest extends TestCase
{
/**
* @var \Che\EventBand\EventPublisher|\PHPUnit_Framework_MockObject_MockObject
*/
private $publisher;
protected function setUp()
{
$this->publisher = $this->getMock('Che\EventBand\EventPublisher');
}
/**
* @test __invoke publishes event
*/
public function eventPublish()
{
$listener = new PublishEventListener($this->publisher);
$event = new Event();
$this->publisher
->expects($this->once())
->method('publishEvent')
->with($event);
$listener($event);
}
/**
* @test __invoke stop propagation
*/
public function stopPropagation()
{
$listener = new PublishEventListener($this->publisher, true);
$event = new Event();
$listener($event);
$this->assertTrue($event->isPropagationStopped());
}
}
|
Remove my dumb logging statement | import React from 'react';
import ReactDom from 'react-dom';
import { Link } from 'react-router';
import _ from 'lodash';
import client from '../../common/store/Contentful';
import marked from 'marked';
import styles from "./style.css";
export default class HomePage extends React.Component {
constructor(props) {
super(props);
var self = this;
this.state = {
fonts: this.props.fontStore.fonts,
content: ''
};
client.getEntries({
'content_type': 'page',
'fields.title': 'Home'
})
.then(function (entries) {
var content = _.get(entries, 'items[0].fields.content');
self.setState({ content });
})
.catch(function(error) {
console.error(error);
});
}
render() {
var fontItems = _.map(this.state.fonts, function(font, index) {
var link = '/karaoke/' + font.name;
return (
<li key={ index } style={{ backgroundColor: font.color }}>
<Link to={ link }>
<p>{ font.name }</p>
</Link>
</li>
);
});
return (
<div id="content">
<ul className={ styles.directory }>
{ fontItems }
</ul>
<div className={ styles['page-content'] } dangerouslySetInnerHTML={{__html: marked(this.state.content)}}>
</div>
</div>
);
}
} | import React from 'react';
import ReactDom from 'react-dom';
import { Link } from 'react-router';
import _ from 'lodash';
import client from '../../common/store/Contentful';
import marked from 'marked';
import styles from "./style.css";
export default class HomePage extends React.Component {
constructor(props) {
super(props);
var self = this;
this.state = {
fonts: this.props.fontStore.fonts,
content: ''
};
client.getEntries({
'content_type': 'page',
'fields.title': 'Home'
})
.then(function (entries) {
var content = _.get(entries, 'items[0].fields.content');
console.log(content)
self.setState({ content });
})
.catch(function(error) {
console.error(error);
});
}
render() {
var fontItems = _.map(this.state.fonts, function(font, index) {
var link = '/karaoke/' + font.name;
return (
<li key={ index } style={{ backgroundColor: font.color }}>
<Link to={ link }>
<p>{ font.name }</p>
</Link>
</li>
);
});
return (
<div id="content">
<ul className={ styles.directory }>
{ fontItems }
</ul>
<div className={ styles['page-content'] } dangerouslySetInnerHTML={{__html: marked(this.state.content)}}>
</div>
</div>
);
}
} |
Support for paginator adaptor < zf 2.4 | <?php
/**
* @author Vanvelthem Sébastien
*/
namespace Soluble\FlexStore\Helper;
use Soluble\FlexStore\Exception;
use Zend\Paginator\Paginator as ZendPaginator;
class Paginator extends ZendPaginator
{
/**
*
* @param integer $totalRows
* @param integer $limit
* @param integer $offset
* @throws Exception\InvalidUsageException
*/
public function __construct($totalRows, $limit, $offset = 0)
{
$totalRows = filter_var($totalRows, FILTER_VALIDATE_INT);
$limit = filter_var($limit, FILTER_VALIDATE_INT);
$offset = filter_var($offset, FILTER_VALIDATE_INT);
if (!is_int($limit) || $limit < 0) {
throw new Exception\InvalidUsageException(__METHOD__ . ' expects limit to be an integer greater than 0');
}
if (!is_int($totalRows) || $totalRows < 0) {
throw new Exception\InvalidUsageException(__METHOD__ . " expects total rows to be an integer greater than 0");
}
if (!is_int($offset) || $offset < 0) {
throw new Exception\InvalidUsageException(__METHOD__ . ' expects offset to be an integer greater than 0');
}
if (class_exists('\Zend\Paginator\Adapter\Null')) {
$adapter = new \Zend\Paginator\Adapter\Null($totalRows);
} else {
$adapter = new \Zend\Paginator\Adapter\NullFill($totalRows);
}
parent::__construct($adapter);
$this->setItemCountPerPage($limit);
$this->setCurrentPageNumber(ceil(($offset + 1) / $limit));
}
}
| <?php
/**
* @author Vanvelthem Sébastien
*/
namespace Soluble\FlexStore\Helper;
use Soluble\FlexStore\Exception;
use Zend\Paginator\Paginator as ZendPaginator;
class Paginator extends ZendPaginator
{
/**
*
* @param integer $totalRows
* @param integer $limit
* @param integer $offset
* @throws Exception\InvalidUsageException
*/
public function __construct($totalRows, $limit, $offset = 0)
{
$totalRows = filter_var($totalRows, FILTER_VALIDATE_INT);
$limit = filter_var($limit, FILTER_VALIDATE_INT);
$offset = filter_var($offset, FILTER_VALIDATE_INT);
if (!is_int($limit) || $limit < 0) {
throw new Exception\InvalidUsageException(__METHOD__ . ' expects limit to be an integer greater than 0');
}
if (!is_int($totalRows) || $totalRows < 0) {
throw new Exception\InvalidUsageException(__METHOD__ . " expects total rows to be an integer greater than 0");
}
if (!is_int($offset) || $offset < 0) {
throw new Exception\InvalidUsageException(__METHOD__ . ' expects offset to be an integer greater than 0');
}
$adapter = new \Zend\Paginator\Adapter\NullFill($totalRows);
parent::__construct($adapter);
$this->setItemCountPerPage($limit);
$this->setCurrentPageNumber(ceil(($offset + 1) / $limit));
}
}
|
Update tests: replace fs with util | var utilPath = require('../../../lib/file/path');
var getRealPkgSrc = require('../../../lib/file/get-real-pkg-src');
var expect = require('expect');
var runtimePath = require('../../util').runtimePath;
describe('Get real paths of the package\'s files', function () {
var optG = {src: runtimePath};
function T(pkg, files) {
var ret = utilPath(optG, pkg);
expect(ret).toEqual(files.map(function (file) {
return runtimePath + file;
}));
if (ret.length) {
expect(pkg.realSrc).toBe(getRealPkgSrc(optG, pkg));
}
}
it('Empty', function () {
T({}, []);
T({files: []}, []);
});
it('Normal use, and that src override name', function () {
T({
name: 'a',
src: '.',
files: [
'a.js',
'b/a.js'
]
}, [
'a.js',
'b/a.js'
]);
});
it('Wildcard', function () {
T({
name: 'b',
files: [
'**/*.js',
'c/*.css'
]
}, [
'b/a.js',
'b/b.js',
'b/c/a.js',
'b/c/a.css'
]);
});
});
| var utilPath = require('../../../lib/file/path');
var getRealPkgSrc = require('../../../lib/file/get-real-pkg-src');
var expect = require('expect');
var fs = require('fs');
describe('Get real paths of the package\'s files', function () {
var optG = {src: './runtime'};
var root = fs.realpathSync(optG.src) + '/';
function T(pkg, files) {
var ret = utilPath(optG, pkg);
expect(ret).toEqual(files.map(function (file) {
return root + file;
}));
if (ret.length) {
expect(pkg.realSrc).toBe(getRealPkgSrc(optG, pkg));
}
}
it('Empty', function () {
T({}, []);
T({files: []}, []);
});
it('Normal use, and that src override name', function () {
T({
name: 'a',
src: '.',
files: [
'a.js',
'b/a.js'
]
}, [
'a.js',
'b/a.js'
]);
});
it('Wildcard', function () {
T({
name: 'b',
files: [
'**/*.js',
'c/*.css'
]
}, [
'b/a.js',
'b/b.js',
'b/c/a.js',
'b/c/a.css'
]);
});
});
|
Remove comments that don't make sense | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo_app(strcat("a,b,c\\n", a, ",2,3"));
""",
'inputs': [{
'id': 'a',
'format': 'json',
'type': 'number'
}],
'swift_args': ['-a=$input{a}'],
'outputs': [{
'id': 'out.csv',
'type': 'table',
'format': 'csv'
}]
}
inputs = {
'a': {
'format': 'number',
'data': 5
}
}
out = romanesco.run(task, inputs=inputs)
self.assertEqual(out, {
'out.csv': {
'data': 'a,b,c\n5,2,3\n',
'format': 'csv'
}
})
| import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo_app(strcat("a,b,c\\n", a, ",2,3"));
""",
'inputs': [{
'id': 'a',
'format': 'json',
'type': 'number'
}],
'swift_args': ['-a=$input{a}'],
'outputs': [{
'id': 'out.csv',
'type': 'table',
'format': 'csv'
}]
}
inputs = {
'a': {
'format': 'number',
'data': 5
}
}
# Use user-specified filename
out = romanesco.run(task, inputs=inputs)
# We bound _stderr as a task output, so it should be in the output
self.assertEqual(out, {
'out.csv': {
'data': 'a,b,c\n5,2,3\n',
'format': 'csv'
}
})
|
Update pycodestyle requirement from <2.4.0,>=2.3.0 to >=2.3.0,<2.6.0
Updates the requirements on [pycodestyle](https://github.com/PyCQA/pycodestyle) to permit the latest version.
- [Release notes](https://github.com/PyCQA/pycodestyle/releases)
- [Changelog](https://github.com/PyCQA/pycodestyle/blob/master/CHANGES.txt)
- [Commits](https://github.com/PyCQA/pycodestyle/compare/2.3.0...2.5.0)
Signed-off-by: dependabot[bot] <[email protected]> | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.1",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >=27.0,<32.0",
],
extras_require = {
"dev": [
"autopep8 == 1.4.0",
"flake8 >=3.5.0,<3.8.0",
"flake8-print",
"pycodestyle >=2.3.0,<2.6.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "OpenFisca-Country-Template",
version = "3.9.1",
author = "OpenFisca Team",
author_email = "[email protected]",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Operating System :: POSIX",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Information Analysis",
],
description = "OpenFisca tax and benefit system for Country-Template",
keywords = "benefit microsimulation social tax",
license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html",
url = "https://github.com/openfisca/country-template",
include_package_data = True, # Will read MANIFEST.in
data_files = [
("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]),
],
install_requires = [
"OpenFisca-Core[web-api] >=27.0,<32.0",
],
extras_require = {
"dev": [
"autopep8 == 1.4.0",
"flake8 >=3.5.0,<3.8.0",
"flake8-print",
"pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake
]
},
packages=find_packages(),
)
|
Implement creating an import record each time a customer imports data | <?php
namespace vr\core\disposable;
use Yii;
use yii\base\BaseObject;
/**
* Class FileBeingUploaded
* @package vr\core\disposable
* @property string filename
*/
class FileBeingUploaded extends BaseObject implements IDisposable
{
/**
* @var
*/
private $_filename;
/**
* @var
*/
private $_handle;
/**
* @param string $content
* @param string|null $extension
* @return self
*/
public static function fromContent(string $content, string $extension = null)
{
$instance = new self();
$instance->generateFileName($extension);
file_put_contents($instance->_filename, $content);
return $instance;
}
/**
* @param $extension
*/
protected function generateFileName($extension)
{
$filename = uniqid(time());
$this->_filename = Yii::getAlias("@runtime/{$filename}.{$extension}");
}
/**
* @param string $mode
* @return resource
*/
public function open($mode = 'r')
{
$this->_handle = fopen($this->_filename, $mode);
return $this->_handle;
}
/**
* @inheritDoc
*/
public function dispose()
{
if ($this->_handle) {
fclose($this->_handle);
}
unlink($this->_filename);
}
/**
* @return mixed
*/
public function getFilename()
{
return $this->_filename;
}
} | <?php
namespace vr\core\disposable;
use Yii;
use yii\base\BaseObject;
/**
* Class FileBeingUploaded
* @package vr\core\disposable
* @property string filename
*/
class FileBeingUploaded extends BaseObject implements IDisposable
{
/**
* @var
*/
private $_filename;
/**
* @var
*/
private $_handle;
/**
* @param string $content
* @param string|null $extension
* @return self
*/
public static function fromContent(string $content, string $extension = null)
{
$instance = new FileBeingUploaded();
$instance->generateFileName($extension);
file_put_contents($instance->_filename, $content);
return $instance;
}
/**
* @param $extension
*/
private function generateFileName($extension)
{
$filename = uniqid(time());
$this->_filename = Yii::getAlias("@runtime/{$filename}.{$extension}");
}
/**
* @param string $mode
* @return resource
*/
public function open($mode = 'r')
{
$this->_handle = fopen($this->_filename, $mode);
return $this->_handle;
}
/**
* @inheritDoc
*/
public function dispose()
{
if ($this->_handle) {
fclose($this->_handle);
}
unlink($this->_filename);
}
/**
* @return mixed
*/
public function getFilename()
{
return $this->_filename;
}
} |
Update Setup command to create the cache dir | <?php
namespace HeyDoc\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SetupCommand extends Command
{
protected function configure()
{
$this
->setName('setup')
->setDescription('Setup project')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->createEmptyDir('docs');
$this->copyFile('docs/settings.yml');
$this->copyFile('docs/index.md');
$this->createEmptyDir('web');
$this->copyFile('web/.htaccess');
$this->copyFile('web/index.php');
$this->createEmptyDir('cache', 0777);
}
private function copyFile($fileName)
{
$fileToCopy = $this->currentDir . DIRECTORY_SEPARATOR . $fileName;
if ($this->fs->exists($fileToCopy)) {
$this->output->writeln(sprintf('>> file already exists <fg=blue>%s</>', $fileName));
return;
}
$sourceDir = realpath(__DIR__.'/../../../HeyDoc/Resources/templates/');
$this->fs->copy($sourceDir . DIRECTORY_SEPARATOR . $fileName, $fileToCopy, false);
$this->output->writeln(sprintf('>> copy file <fg=green>%s</>', $fileName));
}
}
| <?php
namespace HeyDoc\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class SetupCommand extends Command
{
protected function configure()
{
$this
->setName('setup')
->setDescription('Setup project')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->createEmptyDir('docs');
$this->copyFile('docs/settings.yml');
$this->copyFile('docs/index.md');
$this->createEmptyDir('web');
$this->copyFile('web/.htaccess');
$this->copyFile('web/index.php');
}
private function copyFile($fileName)
{
$fileToCopy = $this->currentDir . DIRECTORY_SEPARATOR . $fileName;
if ($this->fs->exists($fileToCopy)) {
$this->output->writeln(sprintf('>> file already exists <fg=blue>%s</>', $fileName));
return;
}
$sourceDir = realpath(__DIR__.'/../../../HeyDoc/Resources/templates/');
$this->fs->copy($sourceDir . DIRECTORY_SEPARATOR . $fileName, $fileToCopy, false);
$this->output->writeln(sprintf('>> copy file <fg=green>%s</>', $fileName));
}
}
|
Remove 1.7.2 and add 1.11/1.12 | <?php
use Illuminate\Database\Seeder;
class MinecraftVersionsSeeder extends Seeder
{
private $versionsByType = [
'PC' => [
5 => '1.7.10',
47 => '1.8',
107 => '1.9',
210 => '1.10',
315 => '1.11',
335 => '1.12',
],
'PE' => [
]
];
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
foreach ($this->versionsByType as $type => $versions) {
foreach ($versions as $protocol_id => $name) {
$exists = DB::table('versions')->where('type', $type)->where('name', $name)->exists();
if (!$exists) {
try {
DB::table('versions')->insert([
'type' => $type,
'protocol_id' => $protocol_id,
'name' => $name,
]);
} catch (\Illuminate\Database\QueryException $e) {
/*
* Ignore duplicate entry exception
*/
if ($e->getCode() != 23000 /* ER_DUP_CODE */) {
throw $e;
}
}
}
}
}
}
}
| <?php
use Illuminate\Database\Seeder;
class MinecraftVersionsSeeder extends Seeder
{
private $versionsByType = [
'PC' => [
4 => '1.7.2',
5 => '1.7.10',
47 => '1.8',
107 => '1.9',
210 => '1.10',
],
'PE' => [
]
];
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
foreach ($this->versionsByType as $type => $versions) {
foreach ($versions as $protocol_id => $name) {
$exists = DB::table('versions')->where('type', $type)->where('name', $name)->exists();
if (!$exists) {
try {
DB::table('versions')->insert([
'type' => $type,
'protocol_id' => $protocol_id,
'name' => $name,
]);
} catch (\Illuminate\Database\QueryException $e) {
/*
* Ignore duplicate entry exception
*/
if ($e->getCode() != 23000 /* ER_DUP_CODE */) {
throw $e;
}
}
}
}
}
}
}
|
Fix so the Subscribe button sends the right podcast ID | $(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var $button = $('.js-subscribe');
$button.click(function() {
$.ajax({
url: '/subscribe/',
data: JSON.stringify({
subscribe: $button.html() === 'Subscribe',
podcast: window.location.pathname.split('/')[2]
}),
contentType: 'application/json',
type: 'POST',
headers: {
'X-CSRFToken': csrftoken
},
success: function(data) {
if (data.status === 'subscribed') {
$button.html('Unsubscribe');
$button.removeClass('btn-primary');
$button.addClass('btn-default');
} else if (data.status === 'unsubscribed') {
$button.html('Subscribe');
$button.removeClass('btn-default');
$button.addClass('btn-primary');
}
}
});
});
}); | $(function() {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var $button = $('.js-subscribe');
$button.click(function() {
$.ajax({
url: '/subscribe/',
data: JSON.stringify({
subscribe: $button.html() === 'Subscribe',
podcast: 1
}),
contentType: 'application/json',
type: 'POST',
headers: {
'X-CSRFToken': csrftoken
},
success: function(data) {
if (data.status === 'subscribed') {
$button.html('Unsubscribe');
$button.removeClass('btn-primary');
$button.addClass('btn-default');
} else if (data.status === 'unsubscribed') {
$button.html('Subscribe');
$button.removeClass('btn-default');
$button.addClass('btn-primary');
}
}
});
});
}); |
Replace breadcrumb data-vocabulary.org microdata with schema.org | <?php
$navItems = $controller->getNavItems(true);
?>
<?php if (count($navItems) > 1): ?>
<nav aria-label="breadcrumb">
<ol class="breadcrumb" itemscope itemtype="http://schema.org/BreadcrumbList">
<?php foreach ($navItems as $i => $ni): ?>
<?php if (!$ni->isCurrent): ?>
<li class="breadcrumb-item" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
<a href="<?php echo $ni->url; ?>" target="<?php echo $ni->target; ?>" itemprop="item">
<span itemprop="name"><?php echo $ni->name; ?></span>
</a>
<meta itemprop="position" content="<?php echo $i + 1; ?>">
</li>
<?php else: ?>
<li class="breadcrumb-item active" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem" aria-current="page">
<span itemprop="name"><?php echo $ni->name; ?></span>
<meta itemprop="position" content="<?php echo $i + 1; ?>">
</li>
<?php endif; ?>
<?php endforeach; ?>
</ol>
</nav>
<?php endif; ?>
| <?php
$navItems = $controller->getNavItems(true);
?>
<?php if (count($navItems) > 1): ?>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<?php foreach ($navItems as $ni): ?>
<?php if (!$ni->isCurrent): ?>
<li class="breadcrumb-item" itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
<a href="<?php echo $ni->url; ?>" target="<?php echo $ni->target; ?>" itemprop="url">
<span itemprop="title"><?php echo $ni->name; ?></span>
</a>
</li>
<?php else: ?>
<li class="breadcrumb-item active" itemscope itemtype="http://data-vocabulary.org/Breadcrumb" aria-current="page">
<span itemprop="title"><?php echo $ni->name; ?></span>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ol>
</nav>
<?php endif; ?>
|
Add extension to DI configuration | <?php
namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('dms_twig_extension');
$rootNode->children()
->arrayNode('fabpot')
->addDefaultsIfNotSet()
->children()
->booleanNode('i18n')->defaultFalse()->end()
->booleanNode('debug')->defaultFalse()->end()
->booleanNode('text')->defaultTrue()->end()
->booleanNode('intl')->defaultTrue()->end()
->end()
->end();
$rootNode->children()
->arrayNode('dms')
->addDefaultsIfNotSet()
->children()
->booleanNode('textual_date')->defaultTrue()->end()
->booleanNode('pad_string')->defaultTrue()->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace DMS\Bundle\TwigExtensionBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('dms_twig_extension');
$rootNode->children()
->arrayNode('fabpot')
->addDefaultsIfNotSet()
->children()
->booleanNode('i18n')->defaultFalse()->end()
->booleanNode('debug')->defaultFalse()->end()
->booleanNode('text')->defaultTrue()->end()
->booleanNode('intl')->defaultTrue()->end()
->end()
->end();
$rootNode->children()
->arrayNode('dms')
->addDefaultsIfNotSet()
->children()
->booleanNode('textual_date')->defaultTrue()->end()
->end()
->end();
return $treeBuilder;
}
}
|
Update to not use newer ES6 function so we can support Node 0.12 | // modules
var assert = require('assert')
var _ = require('underscore')
var fs = require('fs');
var S = require('string');
var passmarked = require('passmarked');
var pluginFunc = require('../lib/rules/lint/prettify');
describe('lint', function(){
describe('#prettify', function(){
// handle the settings
it('Should return a error if the message passed was undefined', function(done){
// handle the stream
pluginFunc(undefined, function(err, content){
// check for a error
if(!err) assert.fail('Was expecting a error for the undefined content');
// done
done();
});
});
// handle the settings
it('Should return a error if the message passed was null', function(done){
// handle the stream
pluginFunc(null, function(err, content){
// check for a error
if(!err) assert.fail('Was expecting a error for the null content');
// done
done();
});
});
// handle the settings
it('Should return a pretified version from our passed in CSS', function(done){
// handle the stream
pluginFunc('.text{color:black;}', function(err, content){
// check for a error
if(err) assert.fail(err);
// check if not empty
if(S(content).isEmpty() == true)
assert.fail('Prettified content was blank')
// should match a cleaned version
if(content.replace(/\s+/gi, '') != '.text{color: black;}'.replace(/\s+/gi, ''))
assert.fail('Did not clean the content correctly.');
// done
done();
});
});
});
});
| // modules
var assert = require('assert')
var _ = require('underscore')
var fs = require('fs');
var S = require('string');
var passmarked = require('passmarked');
var pluginFunc = require('../lib/rules/lint/prettify');
describe('lint', function(){
describe('#prettify', function(){
// handle the settings
it('Should return a error if the message passed was undefined', function(done){
// handle the stream
pluginFunc(undefined, function(err, content){
// check for a error
if(!err) assert.fail('Was expecting a error for the undefined content');
// done
done();
});
});
// handle the settings
it('Should return a error if the message passed was null', function(done){
// handle the stream
pluginFunc(null, function(err, content){
// check for a error
if(!err) assert.fail('Was expecting a error for the null content');
// done
done();
});
});
// handle the settings
it('Should return a pretified version from our passed in CSS', function(done){
// handle the stream
pluginFunc('.text{color:black;}', function(err, content){
// check for a error
if(err) assert.fail(err);
// check if not empty
if(S(content).isEmpty() == true)
assert.fail('Prettified content was blank')
// should match a cleaned version
if(content != `.text
{
color: black;
}`)
assert.fail('Did not clean the content correctly.');
// done
done();
});
});
});
});
|
Refactor to follow style guidelines | import Ember from 'ember';
import ModalMixin from '../mixins/sl-modal';
/**
* @module components
* @class sl-simple-modal
*/
export default Ember.Component.extend( ModalMixin, {
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
// Attributes
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------
// Properties
/**
* Text string for the "accept" button
*
* @property {Ember.String} acceptText
* @default "Accept"
*/
acceptText: 'Accept',
/**
* Text string for the "cancel" button
*
* @property {Ember.String} cancelText
* @default "Cancel"
*/
cancelText: 'Cancel',
/**
* Binding for whether the modal is shown or not
*
* @property {boolean} show
* @default false
*/
show: false,
// -------------------------------------------------------------------------
// Observers
/**
* Observes the `show` value and appropriately shows or hides the modal
*
* @function toggle
* @observes show
* @returns {void}
*/
toggle: function() {
this.$().modal( this.get( 'show' ) ? 'show' : 'hide' );
}.observes( 'show' ),
// -------------------------------------------------------------------------
// Methods
/**
* Custom simple-modal handler for setting the `show` property to false
*
* @function hideHandler
* @returns {void}
*/
hideHandler: function() {
this._super();
this.set( 'show', false );
}
});
| import Ember from 'ember';
import ModalMixin from '../mixins/sl-modal';
/**
* @module components
* @class sl-simple-modal
*/
export default Ember.Component.extend( ModalMixin, {
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
// Attributes
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------
// Properties
/**
* Text string for the "accept" button
*
* @property {string} acceptText
* @default "Accept"
*/
acceptText: 'Accept',
/**
* Text string for the "cancel" button
*
* @property {string} cancelText
* @default "Cancel"
*/
cancelText: 'Cancel',
/**
* Binding for whether the modal is shown or not
*
* @property {boolean} show
* @default false
*/
show: false,
// -------------------------------------------------------------------------
// Observers
/**
* Observes the `show` value and appropriately shows or hides the modal
*
* @function toggle
* @observes show
* @returns {void}
*/
toggle: function() {
this.$().modal( this.get( 'show' ) ? 'show' : 'hide' );
}.observes( 'show' ),
// -------------------------------------------------------------------------
// Methods
/**
* Custom simple-modal handler for setting the `show` property to false
*
* @function hideHandler
* @returns {void}
*/
hideHandler: function() {
this._super();
this.set( 'show', false );
}
});
|
Fix a bug when providing messages for validation rules in Factory class | <?php namespace App\Components\Validation\Sirius;
use App\Components\Validation\FactoryInterface;
use Sirius\Validation\Validator;
/**
* A Sirius Validator factory
*
* @author Benjamin Ulmer
* @link http://github.com/remluben/slim-boilerplate
*/
class SiriusValidatorFactory implements FactoryInterface
{
/**
* @param array $formData
* @param array $rules
* @param array $messages
*
* @return \App\Components\Validation\ValidatorInterface
*/
public function make(array $formData, array $rules, array $messages = array())
{
$validator = new Validator;
foreach($rules as $field => $rules) {
if(!is_array($rules)) {
$rules = array($rules => null);
}
foreach($rules as $key => $value) {
if(is_string($key)) { // real rule name
$rule = $key;
$options = $value;
}
else { // otherwise the key is not the rule name, but the value is. No options specified
$rule = $value;
$options = null;
}
$ruleMessages = isset($messages[$field]) && isset($messages[$field][$rule]) ?
$messages[$field][$rule] : null;
$validator->add($field, $rule, $options, $ruleMessages);
}
}
$validator->validate($formData);
return new SiriusValidatorAdapter($validator);
}
}
| <?php namespace App\Components\Validation\Sirius;
use App\Components\Validation\FactoryInterface;
use Sirius\Validation\Validator;
/**
* A Sirius Validator factory
*
* @author Benjamin Ulmer
* @link http://github.com/remluben/slim-boilerplate
*/
class SiriusValidatorFactory implements FactoryInterface
{
/**
* @param array $formData
* @param array $rules
* @param array $messages
*
* @return \App\Components\Validation\ValidatorInterface
*/
public function make(array $formData, array $rules, array $messages = array())
{
$validator = new Validator;
foreach($rules as $field => $rules) {
if(!is_array($rules)) {
$rules = array($rules => null);
}
foreach($rules as $key => $value) {
if(is_string($key)) { // real rule name
$rule = $key;
$options = $value;
}
else { // otherwise the key is not the rule name, but the value is. No options specified
$rule = $value;
$options = null;
}
$messages = isset($messages[$field]) && isset($messages[$field][$rule]) ?
$messages[$field][$rule] : null;
$validator->add($field, $rule, $options, $messages);
}
}
$validator->validate($formData);
return new SiriusValidatorAdapter($validator);
}
} |
Update for janeway's monkey patch. | from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the journal_code to reverse kwargs if the URL_CONFIG setting is set to 'patch'
"""
if not viewname.startswith('djdt'):
local_request = GlobalRequestMiddleware.get_current_request()
if settings.URL_CONFIG == 'path':
code = local_request.journal.code if local_request.journal else 'press'
if kwargs and not args:
kwargs['journal_code'] = code
else:
kwargs = {'journal_code': code}
# Drop kwargs if user is accessing admin site.
if local_request.path.startswith('/admin/'):
kwargs.pop('journal_code')
# Drop kwargs if we have args (most likely from the template
if args:
kwargs = None
if settings.URL_CONFIG == 'path' and not local_request.path.startswith('/admin/'):
args = tuple([code] + [x for x in args])
else:
args = args
url = django_reverse(viewname, urlconf, args, kwargs, current_app)
# Ensure any unicode characters in the URL are escaped.
return iri_to_uri(url)
| from django.conf import settings
from django.core.urlresolvers import reverse as django_reverse
from django.utils.encoding import iri_to_uri
from core.middleware import GlobalRequestMiddleware
def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
"""
This monkey patch will add the journal_code to reverse kwargs if the URL_CONFIG setting is set to 'patch'
"""
if not viewname.startswith('djdt'):
local_request = GlobalRequestMiddleware.get_current_request()
if settings.URL_CONFIG == 'path':
code = local_request.journal.code if local_request.journal else 'press'
if kwargs and not args:
kwargs['journal_code'] = code
else:
kwargs = {'journal_code': code}
# Drop kwargs if user is accessing admin site.
if local_request.path.startswith('/admin/'):
kwargs.pop('journal_code')
# Drop kwargs if we have args (most likely from the template
if args:
kwargs = None
args = [code] + args
url = django_reverse(viewname, urlconf, args, kwargs, current_app)
# Ensure any unicode characters in the URL are escaped.
return iri_to_uri(url)
|
Add a redirect on successful update of settings. |
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode
from mezzanine.settings.models import Setting
from mezzanine.settings.forms import SettingsForm
class SettingsAdmin(admin.ModelAdmin):
"""
Admin class for settings model. Redirect add/change views to the list
view where a single form is rendered for editing all settings.
"""
def changelist_redirect(self):
app = Setting._meta.app_label
name = Setting.__name__.lower()
changelist_url = reverse("admin:%s_%s_changelist" % (app, name))
return HttpResponseRedirect(changelist_url)
def add_view(self, *args, **kwargs):
return self.changelist_redirect()
def change_view(self, *args, **kwargs):
return self.changelist_redirect()
def changelist_view(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
settings_form = SettingsForm(request.POST or None)
if settings_form.is_valid():
settings_form.save()
return self.changelist_redirect()
extra_context["settings_form"] = settings_form
extra_context["title"] = _("Change %s" %
force_unicode(Setting._meta.verbose_name_plural))
return super(SettingsAdmin, self).changelist_view(request, extra_context)
admin.site.register(Setting, SettingsAdmin)
|
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_unicode
from mezzanine.settings.models import Setting
from mezzanine.settings.forms import SettingsForm
class SettingsAdmin(admin.ModelAdmin):
"""
Admin class for settings model. Redirect add/change views to the list
view where a single form is rendered for editing all settings.
"""
def changelist_redirect(self):
app = Setting._meta.app_label
name = Setting.__name__.lower()
changelist_url = reverse("admin:%s_%s_changelist" % (app, name))
return HttpResponseRedirect(changelist_url)
def add_view(self, *args, **kwargs):
return self.changelist_redirect()
def change_view(self, *args, **kwargs):
return self.changelist_redirect()
def changelist_view(self, request, extra_context=None):
if extra_context is None:
extra_context = {}
settings_form = SettingsForm(request.POST or None)
if settings_form.is_valid():
settings_form.save()
extra_context["settings_form"] = settings_form
extra_context["title"] = _("Change %s" %
force_unicode(Setting._meta.verbose_name_plural))
return super(SettingsAdmin, self).changelist_view(request, extra_context)
admin.site.register(Setting, SettingsAdmin)
|
Allow images in EXTRACTs, etc. | from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive paragraph markers"""
MATCHERS = [paragraph_processor.StarsMatcher(),
paragraph_processor.TableMatcher(),
simple_hierarchy_processor.SimpleHierarchyMatcher(
['NOTE', 'NOTES'], Node.NOTE),
paragraph_processor.HeaderMatcher(),
paragraph_processor.SimpleTagMatcher('P', 'FP'),
us_code.USCodeMatcher(),
paragraph_processor.GraphicsMatcher(),
paragraph_processor.IgnoreTagMatcher('PRTPAGE')]
class FlatsubtreeMatcher(paragraph_processor.BaseMatcher):
"""
Detects tags passed to it on init and processes them with the
FlatParagraphProcessor. Also optionally sets node_type.
"""
def __init__(self, tags, node_type=Node.REGTEXT):
self.tags = list(tags)
self.node_type = node_type
def matches(self, xml):
return xml.tag in self.tags
def derive_nodes(self, xml, processor=None):
processor = FlatParagraphProcessor()
text = (xml.text or '').strip()
node = Node(text=text, node_type=self.node_type,
label=[mtypes.MARKERLESS])
return [processor.process(xml, node)]
| from regparser.tree.depth import markers as mtypes
from regparser.tree.struct import Node
from regparser.tree.xml_parser import (
paragraph_processor, simple_hierarchy_processor, us_code)
class FlatParagraphProcessor(paragraph_processor.ParagraphProcessor):
"""Paragraph Processor which does not try to derive paragraph markers"""
MATCHERS = [paragraph_processor.StarsMatcher(),
paragraph_processor.TableMatcher(),
simple_hierarchy_processor.SimpleHierarchyMatcher(
['NOTE', 'NOTES'], Node.NOTE),
paragraph_processor.HeaderMatcher(),
paragraph_processor.SimpleTagMatcher('P', 'FP'),
us_code.USCodeMatcher(),
paragraph_processor.IgnoreTagMatcher('PRTPAGE')]
class FlatsubtreeMatcher(paragraph_processor.BaseMatcher):
"""
Detects tags passed to it on init and processes them with the
FlatParagraphProcessor. Also optionally sets node_type.
"""
def __init__(self, tags, node_type=Node.REGTEXT):
self.tags = list(tags)
self.node_type = node_type
def matches(self, xml):
return xml.tag in self.tags
def derive_nodes(self, xml, processor=None):
processor = FlatParagraphProcessor()
text = (xml.text or '').strip()
node = Node(text=text, node_type=self.node_type,
label=[mtypes.MARKERLESS])
return [processor.process(xml, node)]
|
Add cors headers to dev server responses | const path = require('path');
module.exports = {
entry: [
path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'),
path.resolve(process.cwd(), 'src/theme/assets/main.js')
],
output: {
publicPath: 'http://localhost:8080/_assets/',
filename: '[name].js',
chunkFilename: '[id].js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader?importLoaders=1&minimize=true',
'postcss-loader'
]
},
{
test: /\.(gif|png|jpe?g|svg)(\?.+)?$/,
use: ['url-loader']
},
{
test: /\.(eot|ttf|woff|woff2)(\?.+)?$/,
use: ['url-loader']
}
]
},
devtool: 'eval',
devServer: {
publicPath: 'http://localhost:8080/_assets/',
headers: {
'Access-Control-Allow-Origin': '*'
}
}
};
| const path = require('path');
module.exports = {
entry: [
path.resolve(process.cwd(), 'src/theme/assets/main-critical.js'),
path.resolve(process.cwd(), 'src/theme/assets/main.js')
],
output: {
publicPath: 'http://localhost:8080/_assets/',
filename: '[name].js',
chunkFilename: '[id].js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader?importLoaders=1&minimize=true',
'postcss-loader'
]
},
{
test: /\.(gif|png|jpe?g|svg)(\?.+)?$/,
use: ['url-loader']
},
{
test: /\.(eot|ttf|woff|woff2)(\?.+)?$/,
use: ['url-loader']
}
]
},
devtool: 'eval',
devServer: {
publicPath: 'http://localhost:8080/_assets/'
}
};
|
Correct config for console environment | <?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'controllerMap' => [
'fixture' => [
'class' => 'yii\console\controllers\FixtureController',
'namespace' => 'common\fixtures',
],
'message' => [
'class' => 'mobilejazz\yii2\cms\console\controllers\ExtendedMessageController'
],
'migrate'=>[
'class'=>'fishvision\migrate\controllers\MigrateController',
'autoDiscover' => true,
'migrationPaths'=>[
'@vendor/yiisoft/yii2/rbac/migrations',
'@vendor/mobilejazz/yii2-mj-cms/src/console/migrations',
'@console/migrations'
]
]
],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
| <?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'controllerMap' => [
'fixture' => [
'class' => 'yii\console\controllers\FixtureController',
'namespace' => 'common\fixtures',
],
'message' => [
'class' => '@mobilejazz\yii2\cms\console\controllers\ExtendedMessageController'
],
'migrate'=>[
'class'=>'fishvision\migrate\controllers\MigrateController',
'autoDiscover' => true,
'migrationPaths'=>[
'@vendor/yiisoft/yii2/rbac/migrations',
'@vendor/mobilejazz/yii2-mj-cms/src/console/migrations',
'@console/migrations'
]
]
],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
|
fix: Correct padding on array aggregations
This was incorrectly building padding based on a single row. | import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)",?')
_param_regexp = re.compile(r"[^\(\),]+")
impl = String
def __init__(self, cols):
self.cols = cols
super().__init__()
def process_result_value(self, value, dialect):
# XXX(dcramer): if the trailing value(s?) of the returning array are NULL, postgres seems to
# not return them, and thus our output array does not match the same length as our column
# selection array
#
# For example if the input is:
# ARRAY_AGG_RESULT(col1, col2)
# And the value of col2 is NULL
# The resulting return value from this query will be:
# ({col1_value},)
elems = self._array_regexp.match(value).group(1)
elems = [e for e in self._chunk_regexp.split(elems) if e]
num_cols = len(self.cols)
padding = (None,) * num_cols
return [
(tuple(self._param_regexp.findall(e)) + padding)[:num_cols] for e in elems
]
def array_agg_row(*arg):
return func.array_agg(func.row(*arg), type_=ArrayOfRecord(arg))
| import re
from sqlalchemy.sql import func
from sqlalchemy.types import String, TypeDecorator
# https://bitbucket.org/zzzeek/sqlalchemy/issues/3729/using-array_agg-around-row-function-does
class ArrayOfRecord(TypeDecorator):
_array_regexp = re.compile(r"^\{(\".+?\")*\}$")
_chunk_regexp = re.compile(r'"(.*?)",?')
_param_regexp = re.compile(r"[^\(\),]+")
impl = String
def __init__(self, cols):
self.cols = cols
super().__init__()
def process_result_value(self, value, dialect):
# XXX(dcramer): if the trailing value(s?) fo t he returning array are NULL, postgres seems to
# not return them, and thus our output array does not match the same length as our column
# selection array
#
# For example if the input is:
# ARRAY_AGG_RESULT(col1, col2)
# And the value of col2 is NULL
# The resulting return value from this query will be:
# ({col1_value},)
elems = self._array_regexp.match(value).group(1)
elems = [e for e in self._chunk_regexp.split(elems) if e]
padding = tuple((len(self.cols) - len(elems)) * (None,))
return [tuple(self._param_regexp.findall(e)) + padding for e in elems]
def array_agg_row(*arg):
return func.array_agg(func.row(*arg), type_=ArrayOfRecord(arg))
|
Change redux dev tool to redux dev tool extension | // Redux
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
// import createLogger from 'redux-logger';
// import Immutable from 'immutable';
import rootReducer from '../reducers';
// const __DEV__ = process.env.NODE_ENV === 'production' ? false : true;
const finalCreateStore = compose(
applyMiddleware(thunk),
window.devToolsExtension || (f => f),
// applyMiddleware(createLogger({
// // Only logs in development mode
// predicate: () => __DEV__,
// // Transform Immutable object to plain json for better debuggin experience
// transformer: (state) => {
// var newState = {};
// for (var i of Object.keys(state)) {
// if (Immutable.Iterable.isIterable(state[i])) {
// newState[i] = state[i].toJS();
// } else {
// newState[i] = state[i];
// }
// };
// return newState;
// }
// }))
)(createStore);
export default function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
};
| // Redux
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import Immutable from 'immutable';
import rootReducer from '../reducers';
const __DEV__ = process.env.NODE_ENV === 'production' ? false : true;
const finalCreateStore = compose(
applyMiddleware(thunk),
applyMiddleware(createLogger({
// Only logs in development mode
predicate: () => __DEV__,
// Transform Immutable object to plain json for better debuggin experience
transformer: (state) => {
var newState = {};
for (var i of Object.keys(state)) {
if (Immutable.Iterable.isIterable(state[i])) {
newState[i] = state[i].toJS();
} else {
newState[i] = state[i];
}
};
return newState;
}
}))
)(createStore);
export default function configureStore(initialState) {
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
};
|
Add period after middle name of users. | <br>
<br>
<div class="row">
<?php foreach ($query as $row): { ?>
<div class="col-lg-5">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object dp img-circle" src="http://placehold.it/700x400" style="width: 100px;height:100px;">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $row['name'];?><small> Admin</small></h4>
<hr style="margin:8px auto">
</div>
</div>
</div>
<?php } ?>
<?php endforeach; ?>
</div>
<div class ="row">
<?php foreach ($query2 as $row): { ?>
<div class="col-lg-5">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object dp img-circle" src="http://placehold.it/700x400" style="width: 100px;height:100px;">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $row['fname'] . " " . $row['mname'] . ". " . $row['lname'];?><small> User</small></h4>
<hr style="margin:8px auto">
</div>
</div>
</div>
<?php } ?>
<?php endforeach; ?>
</div>
| <br>
<br>
<div class="row">
<?php foreach ($query as $row): { ?>
<div class="col-lg-5">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object dp img-circle" src="http://placehold.it/700x400" style="width: 100px;height:100px;">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $row['name'];?><small> Admin</small></h4>
<hr style="margin:8px auto">
</div>
</div>
</div>
<?php } ?>
<?php endforeach; ?>
</div>
<div class ="row">
<?php foreach ($query2 as $row): { ?>
<div class="col-lg-5">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object dp img-circle" src="http://placehold.it/700x400" style="width: 100px;height:100px;">
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $row['fname'] . " " . $row['mname'] . " " . $row['lname'];?><small> User</small></h4>
<hr style="margin:8px auto">
</div>
</div>
</div>
<?php } ?>
<?php endforeach; ?>
</div>
|
Fix bug, set notify_email to always after create portal user | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models
from odoo.tools import email_split
class PortalWizard(models.TransientModel):
_inherit = 'portal.wizard'
class PortalUser(models.TransientModel):
_inherit = 'portal.wizard.user'
@api.multi
def _create_user(self):
"""
Override portal user creation to prevent sending e-mail to new user.
"""
res_users = self.env['res.users'].with_context(
noshortcut=True, no_reset_password=True)
email = email_split(self.email)
if email:
email = email[0]
else:
email = self.partner_id.lastname.lower() + '@cs.local'
values = {
'email': email,
'login': email,
'partner_id': self.partner_id.id,
'groups_id': [(6, 0, [])],
'notify_email': 'none',
}
res = res_users.create(values)
res.notify_email = 'always'
return res
@api.multi
def _send_email(self):
""" Never send invitation e-mails. """
return True
| # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models
from odoo.tools import email_split
class PortalWizard(models.TransientModel):
_inherit = 'portal.wizard'
class PortalUser(models.TransientModel):
_inherit = 'portal.wizard.user'
@api.multi
def _create_user(self):
"""
Override portal user creation to prevent sending e-mail to new user.
"""
res_users = self.env['res.users'].with_context(
noshortcut=True, no_reset_password=True)
email = email_split(self.email)
if email:
email = email[0]
else:
email = self.partner_id.lastname.lower() + '@cs.local'
values = {
'email': email,
'login': email,
'partner_id': self.partner_id.id,
'groups_id': [(6, 0, [])],
'notify_email': 'none',
}
return res_users.create(values)
@api.multi
def _send_email(self):
""" Never send invitation e-mails. """
return True
|
Disable the effects in the config by default | package com.hea3ven.twintails.conf;
import java.io.File;
import java.util.List;
import com.hea3ven.twintails.TwinTailsMod;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class TwinTailsConfig {
public Boolean twinTailsEffects = true;
private Configuration configFile;
public void init(File file) {
configFile = new Configuration(file);
syncWithFile();
}
@SubscribeEvent
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event)
{
if(event.modID.equals(TwinTailsMod.MODID))
syncWithFile();
}
private void syncWithFile() {
twinTailsEffects = configFile.getBoolean(
"TwinTailsEffects",
Configuration.CATEGORY_GENERAL,
false,
"Whether you get effects while wearing twintails or not");
if(configFile.hasChanged())
configFile.save();
}
@SuppressWarnings("rawtypes")
public List getConfigElements(String category) {
return new ConfigElement(configFile.getCategory(category)).getChildElements();
}
public String getPath() {
return configFile.toString();
}
}
| package com.hea3ven.twintails.conf;
import java.io.File;
import java.util.List;
import com.hea3ven.twintails.TwinTailsMod;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class TwinTailsConfig {
public Boolean twinTailsEffects = true;
private Configuration configFile;
public void init(File file) {
configFile = new Configuration(file);
syncWithFile();
}
@SubscribeEvent
public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event)
{
if(event.modID.equals(TwinTailsMod.MODID))
syncWithFile();
}
private void syncWithFile() {
twinTailsEffects = configFile.getBoolean(
"TwinTailsEffects",
Configuration.CATEGORY_GENERAL,
true,
"Whether you get effects while wearing twintails or not");
if(configFile.hasChanged())
configFile.save();
}
@SuppressWarnings("rawtypes")
public List getConfigElements(String category) {
return new ConfigElement(configFile.getCategory(category)).getChildElements();
}
public String getPath() {
return configFile.toString();
}
}
|
Return empty dict if not defined rather than error | import json
import os
import sys
from server_common.ioc_data_source import IocDataSource
from server_common.mysql_abstraction_layer import SQLAbstraction
from server_common.utilities import print_and_log, SEVERITY
def register_ioc_start(ioc_name, pv_database=None, prefix=None):
"""
A helper function to register the start of an ioc.
Args:
ioc_name: name of the ioc to start
pv_database: doctionary of pvs in the iov
prefix: prefix of pvs in this ioc
"""
try:
exepath = sys.argv[0]
if pv_database is None:
pv_database = {}
if prefix is None:
prefix = "none"
ioc_data_source = IocDataSource(SQLAbstraction("iocdb", "iocdb", "$iocdb"))
ioc_data_source.insert_ioc_start(ioc_name, os.getpid(), exepath, pv_database, prefix)
except Exception as e:
print_and_log("Error registering ioc start: {}: {}".format(e.__class__.__name__, e), SEVERITY.MAJOR)
def get_macro_values():
"""
Parse macro environment JSON into dict. To make this work use the icpconfigGetMacros program.
Returns: Macro Key:Value pairs as dict
"""
macros = json.loads(os.environ.get("REFL_MACROS", "{}"))
macros = {key: value for (key, value) in macros.items()}
return macros
| import json
import os
import sys
from server_common.ioc_data_source import IocDataSource
from server_common.mysql_abstraction_layer import SQLAbstraction
from server_common.utilities import print_and_log, SEVERITY
def register_ioc_start(ioc_name, pv_database=None, prefix=None):
"""
A helper function to register the start of an ioc.
Args:
ioc_name: name of the ioc to start
pv_database: doctionary of pvs in the iov
prefix: prefix of pvs in this ioc
"""
try:
exepath = sys.argv[0]
if pv_database is None:
pv_database = {}
if prefix is None:
prefix = "none"
ioc_data_source = IocDataSource(SQLAbstraction("iocdb", "iocdb", "$iocdb"))
ioc_data_source.insert_ioc_start(ioc_name, os.getpid(), exepath, pv_database, prefix)
except Exception as e:
print_and_log("Error registering ioc start: {}: {}".format(e.__class__.__name__, e), SEVERITY.MAJOR)
def get_macro_values():
"""
Parse macro environment JSON into dict. To make this work use the icpconfigGetMacros program.
Returns: Macro Key:Value pairs as dict
"""
macros = json.loads(os.environ.get("REFL_MACROS", ""))
macros = {key: value for (key, value) in macros.items()}
return macros
|
Convert plugin to use Symfony events | <?php
namespace Grav\Plugin;
use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;
class RandomPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents() {
return [
'onAfterInitPlugins' => ['onAfterInitPlugins', 0],
];
}
/**
* Activate plugin if path matches to the configured one.
*/
public function onAfterInitPlugins()
{
/** @var Uri $uri */
$uri = $this->grav['uri'];
$route = $this->config->get('plugins.random.route');
if ($route && $route == $uri->path()) {
$this->enable([
'onAfterGetPage' => ['onAfterGetPage', 0]
]);
}
}
/**
* Display random page.
*/
public function onAfterGetPage()
{
/** @var Taxonomy $taxonomy_map */
$taxonomy_map = $this->grav['taxonomy'];
$filters = (array) $this->config->get('plugins.random.filters');
if (count($filters) > 0) {
$collection = new Collection();
foreach ($filters as $taxonomy => $items) {
if (isset($items)) {
$collection->append($taxonomy_map->findTaxonomy([$taxonomy => $items])->toArray());
}
}
$this->grav['page'] = $collection->random()->current();
}
}
}
| <?php
namespace Grav\Plugin;
use Grav\Common\Page\Collection;
use Grav\Common\Plugin;
use Grav\Common\Registry;
use Grav\Common\Uri;
use Grav\Common\Taxonomy;
class RandomPlugin extends Plugin
{
/**
* @var bool
*/
protected $active = false;
/**
* @var Uri
*/
protected $uri;
/**
* @var array
*/
protected $filters = array();
/**
* Activate plugin if path matches to the configured one.
*/
public function onAfterInitPlugins()
{
$this->uri = Registry::get('Uri');
$route = $this->config->get('plugins.random.route');
if ($route && $route == $this->uri->path()) {
$this->active = true;
}
}
/**
* Display random page.
*/
public function onAfterGetPage()
{
if ($this->active) {
/** @var Taxonomy $taxonomy_map */
$taxonomy_map = Registry::get('Taxonomy');
$filters = (array) $this->config->get('plugins.random.filters');
if (count($filters) > 0) {
$collection = new Collection();
foreach ($filters as $taxonomy => $items) {
if (isset($items)) {
$collection->append($taxonomy_map->findTaxonomy([$taxonomy => $items])->toArray());
}
}
$grav = Registry::get('Grav');
$grav->page = $collection->random()->current();
}
}
}
}
|
Fix site title h1 only for frontpage | <?php
/**
* Site branding & logo
*
* @package air-light
*/
namespace Air_Light;
?>
<div class="site-branding">
<?php if ( is_front_page() ) : ?>
<h1 class="site-title">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<span class="screen-reader-text"><?php bloginfo( 'name' ); ?></span>
<?php include get_theme_file_path( THEME_SETTINGS['logo'] ); ?>
</a>
</h1>
<?php else : ?>
<p class="site-title">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<span class="screen-reader-text"><?php bloginfo( 'name' ); ?></span>
<?php include get_theme_file_path( THEME_SETTINGS['logo'] ); ?>
</a>
</p>
<?php endif;
$description = get_bloginfo( 'description', 'display' );
if ( $description || is_customize_preview() ) : ?>
<p class="site-description screen-reader-text"><?php echo $description; // phpcs:ignore ?></p>
<?php endif; ?>
</div><!-- .site-branding -->
| <?php
/**
* Site branding & logo
*
* @package air-light
*/
namespace Air_Light;
?>
<div class="site-branding">
<?php if ( is_front_page() && is_home() ) : ?>
<h1 class="site-title">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<span class="screen-reader-text"><?php bloginfo( 'name' ); ?></span>
<?php include get_theme_file_path( THEME_SETTINGS['logo'] ); ?>
</a>
</h1>
<?php else : ?>
<p class="site-title">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<span class="screen-reader-text"><?php bloginfo( 'name' ); ?></span>
<?php include get_theme_file_path( THEME_SETTINGS['logo'] ); ?>
</a>
</p>
<?php endif;
$description = get_bloginfo( 'description', 'display' );
if ( $description || is_customize_preview() ) : ?>
<p class="site-description screen-reader-text"><?php echo $description; // phpcs:ignore ?></p>
<?php endif; ?>
</div><!-- .site-branding -->
|
Update ViewConfig generator test to follow new ComponentSchema
Summary:
NOTE: Flow and Jest won't pass on this diff. Sandcastle, should, however, be green on D24236405 (i.e: the tip of this stack).
Changelog: [Internal]
(Note: this ignores all push blocking failures!)
Reviewed By: PeteTheHeat
Differential Revision: D24236504
fbshipit-source-id: 0ca70101a855fb713fa15ed63849b138eb73dc6c | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+react_native
* @flow strict-local
* @format
*/
'use strict';
const fixtures = require('../__test_fixtures__/fixtures.js');
const generator = require('../GenerateViewConfigJs.js');
describe('GenerateViewConfigJs', () => {
Object.keys(fixtures)
.sort()
.forEach(fixtureName => {
const fixture = fixtures[fixtureName];
it(`can generate fixture ${fixtureName}`, () => {
expect(generator.generate(fixtureName, fixture)).toMatchSnapshot();
});
});
it('can generate fixture with a deprecated view config name', () => {
expect(
generator.generate('DEPRECATED_VIEW_CONFIG_NAME', {
modules: {
Component: {
type: 'Component',
components: {
NativeComponentName: {
paperComponentNameDeprecated: 'DeprecatedNativeComponentName',
extendsProps: [
{
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
},
],
events: [],
props: [],
commands: [],
},
},
},
},
}),
).toMatchSnapshot();
});
});
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+react_native
* @flow strict-local
* @format
*/
'use strict';
const fixtures = require('../__test_fixtures__/fixtures.js');
const generator = require('../GenerateViewConfigJs.js');
describe('GenerateViewConfigJs', () => {
Object.keys(fixtures)
.sort()
.forEach(fixtureName => {
const fixture = fixtures[fixtureName];
it(`can generate fixture ${fixtureName}`, () => {
expect(generator.generate(fixtureName, fixture)).toMatchSnapshot();
});
});
it('can generate fixture with a deprecated view config name', () => {
expect(
generator.generate('DEPRECATED_VIEW_CONFIG_NAME', {
modules: {
Component: {
components: {
NativeComponentName: {
paperComponentNameDeprecated: 'DeprecatedNativeComponentName',
extendsProps: [
{
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
},
],
events: [],
props: [],
commands: [],
},
},
},
},
}),
).toMatchSnapshot();
});
});
|
Change unused 'let' to 'const' | export const updateElementInWorkspace = (workspace, payload) => {
const { selectionState } = workspace
if(!selectionState.dragStarted) {
return workspace
}
const { currentMousePosition } = payload
const {
elementId,
startElementPosition,
startMousePosition
} = selectionState
const element = workspace.entities[elementId]
return Object.assign({}, workspace, {
...workspace,
entities: {
...workspace.entities,
[elementId]: {
...element,
position: {
x: startElementPosition.x + currentMousePosition.x - startMousePosition.x,
y: startElementPosition.y + currentMousePosition.y - startMousePosition.y,
}
}
}
})
}
export const addDragStartedToWorkspace = (workspace, payload) => {
const {
elementId,
elementPosition,
mousePosition
} = payload
return setDragStateToWorkspace(
workspace,
{
dragStarted: true,
elementId: elementId,
startElementPosition: elementPosition,
startMousePosition: mousePosition
}
)
}
export const addDragStoppedToWorkspace = (workspace, payload) => {
return setDragStateToWorkspace(
workspace,
{
dragStarted: false
}
)
}
export const setDragStateToWorkspace = (workspace, dragState) => {
return Object.assign({}, workspace, {
...workspace,
selectionState: {
...workspace.selectionState,
...dragState
}
})
}
| export const updateElementInWorkspace = (workspace, payload) => {
const { selectionState } = workspace
if(!selectionState.dragStarted) {
return workspace
}
const { currentMousePosition } = payload
const {
elementId,
startElementPosition,
startMousePosition
} = selectionState
const element = workspace.entities[elementId]
return Object.assign({}, workspace, {
...workspace,
entities: {
...workspace.entities,
[elementId]: {
...element,
position: {
x: startElementPosition.x + currentMousePosition.x - startMousePosition.x,
y: startElementPosition.y + currentMousePosition.y - startMousePosition.y,
}
}
}
})
}
export const addDragStartedToWorkspace = (workspace, payload) => {
let { elementId, elementPosition, mousePosition } = payload
return setDragStateToWorkspace(
workspace,
{
dragStarted: true,
elementId: elementId,
startElementPosition: elementPosition,
startMousePosition: mousePosition
}
)
}
export const addDragStoppedToWorkspace = (workspace, payload) => {
return setDragStateToWorkspace(
workspace,
{
dragStarted: false
}
)
}
export const setDragStateToWorkspace = (workspace, dragState) => {
return Object.assign({}, workspace, {
...workspace,
selectionState: {
...workspace.selectionState,
...dragState
}
})
}
|
Fix encoding of email content | # -*- encoding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from django.conf import settings
def send_text(sender, receiver, subject, body):
msg = MIMEText(body, _charset='utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg["Accept-Language"] = "zh-CN"
msg["Accept-Charset"] = "ISO-8859-1,utf-8"
s = smtplib.SMTP('localhost')
s.sendmail(sender, [receiver], msg.as_string())
s.quit()
def send_invitation(receiver, subject, body):
send_text(
settings.INVITATION_SENDER + '@' + settings.EMAIL_DOMAIN,
receiver,
subject,
body
)
def send_candidate_invitation(receiver, l, r):
send_invitation(
receiver,
u'邀请您接受面试',
u'请点击链接:' + generate_invitation_url(l, r) + u'进入面试房间。'
)
def send_interviewer_invitation(receiver, l, r):
send_invitation(
receiver,
u'邀请您作为主考官参加面试',
u'请点击链接:' + generate_invitation_url(l, r) + u'进入面试房间。'
)
def generate_invitation_url(l, r):
return settings.SITE_URL + '/user/login?l=' + l + '&r=' + r
| # -*- encoding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from django.conf import settings
def send_text(sender, receiver, subject, body):
msg = MIMEText(body, _charset='utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg["Accept-Language"] = "zh-CN"
msg["Accept-Charset"] = "ISO-8859-1,utf-8"
s = smtplib.SMTP('localhost')
s.sendmail(sender, [receiver], msg.as_string())
s.quit()
def send_invitation(receiver, subject, body):
send_text(
settings.INVITATION_SENDER + '@' + settings.EMAIL_DOMAIN,
receiver,
subject,
body
)
def send_candidate_invitation(receiver, l, r):
send_invitation(
receiver,
'邀请您接受面试',
'请点击链接:' + generate_invitation_url(l, r) + '进入面试房间。'
)
def send_interviewer_invitation(receiver, l, r):
send_invitation(
receiver,
'邀请您作为主考官参加面试',
'请点击链接:' + generate_invitation_url(l, r) + '进入面试房间。'
)
def generate_invitation_url(l, r):
return settings.SITE_URL + '/user/login?l=' + l + '&r=' + r
|
Fix wordon filtering when calculating the value | class Letter(object):
_values = {
'#': 0, # Wildcard
'ENIOA': 1,
'SDTR': 2,
'MLKPBG': 3,
'ZVUFJH': 4,
'CW': 5,
'XY': 8,
'Q': 10
}
def __init__(self, letter):
self.letter = letter[-1]
self.wordon = letter[0] == '!'
self.real = letter[-1]
@property
def weight(self):
return self.value + self.wordon * 100
@property
def value(self):
return list(filter(lambda x: self.letter in x[0], self._values.items()))[0][1]
@staticmethod
def from_raw(data):
data = data.split(',')
return list(map(Letter, data))
def __str__(self):
out = self.letter
if self.wordon:
out = '!' + out
if self.letter != self.real:
out += self.real
return out
def __repr__(self):
return "<Letter '{}({})' val '{}'>".format(self.letter, self.real, self.value)
def __eq__(self, other):
assert isinstance(other, Letter)
return self.wordon == other.wordon and self.letter == other.letter | class Letter(object):
_values = {
'#': 0, # Wildcard
'ENIOA': 1,
'SDTR': 2,
'MLKPBG': 3,
'ZVUFJH': 4,
'CW': 5,
'XY': 8,
'Q': 10
}
def __init__(self, letter):
self.letter = letter[-1]
self.wordon = letter[0] == '!'
self.real = letter[-1]
@property
def weight(self):
return self.value + self.wordon * 100
@property
def value(self):
return list(filter(lambda x: self.letter in x[0], self._values.items()))[0][1]
@staticmethod
def from_raw(data):
data = data.split(',')
return list(map(Letter, data))
def __str__(self):
out = self.letter
if self.wordon:
out = '!' + out
if self.letter != self.real:
out += self.real
return out
def __repr__(self):
return "<Letter '{}({})' val '{}'>".format(self.letter, self.real, self.value)
def __cmp__(self, other):
assert isinstance(other, Letter)
return self.wordon == other.wordon and self.letter == other.letter |
Increase timeout for the sake of iPhone tests. | var windowTest = require('./windowTest');
var elmTest = require('./elmTest');
var locationTest = require('./locationTest');
var storageTest = require('./storageTest');
module.exports = function (browser) {
var title =
browser.desiredCapabilities.browserName + "-" +
browser.desiredCapabilities.version + "-" +
browser.desiredCapabilities.platform + " "
browser.desiredCapabilities.build;
describe(title, function () {
this.timeout(900000);
this.slow(4000);
var allPassed = true;
// Before any tests run, initialize the browser.
before(function (done) {
browser.init(function (err) {
if (err) throw err;
done();
});
});
elmTest(browser);
windowTest(browser);
locationTest(browser);
storageTest(browser);
afterEach(function() {
allPassed = allPassed && (this.currentTest.state === 'passed');
});
after(function (done) {
console.log(title + (allPassed ? " PASSED" : " FAILED"));
browser.passed(allPassed, done);
});
});
};
| var windowTest = require('./windowTest');
var elmTest = require('./elmTest');
var locationTest = require('./locationTest');
var storageTest = require('./storageTest');
module.exports = function (browser) {
var title =
browser.desiredCapabilities.browserName + "-" +
browser.desiredCapabilities.version + "-" +
browser.desiredCapabilities.platform + " "
browser.desiredCapabilities.build;
describe(title, function () {
this.timeout(600000);
this.slow(4000);
var allPassed = true;
// Before any tests run, initialize the browser.
before(function (done) {
browser.init(function (err) {
if (err) throw err;
done();
});
});
elmTest(browser);
windowTest(browser);
locationTest(browser);
storageTest(browser);
afterEach(function() {
allPassed = allPassed && (this.currentTest.state === 'passed');
});
after(function (done) {
console.log(title + (allPassed ? " PASSED" : " FAILED"));
browser.passed(allPassed, done);
});
});
};
|
Add size constraint to molecularProfileIds in molecular data endpoint | package org.cbioportal.web.parameter;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Size;
import java.util.List;
import java.io.Serializable;
public class MolecularDataMultipleStudyFilter implements Serializable {
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
private List<SampleMolecularIdentifier> sampleMolecularIdentifiers;
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
private List<String> molecularProfileIds;
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
private List<Integer> entrezGeneIds;
@AssertTrue
private boolean isEitherMolecularProfileIdsOrSampleMolecularIdentifiersPresent() {
return molecularProfileIds != null ^ sampleMolecularIdentifiers != null;
}
public List<SampleMolecularIdentifier> getSampleMolecularIdentifiers() {
return sampleMolecularIdentifiers;
}
public void setSampleMolecularIdentifiers(List<SampleMolecularIdentifier> sampleMolecularIdentifiers) {
this.sampleMolecularIdentifiers = sampleMolecularIdentifiers;
}
public List<String> getMolecularProfileIds() {
return molecularProfileIds;
}
public void setMolecularProfileIds(List<String> molecularProfileIds) {
this.molecularProfileIds = molecularProfileIds;
}
public List<Integer> getEntrezGeneIds() {
return entrezGeneIds;
}
public void setEntrezGeneIds(List<Integer> entrezGeneIds) {
this.entrezGeneIds = entrezGeneIds;
}
}
| package org.cbioportal.web.parameter;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Size;
import java.util.List;
import java.io.Serializable;
public class MolecularDataMultipleStudyFilter implements Serializable {
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
private List<SampleMolecularIdentifier> sampleMolecularIdentifiers;
private List<String> molecularProfileIds;
@Size(min = 1, max = PagingConstants.MAX_PAGE_SIZE)
private List<Integer> entrezGeneIds;
@AssertTrue
private boolean isEitherMolecularProfileIdsOrSampleMolecularIdentifiersPresent() {
return molecularProfileIds != null ^ sampleMolecularIdentifiers != null;
}
public List<SampleMolecularIdentifier> getSampleMolecularIdentifiers() {
return sampleMolecularIdentifiers;
}
public void setSampleMolecularIdentifiers(List<SampleMolecularIdentifier> sampleMolecularIdentifiers) {
this.sampleMolecularIdentifiers = sampleMolecularIdentifiers;
}
public List<String> getMolecularProfileIds() {
return molecularProfileIds;
}
public void setMolecularProfileIds(List<String> molecularProfileIds) {
this.molecularProfileIds = molecularProfileIds;
}
public List<Integer> getEntrezGeneIds() {
return entrezGeneIds;
}
public void setEntrezGeneIds(List<Integer> entrezGeneIds) {
this.entrezGeneIds = entrezGeneIds;
}
}
|
Add missing facebook and google verif codes | """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for the app.
"""
site = get_current_site(request)
return {
'APP': {
'TITLE': _('Carnet du maker - L\'esprit Do It Yourself'),
'TITLE_SHORT': _('Carnet du maker'),
'AUTHOR': 'Fabien Batteix',
'COPYRIGHT': _('TamiaLab 2015'),
'DESCRIPTION': _('L\'esprit du Do It Yourself'),
'TWITTER_USERNAME': 'carnetdumaker',
'GOOGLE_SITE_VERIFICATION_CODE': 't3KwbPbJCHz-enFYH50Hcd8PDN8NWWC9gCMx7uTjhpQ',
'TWITTER_ACCOUNT_ID': '3043075520',
'FACEBOOK_URL': 'https://www.facebook.com/CarnetDuMaker/',
},
'SITE': {
'NAME': site.name,
'DOMAIN': site.domain,
'PROTO': 'https' if request.is_secure() else 'http',
'CURRENT_URL': request.get_full_path(),
}
}
| """
Extra context processors for the CarnetDuMaker app.
"""
from django.contrib.sites.shortcuts import get_current_site
from django.utils.translation import ugettext_lazy as _
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants for the app.
"""
site = get_current_site(request)
return {
'APP': {
'TITLE': _('Carnet du maker - L\'esprit Do It Yourself'),
'TITLE_SHORT': _('Carnet du maker'),
'AUTHOR': 'Fabien Batteix',
'COPYRIGHT': _('TamiaLab 2015'),
'DESCRIPTION': _('L\'esprit du Do It Yourself'),
'TWITTER_USERNAME': 'carnetdumaker',
'GOOGLE_SITE_VERIFICATION_CODE': '', # TODO
'TWITTER_ACCOUNT_ID': '3043075520',
'FACEBOOK_URL': '', # TODO
},
'SITE': {
'NAME': site.name,
'DOMAIN': site.domain,
'PROTO': 'https' if request.is_secure() else 'http',
'CURRENT_URL': request.get_full_path(),
}
}
|
Add span content as content attribute
This allows styles to use it in CSS `.foo[content*=bar]` selectors. | "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "";
var lex = lexer.CeylonLexer(lexer.StringCharacterStream(code));
var cur;
while ((cur = lex.nextToken()) != null) {
if (cur.type.string == "whitespace") {
/*
don’t put whitespace in a span –
this way, styles can use CSS selectors
based on the immediately previous node
without worrying about whitespace
*/
ret += cur.text;
} else {
ret += "<span class=\"";
for (var type in cur.type.__proto__.getT$all()) {
if (type === undefined) break;
ret += type.replace(/.*:/, "");
if (type == "ceylon.lexer.core::TokenType") break;
ret += " ";
}
var escaped = escape(cur.text);
ret += "\" content=\"";
ret += escaped;
ret += "\">";
ret += escaped;
ret += "</span>";
}
}
return ret;
}
| "use strict";
/*
NOT a general purpose escaper! Only valid when *content* of a tag, not within an attribute.
*/
function escape(code) {
return code
.replace("&", "&", "g")
.replace("<", "<", "g")
.replace(">", ">", "g");
}
function lowlight(lang, lexer, code) {
var ret = "";
var lex = lexer.CeylonLexer(lexer.StringCharacterStream(code));
var cur;
while ((cur = lex.nextToken()) != null) {
if (cur.type.string == "whitespace") {
/*
don’t put whitespace in a span –
this way, styles can use CSS selectors
based on the immediately previous node
without worrying about whitespace
*/
ret += cur.text;
} else {
ret += "<span class=\"";
for (var type in cur.type.__proto__.getT$all()) {
if (type === undefined) break;
ret += type.replace(/.*:/, "");
if (type == "ceylon.lexer.core::TokenType") break;
ret += " ";
}
ret += "\">";
ret += escape(cur.text);
ret += "</span>";
}
}
return ret;
}
|
Make admin configuration files overridable. | <?php
namespace Darvin\BotDetectorBundle\DependencyInjection;
use Darvin\BotDetectorBundle\Entity\DetectedBot;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class DarvinBotDetectorExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
// $configuration = new Configuration();
// $config = $this->processConfiguration($configuration, $configs);
//
// $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
//
// foreach ([
// ] as $resource) {
// $loader->load($resource.'.yml');
// }
}
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
if (isset($bundles['DarvinAdminBundle'])) {
$container->prependExtensionConfig('darvin_admin', [
'sections' => [
[
'alias' => 'bot',
'entity' => DetectedBot::DETECTED_BOT_CLASS,
'config' => '@DarvinBotDetectorBundle/Resources/config/admin/detected_bot.yml',
],
],
]);
}
}
}
| <?php
namespace Darvin\BotDetectorBundle\DependencyInjection;
use Darvin\BotDetectorBundle\Entity\DetectedBot;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class DarvinBotDetectorExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
// $configuration = new Configuration();
// $config = $this->processConfiguration($configuration, $configs);
//
// $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
//
// foreach ([
// ] as $resource) {
// $loader->load($resource.'.yml');
// }
}
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
if (isset($bundles['DarvinAdminBundle'])) {
$container->prependExtensionConfig('darvin_admin', [
'sections' => [
[
'alias' => 'bot',
'entity' => DetectedBot::DETECTED_BOT_CLASS,
'config' => __DIR__.'/../Resources/config/admin/detected_bot.yml',
],
],
]);
}
}
}
|
Use StringBuilder instead of StringBuffer. | /*
* Copyright 2007 Open Source Applications Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitedinternet.cosmo.util;
import java.util.Map;
import java.util.Map.Entry;
public class URLQuery {
private Map<String, String[]> parameterMap;
public URLQuery(Map<String, String[]> parameterMap){
this.parameterMap = parameterMap;
}
public String toString(Map<String, String[]> overrideMap){
StringBuilder s = new StringBuilder();
s.append("?");
for (Entry<String, String[]> entry: parameterMap.entrySet()){
String key = entry.getKey();
String[] values = overrideMap.containsKey(key)?
overrideMap.get(key) : parameterMap.get(key);
for (String query: values){
s.append(key);
s.append("=");
s.append(query);
s.append("&");
}
}
return s.substring(0, s.length()-1);
}
}
| /*
* Copyright 2007 Open Source Applications Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitedinternet.cosmo.util;
import java.util.Map;
import java.util.Map.Entry;
public class URLQuery {
private Map<String, String[]> parameterMap;
public URLQuery(Map<String, String[]> parameterMap){
this.parameterMap = parameterMap;
}
public String toString(Map<String, String[]> overrideMap){
StringBuffer s = new StringBuffer();
s.append("?");
for (Entry<String, String[]> entry: parameterMap.entrySet()){
String key = entry.getKey();
String[] values = overrideMap.containsKey(key)?
overrideMap.get(key) : parameterMap.get(key);
for (String query: values){
s.append(key);
s.append("=");
s.append(query);
s.append("&");
}
}
return s.substring(0, s.length()-1);
}
}
|
Fix regexp for theme changes | /*******************************
Default Paths
*******************************/
module.exports = {
base : '',
theme : './src/theme.config',
docs : {
source : '../docs/server/files/release/',
output : '../docs/release/'
},
// files cleaned after install
setupFiles: [
'./src/theme.config.example',
'./semantic.json.example',
'./src/_site'
],
// modified to create configs
templates: {
config : './semantic.json.example',
site : './src/_site',
theme : './src/theme.config.example'
},
regExp: {
themePath: /.*\/themes\/.*?\//mg
},
// folder pathsr
folders: {
config : './',
site : './src/site',
theme : './src/'
},
// file paths
files: {
composer : 'composer.json',
config : './semantic.json',
npm : './package.json',
site : './src/site',
theme : './src/theme.config'
},
// same as semantic.json.example
paths: {
source: {
config : 'src/theme.config',
definitions : 'src/definitions/',
site : 'src/site/',
themes : 'src/themes/'
},
output: {
packaged : 'dist/',
uncompressed : 'dist/components/',
compressed : 'dist/components/',
themes : 'dist/themes/'
},
clean : 'dist/'
}
}; | /*******************************
Default Paths
*******************************/
module.exports = {
base : '',
theme : './src/theme.config',
docs : {
source : '../docs/server/files/release/',
output : '../docs/release/'
},
// files cleaned after install
setupFiles: [
'./src/theme.config.example',
'./semantic.json.example',
'./src/_site'
],
// modified to create configs
templates: {
config : './semantic.json.example',
site : './src/_site',
theme : './src/theme.config.example'
},
regExp: {
themeRoot: /.*\/themes\/.*?\//mg
},
// folder pathsr
folders: {
config : './',
site : './src/site',
theme : './src/'
},
// file paths
files: {
composer : 'composer.json',
config : './semantic.json',
npm : './package.json',
site : './src/site',
theme : './src/theme.config'
},
// same as semantic.json.example
paths: {
source: {
config : 'src/theme.config',
definitions : 'src/definitions/',
site : 'src/site/',
themes : 'src/themes/'
},
output: {
packaged : 'dist/',
uncompressed : 'dist/components/',
compressed : 'dist/components/',
themes : 'dist/themes/'
},
clean : 'dist/'
}
}; |
Use ls instead of test
Older versions of Android do not ship with test, and so pulling
screenshots always fails. This changes the method for testing
the existence of metadata.xml to use ls instead, which is
available on all Android versions. | #!/usr/bin/env python
#
# Copyright (c) 2014-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
from . import common
from .common import get_adb
class SimplePuller:
"""Pulls a given file from the device"""
def __init__(self, adb_args=[]):
self._adb_args = list(adb_args)
def remote_file_exists(self, src):
output = common.check_output(
[get_adb()] + self._adb_args + ["shell",
"ls %s && echo EXISTS || echo DOES_NOT_EXIST" % src])
return "EXISTS" in output
def pull(self, src, dest):
subprocess.check_call(
[get_adb()] + self._adb_args + ["pull", src, dest],
stderr=subprocess.STDOUT)
def get_external_data_dir(self):
output = common.check_output(
[get_adb()] + self._adb_args + ["shell", "echo", "$EXTERNAL_STORAGE"])
return output.strip().split()[-1]
| #!/usr/bin/env python
#
# Copyright (c) 2014-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import subprocess
from . import common
from .common import get_adb
class SimplePuller:
"""Pulls a given file from the device"""
def __init__(self, adb_args=[]):
self._adb_args = list(adb_args)
def remote_file_exists(self, src):
output = common.check_output(
[get_adb()] + self._adb_args + ["shell",
"test -e %s && echo EXISTS || echo DOES_NOT_EXIST" % src])
return "EXISTS" in output
def pull(self, src, dest):
subprocess.check_call(
[get_adb()] + self._adb_args + ["pull", src, dest],
stderr=subprocess.STDOUT)
def get_external_data_dir(self):
output = common.check_output(
[get_adb()] + self._adb_args + ["shell", "echo", "$EXTERNAL_STORAGE"])
return output.strip().split()[-1]
|
Remove declaration of dependency on simplejson | #!/usr/bin/env python
from distutils.core import setup
def readfile(fname):
with open(fname) as f:
content = f.read()
return content
setup(name='sockjs-cyclone',
version='1.0.2',
author='Flavio Grossi',
author_email='[email protected]',
description='SockJS python server for the Cyclone Web Server',
license=readfile('LICENSE'),
long_description=readfile('README.rst'),
keywords=[ 'sockjs',
'cyclone',
'web server',
'websocket'
],
url='http://github.com/flaviogrossi/sockjs-cyclone/',
packages=[ 'sockjs',
'sockjs.cyclone',
'sockjs.cyclone.transports'
],
requires=[ 'twisted (>=12.0)',
'cyclone (>=1.0)'
],
install_requires=[ 'twisted>=12.0',
'cyclone>=1.0-rc8'
],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Framework :: Twisted',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: HTTP Servers',
'Topic :: Software Development :: Libraries :: Python Modules',
)
)
| #!/usr/bin/env python
from distutils.core import setup
def readfile(fname):
with open(fname) as f:
content = f.read()
return content
setup(name='sockjs-cyclone',
version='1.0.2',
author='Flavio Grossi',
author_email='[email protected]',
description='SockJS python server for the Cyclone Web Server',
license=readfile('LICENSE'),
long_description=readfile('README.rst'),
keywords=[ 'sockjs',
'cyclone',
'web server',
'websocket'
],
url='http://github.com/flaviogrossi/sockjs-cyclone/',
packages=[ 'sockjs',
'sockjs.cyclone',
'sockjs.cyclone.transports'
],
requires=[ 'twisted (>=12.0)',
'cyclone (>=1.0)',
'simplejson'
],
install_requires=[ 'twisted>=12.0',
'cyclone>=1.0-rc8',
'simplejson'
],
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Framework :: Twisted',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: HTTP Servers',
'Topic :: Software Development :: Libraries :: Python Modules',
)
)
|
Correct UK and EU Widgets.js URLs | <?php
// Be sure your webserver is configured to never display the contents of this file under any circumstances.
// The secret_key value below should be protected and never shared with anyone.
$amazonpay_config = array(
'merchant_id' => '', // Merchant/SellerID
'access_key' => '', // MWS Access Key
'secret_key' => '', // MWS Secret Key
'client_id' => '', // Login With Amazon Client ID
'region' => 'us', // us, de, uk, jp
'currency_code' => 'USD', // USD, EUR, GBP, JPY
'sandbox' => true); // Use sandbox test mode
function getWidgetsJsURL($config)
{
if ($config['sandbox'])
$sandbox = "sandbox/";
else
$sandbox = "";
switch (strtolower($config['region'])) {
case "us":
return "https://static-na.payments-amazon.com/OffAmazonPayments/us/" . $sandbox . "js/Widgets.js";
break;
case "uk":
return "https://static-eu.payments-amazon.com/OffAmazonPayments/gbp/" . $sandbox . "lpa/js/Widgets.js";
break;
case "jp":
return "https://static-fe.payments-amazon.com/OffAmazonPayments/jp/" . $sandbox . "lpa/js/Widgets.js";
break;
default:
return "https://static-eu.payments-amazon.com/OffAmazonPayments/eur/" . $sandbox . "lpa/js/Widgets.js";
break;
}
}
?>
| <?php
// Be sure your webserver is configured to never display the contents of this file under any circumstances.
// The secret_key value below should be protected and never shared with anyone.
$amazonpay_config = array(
'merchant_id' => '', // Merchant/SellerID
'access_key' => '', // MWS Access Key
'secret_key' => '', // MWS Secret Key
'client_id' => '', // Login With Amazon Client ID
'region' => 'us', // us, de, uk, jp
'currency_code' => 'USD', // USD, EUR, GBP, JPY
'sandbox' => true); // Use sandbox test mode
function getWidgetsJsURL($config)
{
if ($config['sandbox'])
$sandbox = "sandbox/";
else
$sandbox = "";
switch (strtolower($config['region'])) {
case "us":
return "https://static-na.payments-amazon.com/OffAmazonPayments/us/" . $sandbox . "js/Widgets.js";
break;
case "uk":
return "https://static-eu.payments-amazon.com/OffAmazonPayments/uk/" . $sandbox . "lpa/js/Widgets.js";
break;
case "jp":
return "https://static-fe.payments-amazon.com/OffAmazonPayments/jp/" . $sandbox . "lpa/js/Widgets.js";
break;
default:
return "https://static-eu.payments-amazon.com/OffAmazonPayments/de/" . $sandbox . "lpa/js/Widgets.js";
break;
}
}
?>
|
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer. | """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic in (0x00061561, 0x61150600):
return "dbhash"
# Unknown
return ""
| """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic == 0x061561:
return "dbhash"
# Unknown
return ""
|
Fix way of declare method in a object. | const InventoryError = require('../../errors').InventoryError
const models = require('./')
const Payment = models.payments
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('pokemons', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, {
classMethods: {
associate () {
},
getPokemonWithLockForUpdate: (pokemonId, t) =>
Pokemon
.findOne({
where: {
id: pokemonId
},
lock: {
level: t.LOCK.UPDATE,
of: Payment
}
}),
decreasePokemonStock: (pokemon, quantity) =>
Pokemon
.update({
stock: pokemon.stock - quantity
}, {
where: {
id: pokemon.id
}
}),
increasePokemonStock: (pokemon, quantity) =>
Pokemon
.update({
stock: pokemon.stock + quantity
}, {
where: {
id: pokemon.id
}
})
},
instanceMethods: {
checkInventory: (quantity) => {
if (this.stock < quantity) {
throw new InventoryError(this.name, this.stock)
}
}
}
})
return Pokemon
}
| const InventoryError = require('../../errors').InventoryError
const models = require('./')
const Payment = models.payments
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('pokemons', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, {
classMethods: {
associate () {
},
getPokemonWithLockForUpdate: (pokemonId, t) =>
Pokemon
.findOne({
where: {
id: pokemonId
},
lock: {
level: t.LOCK.UPDATE,
of: Payment
}
}),
decreasePokemonStock: (pokemon, quantity) =>
Pokemon
.update({
stock: pokemon.stock - quantity
}, {
where: {
id: pokemon.id
}
}),
increasePokemonStock: (pokemon, quantity) =>
Pokemon
.update({
stock: pokemon.stock + quantity
}, {
where: {
id: pokemon.id
}
})
},
instanceMethods: {
checkInventory (quantity) {
if (this.stock < quantity) {
throw new InventoryError(this.name, this.stock)
}
}
}
})
return Pokemon
}
|
Replace @ with , otherwise there is blank output from ansible-lint | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
cmd = ('ansible-lint', '${args}', '${file}')
regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
defaults = {
'selector': 'source.ansible',
'args': '--nocolor -p',
'--exclude= +': ['.galaxy'],
'-c': '',
'-r': '',
'-R': '',
'-t': '',
'-x': '',
}
inline_overrides = ['c', 'exclude', 'r', 'R', 't', 'x']
| #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provides an interface to ansible-lint."""
# ansbile-lint verison requirements check
version_args = '--version'
version_re = r'(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 3.0.1'
# linter settings
cmd = ('ansible-lint', '${args}', '@')
regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
multiline = False
# ansible-lint does not support column number
word_re = False
line_col_base = (1, 1)
tempfile_suffix = 'yml'
error_stream = util.STREAM_STDOUT
defaults = {
'selector': 'source.ansible',
'args': '--nocolor -p',
'--exclude= +': ['.galaxy'],
'-c': '',
'-r': '',
'-R': '',
'-t': '',
'-x': '',
}
inline_overrides = ['c', 'exclude', 'r', 'R', 't', 'x']
|
Remove int typehint.
Maybe passing parameter like ‘123’… | <?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat\Applications\WeWork\Department;
use EasyWeChat\Kernel\BaseClient;
/**
* This is WeWork Department Client.
*
* @author mingyoung <[email protected]>
*/
class Client extends BaseClient
{
/**
* Create a department.
*
* @param array $data
*
* @return mixed
*/
public function create(array $data)
{
return $this->httpPostJson('department/create', $data);
}
/**
* Update a department.
*
* @param array $data
*
* @return mixed
*/
public function update(array $data)
{
return $this->httpPostJson('department/update', $data);
}
/**
* Delete a department.
*
* @param int $id
*
* @return mixed
*/
public function delete($id)
{
return $this->httpGet('department/delete', compact('id'));
}
/**
* Get department lists.
*
* @param int|null $id
*
* @return mixed
*/
public function lists($id = null)
{
return $this->httpGet('department/list', compact('id'));
}
}
| <?php
/*
* This file is part of the overtrue/wechat.
*
* (c) overtrue <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace EasyWeChat\Applications\WeWork\Department;
use EasyWeChat\Kernel\BaseClient;
/**
* This is WeWork Department Client.
*
* @author mingyoung <[email protected]>
*/
class Client extends BaseClient
{
/**
* Create a department.
*
* @param array $data
*
* @return mixed
*/
public function create(array $data)
{
return $this->httpPostJson('department/create', $data);
}
/**
* Update a department.
*
* @param array $data
*
* @return mixed
*/
public function update(array $data)
{
return $this->httpPostJson('department/update', $data);
}
/**
* Delete a department.
*
* @param int $id
*
* @return mixed
*/
public function delete(int $id)
{
return $this->httpGet('department/delete', compact('id'));
}
/**
* Get department lists.
*
* @param int|null $id
*
* @return mixed
*/
public function lists(int $id = null)
{
return $this->httpGet('department/list', compact('id'));
}
}
|
Add log message if data we can't parse appears
If the datum isn't numeric and doesn't match the 'no data' pattern,
something has gone horribly wrong. | # -*- coding: utf-8 -*-
import string
def sanitise_string(messy_str):
"""Whitelist characters in a string"""
valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
return u''.join(char for char in messy_str if char in valid_chars).strip()
class Service(object):
def __init__(self, numeric_id, detailed_data):
self.numeric_id = numeric_id
self.detailed_data = detailed_data
def attribute_exists(self, key):
return key in self.detailed_data
def get_datum(self, key):
datum = self.handle_bad_data(self.get(key))
return datum
def get(self, key):
return self.detailed_data[key]
def identifier(self):
"""Return a unique identifier for the service"""
return self.get('Slug')
def service_title(self):
return self.get('Name of service')
def abbreviated_department(self):
return self.get('Abbr')
def handle_bad_data(self, datum):
# TODO: Should we be more explicit about non-requested (***) data?
if datum == '' or datum == '-' or datum == '***':
return None
elif not isinstance(datum, (int, long, float, complex)):
# If the value we get from the spreadsheet is not numeric, send
# that to Backdrop as a null data point
print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier())
return None
else:
return datum
| # -*- coding: utf-8 -*-
import string
def sanitise_string(messy_str):
"""Whitelist characters in a string"""
valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits)
return u''.join(char for char in messy_str if char in valid_chars).strip()
class Service(object):
def __init__(self, numeric_id, detailed_data):
self.numeric_id = numeric_id
self.detailed_data = detailed_data
def attribute_exists(self, key):
return key in self.detailed_data
def get_datum(self, key):
datum = self.handle_bad_data(self.get(key))
return datum
def get(self, key):
return self.detailed_data[key]
def identifier(self):
"""Return a unique identifier for the service"""
return self.get('Slug')
def service_title(self):
return self.get('Name of service')
def abbreviated_department(self):
return self.get('Abbr')
def handle_bad_data(self, datum):
# TODO: Should we be more explicit about non-requested (***) data?
if datum == '' or datum == '-' or datum == '***':
return None
elif not isinstance(datum, (int, long, float, complex)):
# If the value we get from the spreadsheet is not numeric, send
# that to Backdrop as a null data point
return None
else:
return datum
|
Move to more appropriate place | <?php
namespace GnuCash\Models\Tests;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit_Framework_TestCase;
abstract class EloquentTestCase extends PHPUnit_Framework_TestCase
{
protected $connection = 'gnucash_book_test';
public function setUp()
{
$this->configureDatabase();
$this->migrateTable();
}
protected function configureDatabase()
{
$db = new DB();
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
], $this->connection);
$db->bootEloquent();
$db->setAsGlobal();
Eloquent::unguard();
}
public function migrateTable()
{
$columns = $this->columns();
DB::schema($this->connection)->create($this->table(), function (Blueprint $table) use ($columns) {
foreach ($columns as $name => $type) {
$table->$type($name);
if (in_array($name, ['id', 'guid'])) {
$table->primary($name);
}
}
});
}
abstract protected function table();
abstract protected function columns();
}
| <?php
namespace GnuCash\Models\Tests;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit_Framework_TestCase;
abstract class EloquentTestCase extends PHPUnit_Framework_TestCase
{
protected $connection = 'gnucash_book_test';
public function setUp()
{
$this->configureDatabase();
$this->migrateTable();
}
protected function configureDatabase()
{
$db = new DB();
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
], $this->connection);
$db->bootEloquent();
$db->setAsGlobal();
}
public function migrateTable()
{
$columns = $this->columns();
DB::schema($this->connection)->create($this->table(), function (Blueprint $table) use ($columns) {
foreach ($columns as $name => $type) {
$table->$type($name);
if (in_array($name, ['id', 'guid'])) {
$table->primary($name);
}
}
});
Eloquent::unguard();
}
abstract protected function table();
abstract protected function columns();
}
|
Set some default connection information to maintain consistency for the dataCollector | <?php
namespace Leezy\PheanstalkBundle;
use Pheanstalk_Pheanstalk;
class ConnectionLocator
{
private $connections;
private $info;
private $default;
public function __construct()
{
$this->connections = array();
}
/**
* @return array
*/
public function getConnections()
{
return $this->connections;
}
/**
* @param string $name
*
* @return \Pheanstalk_Connection $connection
*/
public function getConnection($name = null) {
$name = null !== $name ?: $this->default;
if (array_key_exists($name, $this->connections)) {
return $this->connections[$name];
}
return null;
}
/**
* @return array
*/
public function getConnectionsInfo()
{
return $this->info;
}
/**
* @param string $name
* @param Pheanstalk_Pheanstalk $connection
* @param array $info
*/
public function addConnection($name, Pheanstalk_Pheanstalk $connection, array $info = array())
{
$this->connections[$name] = $connection;
// Gather connection information
$this->info[$name] = array(
'host' => isset($info['host']) ? $info['host'] : null,
'port' => isset($info['port']) ? $info['port'] : null,
'timeout' => isset($info['timeout']) ? $info['timeout'] : null,
'default' => isset($info['default']) ? $info['default'] : false,
'resource' => $connection,
);
// Set the default connection name
if (true === $this->info[$name]['default']) {
$this->default = $name;
}
}
}
| <?php
namespace Leezy\PheanstalkBundle;
use Pheanstalk_Pheanstalk;
class ConnectionLocator
{
private $connections;
private $info;
private $default;
public function __construct()
{
$this->connections = array();
}
/**
* @return array
*/
public function getConnections()
{
return $this->connections;
}
/**
* @param string $name
*
* @return \Pheanstalk_Connection $connection
*/
public function getConnection($name = null) {
$name = null !== $name ?: $this->default;
if (array_key_exists($name, $this->connections)) {
return $this->connections[$name];
}
return null;
}
/**
* @return array
*/
public function getConnectionsInfo()
{
return $this->info;
}
/**
* @param string $name
* @param Pheanstalk_Pheanstalk $connection
* @param array $info
*/
public function addConnection($name, Pheanstalk_Pheanstalk $connection, array $info)
{
$this->connections[$name] = $connection;
$this->info[$name] = array_merge($info, array('resource' => $connection));
if (true === $info['default']) {
$this->default = $name;
}
}
}
|
Add validation event handling for grid binders | define(['override', 'jquery',], function(override, $) {
"use strict";
return function(grid, pluginOptions) {
override(grid, function($super) {
return {
init: function init() {
$super.init.apply(this, arguments);
this.container.on("mousedown", ".pg-rowgroup .pg-row", function(evt) {
var id = $(evt.currentTarget).data('row-id');
grid.selection.selectSingleRow(id);
});
if(pluginOptions.onrowselected) grid.on("rowselected", pluginOptions.onrowselected);
},
selection: {
selectSingleRow: function(id) {
if(this.selectedElements) {
this.selectedElements.removeClass("pg-selected");
}
this.selectedElements = grid.container.find("> .pg-rowgroup > .pg-container > .pg-row[data-row-id='" + id + "']");
this.selectedElements.addClass("pg-selected");
grid.trigger("rowselected", id);
},
selectedId: function() {
if (!this.selectedElements) {
return undefined;
}
return this.selectedElements.data('row-id');
}
}
}
});
};
}); | define(['override', 'jquery',], function(override, $) {
"use strict";
return function(grid, pluginOptions) {
override(grid, function($super) {
return {
init: function init() {
$super.init.apply(this, arguments);
this.container.on("mousedown", ".pg-rowgroup .pg-row", function(evt) {
var id = $(evt.currentTarget).data('row-id');
grid.selection.selectSingleRow(id);
});
if(pluginOptions.onrowselected) grid.on("rowselected", pluginOptions.onrowselected);
},
selection: {
selectSingleRow: function(id) {
if(this.selectedElements) {
this.selectedElements.removeClass("pg-selected");
}
this.selectedElements = grid.container.find("> .pg-rowgroup > .pg-container > .pg-row[data-row-id='" + id + "']");
this.selectedElements.addClass("pg-selected");
grid.trigger("rowselected", id);
}
}
}
});
};
}); |
Add .apply() to inventory loading to refresh ng-repeat | myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
inventoryService.loadInventories()
.then(function(inventories) {
console.log("Loaded stored inventories: ", inventories);
$scope.inventories = inventories;
$scope.apply();
});
$scope.inventory = inventoryService.getInventory($routeParams.id);
$scope.goBack = function() {
$window.history.go(-1);
};
$scope.newInventory = function() {
var inventory = inventoryService.newInventory();
$location.path(`/new/${inventory.id}`);
};
$scope.viewInventory = function(inv) {
// TODO: remove old setCurrentInventory method
// inventoryService.setCurrentInventory(inv);
$location.path('/view');
};
$scope.addInventory = function() {
$scope.inventories.push($scope.inventory);
inventoryService.putInventories($scope.inventories);
};
$scope.editInventory = function(inv) {
// TODO: remove old setCurrentInventory method
// inventoryService.setCurrentInventory(inv);
$location.path('/edit');
};
$scope.newItem = function() {
$location.path('/item/new');
};
$scope.addItem = function() {
$scope.inventory.items.push(item);
inventoryService.putInventories($scope.inventories);
};
});
| myApp.controller('InventoryController', function($scope, $window, $location, $routeParams, inventoryService) {
inventoryService.loadInventories()
.then(function(inventories) {
console.log("Loaded stored inventories: ", inventories);
$scope.inventories = inventories;
});
$scope.inventory = inventoryService.getInventory($routeParams.id);
$scope.goBack = function() {
$window.history.go(-1);
};
$scope.newInventory = function() {
var inventory = inventoryService.newInventory();
$location.path(`/new/${inventory.id}`);
};
$scope.viewInventory = function(inv) {
// TODO: remove old setCurrentInventory method
// inventoryService.setCurrentInventory(inv);
$location.path('/view');
};
$scope.addInventory = function() {
$scope.inventories.push($scope.inventory);
inventoryService.putInventories($scope.inventories);
};
$scope.editInventory = function(inv) {
// TODO: remove old setCurrentInventory method
// inventoryService.setCurrentInventory(inv);
$location.path('/edit');
};
$scope.newItem = function() {
$location.path('/item/new');
};
$scope.addItem = function() {
$scope.inventory.items.push(item);
inventoryService.putInventories($scope.inventories);
};
});
|
Bump version for UDF/blob support | from setuptools import setup
### Add find_packages function, see
# https://wiki.python.org/moin/Distutils/Cookbook/AutoPackageDiscovery
import os
def is_package(path):
return (
os.path.isdir(path) and
os.path.isfile(os.path.join(path, '__init__.py'))
)
def find_packages(path=".", base="", exclude=None):
"""Find all packages in path"""
if not exclude:
exclude = []
packages = {}
for item in os.listdir(path):
dir = os.path.join(path, item)
if is_package(dir) and dir not in exclude:
if base:
module_name = "{base}.{item}".format(base=base,item=item)
else:
module_name = item
packages[module_name] = dir
packages.update(find_packages(dir, module_name))
return packages
###
setup(name='raco',
version='1.3.0',
description='Relational Algebra COmpiler',
author='Bill Howe, Andrew Whitaker, Daniel Halperin',
author_email='[email protected]',
url='https://github.com/uwescience/raco',
packages=find_packages(exclude=['clang']),
package_data={'': ['c_templates/*.template','grappa_templates/*.template']},
install_requires=['networkx', 'ply', 'pyparsing', 'SQLAlchemy', 'jinja2', 'requests', 'requests_toolbelt' ],
scripts=['scripts/myrial']
)
| from setuptools import setup
### Add find_packages function, see
# https://wiki.python.org/moin/Distutils/Cookbook/AutoPackageDiscovery
import os
def is_package(path):
return (
os.path.isdir(path) and
os.path.isfile(os.path.join(path, '__init__.py'))
)
def find_packages(path=".", base="", exclude=None):
"""Find all packages in path"""
if not exclude:
exclude = []
packages = {}
for item in os.listdir(path):
dir = os.path.join(path, item)
if is_package(dir) and dir not in exclude:
if base:
module_name = "{base}.{item}".format(base=base,item=item)
else:
module_name = item
packages[module_name] = dir
packages.update(find_packages(dir, module_name))
return packages
###
setup(name='raco',
version='1.2.0',
description='Relational Algebra COmpiler',
author='Bill Howe, Andrew Whitaker, Daniel Halperin',
author_email='[email protected]',
url='https://github.com/uwescience/raco',
packages=find_packages(exclude=['clang']),
package_data={'': ['c_templates/*.template','grappa_templates/*.template']},
install_requires=['networkx', 'ply', 'pyparsing', 'SQLAlchemy', 'jinja2', 'requests', 'requests_toolbelt' ],
scripts=['scripts/myrial']
)
|
Allow one last call to process before stopping | import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
self.is_stopping = False
def run(self):
while True:
got_task = False
data = None
if self.no_wait:
try:
data = self.queue.get_nowait()
got_task = True
except queue.Empty:
data = None
got_task = False
else:
data = self.queue.get()
got_task = True
if data:
index = 'routine_command'
routine_command = data[index] if index in data else None
if routine_command == 'stop':
self.is_stopping = True
self.process(data)
if got_task:
self.queue.task_done()
if self.is_stopping:
break
def process(self, data):
pass
| import threading
import queue
class Routine(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue = queue.Queue()
self.manager = None
self.no_wait = False
def run(self):
while True:
got_task = False
data = None
if self.no_wait:
try:
data = self.queue.get_nowait()
got_task = True
except queue.Empty:
data = None
got_task = False
else:
data = self.queue.get()
got_task = True
if data:
index = 'routine_command'
routine_command = data[index] if index in data else None
if routine_command == 'stop':
return
self.process(data)
if got_task:
self.queue.task_done()
def process(self, data):
pass
|
Fix Client crash on server | package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
this.animationName = ByteBufUtils.readUTF8String(buf);
long most = buf.readLong();
long least = buf.readLong();
this.uuid = new UUID(most, least);
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
buf.writeLong(this.uuid.getMostSignificantBits());
buf.writeLong(this.uuid.getLeastSignificantBits());
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
}
| package com.leviathanstudio.craftstudio.network;
import java.util.List;
import java.util.UUID;
import com.leviathanstudio.craftstudio.common.animation.IAnimated;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import io.netty.buffer.ByteBuf;
public class CraftStudioBasePacket implements IMessage
{
protected String animationName;
protected UUID uuid;
public CraftStudioBasePacket()
{
}
public CraftStudioBasePacket(String animationNameIn, IAnimated animated)
{
this.animationName = animationNameIn;
this.uuid = animated.getUUID();
}
@Override
public void fromBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
buf.writeLong(this.uuid.getMostSignificantBits());
buf.writeLong(this.uuid.getLeastSignificantBits());
}
@Override
public void toBytes(ByteBuf buf)
{
ByteBufUtils.writeUTF8String(buf, this.animationName);
long most = buf.readLong();
long least = buf.readLong();
this.uuid = new UUID(most, least);
}
public Entity getEntityByUUID(List<Entity> list, UUID uuid)
{
for (Entity e : list)
if (e.getPersistentID().equals(uuid))
return e;
return null;
}
}
|
Add default to max_places in proposal form | # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
class ProposalForm(forms.Form):
title = forms.CharField(
max_length=100, required=True,
)
subtitle = forms.CharField(
required = False,
widget = forms.Textarea,
)
duration = forms.CharField(
max_length=50, required=True,
)
max_places = forms.IntegerField(
min_value = 0, required=True, initial = 0,
)
show_owners = forms.BooleanField(
initial = False, required = False,
)
requires_inscription = forms.BooleanField(
initial = False, required = False,
)
owners = forms.CharField(
required = False,
widget = forms.Textarea,
)
organizers = forms.CharField(
required = False,
widget = forms.Textarea,
)
text = forms.CharField(
required = False,
widget = forms.Textarea,
)
logistics = forms.CharField(
required = False,
widget = forms.Textarea,
)
notes_organization = forms.CharField(
required = False,
widget = forms.Textarea,
)
| # -*- encoding: utf-8 -*-
from django import forms
class ActivitySubscribeForm(forms.Form):
id = forms.IntegerField(
min_value = 0, required=True,
widget = forms.HiddenInput,
)
title = forms.CharField(
max_length=100, required=True,
widget = forms.HiddenInput,
)
class ProposalForm(forms.Form):
title = forms.CharField(
max_length=100, required=True,
)
subtitle = forms.CharField(
required = False,
widget = forms.Textarea,
)
duration = forms.CharField(
max_length=50, required=True,
)
max_places = forms.IntegerField(
min_value = 0, required=True,
)
show_owners = forms.BooleanField(
initial = False, required = False,
)
requires_inscription = forms.BooleanField(
initial = False, required = False,
)
owners = forms.CharField(
required = False,
widget = forms.Textarea,
)
organizers = forms.CharField(
required = False,
widget = forms.Textarea,
)
text = forms.CharField(
required = False,
widget = forms.Textarea,
)
logistics = forms.CharField(
required = False,
widget = forms.Textarea,
)
notes_organization = forms.CharField(
required = False,
widget = forms.Textarea,
)
|
Make query pass and change structure of results | <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Organisms with given ids
*/
class Organisms extends \WebService {
/**
* @param $querydata[ids] array of organism ids
* @returns array of organisms
*/
public function execute($querydata) {
global $db;
$limit = 5;
if(in_array('limit', array_keys($querydata))){
$limit = $querydata['limit'];
}
$search = $querydata['search'];
$query_get_organisms = <<<EOF
SELECT *
FROM organism WHERE organism.genus LIKE '%$search%' LIMIT ?
EOF;
$stm_get_organisms = $db->prepare($query_get_organisms);
$data = array();
$stm_get_organisms->execute(array($limit));
while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) {
$result = array();
$result['organism_id'] = $row['organism_id'];
$result['scientific_name'] = $row['species'];
$result['rank'] = $row['genus'];
$result['common_name'] = $row['common_name'];
if($row["abbreviation"]!=null){
$result['rank']='species';
}
$data[] = $result;
}
return $data;
}
}
?>
| <?php
namespace ajax\listing;
use \PDO as PDO;
/**
* Web Service.
* Returns Organisms with given ids
*/
class Organisms extends \WebService {
/**
* @param $querydata[ids] array of organism ids
* @returns array of organisms
*/
public function execute($querydata) {
global $db;
$limit = 5;
var_dump($querydata);
if(in_array('limit', array_keys($querydata))){
$limit = $querydata['limit'];
}
$search = $querydata['search'];
$query_get_organisms = <<<EOF
SELECT *
FROM organism WHERE organism.genus LIKE '$search' LIMIT ?
EOF;
$stm_get_organisms = $db->prepare($query_get_organisms);
$data = array();
$stm_get_organisms->execute(array($limit));
while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) {
if($row["abbreviation"]==null){
$row['genus']=$row['species'];
$row['species']="unknown";
}
$data[] = $row;
}
return $data;
}
}
?>
|
Add a method to draw a screen space aligned (untextured) quad | package com.rabenauge.gl;
import android.opengl.GLU;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
/*
* A class for various static helper methods.
*/
public class Helper {
// Vertices and texture coordinates for rendering a bitmap in order LR, LL, UL, UR.
private static final float w=1, h=1;
private static final FloatBuffer v=FloatBuffer.allocate(8).put(w).put(h).put(0).put(h).put(0).put(0).put(w).put(0);
public static void drawScreenSpaceQuad(GL10 gl) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluOrtho2D(gl, 0, w, h, 0);
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, v);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, 4);
}
public static void drawScreenSpaceTexture(Texture2D tex) {
tex.makeCurrent();
tex.gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, v);
drawScreenSpaceQuad(tex.gl);
}
public static void toggleState(GL10 gl, int cap, boolean state) {
if (state) {
gl.glEnable(cap);
}
else {
gl.glDisable(cap);
}
}
}
| package com.rabenauge.gl;
import android.opengl.GLU;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
/*
* A class for various static helper methods.
*/
public class Helper {
// Vertices and texture coordinates for rendering a bitmap in order LR, LL, UL, UR.
private static final float w=1, h=1;
private static final FloatBuffer v=FloatBuffer.allocate(8).put(w).put(h).put(0).put(h).put(0).put(0).put(w).put(0);
public static void drawScreenSpaceTexture(Texture2D tex) {
tex.makeCurrent();
tex.gl.glMatrixMode(GL10.GL_PROJECTION);
tex.gl.glLoadIdentity();
GLU.gluOrtho2D(tex.gl, 0, w, h, 0);
tex.gl.glVertexPointer(2, GL10.GL_FLOAT, 0, v);
tex.gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, v);
tex.gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, 4);
}
public static void toggleState(GL10 gl, int cap, boolean state) {
if (state) {
gl.glEnable(cap);
}
else {
gl.glDisable(cap);
}
}
}
|
Add empty results to make Select2 happy | <?
include '../scat.php';
$term= $_REQUEST['term'];
$products= array();
if (!$term) {
die_jsonp([ 'error' => "Need to supply some search terms.",
'results' => [] ]);
}
$products= Model::factory('Product')
->select("product.*")
->select("department.name", "department_name")
->select("department.slug", "department_slug")
->select("brand.name", "brand_name")
->select_expr('(SELECT slug
FROM department AS parent
WHERE department.parent_id = parent.id)',
'parent_slug')
->join('brand', array('product.brand_id', '=', 'brand.id'))
->join('department', array('product.department_id', '=',
'department.id'))
->where_raw('MATCH(product.name, product.description)
AGAINST (? IN NATURAL LANGUAGE MODE)',
array($term))
->where('active', 1)
->find_array();
/* Select2 */
if ($_REQUEST['_type'] == 'query') {
$data= [ 'results' => [], 'pagination' => [ 'more' => false ]];
foreach ($products as $product) {
$data['results'][]= [ 'id' => $product['id'], 'text' => $product['name'] ];
}
echo jsonp($data);
exit;
}
/* Other queries */
echo jsonp($products);
| <?
include '../scat.php';
$term= $_REQUEST['term'];
$products= array();
if (!$term) {
die_jsonp("Need to supply some search terms.");
}
$products= Model::factory('Product')
->select("product.*")
->select("department.name", "department_name")
->select("department.slug", "department_slug")
->select("brand.name", "brand_name")
->select_expr('(SELECT slug
FROM department AS parent
WHERE department.parent_id = parent.id)',
'parent_slug')
->join('brand', array('product.brand_id', '=', 'brand.id'))
->join('department', array('product.department_id', '=',
'department.id'))
->where_raw('MATCH(product.name, product.description)
AGAINST (? IN NATURAL LANGUAGE MODE)',
array($term))
->where('active', 1)
->find_array();
/* Select2 */
if ($_REQUEST['_type'] == 'query') {
$data= [ 'results' => [], 'pagination' => [ 'more' => false ]];
foreach ($products as $product) {
$data['results'][]= [ 'id' => $product['id'], 'text' => $product['name'] ];
}
echo jsonp($data);
exit;
}
/* Other queries */
echo jsonp($products);
|
Move signal ignore to run | from multiprocessing import Process, Value
import os
import config
import servo
import signal
class ServoProcess(Process):
def __init__(self):
print '----> Checking servo driver...'
if not os.path.exists('/dev/servoblaster'):
raise Exception('Servo driver was not found. Is servoblaster loaded?')
else:
print '----> Servo driver loaded'
Process.__init__(self)
self.spoon = servo.Servo(config.SPOON_SERVO_ID)
self.leg = servo.Servo(config.LEG_SERVO_ID)
self.initialized = Value('b', False)
def run(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
print '----> Initiating servo calibration sequence...'
i = config.SERVO_MAX_WIDTH - config.SERVO_MIN_WIDTH
while(i > 0):
self.spoon.decrease_pwm(10)
self.leg.decrease_pwm(10)
i -= 10
print '----> Servo calibration complete'
self.initialized.value = True
while(1):
self.spoon.update()
self.spoon.alter_pwm()
self.leg.update()
self.leg.alter_pwm()
| from multiprocessing import Process, Value
import os
import config
import servo
import signal
class ServoProcess(Process):
def __init__(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
print '----> Checking servo driver...'
if not os.path.exists('/dev/servoblaster'):
raise Exception('Servo driver was not found. Is servoblaster loaded?')
else:
print '----> Servo driver loaded'
Process.__init__(self)
self.spoon = servo.Servo(config.SPOON_SERVO_ID)
self.leg = servo.Servo(config.LEG_SERVO_ID)
self.initialized = Value('b', False)
def run(self):
print '----> Initiating servo calibration sequence...'
i = config.SERVO_MAX_WIDTH - config.SERVO_MIN_WIDTH
while(i > 0):
self.spoon.decrease_pwm(10)
self.leg.decrease_pwm(10)
i -= 10
print '----> Servo calibration complete'
self.initialized.value = True
while(1):
self.spoon.update()
self.spoon.alter_pwm()
self.leg.update()
self.leg.alter_pwm()
|
Make the list of period dynamic | /* global process */
'use strict';
function config() {
var periodFormat = '{0}-{1}';
var firstHandledYear = 2007;
var lastHandledPeriod = 2017;
var currentPeriod = periodFormat.replace('{0}', lastHandledPeriod).replace('{1}', lastHandledPeriod + 1);
var availablesPeriod = [];
for (var i = lastHandledPeriod; i >= firstHandledYear; i--) {
availablesPeriod.push(periodFormat.replace('{0}', i).replace('{1}', i + 1));
}
return {
port: process.env.PORT || 5000,
downloadImages: false,
paths: {
tableData: './data/{0}/{1}/table.json',
scorersData: './data/{0}/{1}/scorers.json',
assistsData: './data/{0}/{1}/assists.json',
resultsData: './data/{0}/{1}/results.json',
tournamentData: './data/{0}/{1}/tournament.json',
groupsData: './data/{0}/{1}/groups.json',
logosData: './data/images/logos/{0}.gif',
flagsData: './data/images/flags/{0}.gif'
},
periods: {
current: currentPeriod,
availables: availablesPeriod
}
};
}
module.exports = config();
| /* global process */
'use strict';
function config() {
return {
port: process.env.PORT || 5000,
downloadImages: false,
paths: {
tableData: './data/{0}/{1}/table.json',
scorersData: './data/{0}/{1}/scorers.json',
assistsData: './data/{0}/{1}/assists.json',
resultsData: './data/{0}/{1}/results.json',
tournamentData: './data/{0}/{1}/tournament.json',
groupsData: './data/{0}/{1}/groups.json',
logosData: './data/images/logos/{0}.gif',
flagsData: './data/images/flags/{0}.gif'
},
periods: {
current: '2017-2018',
availables: [
'2017-2018',
'2016-2017',
'2015-2016',
'2014-2015',
'2013-2014',
'2012-2013',
'2011-2012',
'2010-2011',
'2009-2010',
'2008-2009',
'2007-2008']
}
};
}
module.exports = config(); |
Refactor send_message to remove completion block | from http_client import HttpClient
from models.message import ReceivedMessage
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message):
response, error = self.client.submit_request(
'/me/messages',
'POST',
message.to_json(),
None)
if error is not None:
print 'Error Encountered! Could not send message\n'
print 'Message: %s' % error
return response, error
def set_welcome(self, message, completion):
def _completion(response, error):
if error is not None:
pass
else:
completion(response)
self.client.submit_request(
'/me/thread_settings',
'POST',
message.to_json(),
_completion)
def messages_for_request(self, request):
"""
Handle incoming requests from the webhook
"""
entries = request.json['entry']
messages = []
for entry in entries:
message = {}
for msg in entry['messaging']:
messages.append(ReceivedMessage(msg))
return messages
def message_from_reciept(receipt):
"""
Handle receipts
"""
raise NotImplementedError
| from http_client import HttpClient
from models.message import ReceivedMessage
class Bot():
"""
@brief Facebook messenger bot
"""
def __init__(self, token):
self.api_token = token
self.client = HttpClient(token)
def send_message(self, message, completion):
def _completion(response, error):
if error is not None:
print 'Error Encountered! Could not send message\n'
print 'Message: %s' % error
else:
completion(response)
self.client.submit_request(
'/me/messages',
'POST',
message.to_json(),
_completion)
def set_welcome(self, message, completion):
def _completion(response, error):
if error is not None:
pass
else:
completion(response)
self.client.submit_request(
'/me/thread_settings',
'POST',
message.to_json(),
_completion)
def messages_for_request(self, request):
"""
Handle incoming requests from the webhook
"""
entries = request.json['entry']
messages = []
for entry in entries:
message = {}
for msg in entry['messaging']:
messages.append(ReceivedMessage(msg))
return messages
def message_from_reciept(receipt):
"""
Handle receipts
"""
raise NotImplementedError
|
Remove 1 sec timeout used in testing | <?php
namespace GitlabXMPPHook\XMPP;
use XMPPHP_XMPP as Xmpp;
use GitlabXMPPHook\Exception;
class XMPPClient
{
protected $connection;
public function __construct($scope)
{
if (is_null($scope->host) || is_null($scope->port) || is_null($scope->username) || is_null($scope->password))
throw new Exception\InvalidXMPPOptions("Missing XMPP Settings");
$this->connection = new Xmpp(
$scope->host,
$scope->port,
$scope->username,
$scope->password,
'GitlabXMPPHook-Bot/' . $scope->version,
null, // hostname can be determined from full JID
$printlog = $scope->debug,
$loglevel = \XMPPHP_Log::LEVEL_DEBUG
);
try {
$this->connection->connect();
$this->connection->processUntil('session_start');
$this->connection->presence();
sleep(0.2); // Give a few seconds for the dust to settle. Openfire don't like things happening too fast
} catch (\XMPPHP_Exception $e) {
throw new Exception\FailedConnection($e);
}
}
public function __destruct()
{
$this->connection->disconnect();
}
} | <?php
namespace GitlabXMPPHook\XMPP;
use XMPPHP_XMPP as Xmpp;
use GitlabXMPPHook\Exception;
class XMPPClient
{
protected $connection;
public function __construct($scope)
{
if (is_null($scope->host) || is_null($scope->port) || is_null($scope->username) || is_null($scope->password))
throw new Exception\InvalidXMPPOptions("Missing XMPP Settings");
$this->connection = new Xmpp(
$scope->host,
$scope->port,
$scope->username,
$scope->password,
'GitlabXMPPHook-Bot/' . $scope->version,
null, // hostname can be determined from full JID
$printlog = $scope->debug,
$loglevel = \XMPPHP_Log::LEVEL_DEBUG
);
try {
$this->connection->connect(1);
$this->connection->processUntil('session_start');
$this->connection->presence();
sleep(0.2); // Give a few seconds for the dust to settle. Openfire don't like things happening too fast
} catch (\XMPPHP_Exception $e) {
throw new Exception\FailedConnection($e);
}
}
public function __destruct()
{
$this->connection->disconnect();
}
} |
Add method to get the most appropriate DataView | from restlib2.resources import Resource
from avocado.models import DataContext, DataView
class BaseResource(Resource):
param_defaults = {}
def get_params(self, request):
params = request.GET.copy()
for param, default in self.param_defaults.items():
params.setdefault(param, default)
return params
def get_context(self, request):
params = self.get_params(request)
context = params.get('context')
# Explicit request to not use a context
if context != 'null':
kwargs = {
'archived': False,
}
if hasattr(request, 'user') and request.user.is_authenticated():
kwargs['user'] = request.user
else:
kwargs['session_key'] = request.session.session_key
# Assume it is a primary key and fallback to the sesssion
try:
kwargs['pk'] = int(context)
except (ValueError, TypeError):
kwargs['session'] = True
try:
return DataContext.objects.get(**kwargs)
except DataContext.DoesNotExist:
pass
return DataContext()
def get_view(self, request):
params = self.get_params(request)
view = params.get('view')
# Explicit request to not use a view
if view != 'null':
kwargs = {
'archived': False,
}
if hasattr(request, 'user') and request.user.is_authenticated():
kwargs['user'] = request.user
else:
kwargs['session_key'] = request.session.session_key
# Assume it is a primary key and fallback to the sesssion
try:
kwargs['pk'] = int(view)
except (ValueError, TypeError):
kwargs['session'] = True
try:
return DataView.objects.get(**kwargs)
except DataView.DoesNotExist:
pass
return DataView()
| from restlib2.resources import Resource
from avocado.models import DataContext
class BaseResource(Resource):
param_defaults = {}
def get_params(self, request):
params = request.GET.copy()
for param, default in self.param_defaults.items():
params.setdefault(param, default)
return params
def get_context(self, request):
params = self.get_params(request)
context = params.get('context')
# Explicit request to not use a context
if context != 'null':
kwargs = {
'archived': False,
}
if hasattr(request, 'user') and request.user.is_authenticated():
kwargs['user'] = request.user
else:
kwargs['session_key'] = request.session.session_key
# Assume it is a primary key and fallback to the sesssion
try:
kwargs['pk'] = int(context)
except (ValueError, TypeError):
kwargs['session'] = True
try:
return DataContext.objects.get(**kwargs)
except DataContext.DoesNotExist:
pass
return DataContext()
|
Return the order details URL from email body.
There is currently no Agile API method that will return the order
details for an activity so the URL from the email must be used in
conjunction with a web scraper to get the relevant details. | import requests
from base64 import urlsafe_b64decode
from credentials import label_id, url1, url2
from gmailauth import refresh
# access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:2d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
def get_message(headers, identity):
params = {'id': identity, 'format': 'raw'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
raw = j['raw']
d = urlsafe_b64decode(raw)
p = d.decode()
s = p.find('https')
l = len(p)
print(p[s:l])
print('----------')
return(p[s:l])
# for item in list_messages(headers):
# get_message(headers, item)
| import requests
from credentials import label_id
from gmailauth import refresh
access_token = refresh()
headers = {'Authorization': ('Bearer ' + access_token)}
def list_messages(headers):
params = {'labelIds': label_id, 'q': 'newer_than:3d'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages',
headers=headers, params=params)
j = r.json()
messages = []
if 'messages' in j:
messages.extend(j['messages'])
# return messages
message_ids = []
for item in messages:
message_ids.append(item['id'])
return message_ids
print(list_messages(headers))
def get_message(headers, identity):
params = {'id': identity, format: 'metadata'}
r = requests.get('https://www.googleapis.com/gmail/v1/users/me/messages/id',
headers=headers, params=params)
j = r.json()
print(r.status_code, r.reason)
h = j['payload']
subject = ''
for header in h['headers']:
if header['name'] == 'Subject':
subject = header['value']
break
print(subject)
for item in list_messages(headers):
get_message(headers, item)
# get_message(headers, list_messages(headers))
|
Sort redis restore so that output is consistent | <?php
namespace PHPSW\Command\Redis;
use Knp\Command\Command,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Finder\Finder;
class RestoreCommand extends Command
{
protected function configure()
{
$this->setName('redis:restore-fixtures');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getSilexApplication();
$fixtures = $app['console.project_directory'] . '/fixtures';
$redis = $app['redis'];
foreach (Finder::create()->depth(0)->in($fixtures) as $node) {
$hash = $node->getFilename();
echo $hash . ': ';
if ($node->isDir()) {
foreach (Finder::create()->files()->in($node->getPathname())->sortByName() as $file) {
$key = $file->getFilename();
$redis->hset($hash, $key, $this->parse($file->getContents()));
echo '.';
}
} else {
$redis->set($hash, $this->parse($node->getContents()));
echo '.';
}
echo PHP_EOL;
}
}
protected function parse($value)
{
if (preg_match('#^\{|\[.*\]|\}$#', $value)) {
$value = json_encode(json_decode($value));
}
return $value;
}
}
| <?php
namespace PHPSW\Command\Redis;
use Knp\Command\Command,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Finder\Finder;
class RestoreCommand extends Command
{
protected function configure()
{
$this->setName('redis:restore-fixtures');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$app = $this->getSilexApplication();
$fixtures = $app['console.project_directory'] . '/fixtures';
$redis = $app['redis'];
foreach (Finder::create()->depth(0)->in($fixtures) as $node) {
$hash = $node->getFilename();
echo $hash . ': ';
if ($node->isDir()) {
foreach (Finder::create()->files()->in($node->getPathname()) as $file) {
$key = $file->getFilename();
$redis->hset($hash, $key, $this->parse($file->getContents()));
echo '.';
}
} else {
$redis->set($hash, $this->parse($node->getContents()));
echo '.';
}
echo PHP_EOL;
}
}
protected function parse($value)
{
if (preg_match('#^\{|\[.*\]|\}$#', $value)) {
$value = json_encode(json_decode($value));
}
return $value;
}
}
|
Use LocationChoiceProvider in enikshay location view | from collections import namedtuple
from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider
Report = namedtuple('Report', 'domain')
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
location_choice_provider = LocationChoiceProvider(Report(domain=domain), None)
location_choice_provider.configure({'include_descendants': True})
return JsonResponse(
{
'results': [
{'id': location.value, 'text': location.display}
for location in location_choice_provider.query(query_context)
],
'total': location_choice_provider.query_count(query_context)
}
)
| from django.http.response import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from corehq.apps.domain.decorators import login_and_domain_required
from corehq.apps.locations.models import SQLLocation
from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext
class LocationsView(View):
@method_decorator(login_and_domain_required)
def dispatch(self, *args, **kwargs):
return super(LocationsView, self).dispatch(*args, **kwargs)
def _locations_query(self, domain, query_text):
if query_text:
return SQLLocation.active_objects.filter_path_by_user_input(
domain=domain, user_input=query_text)
else:
return SQLLocation.active_objects.filter(domain=domain)
def query(self, domain, query_context):
locations = self._locations_query(domain, query_context.query).order_by('name')
return [
{'id': loc.location_id, 'text': loc.display_name}
for loc in locations[query_context.offset:query_context.offset + query_context.limit]
]
def query_count(self, domain, query):
return self._locations_query(domain, query).count()
def get(self, request, domain, *args, **kwargs):
query_context = ChoiceQueryContext(
query=request.GET.get('q', None),
limit=int(request.GET.get('limit', 20)),
page=int(request.GET.get('page', 1)) - 1
)
return JsonResponse(
{
'results': self.query(domain, query_context),
'total': self.query_count(domain, query_context)
}
)
|
Rename one test so it actually gets run. | import os
import morepath
from webtest import TestApp as Client
import pytest
from .fixtures import template
def setup_module(module):
morepath.disable_implicit()
def test_template_fixture():
config = morepath.setup()
config.scan(template)
config.commit()
c = Client(template.App())
response = c.get('/world')
assert response.body == b'<p>Hello world!</p>\n'
def test_template_inline():
config = morepath.setup()
class App(morepath.App):
testing_config = config
@App.path(path='{name}')
class Person(object):
def __init__(self, name):
self.name = name
@App.template_engine(extension='.format')
def get_format_render(path, original_render, settings):
with open(path, 'rb') as f:
template = f.read()
def render(content, request):
return original_render(template.format(**content), request)
return render
# relative paths don't work inside a test, only in a real
# fixture
full_template_path = os.path.join(os.path.dirname(__file__),
'templates/person.format')
@App.html(model=Person, template=full_template_path)
def person_default(self, request):
return { 'name': self.name }
config.commit()
c = Client(App())
response = c.get('/world')
assert response.body == b'<p>Hello world!</p>\n'
| import os
import morepath
from webtest import TestApp as Client
import pytest
from .fixtures import template
def setup_module(module):
morepath.disable_implicit()
def test_template():
config = morepath.setup()
config.scan(template)
config.commit()
c = Client(template.App())
response = c.get('/world')
assert response.body == b'<p>Hello world!</p>\n'
def test_template():
config = morepath.setup()
class App(morepath.App):
testing_config = config
@App.path(path='{name}')
class Person(object):
def __init__(self, name):
self.name = name
@App.template_engine(extension='.format')
def get_format_render(path, original_render, settings):
with open(path, 'rb') as f:
template = f.read()
def render(content, request):
return original_render(template.format(**content), request)
return render
# relative paths don't work inside a test, only in a real
# fixture
full_template_path = os.path.join(os.path.dirname(__file__),
'templates/person.format')
@App.html(model=Person, template=full_template_path)
def person_default(self, request):
return { 'name': self.name }
config.commit()
c = Client(App())
response = c.get('/world')
assert response.body == b'<p>Hello world!</p>\n'
|
Use highlighted taxonomies instead of top level taxonomies | import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
// store: Ember.inject.service(),
theme: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
.query('highlightedTaxonomies', {
page: {
size: 20
}
})
),
brandedProviders: this
.store
.findAll('preprint-provider', { reload: true })
.then(result => result
.filter(item => item.id !== 'osf')
)
});
},
actions: {
search(q) {
let route = 'discover';
if (this.get('theme.isSubRoute'))
route = `provider.${route}`;
this.transitionTo(route, { queryParams: { q: q } });
}
}
});
| import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from 'ember-osf/mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* Loads all disciplines and preprint providers to the index page
* @class Index Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
// store: Ember.inject.service(),
theme: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
taxonomies: this.get('theme.provider')
.then(provider => provider
.query('taxonomies', {
filter: {
parents: 'null'
},
page: {
size: 20
}
})
),
brandedProviders: this
.store
.findAll('preprint-provider', { reload: true })
.then(result => result
.filter(item => item.id !== 'osf')
)
});
},
actions: {
search(q) {
let route = 'discover';
if (this.get('theme.isSubRoute'))
route = `provider.${route}`;
this.transitionTo(route, { queryParams: { q: q } });
}
}
});
|
Fix coverage to cover all files | module.exports = function (config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
// Angular libraries
'lib/angular.js',
'lib/angular-mocks.js',
// Application files
'js/app.js',
'js/services/*.js',
// Test files
'tests/specs/*.js'
],
preprocessors: {
'js/**/*.js': ['coverage']
},
coverageReporter: {
reporters: [
{type: 'cobertura', dir: 'tests/coverage/cobertura'},
{type: 'html', dir: 'tests/coverage/html'}
]
},
reporters: ['dots', 'coverage', 'junit'],
junitReporter: {
outputFile: 'tests/results/junit-result.xml'
},
port: 9876,
runnerPort: 9910,
color: true,
logLevel: config.LOG_INFO,
browsers: ['PhantomJS'],
singleRun: true
})
}
| module.exports = function (config) {
config.set({
basePath: '../..',
frameworks: ['jasmine'],
files: [
// Angular libraries
'lib/angular.js',
'lib/angular-mocks.js',
// Application files
'js/app.js',
'js/services/*.js',
// Test files
'tests/specs/*.js'
],
preprocessors: {
'js/*.js': ['coverage']
},
coverageReporter: {
reporters: [
{type: 'cobertura', dir: 'tests/coverage/cobertura'},
{type: 'html', dir: 'tests/coverage/html'}
]
},
reporters: ['dots', 'coverage', 'junit'],
junitReporter: {
outputFile: 'tests/results/junit-result.xml'
},
port: 9876,
runnerPort: 9910,
color: true,
logLevel: config.LOG_INFO,
browsers: ['PhantomJS'],
singleRun: true
})
}
|
[Maintenance] Adjust variable names to interfaces | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
final class SyliusAdminExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container): void
{
$config = $this->processConfiguration($this->getConfiguration([], $container), $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$container->setParameter('sylius.admin.notification.enabled', $config['notifications']['enabled']);
$container->setParameter('sylius.admin.notification.frequency', $config['notifications']['frequency']);
$container->setParameter('sylius.admin.shop_enabled', false);
$bundles = $container->getParameter('kernel.bundles');
if (array_key_exists('SyliusShopBundle', $bundles)) {
$loader->load('services/integrations/shop.xml');
$container->setParameter('sylius.admin.shop_enabled', true);
}
$loader->load('services.xml');
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AdminBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
final class SyliusAdminExtension extends Extension
{
public function load(array $config, ContainerBuilder $container): void
{
$config = $this->processConfiguration($this->getConfiguration([], $container), $config);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$container->setParameter('sylius.admin.notification.enabled', $config['notifications']['enabled']);
$container->setParameter('sylius.admin.notification.frequency', $config['notifications']['frequency']);
$container->setParameter('sylius.admin.shop_enabled', false);
$bundles = $container->getParameter('kernel.bundles');
if (array_key_exists('SyliusShopBundle', $bundles)) {
$loader->load('services/integrations/shop.xml');
$container->setParameter('sylius.admin.shop_enabled', true);
}
$loader->load('services.xml');
}
}
|
Fix the config to have names of managers | <?php
namespace Mcfedr\QueueManagerBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('mcfedr_queue_manager')
->children()
->booleanNode('debug')->defaultFalse()->end()
->integerNode('retry_limit')->defaultValue(3)->end()
->integerNode('sleep_seconds')->defaultValue(5)->end()
->arrayNode('drivers')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('class')->isRequired()->cannotBeEmpty()->end()
->scalarNode('command_class')->end()
->variableNode('options')->end()
->end()
->end()
->end()
->arrayNode('managers')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->addDefaultsIfNotSet()
->children()
->scalarNode('driver')->cannotBeEmpty()->end()
->variableNode('options')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| <?php
namespace Mcfedr\QueueManagerBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('mcfedr_queue_manager')
->children()
->booleanNode('debug')->defaultFalse()->end()
->integerNode('retry_limit')->defaultValue(3)->end()
->integerNode('sleep_seconds')->defaultValue(5)->end()
->arrayNode('drivers')
->prototype('array')
->children()
->scalarNode('class')->isRequired()->cannotBeEmpty()->end()
->scalarNode('command_class')->end()
->variableNode('options')->end()
->end()
->end()
->end()
->arrayNode('managers')
->requiresAtLeastOneElement()
->prototype('array')
->addDefaultsIfNotSet()
->children()
->scalarNode('driver')->cannotBeEmpty()->end()
->variableNode('options')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
|
Use old array syntax for Autocomplete | <?php
/* vim: set shiftwidth=2 expandtab softtabstop=2: */
namespace Boris;
class Autocompletion {
private $symbols = [];
public function __construct() {
}
public function complete($status)
{
$chunk = substr($status['line'], 0, $status['cursor']);
/**
* Verify if we are in a variable context
* Take the last word and check if the first character is a '$'
*/
$tokens = preg_split('/[^a-zA-Z_\$]/', $chunk);
$current = end($tokens);
if($current && $current[0] == '$') {
return $this->getVariables();
} else {
return $this->getSymbols();
}
}
private function getSymbols() {
if(empty($this->symbols)) {
$this->symbols = call_user_func_array(
"array_merge", array_values(get_defined_functions())
);
$this->symbols = array_merge(
$this->symbols, array_keys(get_defined_constants())
);
}
return $this->symbols;
}
private function getVariables() {
/**
* TODO: Find a way to access EvalWorker context/scope to access vars
*/
return array('this', 'container');
}
}
| <?php
/* vim: set shiftwidth=2 expandtab softtabstop=2: */
namespace Boris;
class Autocompletion {
private $symbols = [];
public function __construct() {
}
public function complete($status)
{
$chunk = substr($status['line'], 0, $status['cursor']);
/**
* Verify if we are in a variable context
* Take the last word and check if the first character is a '$'
*/
$tokens = preg_split('/[^a-zA-Z_\$]/', $chunk);
$current = end($tokens);
if($current && $current[0] == '$') {
return $this->getVariables();
} else {
return $this->getSymbols();
}
}
private function getSymbols() {
if(empty($this->symbols)) {
$this->symbols = call_user_func_array(
"array_merge", array_values(get_defined_functions())
);
$this->symbols = array_merge(
$this->symbols, array_keys(get_defined_constants())
);
}
return $this->symbols;
}
private function getVariables() {
/**
* TODO: Find a way to access EvalWorker context/scope to access vars
*/
return ['this', 'container'];
}
} |
Make goLayerVisibility a directive of type A | goog.provide('go_layervisibility_directive');
goog.require('go');
goog.require('goog.asserts');
/**
* Directive to control the visibility of a layer. To be used with
* a checkbox like element. Requires ngModel.
*
* Usage:
* <input type="checkbox" ng-model="layervisible" go-layer-visibility="layer">
*/
goModule.directive('goLayerVisibility', ['goDefaultMap', '$timeout', '$parse',
/**
* @param {string} goDefaultMap Default map constant.
* @param {angular.$timeout} $timeout Timeout service.
* @param {angular.$parse} $parse Parse service.
* @return {angular.Directive} The directive specs.
*/
function(goDefaultMap, $timeout, $parse) {
return {
restrict: 'A',
require: '?ngModel',
link:
/**
* @param {angular.Scope} scope Scope.
* @param {angular.JQLite} element Element.
* @param {angular.Attributes} attr Attributes.
* @param {(!Object|!Array.<!Object>)} ctrl Controller.
*/
function(scope, element, attr, ctrl) {
var name;
name = 'goLayerVisibility';
var layer = /** @type {ol.layer.Layer} */ (scope.$eval(attr[name]));
goog.asserts.assertInstanceof(layer, ol.layer.Layer);
name = 'ngModel';
var ngModelGet = $parse(attr[name]);
var ngModelSet = ngModelGet.assign;
ctrl.$viewChangeListeners.push(function() {
$timeout(function() {
layer.setVisible(ctrl.$modelValue);
}, 0, false);
});
layer.on('change:visible', function() {
scope.$apply(function() {
ngModelSet(scope, layer.getVisible());
});
});
if (!goog.isDef(ngModelGet(scope))) {
ngModelSet(scope, layer.getVisible());
} else {
$timeout(function() {
layer.setVisible(ctrl.$modelValue);
}, 0, false);
}
}
};
}]);
| goog.provide('go_layervisibility_directive');
goog.require('go');
goog.require('goog.asserts');
goModule.directive('goLayerVisibility', [
/**
* @return {angular.Directive} The directive specs.
*/
function() {
return {
restrict: 'E',
template: '<input type="checkbox" ng-model="l.visible"/>',
scope: {
'l': '=goLayer'
},
link:
/**
* @param {angular.Scope} scope Scope.
* @param {angular.JQLite} element Element.
* @param {angular.Attributes} attrs Attributes.
*/
function(scope, element, attrs) {
/** @type {ol.layer.Layer} */
var layer = scope['l'];
goog.asserts.assertInstanceof(layer, ol.layer.Layer);
Object.defineProperty(layer, 'visible', {
get: function() {
return this.getVisible();
},
set: function(val) {
this.setVisible(val);
}
});
}
};
}]);
|
Use current host and port for communicating with websocket | 'use strict';
$(function() {
var conn;
var msg = $("#msg");
var log = $("#log");
var hostAndPort = location.hostname+(location.port ? ':'+location.port: '');
var webSocketAddr = "ws://" + hostAndPort + "/ws";
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
$("#form").submit(function() {
if (!conn) {
return false;
}
if (!msg.val()) {
return false;
}
conn.send(msg.val());
msg.val("");
return false
});
if (window["WebSocket"]) {
conn = new WebSocket(webSocketAddr);
conn.onclose = function(evt) {
appendLog($("<div><b>Connection closed.</b></div>"))
}
conn.onmessage = function(evt) {
appendLog($("<div/>").text(evt.data))
}
} else {
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
}
}); | 'use strict';
$(function() {
var conn;
var msg = $("#msg");
var log = $("#log");
var webSocketAddr = "ws://0.0.0.0:4001/ws"
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
$("#form").submit(function() {
if (!conn) {
return false;
}
if (!msg.val()) {
return false;
}
conn.send(msg.val());
msg.val("");
return false
});
if (window["WebSocket"]) {
conn = new WebSocket(webSocketAddr);
conn.onclose = function(evt) {
appendLog($("<div><b>Connection closed.</b></div>"))
}
conn.onmessage = function(evt) {
appendLog($("<div/>").text(evt.data))
}
} else {
appendLog($("<div><b>Your browser does not support WebSockets.</b></div>"))
}
}); |
Make the drush command recognize the custom alias name. | <?php
namespace CommerceGuys\Platform\Cli\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DrushCommand extends PlatformCommand
{
protected function configure()
{
$this
->setName('drush')
->setDescription('Invoke a drush command using the site alias for the current environment.');
$this->ignoreValidationErrors();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->ensureDrushInstalled();
// Try to autodetect the project and environment.
// There is no point in allowing the user to override them
// using --project and --environment, in that case they can run
// drush by themselves and specify the site alias manually.
$this->project = $this->getCurrentProject();
if (!$this->project) {
$output->writeln("<error>You must run this command from a project folder.</error>");
return;
}
$this->environment = $this->getCurrentEnvironment($this->project);
if (!$this->environment) {
$output->writeln("<error>Could not determine the current environment.</error>");
return;
}
$aliasGroup = isset($this->project['alias-group']) ? $this->project['alias-group'] : $this->project['id'];
$alias = $aliasGroup . '.' . $this->environment['id'];
$command = 'drush @' . $alias . ' ';
// Take the entire input string (all arguments and options) after the
// name of the drush command.
$command .= substr($input->__toString(), 6);
passthru($command);
}
}
| <?php
namespace CommerceGuys\Platform\Cli\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DrushCommand extends PlatformCommand
{
protected function configure()
{
$this
->setName('drush')
->setDescription('Invoke a drush command using the site alias for the current environment.');
$this->ignoreValidationErrors();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->ensureDrushInstalled();
// Try to autodetect the project and environment.
// There is no point in allowing the user to override them
// using --project and --environment, in that case they can run
// drush by themselves and specify the site alias manually.
$this->project = $this->getCurrentProject();
if (!$this->project) {
$output->writeln("<error>You must run this command from a project folder.</error>");
return;
}
$this->environment = $this->getCurrentEnvironment($this->project);
if (!$this->environment) {
$output->writeln("<error>Could not determine the current environment.</error>");
return;
}
$alias = $this->project['id'] . '.' . $this->environment['id'];
$command = 'drush @' . $alias . ' ';
// Take the entire input string (all arguments and options) after the
// name of the drush command.
$command .= substr($input->__toString(), 6);
passthru($command);
}
}
|
Change development status to Beta | from setuptools import setup
import io
import os
def read(fname, encoding='utf-8'):
here = os.path.dirname(__file__)
with io.open(os.path.join(here, fname), encoding=encoding) as f:
return f.read()
setup(
name='pretext',
version='0.0.3',
description='Use doctest with bytes, str & unicode on Python 2.x and 3.x',
long_description=read('README.rst'),
url='https://github.com/moreati/b-prefix-all-the-doctests',
author='Alex Willmer',
author_email='[email protected]',
license='Apache Software License 2.0',
py_modules=['pretext'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'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',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Documentation',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Testing',
],
keywords='doctest bytes unicode bytestring prefix literal string str',
)
| from setuptools import setup
import io
import os
def read(fname, encoding='utf-8'):
here = os.path.dirname(__file__)
with io.open(os.path.join(here, fname), encoding=encoding) as f:
return f.read()
setup(
name='pretext',
version='0.0.3',
description='Use doctest with bytes, str & unicode on Python 2.x and 3.x',
long_description=read('README.rst'),
url='https://github.com/moreati/b-prefix-all-the-doctests',
author='Alex Willmer',
author_email='[email protected]',
license='Apache Software License 2.0',
py_modules=['pretext'],
include_package_data=True,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'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',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Documentation',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Testing',
],
keywords='doctest bytes unicode bytestring prefix literal string str',
)
|
Fix RawPostDataException on request.body access.
Django's HttpRequest class doesn't like the `request.body` to be accessed more than one time. Upon the second attempt to read from `request.body`, Django throws a `RawPostDataException`. Since the previous code in this spot was conditional upon a `hasattr(request, 'body')` check, and because hasattr returns False when the attribute access raises an exception, raygun was falling back to looking up the rawData field from `request.raw_post_data`. But that attribute doesn't exist in newer versions of Django, so we were getting exceptions in the raygun4py's Django process_exception middleware, which is a royal pain in the tush.
So, this change does the hasattr check on both attributes, and only includes rawData if one of the `request.body` or `request.raw_post_data` attributes actually exists and is readable. | from __future__ import absolute_import
from django.conf import settings
from raygun4py import raygunprovider
class Provider(object):
def __init__(self):
config = getattr(settings, 'RAYGUN4PY_CONFIG', {})
apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None))
self.sender = raygunprovider.RaygunSender(apiKey, config=config)
def process_exception(self, request, exception):
raygunRequest = self._mapRequest(request)
self.sender.send_exception(exception=exception, request=raygunRequest)
def _mapRequest(self, request):
headers = request.META.items()
_headers = dict()
for k, v in headers:
if not k.startswith('wsgi'):
_headers[k] = v
return {
'hostName': request.get_host(),
'url': request.path,
'httpMethod': request.method,
'ipAddress': request.META.get('REMOTE_ADDR', '?'),
'queryString': dict((key, request.GET[key]) for key in request.GET),
'form': dict((key, request.POST[key]) for key in request.POST),
'headers': _headers,
'rawData': request.body if hasattr(request, 'body') else getattr(request, 'raw_post_data', {})
}
| from __future__ import absolute_import
from django.conf import settings
from raygun4py import raygunprovider
class Provider(object):
def __init__(self):
config = getattr(settings, 'RAYGUN4PY_CONFIG', {})
apiKey = getattr(settings, 'RAYGUN4PY_API_KEY', config.get('api_key', None))
self.sender = raygunprovider.RaygunSender(apiKey, config=config)
def process_exception(self, request, exception):
raygunRequest = self._mapRequest(request)
self.sender.send_exception(exception=exception, request=raygunRequest)
def _mapRequest(self, request):
headers = request.META.items()
_headers = dict()
for k, v in headers:
if not k.startswith('wsgi'):
_headers[k] = v
return {
'hostName': request.get_host(),
'url': request.path,
'httpMethod': request.method,
'ipAddress': request.META.get('REMOTE_ADDR', '?'),
'queryString': dict((key, request.GET[key]) for key in request.GET),
'form': dict((key, request.POST[key]) for key in request.POST),
'headers': _headers,
'rawData': request.body if hasattr(request, 'body') else getattr(request, 'raw_post_data', {})
}
|
Fix event binding selector in unified mode | import {mapValues} from 'lodash';
import shallowEquals from 'shallow-equal/objects';
import arrayShallowEquals from 'shallow-equal/arrays';
// Simplified version of reselect
export const createSelector = (select, inputEquals = arrayShallowEquals) => {
let lastInput = null;
let lastResult = null;
return (...input) => {
if (!lastInput || !inputEquals(lastInput, input)) {
lastResult = select(...input);
lastInput = input;
}
return lastResult;
};
};
const composeCallback = (customCallback, ownCallback) => e => {
ownCallback(e);
customCallback(); // `customCallback` is already bound with `arg`
};
export const createEventsBindingSelector = (ownEvents = {}) => {
const ownEventEntries = Object.entries(ownEvents);
return createSelector(
// Bind args of all event callbacks to given input
(events, arg) => {
const customEvents = mapValues(events, fn => () => fn(arg));
return ownEventEntries.reduce(
(events, [name, ownCallback]) => {
const customCallback = events[name];
const callback = customCallback ? composeCallback(customCallback, ownCallback) : ownCallback;
return {
...events,
[name]: callback
};
},
customEvents
);
},
// [events, {change, side}]
(prev, next) => shallowEquals(prev[0], next[0]) && shallowEquals(prev[1], next[1])
);
};
| import {mapValues} from 'lodash';
import shallowEquals from 'shallow-equal/objects';
// Simplified version of reselect
const createSelector = (select, inputEquals) => {
let lastInput = null;
let lastResult = null;
return (...input) => {
if (!lastInput || !inputEquals(lastInput, input)) {
lastResult = select(...input);
lastInput = input;
}
return lastResult;
};
};
const composeCallback = (customCallback, ownCallback) => e => {
ownCallback(e);
customCallback(); // `customCallback` is already bound with `arg`
};
export const createEventsBindingSelector = ownEvents => {
const ownEventEntries = Object.entries(ownEvents);
return createSelector(
// Bind args of all event callbacks to given input
(events, arg) => {
const customEvents = mapValues(events, fn => () => fn(arg));
return ownEventEntries.reduce(
(events, [name, ownCallback]) => {
const customCallback = events[name];
const callback = customCallback ? composeCallback(customCallback, ownCallback) : ownCallback;
return {
...events,
[name]: callback
};
},
customEvents
);
},
// [events, {change, side}]
(prev, next) => shallowEquals(prev[0], next[0]) && shallowEquals(prev[1], next[1])
);
};
|
Fix a bug where user-agents could specify their own session ID. | # encoding: utf-8
from __future__ import unicode_literals
from web.auth import authenticate, deauthenticate
from web.core import config, url, session
from web.core.http import HTTPFound
from brave.api.client import API
log = __import__('logging').getLogger(__name__)
class AuthenticationMixIn(object):
def authorize(self):
# Perform the initial API call and direct the user.
api = API(config['api.endpoint'], config['api.identity'], config['api.private'], config['api.public'])
success = str(url.complete('/authorized'))
failure = str(url.complete('/nolove'))
result = api.core.authorize(success=success, failure=failure)
raise HTTPFound(location=result.location)
def ciao(self):
deauthenticate(True)
raise HTTPFound(location='/')
def authorized(self, token):
# Capture the returned token and use it to look up the user details.
# If we don't have this character, create them.
# Store the token against this user account.
# Note that our own 'sessions' may not last beyond the UTC date returned as 'expires'.
# (Though they can be shorter!)
# Prevent users from specifying their session IDs (Some user-agents were sending null ids, leading to users
# authenticated with a session id of null
session.regenerate_id()
# We request an authenticated session from the server.
authenticate(token)
raise HTTPFound(location='/')
def nolove(self, token):
return 'sound.irc.template.whynolove', dict()
| # encoding: utf-8
from __future__ import unicode_literals
from web.auth import authenticate, deauthenticate
from web.core import config, url
from web.core.http import HTTPFound
from brave.api.client import API
log = __import__('logging').getLogger(__name__)
class AuthenticationMixIn(object):
def authorize(self):
# Perform the initial API call and direct the user.
api = API(config['api.endpoint'], config['api.identity'], config['api.private'], config['api.public'])
success = str(url.complete('/authorized'))
failure = str(url.complete('/nolove'))
result = api.core.authorize(success=success, failure=failure)
raise HTTPFound(location=result.location)
def ciao(self):
deauthenticate(True)
raise HTTPFound(location='/')
def authorized(self, token):
# Capture the returned token and use it to look up the user details.
# If we don't have this character, create them.
# Store the token against this user account.
# Note that our own 'sessions' may not last beyond the UTC date returned as 'expires'.
# (Though they can be shorter!)
# We request an authenticated session from the server.
authenticate(token)
raise HTTPFound(location='/')
def nolove(self, token):
return 'sound.irc.template.whynolove', dict()
|
Use markdown as README format | #!/usr/bin/env python
import os
import setuptools
def read(filename):
return open(os.path.join(os.path.dirname(__file__), filename)).read()
setuptools.setup(
name='alerta',
version=read('VERSION'),
description='Alerta unified command-line tool and SDK',
long_description=read('README.md'),
long_description_content_type='text/markdown',
license='Apache License 2.0',
author='Nick Satterly',
author_email='[email protected]',
packages=setuptools.find_packages(exclude=['tests']),
install_requires=[
'Click',
'requests',
'tabulate',
'pytz',
'six'
],
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'alerta = alertaclient.cli:cli'
]
},
keywords='alerta client unified command line tool sdk',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'Intended Audience :: Telecommunications Industry',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.5',
'Topic :: System :: Monitoring',
'Topic :: Software Development :: Libraries :: Python Modules'
],
python_requires='>=3.5'
)
| #!/usr/bin/env python
import setuptools
with open('VERSION') as f:
version = f.read().strip()
with open('README.md') as f:
readme = f.read()
setuptools.setup(
name='alerta',
version=version,
description='Alerta unified command-line tool and SDK',
long_description=readme,
url='http://github.com/alerta/python-alerta',
license='MIT',
author='Nick Satterly',
author_email='[email protected]',
packages=setuptools.find_packages(exclude=['tests']),
install_requires=[
'Click',
'requests',
'tabulate',
'pytz',
'six'
],
include_package_data=True,
zip_safe=False,
entry_points={
'console_scripts': [
'alerta = alertaclient.cli:cli'
]
},
keywords='alerta client unified command line tool sdk',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'Intended Audience :: Telecommunications Industry',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.5',
'Topic :: System :: Monitoring',
],
python_requires='>=3.5'
)
|
Add date and time info | package com.arinerron.forux.core;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Logger {
public static int PRINT_TO_CONSOLE = 0;
public static int PRINT_TO_FILE = 1;
public static int PRINT_TO_CONSOLE_AND_FILE = 2;
private Game game = null;
private int type = Logger.PRINT_TO_CONSOLE_AND_FILE;
public Logger(Game game) {
this.game = game;
}
private void log(Object o) {
if(this.getLoggerType() % 2 == 0)
System.out.println(o);
if(this.getLoggerType() > 0)
;// make write to file later
}
public void log(String type, Object o) {
log("[" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) + type.toUpperCase() + "] " + o);
}
public void info(Object o) {
log("INFO", o);
}
public void warn(Object o) {
log("WARN", o);
}
public void error(Object o) {
log("ERROR", o);
}
public void error(Exception e) {
log("ERROR", e.getMessage());
e.printStackTrace();
}
public void setLoggerType(int type) {
this.type = type;
}
public Game getGame() {
return this.game;
}
public int getLoggerType() {
return this.type;
}
}
| package com.arinerron.forux.core;
public class Logger {
public static int PRINT_TO_CONSOLE = 0;
public static int PRINT_TO_FILE = 1;
public static int PRINT_TO_CONSOLE_AND_FILE = 2;
private Game game = null;
private int type = Logger.PRINT_TO_CONSOLE_AND_FILE;
public Logger(Game game) {
this.game = game;
}
private void log(Object o) {
if(this.getLoggerType() % 2 == 0)
System.out.println(o);
if(this.getLoggerType() > 0)
;// make write to file later
}
public void log(String type, Object o) {
log("[" + type.toUpperCase() + "] " + o);
}
public void info(Object o) {
log("INFO", o);
}
public void warn(Object o) {
log("WARN", o);
}
public void error(Object o) {
log("ERROR", o);
}
public void error(Exception e) {
log("ERROR", e.getMessage());
e.printStackTrace();
}
public void setLoggerType(int type) {
this.type = type;
}
public Game getGame() {
return this.game;
}
public int getLoggerType() {
return this.type;
}
}
|
Add heredoc sql interpolation test | // SYNTAX TEST "Packages/php-grammar/PHP.tmLanguage"
<?php
$double_quotes = "SELECT * FROM tbl";
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'SELECT * FROM tbl';
// ^ source.sql keyword
// ^ source.sql keyword
$double_quotes = "UPDATE t1 SET col1 = col1 + 1, col2 = col1;";
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'UPDATE t1 SET col1 = col1 + 1, col2 = col1;';
// ^ source.sql keyword
// ^ source.sql keyword
$double_quotes = "INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);";
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);';
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$HERDOC = <<<SQL
SELECT * FROM users WHERE active;
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
SQL;
| // SYNTAX TEST "Packages/php-grammar/PHP.tmLanguage"
<?php
$double_quotes = "SELECT * FROM tbl";
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'SELECT * FROM tbl';
// ^ source.sql keyword
// ^ source.sql keyword
$double_quotes = "UPDATE t1 SET col1 = col1 + 1, col2 = col1;";
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'UPDATE t1 SET col1 = col1 + 1, col2 = col1;';
// ^ source.sql keyword
// ^ source.sql keyword
$double_quotes = "INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);";
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
$single_quotes = 'INSERT INTO tbl_name (col1, col2) VALUES (15, col1 * 2);';
// ^ source.sql keyword
// ^ source.sql keyword
// ^ source.sql keyword
|
Fix all specs failing due to strict types being enabled | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Addressing\Comparator;
use Sylius\Component\Addressing\Model\AddressInterface;
/**
* @author Jan Góralski <[email protected]>
*/
final class AddressComparator implements AddressComparatorInterface
{
/**
* {@inheritdoc}
*/
public function equal(AddressInterface $firstAddress, AddressInterface $secondAddress)
{
return $this->normalizeAddress($firstAddress) === $this->normalizeAddress($secondAddress);
}
/**
* @param AddressInterface $address
*
* @return array
*/
private function normalizeAddress(AddressInterface $address)
{
return array_map(function ($value) {
return strtolower(trim((string) $value));
}, [
$address->getCity(),
$address->getCompany(),
$address->getCountryCode(),
$address->getFirstName(),
$address->getLastName(),
$address->getPhoneNumber(),
$address->getPostcode(),
$address->getProvinceCode(),
$address->getProvinceName(),
$address->getStreet(),
]);
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Component\Addressing\Comparator;
use Sylius\Component\Addressing\Model\AddressInterface;
/**
* @author Jan Góralski <[email protected]>
*/
final class AddressComparator implements AddressComparatorInterface
{
/**
* {@inheritdoc}
*/
public function equal(AddressInterface $firstAddress, AddressInterface $secondAddress)
{
return $this->normalizeAddress($firstAddress) === $this->normalizeAddress($secondAddress);
}
/**
* @param AddressInterface $address
*
* @return array
*/
private function normalizeAddress(AddressInterface $address)
{
return array_map(function ($value) {
return trim(strtolower($value));
}, [
$address->getCity(),
$address->getCompany(),
$address->getCountryCode(),
$address->getFirstName(),
$address->getLastName(),
$address->getPhoneNumber(),
$address->getPostcode(),
$address->getProvinceCode(),
$address->getProvinceName(),
$address->getStreet(),
]);
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.