text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Enable animateScreenLights only for devices running 4.2+
animateScreenLights is needed for CRT effect which is not currently
available for 4.1 devices, anyway...
This fixes some weird display on/off issues on these devices. | package com.ceco.gm2.gravitybox;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import android.os.Build;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;
public class SystemWideResources {
public static void initResources(final XSharedPreferences prefs) {
try {
XModuleResources modRes = XModuleResources.createInstance(GravityBox.MODULE_PATH, null);
if (Build.VERSION.SDK_INT > 16) {
XResources.setSystemWideReplacement("android", "bool", "config_animateScreenLights", true);
}
boolean holoBgDither = prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_DITHER, false);
if (prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_SOLID_BLACK, false)) {
XResources.setSystemWideReplacement(
"android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark_solid));
} else if (holoBgDither) {
XResources.setSystemWideReplacement(
"android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark));
}
if (holoBgDither) {
XResources.setSystemWideReplacement(
"android", "drawable", "background_holo_light", modRes.fwd(R.drawable.background_holo_light));
}
} catch (Throwable t) {
XposedBridge.log(t);
}
}
}
| package com.ceco.gm2.gravitybox;
import android.content.res.XModuleResources;
import android.content.res.XResources;
import de.robv.android.xposed.XSharedPreferences;
import de.robv.android.xposed.XposedBridge;
public class SystemWideResources {
public static void initResources(final XSharedPreferences prefs) {
try {
XModuleResources modRes = XModuleResources.createInstance(GravityBox.MODULE_PATH, null);
XResources.setSystemWideReplacement("android", "bool", "config_animateScreenLights", true);
boolean holoBgDither = prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_DITHER, false);
if (prefs.getBoolean(GravityBoxSettings.PREF_KEY_HOLO_BG_SOLID_BLACK, false)) {
XResources.setSystemWideReplacement(
"android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark_solid));
} else if (holoBgDither) {
XResources.setSystemWideReplacement(
"android", "drawable", "background_holo_dark", modRes.fwd(R.drawable.background_holo_dark));
}
if (holoBgDither) {
XResources.setSystemWideReplacement(
"android", "drawable", "background_holo_light", modRes.fwd(R.drawable.background_holo_light));
}
} catch (Throwable t) {
XposedBridge.log(t);
}
}
}
|
Add forgotten JS for VK like button. | // Заменяем MSN_ID на текстовые описания.
function set_userlist_msn(){
$('tr td:nth-child(2)', '.uTable').each(function(i){
var $this = $(this);
var h = $this.html();
if (~~h)
$this.addClass('fraction-name' + h).html(' ');
});
}
$(function () {
// Ссылки на профили пользователей
$('.profile-link').click(function () {
window.open($(this).attr('href'), 'up1', 'scrollbars=1,top=0,left=0,resizable=1,width=750,height=420');
return false;
});
// Ссылки для копирования информации
$('.prompt-link').click(function () {
var $this = $(this);
prompt($this.attr('title'), $this.attr('href'));
return false;
});
// Подключаем VK_API если нужно.
if ($('main.content').hasClass('vk-init')) {
VK.init({apiId: 2014686, onlyWidgets: true});
var $vk_like_btn = $('#vk_like');
if ($vk_like_btn.length) {
VK.Widgets.Like("vk_like", {type: "button", verb: 1});
}
// Подключаем ВКомментарии если нужно.
var vk_uid = parseInt($('#vk_comments').attr('data-uid'));
if (vk_uid) {
VK.Widgets.Comments("vk_comments", {limit: 10}, vk_uid);
}
}
});
| // Заменяем MSN_ID на текстовые описания.
function set_userlist_msn(){
$('tr td:nth-child(2)', '.uTable').each(function(i){
var $this = $(this);
var h = $this.html();
if (~~h)
$this.addClass('fraction-name' + h).html(' ');
});
}
$(function () {
// Ссылки на профили пользователей
$('.profile-link').click(function () {
window.open($(this).attr('href'), 'up1', 'scrollbars=1,top=0,left=0,resizable=1,width=750,height=420');
return false;
});
// Ссылки для копирования информации
$('.prompt-link').click(function () {
var $this = $(this);
prompt($this.attr('title'), $this.attr('href'));
return false;
});
// Подключаем VK_API если нужно.
if ($('main.content').hasClass('vk-init')) {
VK.init({apiId: 2014686, onlyWidgets: true});
// Подключаем ВКомментарии если нужно.
var vk_uid = parseInt($('#vk_comments').attr('data-uid'));
if (vk_uid) {
VK.Widgets.Comments("vk_comments", {limit: 10}, vk_uid);
}
}
});
|
Use the version constant, and fixed comments | <?php
/**
* This file is part of the ImboClientCli package
*
* (c) Christer Edvartsen <[email protected]>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace ImboClientCli;
use ImboClientCli\Command,
Symfony\Component\Console;
/**
* Main application class
*
* @package Application
* @author Christer Edvartsen <[email protected]>
*/
class Application extends Console\Application {
/**
* Class constructor
*
* Register all commands and set up some global options
*/
public function __construct() {
parent::__construct('ImboClientCli', Version::VERSION);
// Register commands
$this->addCommands(array(
new Command\Activate(),
new Command\AddImage(),
new Command\Deactivate(),
new Command\DeleteImage(),
new Command\ListImboServers(),
new Command\NumImages(),
new Command\ServerStatus(),
));
// Add global options
$this->getDefinition()->addOption(
new Console\Input\InputOption(
'config',
null,
Console\Input\InputOption::VALUE_OPTIONAL,
'Path to configuration file'
)
);
}
}
| <?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <[email protected]>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
namespace ImboClientCli;
use ImboClientCli\Command,
Symfony\Component\Console;
/**
* Main application class
*
* @package Application
* @author Christer Edvartsen <[email protected]>
*/
class Application extends Console\Application {
/**
* Class constructor
*
* Register all commands and set up some global options
*/
public function __construct() {
parent::__construct('ImboClientCli', Version::getVersionNumber());
// Register commands
$this->addCommands(array(
new Command\Activate(),
new Command\AddImage(),
new Command\Deactivate(),
new Command\DeleteImage(),
new Command\ListImboServers(),
new Command\NumImages(),
new Command\ServerStatus(),
));
// Add global options
$this->getDefinition()->addOption(
new Console\Input\InputOption(
'config',
null,
Console\Input\InputOption::VALUE_OPTIONAL,
'Path to configuration file'
)
);
}
}
|
Improve versions page to show plain text of multiple languages. | @extends('folio::admin.layout')
<?php
$settings_title = config('settings.title');
if($settings_title == '') {
$settings_title = "Folio";
}
$site_title = 'Versions of Item '.$item->id.' | '. $settings_title;
?>
@section('title', 'Versions of Item '.$item->id)
@section('floating.menu')
{!! view('folio::partial.c-floating-menu', ['buttons' => [
'<i class="fa fa-chevron-left"></i>' => $item->editPath(),
]]) !!}
@stop
@section('content')
<div class="[ c-admin ] [ u-pad-b-12x ]">
<p>
<a href="/admin/item/edit/{{ $item->id }}">Return to Item</a>
</p>
@foreach($item->versions->reverse() as $key=>$version)
<?php
$date = new Date($version->updated_at);
$date = ucWords($date->format('F').' '.$date->format('j, Y').$date->format(' H:i:s'));
$text_languages = json_decode($version->getModel()->text);
?>
<div class="[ u-pad-b-1x u-pad-t-2x ] [ c-admin--font-light ] ">
{{ $date }}
</div>
@foreach ($text_languages as $lang => $text)
{!! $lang !!}<br/>
<textarea>{!! $text !!}</textarea>
<br/>
@endforeach
<br/>
@endforeach
</div>
@endsection
| @extends('folio::admin.layout')
<?php
$settings_title = config('settings.title');
if($settings_title == '') {
$settings_title = "Folio";
}
$site_title = 'Versions of Item '.$item->id.' | '. $settings_title;
?>
@section('title', 'Versions of Item '.$item->id)
@section('floating.menu')
{!! view('folio::partial.c-floating-menu', ['buttons' => [
'<i class="fa fa-chevron-left"></i>' => $item->editPath(),
]]) !!}
@stop
@section('content')
<div class="[ c-admin ] [ u-pad-b-12x ]">
<p>
<a href="/admin/item/edit/{{ $item->id }}">Return to Item</a>
</p>
@foreach($item->versions->reverse() as $key=>$version)
<?php
$date = new Date($version->updated_at);
$date = ucWords($date->format('F').' '.$date->format('j, Y').$date->format(' H:i:s'));
?>
<div class="[ u-pad-b-1x u-pad-t-2x ] [ c-admin--font-light ] ">
{{ $date }}
</div>
<textarea>{!! $version->getModel()->text; !!}</textarea>
<br/>
@endforeach
</div>
@endsection
|
Allow inside behaviors inside auth controller | <?php
namespace frenna\auth\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frenna\auth\models\LoginForm;
class AuthController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => ['true'],
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
]
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionLogin()
{
if(Yii::$app->user->isGuest) {
$loginForm = new LoginForm();
$post = Yii::$app->request->post();
if($loginForm->load($post) && $loginForm->login()) {
return $this->goBack();
}
return $this->render('auth/login', [
"model" => $loginForm
]);
}
return $this->goHome();
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
| <?php
namespace frenna\auth\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frenna\auth\models\LoginForm;
class AuthController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allows' => ['true'],
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
]
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionLogin()
{
if(Yii::$app->user->isGuest) {
$loginForm = new LoginForm();
$post = Yii::$app->request->post();
if($loginForm->load($post) && $loginForm->login()) {
return $this->goBack();
}
return $this->render('auth/login', [
"model" => $loginForm
]);
}
return $this->goHome();
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
|
Return value of get_result is a pair of (task, result data) | import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.GenericInterface()
self.master = pymw.PyMW_Master(mwinterface, delete_files=not debug)
def mine(self, artist):
self.mine_internal(Node(artist, NodeTypes.ARTIST))
(finished_task, new_relationships) = self.master.get_result()
while new_relationships:
for n in new_relationships:
self.relationships.append(n)
if n.get_predicate() not in self.nodes:
self.mine_internal(n.get_predicate())
def mine_internal(self, current_node, level=0, parent=None, relationship=None):
self.nodes.append(current_node)
infoboxplugin = artgraph.plugins.infobox.InfoboxPlugin(current_node)
self.task_queue.append(self.master.submit_task(infoboxplugin.get_nodes, input_data=(infoboxplugin,), modules=("artgraph",), data_files=("my.cnf",)))
| import pymw
import pymw.interfaces
import artgraph.plugins.infobox
from artgraph.node import NodeTypes
from artgraph.node import Node
class Miner(object):
nodes = []
relationships = []
master = None
task_queue = []
def __init__(self, debug=False):
mwinterface = pymw.interfaces.GenericInterface()
self.master = pymw.PyMW_Master(mwinterface, delete_files=not debug)
def mine(self, artist):
self.mine_internal(Node(artist, NodeTypes.ARTIST))
new_relationships = self.master.get_result()
while new_relationships:
for n in new_relationships:
self.relationships.append(n)
if n.get_predicate() not in self.nodes:
self.mine_internal(n.get_predicate())
def mine_internal(self, current_node, level=0, parent=None, relationship=None):
self.nodes.append(current_node)
infoboxplugin = artgraph.plugins.infobox.InfoboxPlugin(current_node)
self.task_queue.append(self.master.submit_task(infoboxplugin.get_nodes, input_data=(infoboxplugin,), modules=("artgraph",), data_files=("my.cnf",)))
|
Return 501 on pip search requests | """Simple blueprint."""
import os
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['POST'])
def search_simple():
"""Handling pip search."""
return make_response('Not implemented', 501)
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
| """Simple blueprint."""
import os
from flask import Blueprint, current_app, render_template
blueprint = Blueprint('simple', __name__, url_prefix='/simple',
template_folder='templates')
@blueprint.route('', methods=['GET'])
def get_simple():
"""List all packages."""
packages = os.listdir(current_app.config['BASEDIR'])
return render_template('simple.html', packages=packages)
@blueprint.route('/<package>', methods=['GET'])
@blueprint.route('/<package>/', methods=['GET'])
def get_package(package):
"""List versions of a package."""
package_path = os.path.join(current_app.config['BASEDIR'],
package.lower())
files = os.listdir(package_path)
packages = []
for filename in files:
if filename.endswith('md5'):
with open(os.path.join(package_path, filename), 'r') as md5_digest:
item = {
'name': package,
'version': filename.replace('.md5', ''),
'digest': md5_digest.read()
}
packages.append(item)
return render_template('simple_package.html', packages=packages,
letter=package[:1].lower())
|
Check id in attributes before remove | import Backbone from 'backbone';
export default Backbone.Model.extend({
build(model, opts = {}) {
const models = model.components();
const htmlOpts = {};
const { em } = opts;
// Remove unnecessary IDs
if (opts.cleanId && em) {
const rules = em.get('CssComposer').getAll();
const idRules = rules
.toJSON()
.map(rule => {
const sels = rule.selectors;
const sel = sels && sels.length === 1 && sels.models[0];
return sel && sel.isId() && sel.get('name');
})
.filter(i => i);
htmlOpts.attributes = (mod, attrs) => {
const { id } = attrs;
if (
id &&
id[0] === 'i' && // all autogenerated IDs start with 'i'
!mod.get('script') && // if the component has script, we have to leave the ID
!mod.get('attributes').id && // id is not intentionally in attributes
idRules.indexOf(id) < 0 // we shouldn't have any rule with this ID
) {
delete attrs.id;
}
return attrs;
};
}
if (opts.exportWrapper) {
return model.toHTML({
...htmlOpts,
...(opts.wrapperIsBody && { tag: 'body' })
});
}
return this.buildModels(models, htmlOpts);
},
buildModels(models, opts = {}) {
let code = '';
models.forEach(mod => (code += mod.toHTML(opts)));
return code;
}
});
| import Backbone from 'backbone';
export default Backbone.Model.extend({
build(model, opts = {}) {
const models = model.components();
const htmlOpts = {};
const { em } = opts;
// Remove unnecessary IDs
if (opts.cleanId && em) {
const rules = em.get('CssComposer').getAll();
const idRules = rules
.toJSON()
.map(rule => {
const sels = rule.selectors;
const sel = sels && sels.length === 1 && sels.models[0];
return sel && sel.isId() && sel.get('name');
})
.filter(i => i);
htmlOpts.attributes = (mod, attrs) => {
const { id } = attrs;
if (
id &&
id[0] === 'i' && // all autogenerated IDs start with 'i'
!mod.get('script') && // if the component has script, we have to leave the ID
idRules.indexOf(id) < 0 // we shouldn't have any rule with this ID
) {
delete attrs.id;
}
return attrs;
};
}
if (opts.exportWrapper) {
return model.toHTML({
...htmlOpts,
...(opts.wrapperIsBody && { tag: 'body' })
});
}
return this.buildModels(models, htmlOpts);
},
buildModels(models, opts = {}) {
let code = '';
models.forEach(mod => (code += mod.toHTML(opts)));
return code;
}
});
|
Add hint if no keywords found | const fs = require('fs')
const lang = process.argv[2]
const promptly = require('promptly')
const data = require('unicode-emoji-json')
if (!lang) {
const files = fs.readdirSync('dist')
const langs = files.map(tag => tag.match(/-(.+)\./)[1])
console.log(`Please provide a langage tag: ${langs.join(', ')}`)
} else {
start()
}
async function start() {
const path = `dist/emoji-${lang}.json`
const file = require(`../${path}`)
for (const emoji in file) {
const kws = file[emoji]
// Remove todo comment
const todo = kws.indexOf('// TODO')
if (todo >= 0) kws.splice(todo, 1)
if (needsWork(kws)) {
const hint = kws.length > 0 ? `: ${kws.join(', ')}` : `(${data[emoji]['name']})`
console.log(`${emoji}${hint}`)
let kw = null
while (kw !== '') {
kw = await promptly.prompt('Add a keyword:', {default: ''})
if (kw) kws.push(kw)
}
if (kws.length >= 1) {
console.log(`[saved] ${emoji}: ${kws.join(', ')}\n`)
fs.writeFileSync(`./${path}`, JSON.stringify(file, null, 2))
} else {
continue
}
} else {
continue
}
}
}
function needsWork(keywords) {
if (keywords.length <= 1) return true
if (keywords.includes('// TODO')) return true
return false
} | const fs = require('fs')
const lang = process.argv[2]
const promptly = require('promptly')
if (!lang) {
const files = fs.readdirSync('dist')
const langs = files.map(tag => tag.match(/-(.+)\./)[1])
console.log(`Please provide a langage tag: ${langs.join(', ')}`)
} else {
start()
}
async function start() {
const path = `dist/emoji-${lang}.json`
const file = require(`../${path}`)
for (const emoji in file) {
const kws = file[emoji]
// Remove todo comment
const todo = kws.indexOf('// TODO')
if (todo >= 0) kws.splice(todo, 1)
if (needsWork(kws)) {
console.log(`${emoji}: ${kws.join(', ')}`)
let kw = null
while (kw !== '') {
kw = await promptly.prompt('Add a keyword:', {default: ''})
if (kw) kws.push(kw)
}
if (kws.length >= 1) {
console.log(`[saved] ${emoji}: ${kws.join(', ')}\n`)
fs.writeFileSync(`./${path}`, JSON.stringify(file, null, 2))
} else {
continue
}
} else {
continue
}
}
}
function needsWork(keywords) {
if (keywords.length <= 1) return true
if (keywords.includes('// TODO')) return true
return false
} |
Add data setter and getter for Plot | from PyOpenWorm import *
class Plot(DataObject):
"""
Object for storing plot data in PyOpenWorm.
Must be instantiated with a 2D list of coordinates.
"""
def __init__(self, data=False, *args, **kwargs):
DataObject.__init__(self, **kwargs)
Plot.DatatypeProperty('_data_string', self, multiple=False)
if data:
self.set_data(data)
def _to_string(self, input_list):
"""
Converts input_list to a string
for serialized storage in PyOpenWorm.
"""
return '|'.join([str(item) for item in input_list])
def _to_list(self, input_string):
"""
Converts from internal serlialized string
to a 2D list.
"""
out_list = []
for pair_string in input_string.split('|'):
pair_as_list = pair_string \
.replace('[', '') \
.replace(']', '') \
.split(',')
out_list.append(
map(float, pair_as_list)
)
return out_list
def set_data(self, data):
"""
Set the data attribute, which is user-facing,
as well as the serialized _data_string
attribute, which is used for db storage.
"""
try:
# make sure we're dealing with a 2D list
assert isinstance(data, list)
assert isinstance(data[0], list)
self._data_string(self._to_string(data))
self.data = data
except (AssertionError, IndexError):
raise ValueError('Attribute "data" must be a 2D list of numbers.')
def get_data(self):
"""
Get the data stored for this plot.
"""
if self._data_string():
return self._to_list(self._data_string())
else:
raise AttributeError('You must call "set_data" first.')
| from PyOpenWorm import *
class Plot(DataObject):
"""
Object for storing plot data in PyOpenWorm.
Must be instantiated with a 2D list of coordinates.
"""
def __init__(self, data=False, *args, **kwargs):
DataObject.__init__(self, **kwargs)
Plot.DatatypeProperty('_data_string', self, multiple=False)
if (isinstance(data, list)) and (isinstance(data[0], list)):
# data is user-facing, _data_string is for db
self._data_string(self._to_string(data))
self.data = data
else:
raise ValueError('Plot must be instantiated with 2D list.')
def _to_string(self, input_list):
"""
Converts input_list to a string
for serialized storage in PyOpenWorm.
"""
return '|'.join([str(item) for item in input_list])
def _to_list(self, input_string):
"""
Converts from internal serlialized string
to a 2D list.
"""
out_list = []
for pair_string in input_string.split('|'):
pair_as_list = pair_string \
.replace('[', '') \
.replace(']', '') \
.split(',')
out_list.append(
map(float, pair_as_list)
)
return out_list
|
Update naming convention to fix bug | (function(){
"use strict"
$(document).ready(init);
function init(){
$(".sort").on('click', sortActivities);
$(".user-activities").on('click', ".card", showDescription);
}
function sortActivities() {
var type = $(this).text().toLowerCase(),
$activities = $(".user-activity"),
orderedByDateActivities = [];
if (type == "name") {
orderedByDateActivities = $activities.sort(function(a,b){
return $(a).find(".activity__name").text() > $(b).find(".activity__name").text();
});
$(".user-activities").empty().append(orderedByDateActivities);
}
else if (type == "date") {
orderedByDateActivities = $activities.sort(function(a,b){
return (new Date($(a).find(".activity__date").text())) > (new Date($(b).find(".activity__date").text()));
});
$(".user-activities").empty().append(orderedByDateActivities);
}
else if (type == "venue") {
orderedByDateActivities = $activities.sort(function(a,b){
return $(a).find(".activity__venue-name").text() > $(b).find(".activity__venue-name").text();
});
$(".user-activities").empty().append(orderedByDateActivities);
}
}
function showDescription() {
var selectedActvity = $(this).closest('.user-activity');
var description = selectedActvity.find('.activity__description').toggleClass("hidden");
}
})();
| (function(){
"use strict"
$(document).ready(init);
function init(){
$(".sort").on('click', sortActivities);
$(".user-activities").on('click', ".card", showDescription);
}
function sortActivities() {
var type = $(this).text().toLowerCase(),
$activities = $(".dashboard__activity"),
orderedByDateActivities
if (type == "name") {
orderedByDateActivities = $activities.sort(function(a,b){
return $(a).find(".activity__name").text() > $(b).find(".activity__name").text();
});
$(".user-activities").empty().html(orderedByDateActivities);
}
else if (type == "date") {
orderedByDateActivities = $activities.sort(function(a,b){
return (new Date($(a).find(".activity__date").text())) > (new Date($(b).find(".activity__date").text()));
});
$(".user-activities").empty().html(orderedByDateActivities);
}
else if (type == "venue") {
orderedByDateActivities = $activities.sort(function(a,b){
return $(a).find(".activity__venue-name").text() > $(b).find(".activity__venue-name").text();
});
$(".user-activities").empty().html(orderedByDateActivities);
}
}
function showDescription() {
var selectedActvity = $(this).closest('.user-activity');
var description = selectedActvity.find('.activity__description').toggleClass("hidden");
}
})();
|
Use a versioned filename for the PCL profiles. | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='mono-pcl-profiles-2013-10-25',
version='2013-10-25',
sources=['http://storage.bos.xamarin.com/bot-provisioning/mono-pcl-profiles-2013-10-25.tar.gz'])
self.source_dir_name = "mono-pcl-profiles"
def prep(self):
self.extract_archive(self.sources[0],
validate_only=False,
overwrite=True)
def build(self):
pass
# A bunch of shell script written inside python literals ;(
def install(self):
dest = os.path.join(self.prefix, "lib", "mono", "xbuild-frameworks", ".NETPortable")
if not os.path.exists(dest):
os.makedirs(dest)
shutil.rmtree(dest, ignore_errors=True)
pcldir = os.path.join(self.package_build_dir(), self.source_dir_name, ".NETPortable")
self.sh("rsync -abv -q %s/* %s" % (pcldir, dest))
PCLReferenceAssembliesPackage()
| import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='mono-pcl-profiles',
version='2013-10-23',
sources=['http://storage.bos.xamarin.com/mono-pcl/58/5825e0404974d87799504a0df75ea4dca91f9bfe/mono-pcl-profiles.tar.gz'])
self.source_dir_name = "mono-pcl-profiles"
def prep(self):
self.extract_archive(self.sources[0],
validate_only=False,
overwrite=True)
def build(self):
pass
# A bunch of shell script written inside python literals ;(
def install(self):
dest = os.path.join(self.prefix, "lib", "mono", "xbuild-frameworks", ".NETPortable")
if not os.path.exists(dest):
os.makedirs(dest)
shutil.rmtree(dest, ignore_errors=True)
pcldir = os.path.join(self.package_build_dir(), self.source_dir_name, ".NETPortable")
self.sh("rsync -abv -q %s/* %s" % (pcldir, dest))
PCLReferenceAssembliesPackage()
|
Use super() instead of super(classname, self) | # Copyright 2019 Akretion France <https://akretion.com/>
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
def action_post(self):
for move in self:
for line in move.line_ids:
if line.product_id and line.product_id.must_have_dates:
if not line.start_date or not line.end_date:
raise UserError(
_(
"Missing Start Date and End Date for invoice "
"line with Product '%s' which has the "
"property 'Must Have Start and End Dates'."
)
% (line.product_id.display_name)
)
return super().action_post()
| # Copyright 2019 Akretion France <https://akretion.com/>
# @author: Alexis de Lattre <[email protected]>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
def action_post(self):
for move in self:
for line in move.line_ids:
if line.product_id and line.product_id.must_have_dates:
if not line.start_date or not line.end_date:
raise UserError(
_(
"Missing Start Date and End Date for invoice "
"line with Product '%s' which has the "
"property 'Must Have Start and End Dates'."
)
% (line.product_id.display_name)
)
return super(AccountMove, self).action_post()
|
Remove before and beforeEach functions in leiu of a getHub function | var _ = require( 'lodash' );
var should = require( 'should' );
var sinon = require( 'sinon' );
var pequire = require( 'proxyquire' );
var TYPES = [ String, Number, Boolean, Object, Array, null, undefined ];
var getHub = function ( overrides ) {
overrides = _.assign( {}, overrides )
return pequire( '../lib/index', overrides );
};
describe( 'gulp-hub', function () {
it( 'is a function', function () {
getHub().should.be.an.instanceOf( Function );
} );
it( 'takes one argument: A non-empty glob (string) or an array', function () {
var hub = getHub();
var testPatterns = [];
testPatterns.push( TYPES, 'ok' );
testPatterns = _.flatten( testPatterns )
testPatterns.forEach( function ( testPattern ) {
if ( testPattern === 'ok' ) {
hub.bind( null, testPattern ).should.not.throw();
} else {
hub.bind( null, testPattern ).should.throw(
'A non-empty glob pattern or array of glob patterns is required.'
);
}
} );
} );
it( 'loads all specified gulpfiles' );
it( 'creates a gulp task tree' );
} );
| var _ = require( 'lodash' );
var should = require( 'should' );
var sinon = require( 'sinon' );
var pequire = require( 'proxyquire' );
var TYPES = [ String, Number, Boolean, Object, Array, null, undefined ];
describe( 'gulp-hub', function () {
before( function () {
this.getTestModule = function () {
return pequire( '../lib/index', {} );
};
} );
beforeEach( function () {
this.testModule = this.getTestModule();
} );
it( 'is a function', function () {
this.testModule.should.be.an.instanceOf( Function );
} );
it( 'takes one argument: A non-empty glob (string) or an array', function () {
var hub = this.testModule;
var testPatterns = [];
testPatterns.push( TYPES, 'ok' );
testPatterns = _.flatten( testPatterns )
testPatterns.forEach( function ( testPattern ) {
if ( testPattern === 'ok' ) {
hub.bind( null, testPattern ).should.not.throw();
} else {
hub.bind( null, testPattern ).should.throw(
'A non-empty glob pattern or array of glob patterns is required.'
);
}
} );
} );
it( 'loads all specified gulpfiles' );
it( 'creates a gulp task tree' );
} );
|
grunt: Update glob for files to lint with ESLint
Now linting .js files in benchmark/ | /* eslint-disable camelcase, global-require */
'use strict';
module.exports = function(grunt) {
require('jit-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jsonlint: {
all: ['*.json'],
},
eslint: {
all: {
src: '**/*.js',
ignore: '**/node_modules/**',
},
},
mochaTest: {
test: {
src: 'test/*.js',
},
options: {
colors: true,
},
},
mocha_istanbul: {
coverage: {
src: 'test/*.js',
options: {
reportFormats: ['html'],
},
},
coveralls: {
src: 'test/*.js',
options: {
coverage: true,
reportFormats: ['lcovonly'],
},
},
options: {
mochaOptions: ['--colors'],
},
},
});
grunt.event.on('coverage', function(lcov, done) {
require('coveralls').handleInput(lcov, done);
});
// Register tasks
grunt.registerTask('lint', ['jsonlint', 'eslint']);
grunt.registerTask('test', [process.env.CI ? 'mocha_istanbul:coveralls' : 'mochaTest']);
grunt.registerTask('coverage', ['mocha_istanbul:coverage']);
grunt.registerTask('default', ['lint', 'test']);
};
| /* eslint-disable camelcase, global-require */
'use strict';
module.exports = function(grunt) {
require('jit-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jsonlint: {
all: ['*.json'],
},
eslint: {
all: {
src: ['*.js', 'test/*.js'],
ignore: '*.min.js',
},
},
mochaTest: {
test: {
src: 'test/*.js',
},
options: {
colors: true,
},
},
mocha_istanbul: {
coverage: {
src: 'test/*.js',
options: {
reportFormats: ['html'],
},
},
coveralls: {
src: 'test/*.js',
options: {
coverage: true,
reportFormats: ['lcovonly'],
},
},
options: {
mochaOptions: ['--colors'],
},
},
});
grunt.event.on('coverage', function(lcov, done) {
require('coveralls').handleInput(lcov, done);
});
// Register tasks
grunt.registerTask('lint', ['jsonlint', 'eslint']);
grunt.registerTask('test', [process.env.CI ? 'mocha_istanbul:coveralls' : 'mochaTest']);
grunt.registerTask('coverage', ['mocha_istanbul:coverage']);
grunt.registerTask('default', ['lint', 'test']);
};
|
Allow end-user to force `isWindowFocused` prop | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Close from './Close';
import Minimize from './Minimize';
import Resize from './Resize';
var styles = {
controls: {
WebkitUserSelect: 'none',
userSelect: 'none',
cursor: 'default',
display: 'flex',
width: '61px'
},
inset: {
marginLeft: '5px'
}
};
class Controls extends Component {
static propTypes = {
inset: PropTypes.bool,
isFullscreen: PropTypes.bool,
onCloseClick: PropTypes.func,
onMinimizeClick: PropTypes.func,
onMaximizeClick: PropTypes.func,
onResizeClick: PropTypes.func
};
constructor() {
super();
this.state = {
isOver: false
};
}
render() {
return (
<div
style={{ ...styles.controls }}
onMouseEnter={() => this.setState({ isOver: true })}
onMouseLeave={() => this.setState({ isOver: false })}
>
<Close
onClick={this.props.onCloseClick}
showIcon={this.state.isOver}
isWindowFocused={this.props.isWindowFocused}
/>
<Minimize
onClick={this.props.onMinimizeClick}
showIcon={this.state.isOver}
isWindowFocused={this.props.isWindowFocused}
/>
<Resize
isFullscreen={this.props.isFullscreen}
onClick={this.props.onResizeClick}
onMaximizeClick={this.props.onMaximizeClick}
showIcon={this.state.isOver}
isWindowFocused={this.props.isWindowFocused}
/>
</div>
);
}
}
export default Controls;
| import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Close from './Close';
import Minimize from './Minimize';
import Resize from './Resize';
var styles = {
controls: {
WebkitUserSelect: 'none',
userSelect: 'none',
cursor: 'default',
display: 'flex',
width: '61px'
},
inset: {
marginLeft: '5px'
}
};
class Controls extends Component {
static propTypes = {
inset: PropTypes.bool,
isFullscreen: PropTypes.bool,
onCloseClick: PropTypes.func,
onMinimizeClick: PropTypes.func,
onMaximizeClick: PropTypes.func,
onResizeClick: PropTypes.func
};
constructor() {
super();
this.state = {
isOver: false
};
}
render() {
return (
<div
style={{ ...styles.controls }}
onMouseEnter={() => this.setState({ isOver: true })}
onMouseLeave={() => this.setState({ isOver: false })}
>
<Close onClick={this.props.onCloseClick} showIcon={this.state.isOver} />
<Minimize
onClick={this.props.onMinimizeClick}
showIcon={this.state.isOver}
/>
<Resize
isFullscreen={this.props.isFullscreen}
onClick={this.props.onResizeClick}
onMaximizeClick={this.props.onMaximizeClick}
showIcon={this.state.isOver}
/>
</div>
);
}
}
export default Controls;
|
Add option to delayer plugin to start disabled
It's useful to add the delayer plugin to have it available, but
without enabling by default. Thus, add an option to disable it by
default on startup. | var robohydra = require("robohydra"),
heads = robohydra.heads,
RoboHydraHead = heads.RoboHydraHead;
exports.getBodyParts = function(conf) {
"use strict";
var delayMilliseconds = conf.delaymillis || 2000,
delayPath = conf.delaypath || '/.*',
delayDisabled = !!conf.delaydisabled;
conf.robohydra.registerDynamicHead(new RoboHydraHead({
name: 'delayer',
path: delayPath,
handler: function(req, res, next) {
setTimeout(function() {
next(req, res);
}, delayMilliseconds);
}
}));
return {
heads: [
new RoboHydraHead({
name: 'delayer-config',
detached: delayDisabled,
path: '/robohydra-admin/delay/:delayValue',
handler: function(req, res) {
delayMilliseconds = parseInt(req.params.delayValue, 10);
res.send("Delay is now set to " + delayMilliseconds +
" milliseconds");
}
})
]
};
};
| var robohydra = require("robohydra"),
heads = robohydra.heads,
RoboHydraHead = heads.RoboHydraHead;
exports.getBodyParts = function(conf) {
"use strict";
var delayMilliseconds = conf.delaymillis || 2000,
delayPath = conf.delaypath || '/.*';
conf.robohydra.registerDynamicHead(new RoboHydraHead({
name: 'delayer',
path: delayPath,
handler: function(req, res, next) {
setTimeout(function() {
next(req, res);
}, delayMilliseconds);
}
}));
return {
heads: [
new RoboHydraHead({
name: 'delayer-config',
path: '/robohydra-admin/delay/:delayValue',
handler: function(req, res) {
delayMilliseconds = parseInt(req.params.delayValue, 10);
res.send("Delay is now set to " + delayMilliseconds +
" milliseconds");
}
})
]
};
};
|
Make directory listing exclude LICENSE file and IntelliJ project files | <?php
return array(
// Basic settings
'hide_dot_files' => true,
'list_folders_first' => true,
'list_sort_order' => 'natcasesort_reverse',
'theme_name' => 'bootstrap',
'external_links_new_window' => true,
// Hidden files
'hidden_files' => array(
'.ht*',
'*/.ht*',
'resources',
'resources/*',
'userpics',
'fancybox',
'analytics.inc',
'*.css',
'*.php',
'*.html',
'*.ico',
'*.gz',
'*.tgz',
'LICENSE',
'*.iml'
),
// Files that, if present in a directory, make the directory
// a direct link rather than a browse link.
'index_files' => array(
'index.htm',
'index.html',
'index.php'
),
// File hashing threshold
'hash_size_limit' => 268435456, // 256 MB
// Custom sort order
'reverse_sort' => array(
// 'path/to/folder'
),
// Allow to download directories as zip files
'zip_dirs' => false,
// Stream zip file content directly to the client,
// without any temporary file
'zip_stream' => true,
'zip_compression_level' => 0,
// Disable zip downloads for particular directories
'zip_disable' => array(
// 'path/to/folder'
),
);
| <?php
return array(
// Basic settings
'hide_dot_files' => true,
'list_folders_first' => true,
'list_sort_order' => 'natcasesort_reverse',
'theme_name' => 'bootstrap',
'external_links_new_window' => true,
// Hidden files
'hidden_files' => array(
'.ht*',
'*/.ht*',
'resources',
'resources/*',
'userpics',
'fancybox',
'analytics.inc',
'*.css',
'*.php',
'*.html',
'*.ico',
'*.gz',
'*.tgz'
),
// Files that, if present in a directory, make the directory
// a direct link rather than a browse link.
'index_files' => array(
'index.htm',
'index.html',
'index.php'
),
// File hashing threshold
'hash_size_limit' => 268435456, // 256 MB
// Custom sort order
'reverse_sort' => array(
// 'path/to/folder'
),
// Allow to download directories as zip files
'zip_dirs' => false,
// Stream zip file content directly to the client,
// without any temporary file
'zip_stream' => true,
'zip_compression_level' => 0,
// Disable zip downloads for particular directories
'zip_disable' => array(
// 'path/to/folder'
),
);
|
Upgrade ldap3 0.9.9.2 => 1.0.2 | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'cas': [
'django-cas-client>=1.2.0',
],
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.2',
],
'dev': [
'django>=1.7',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'cas': [
'django-cas-client>=1.2.0',
],
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=0.9.9.2',
],
'dev': [
'django>=1.7',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Update image upload button styling | import React, { Component } from 'react';
import { connect } from 'react-redux';
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
// import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
<button
className="btn btn-default"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
uploadPicture(recipe);
}}>Upload</button>
);
}
}
const mapStateToProps = (state) => {
return {
recipe: state.recipe,
};
};
const mapDispatchToProps = (dispatch) => {
return {
uploadPicture: (recipe) => {
fetchFPKey((key) => {
filepicker.setKey(key);
filepicker.pick(
{
mimetype: 'image/*',
container: 'window',
},
(data) => {
const newSet = { images: recipe.images };
newSet.images.push(data.url);
dispatch(actions.editRecipe(newSet));
},
(error) => console.log(error)
);
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import actions from '../actions/index.js';
import { fetchFPKey } from '../utils/utils';
const filepicker = require('filepicker-js');
import '../scss/_createRecipe.scss';
class ImageUpload extends Component {
render() {
const { recipe, uploadPicture } = this.props;
return (
<div>
<button
className="btn btn-add"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
uploadPicture(recipe);
}}>Add Pics</button>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
recipe: state.recipe,
};
};
const mapDispatchToProps = (dispatch) => {
return {
uploadPicture: (recipe) => {
fetchFPKey((key) => {
filepicker.setKey(key);
filepicker.pick(
{
mimetype: 'image/*',
container: 'window',
},
(data) => {
const newSet = { images: recipe.images };
newSet.images.push(data.url);
dispatch(actions.editRecipe(newSet));
},
(error) => console.log(error)
);
});
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ImageUpload);
|
Fix test failures on py3. | # vim: set ts=4 sw=4 et: coding=UTF-8
from rpmsection import Section
class RpmInstall(Section):
'''
Remove commands that wipe out the build root.
Replace %makeinstall (suse-ism).
'''
def add(self, line):
install_command = 'make DESTDIR=%{buildroot} install %{?_smp_mflags}'
line = self._complete_cleanup(line)
line = self._replace_remove_la(line)
# we do not want to cleanup buildroot, it is already clean
if self.reg.re_clean.search(line):
return
# do not use install macros as we have trouble with it for now
# we can convert it later on
if self.reg.re_install.match(line):
line = install_command
# we can deal with additional params for %makeinstall so replace that too
line = line.replace('%{makeinstall}', install_command)
Section.add(self, line)
def _replace_remove_la(self, line):
"""
Replace all known variations of la file deletion with one unified
"""
if (self.reg.re_rm.search(line) and len(self.reg.re_rm_double.split(line)) == 1) or \
(self.reg.re_find.search(line) and len(self.reg.re_find_double.split(line)) == 2):
line = 'find %{buildroot} -type f -name "*.la" -delete -print'
return line
| # vim: set ts=4 sw=4 et: coding=UTF-8
import string
from rpmsection import Section
class RpmInstall(Section):
'''
Remove commands that wipe out the build root.
Replace %makeinstall (suse-ism).
'''
def add(self, line):
install_command = 'make DESTDIR=%{buildroot} install %{?_smp_mflags}'
line = self._complete_cleanup(line)
line = self._replace_remove_la(line)
# we do not want to cleanup buildroot, it is already clean
if self.reg.re_clean.search(line):
return
# do not use install macros as we have trouble with it for now
# we can convert it later on
if self.reg.re_install.match(line):
line = install_command
# we can deal with additional params for %makeinstall so replace that too
line = string.replace(line, '%{makeinstall}', install_command)
Section.add(self, line)
def _replace_remove_la(self, line):
"""
Replace all known variations of la file deletion with one unified
"""
if (self.reg.re_rm.search(line) and len(self.reg.re_rm_double.split(line)) == 1) or \
(self.reg.re_find.search(line) and len(self.reg.re_find_double.split(line)) == 2):
line = 'find %{buildroot} -type f -name "*.la" -delete -print'
return line
|
Update minimum support boto version.
boto 2.20.0 introduces kinesis. alternatively, this requirement could be
relaxed by using conditional imports. | #!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto>=2.20.0",
"flask",
"httpretty>=0.6.1",
"requests",
"xmltodict",
"six",
"werkzeug",
]
import sys
if sys.version_info < (2, 7):
# No buildint OrderedDict before 2.7
install_requires.append('ordereddict')
setup(
name='moto',
version='0.4.1',
description='A library that allows your python tests to easily'
' mock out the boto library',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/moto',
entry_points={
'console_scripts': [
'moto_server = moto.server:main',
],
},
packages=find_packages(exclude=("tests", "tests.*")),
install_requires=install_requires,
license="Apache",
test_suite="tests",
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Testing",
],
)
| #!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto",
"flask",
"httpretty>=0.6.1",
"requests",
"xmltodict",
"six",
"werkzeug",
]
import sys
if sys.version_info < (2, 7):
# No buildint OrderedDict before 2.7
install_requires.append('ordereddict')
setup(
name='moto',
version='0.4.1',
description='A library that allows your python tests to easily'
' mock out the boto library',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/moto',
entry_points={
'console_scripts': [
'moto_server = moto.server:main',
],
},
packages=find_packages(exclude=("tests", "tests.*")),
install_requires=install_requires,
license="Apache",
test_suite="tests",
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Testing",
],
)
|
Correct concat helper separator handler | /*
*
Fugerit Java Library is distributed under the terms of :
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Full license :
http://www.apache.org/licenses/LICENSE-2.0
Project site:
http://www.fugerit.org/java/
SCM site :
https://github.com/fugerit79/fj-lib
*
*/
package org.fugerit.java.core.lang.helpers;
public class ConcatHelper {
public static final String CONCAT_SEPARATOR_DEFAULT = "/";
public static String convertNullToBlank( String v ) {
String r = "";
if ( v != null ) {
r = v;
}
return r;
}
public static String concatWithDefaultSeparator( String... values ) {
return concat( CONCAT_SEPARATOR_DEFAULT, values );
}
public static String concat( String separator, String... values ) {
StringBuffer buffer = new StringBuffer();
buffer.append( convertNullToBlank( values[0] ) );
for ( int k=1; k<values.length; k++ ) {
buffer.append( separator );
buffer.append( convertNullToBlank( values[k] ) );
}
return buffer.toString();
}
}
| /*
*
Fugerit Java Library is distributed under the terms of :
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Full license :
http://www.apache.org/licenses/LICENSE-2.0
Project site:
http://www.fugerit.org/java/
SCM site :
https://github.com/fugerit79/fj-lib
*
*/
package org.fugerit.java.core.lang.helpers;
public class ConcatHelper {
public static final String CONCAT_SEPARATOR_DEFAULT = "/";
public static String convertNullToBlank( String v ) {
String r = "";
if ( v != null ) {
r = v;
}
return r;
}
public static String concatWithDefaultSeparator( String... values ) {
return concat( CONCAT_SEPARATOR_DEFAULT, values );
}
public static String concat( String separator, String... values ) {
StringBuffer buffer = new StringBuffer();
buffer.append( convertNullToBlank( values[0] ) );
for ( int k=1; k<values.length; k++ ) {
buffer.append( CONCAT_SEPARATOR_DEFAULT );
buffer.append( convertNullToBlank( values[k] ) );
}
return buffer.toString();
}
}
|
Use MessageInterface for reading constants. | <?php
namespace Retrinko\CottonTail\Message;
use PhpAmqpLib\Message\AMQPMessage;
use Retrinko\CottonTail\Message\Messages\BasicMessage;
use Retrinko\CottonTail\Message\Messages\RpcRequestMessage;
use Retrinko\CottonTail\Message\Messages\RpcResponseMessage;
class MessageFactory
{
/**
* @param AMQPMessage $amqpMessage
*
* @return BasicMessage|RpcRequestMessage|RpcResponseMessage
*
*/
public static function byAMQPMessage(AMQPMessage $amqpMessage)
{
try
{
$msgType = $amqpMessage->get(MessageInterface::PROPERTY_TYPE);
}
catch (\Exception $e)
{
// No type defined in AMQPMessage properties. Load BasicMessage.
$msgType = '';
}
switch ($msgType)
{
case MessageInterface::TYPE_RPC_RESPONSE:
$message = RpcResponseMessage::loadAMQPMessage($amqpMessage);
break;
case MessageInterface::TYPE_RPC_REQUEST:
$message = RpcRequestMessage::loadAMQPMessage($amqpMessage);
break;
case MessageInterface::TYPE_BASIC:
default:
$message = BasicMessage::loadAMQPMessage($amqpMessage);
break;
}
return $message;
}
} | <?php
namespace Retrinko\CottonTail\Message;
use PhpAmqpLib\Message\AMQPMessage;
use Retrinko\CottonTail\Message\Messages\BasicMessage;
use Retrinko\CottonTail\Message\Messages\RpcRequestMessage;
use Retrinko\CottonTail\Message\Messages\RpcResponseMessage;
class MessageFactory
{
/**
* @param AMQPMessage $amqpMessage
*
* @return BasicMessage|RpcRequestMessage|RpcResponseMessage
*
*/
public static function byAMQPMessage(AMQPMessage $amqpMessage)
{
try
{
$msgType = $amqpMessage->get(BasicMessage::PROPERTY_TYPE);
}
catch (\Exception $e)
{
// No type defined in AMQPMessage properties. Load BasicMessage.
$msgType = '';
}
switch ($msgType)
{
case BasicMessage::TYPE_RPC_RESPONSE:
$message = RpcResponseMessage::loadAMQPMessage($amqpMessage);
break;
case BasicMessage::TYPE_RPC_REQUEST:
$message = RpcRequestMessage::loadAMQPMessage($amqpMessage);
break;
case BasicMessage::TYPE_PLAIN_TEXT:
default:
$message = BasicMessage::loadAMQPMessage($amqpMessage);
break;
}
return $message;
}
} |
Use button instead of NavbarToggler | import './header.scss';
import React from 'react';
import {Link} from 'react-router';
import FontAwesome from 'react-fontawesome';
import { Navbar, NavbarBrand, Nav, NavItem, NavLink, NavbarToggler, Collapse } from 'reactstrap';
class Header extends React.Component {
constructor(props){
super(props);
this.toggleNavbar = this.toggleNavbar.bind(this);
this.state = {
collapsed: false
};
}
toggleNavbar(){
this.setState({
collapsed: !this.state.collapsed
});
}
renderLoginButton(){
return (
<NavItem>
<Link to={'/login'} className="nav-link">Login</Link>
</NavItem>);
}
renderRegisterButton(){
return (
<NavItem>
<Link to={'/register'} className="nav-link">Register</Link>
</NavItem>);
}
renderLogoutButton(){
return (
<NavItem>
<Link to={'/logout'} className="nav-link">Logout</Link>
</NavItem>);
}
render() {
return (
<header>
<Navbar color="inverse" dark full>
<button className="navbar-toggler hidden-md-up pull-left" type="button" onClick={this.props.onHamburgerClick}></button>
<Nav navbar className="pull-right">
{this.props.isAuthenticated && this.renderLogoutButton()}
{!this.props.isAuthenticated && this.renderRegisterButton()}
{!this.props.isAuthenticated && this.renderLoginButton()}
</Nav>
</Navbar>
</header>
);
}
}
export default Header;
| import './header.scss';
import React from 'react';
import {Link} from 'react-router';
import FontAwesome from 'react-fontawesome';
import { Navbar, NavbarBrand, Nav, NavItem, NavLink, NavbarToggler, Collapse } from 'reactstrap';
class Header extends React.Component {
constructor(props){
super(props);
this.toggleNavbar = this.toggleNavbar.bind(this);
this.state = {
collapsed: false
};
}
toggleNavbar(){
this.setState({
collapsed: !this.state.collapsed
});
}
renderLoginButton(){
return (
<NavItem>
<Link to={'/login'} className="nav-link">Login</Link>
</NavItem>);
}
renderRegisterButton(){
return (
<NavItem>
<Link to={'/register'} className="nav-link">Register</Link>
</NavItem>);
}
renderLogoutButton(){
return (
<NavItem>
<Link to={'/logout'} className="nav-link">Logout</Link>
</NavItem>);
}
render() {
return (
<header>
<Navbar color="inverse" dark full>
<NavbarToggler className="hidden-md-up pull-left collapsed" onClick={this.props.onHamburgerClick} />
<Nav navbar className="pull-right">
{this.props.isAuthenticated && this.renderLogoutButton()}
{!this.props.isAuthenticated && this.renderRegisterButton()}
{!this.props.isAuthenticated && this.renderLoginButton()}
</Nav>
</Navbar>
</header>
);
}
}
export default Header;
|
Fix js config caching issue | /**
* Module dependencies.
*/
var Promise = require('bluebird');
var yaml = require('js-yaml');
var _ = require('lodash');
var path = require('path');
var logger = require('winston');
var fs = Promise.promisifyAll(require('fs'));
/*
* Export the data object.
*/
module.exports = {
/*
* Load data from file, optionally with a set of defaults applied.
* Returns a promise.
*
* @api private
*/
load: function(filePath, defaults){
defaults = defaults || {};
var pathInfo = path.parse(path.resolve(filePath));
var ext = pathInfo.ext.toLowerCase();
if (ext == '.js') {
try {
delete require.cache[require.resolve(filePath)]; // Always fetch a fresh copy
var data = Promise.resolve(require(filePath));
} catch(e) {
var data = Promise.reject(e);
}
} else {
var data = fs.readFileAsync(filePath).then(function(contents){
switch(ext) {
case ".json":
return JSON.parse(contents);
break;
case ".yml":
case ".yaml":
return yaml.safeLoad(contents);
break;
}
});
}
return data.catch(function(e){
logger.error('Error loading data file ' + filePath + ': ' + e.message);
return {};
}).then(function(data){
return _.defaultsDeep(data, defaults);
});
}
};
| /**
* Module dependencies.
*/
var Promise = require('bluebird');
var yaml = require('js-yaml');
var _ = require('lodash');
var path = require('path');
var logger = require('winston');
var fs = Promise.promisifyAll(require('fs'));
/*
* Export the data object.
*/
module.exports = {
/*
* Load data from file, optionally with a set of defaults applied.
* Returns a promise.
*
* @api private
*/
load: function(filePath, defaults){
defaults = defaults || {};
var pathInfo = path.parse(path.resolve(filePath));
var ext = pathInfo.ext.toLowerCase();
if (ext == '.js') {
try {
var data = Promise.resolve(require(filePath));
} catch(e) {
var data = Promise.reject(e);
}
} else {
var data = fs.readFileAsync(filePath).then(function(contents){
switch(ext) {
case ".json":
return JSON.parse(contents);
break;
case ".yml":
case ".yaml":
return yaml.safeLoad(contents);
break;
}
});
}
return data.catch(function(e){
logger.error('Error loading data file ' + filePath + ': ' + e.message);
return {};
}).then(function(data){
return _.defaultsDeep(data, defaults);
});
}
};
|
[Security] Delete old session on auth strategy migrate | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* The default session strategy implementation.
*
* Supports the following strategies:
* NONE: the session is not changed
* MIGRATE: the session id is updated, attributes are kept
* INVALIDATE: the session id is updated, attributes are lost
*
* @author Johannes M. Schmitt <[email protected]>
*/
class SessionAuthenticationStrategy implements SessionAuthenticationStrategyInterface
{
const NONE = 'none';
const MIGRATE = 'migrate';
const INVALIDATE = 'invalidate';
private $strategy;
public function __construct($strategy)
{
$this->strategy = $strategy;
}
/**
* {@inheritdoc}
*/
public function onAuthentication(Request $request, TokenInterface $token)
{
switch ($this->strategy) {
case self::NONE:
return;
case self::MIGRATE:
$request->getSession()->migrate(true);
return;
case self::INVALIDATE:
$request->getSession()->invalidate();
return;
default:
throw new \RuntimeException(sprintf('Invalid session authentication strategy "%s"', $this->strategy));
}
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* The default session strategy implementation.
*
* Supports the following strategies:
* NONE: the session is not changed
* MIGRATE: the session id is updated, attributes are kept
* INVALIDATE: the session id is updated, attributes are lost
*
* @author Johannes M. Schmitt <[email protected]>
*/
class SessionAuthenticationStrategy implements SessionAuthenticationStrategyInterface
{
const NONE = 'none';
const MIGRATE = 'migrate';
const INVALIDATE = 'invalidate';
private $strategy;
public function __construct($strategy)
{
$this->strategy = $strategy;
}
/**
* {@inheritdoc}
*/
public function onAuthentication(Request $request, TokenInterface $token)
{
switch ($this->strategy) {
case self::NONE:
return;
case self::MIGRATE:
$request->getSession()->migrate();
return;
case self::INVALIDATE:
$request->getSession()->invalidate();
return;
default:
throw new \RuntimeException(sprintf('Invalid session authentication strategy "%s"', $this->strategy));
}
}
}
|
AEIV-175: Integrate column management with grid view functionality
- fixed review issues | define(function(require) {
'use strict';
var ColumnManagerItemView;
var $ = require('jquery');
var BaseView = require('oroui/js/app/views/base/view');
ColumnManagerItemView = BaseView.extend({
template: require('tpl!orodatagrid/templates/column-manager/column-manager-item.html'),
tagName: 'tr',
attributes: function() {
return {
'data-cid': this.cid
};
},
events: {
'change input[type=checkbox][data-role=renderable]': 'updateModel'
},
listen: {
// for some reason events delegated in view constructor does not work
addedToParent: 'delegateEvents',
// update view on model change
'change:disabledVisibilityChange model': 'render',
'change:renderable model': 'updateView'
},
/**
* @inheritDoc
*/
getTemplateData: function() {
var data = ColumnManagerItemView.__super__.getTemplateData.call(this);
data.cid = this.model.cid;
return data;
},
/**
* Handles DOM event for a column visibility change and updates model's attribute
*
* @param {jQuery.Event} e
*/
updateModel: function(e) {
var renderable = $(e.target).prop('checked');
this.model.set('renderable', renderable);
},
/**
* Handles model event and updates the view
*/
updateView: function() {
var renderable = this.model.get('renderable');
this.$('input[type=checkbox][data-role=renderable]').prop('checked', renderable);
}
});
return ColumnManagerItemView;
});
| define(function(require) {
'use strict';
var ColumnManagerItemView;
var $ = require('jquery');
var BaseView = require('oroui/js/app/views/base/view');
ColumnManagerItemView = BaseView.extend({
template: require('tpl!orodatagrid/templates/column-manager/column-manager-item.html'),
tagName: 'tr',
attributes: function() {
return {
'data-cid': this.cid
};
},
events: {
'change input[type=checkbox][data-role=renderable]': 'onChangeVisibility'
},
listen: {
// for some reason events delegated in view constructor does not work
addedToParent: 'delegateEvents',
// update view on model change
'change:disabledVisibilityChange model': 'render',
'change:renderable model': 'render'
},
/**
* @inheritDoc
*/
getTemplateData: function() {
var data = ColumnManagerItemView.__super__.getTemplateData.call(this);
data.cid = this.model.cid;
return data;
},
/**
* Handles DOM event for a column visibility change and updates model's attribute
*
* @param {jQuery.Event} e
*/
onChangeVisibility: function(e) {
var renderable = $(e.target).prop('checked');
this.model.set('renderable', renderable);
}
});
return ColumnManagerItemView;
});
|
Fix webworker ES6 syntax to ES5 | importScripts('/static/vendor/scripts/highlight.pack.js');
var unescape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': '\'',
};
var regex = new RegExp(Object.keys(unescape).join('|'), 'g');
function unescapeFn(match) {
return unescape[match];
}
function highlightBlockHTML(block) {
block = block.replace(regex, unescapeFn);
return self.hljs.highlight('html', block);
};
function highlightBlockCSS(block) {
block = block.replace(regex, unescapeFn);
return self.hljs.highlight('css', block);
};
function highlightBlockJS(block) {
block = block.replace(regex, unescapeFn);
return self.hljs.highlight('js', block);
};
onmessage = function(event) {
var highlightFn;
switch(event.data.type) {
case 'html':
highlightFn = highlightBlockHTML;
break;
case 'css':
highlightFn = highlightBlockCSS;
break;
case 'js':
highlightFn = highlightBlockJS;
break;
default:
throw new Error('unsupported highlight type in web worker: ' + event.data.type);
break;
}
var result = event.data.blocks.map(highlightFn).map(function(h) { return h.value; });
postMessage({
type: event.data.type,
blocks: result,
});
};
| importScripts('/static/vendor/scripts/highlight.pack.js');
var unescape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': '\'',
};
var regex = new RegExp(Object.keys(unescape).join('|'), 'g');
function unescapeFn(match) {
return unescape[match];
}
function highlightBlockHTML(block) {
block = block.replace(regex, unescapeFn);
return self.hljs.highlight('html', block);
};
function highlightBlockCSS(block) {
block = block.replace(regex, unescapeFn);
return self.hljs.highlight('css', block);
};
function highlightBlockJS(block) {
block = block.replace(regex, unescapeFn);
return self.hljs.highlight('js', block);
};
onmessage = function(event) {
let highlightFn;
switch(event.data.type) {
case 'html':
highlightFn = highlightBlockHTML;
break;
case 'css':
highlightFn = highlightBlockCSS;
break;
case 'js':
highlightFn = highlightBlockJS;
break;
default:
throw new Error('unsupported highlight type in web worker: ' + event.data.type);
break;
}
var result = event.data.blocks.map(highlightFn).map(h => h.value);
postMessage({
type: event.data.type,
blocks: result,
});
};
|
Allow message field to be deselected | CRM.$(function($) {
var $messageField = $('#customData .custom-group-Letter_To input[data-crm-custom="Letter_To:Message_Field"]');
$messageField.attr({
placeholder: '- Select Field -',
allowClear: 'true',
});
createEntityRef($messageField, $('#profile_id').val());
$('#profile_id').change( function() {
$messageField.crmEntityRef('destroy');
$messageField.val('');
createEntityRef($messageField, $('#profile_id').val());
});
function createEntityRef($field, profileId) {
noteFields = getNoteFields();
$field.crmEntityRef({
entity: 'UFField',
placeholder: '- Select Field -',
api: {
params: {
uf_group_id: profileId,
field_name: {"IN": noteFields}
}
},
select: {minimumInputLength: 0},
});
}
function getNoteFields() {
var noteFields = ['activity_details'];
CRM.api3('CustomGroup', 'get', {
sequential: 1,
extends: 'Activity',
'api.CustomField.get': {
data_type: 'Memo',
return: 'name'
}
}).done(function(result) {
result['values'].forEach(function(val) {
val['api.CustomField.get']['values'].forEach(function(field) {
noteFields.push(field.name);
});
});
return noteFields;
});
}
});
| CRM.$(function($) {
var $messageField = $('#customData .custom-group-Letter_To input[data-crm-custom="Letter_To:Message_Field"]')
createEntityRef($messageField, $('#profile_id').val());
$('#profile_id').change( function() {
$messageField.crmEntityRef('destroy');
$messageField.val('');
createEntityRef($messageField, $('#profile_id').val());
});
function createEntityRef($field, profileId) {
noteFields = getNoteFields();
$field.crmEntityRef({
entity: 'UFField',
placeholder: '- Select Field -',
api: {
params: {
uf_group_id: profileId,
field_name: {"IN": noteFields}
}
},
select: {minimumInputLength: 0},
});
}
function getNoteFields() {
var noteFields = ['activity_details'];
CRM.api3('CustomGroup', 'get', {
sequential: 1,
extends: 'Activity',
'api.CustomField.get': {
data_type: 'Memo',
return: 'name'
}
}).done(function(result) {
result['values'].forEach(function(val) {
val['api.CustomField.get']['values'].forEach(function(field) {
noteFields.push(field.name);
});
});
return noteFields;
});
}
});
|
Add method to get complete Authorization Header for adorsys | package de.fau.amos.virtualledger.server.auth;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
public class KeycloakUtilizer {
/**
* extracts the email adress from the keycloak context.
* returns null if not successful.
*/
public String getEmail() {
return getAccessToken().getEmail();
}
/**
* extracts the first name from the keycloak context.
* returns null if not successful.
*/
public String getFirstName() {
return getAccessToken().getGivenName();
}
/**
* extracts the last name from the keycloak context.
* returns null if not successful.
*/
public String getLastName() {
return getAccessToken().getFamilyName();
}
private AccessToken getAccessToken() {
return getKeycloakSecurityContext().getToken();
}
public String getAuthorizationHeader() {
return "Bearer: " + getTokenString();
}
public String getTokenString() {
return getKeycloakSecurityContext().getTokenString();
}
private KeycloakSecurityContext getKeycloakSecurityContext() {
try {
//noinspection unchecked
return ((KeycloakPrincipal<KeycloakSecurityContext>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getKeycloakSecurityContext();
} catch (final Exception e) {
throw new KeycloakException("Failure at getting data about the user by the identity token!");
}
}
}
| package de.fau.amos.virtualledger.server.auth;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
public class KeycloakUtilizer {
/**
* extracts the email adress from the keycloak context.
* returns null if not successful.
*/
public String getEmail() {
return getAccessToken().getEmail();
}
/**
* extracts the first name from the keycloak context.
* returns null if not successful.
*/
public String getFirstName() {
return getAccessToken().getGivenName();
}
/**
* extracts the last name from the keycloak context.
* returns null if not successful.
*/
public String getLastName() {
return getAccessToken().getFamilyName();
}
private AccessToken getAccessToken() {
return getKeycloakSecurityContext().getToken();
}
public String getTokenString() {
return getKeycloakSecurityContext().getTokenString();
}
private KeycloakSecurityContext getKeycloakSecurityContext() {
try {
//noinspection unchecked
return ((KeycloakPrincipal<KeycloakSecurityContext>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getKeycloakSecurityContext();
} catch (final Exception e) {
throw new KeycloakException("Failure at getting data about the user by the identity token!");
}
}
}
|
Add check whether $cancellable is an object | <?php
namespace React\Promise\Internal;
/**
* @internal
*/
final class CancellationQueue
{
private $started = false;
private $queue = [];
public function __invoke(): void
{
if ($this->started) {
return;
}
$this->started = true;
$this->drain();
}
public function enqueue($cancellable): void
{
if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) {
return;
}
$length = \array_push($this->queue, $cancellable);
if ($this->started && 1 === $length) {
$this->drain();
}
}
private function drain(): void
{
for ($i = \key($this->queue); isset($this->queue[$i]); $i++) {
$cancellable = $this->queue[$i];
$exception = null;
try {
$cancellable->cancel();
} catch (\Throwable $exception) {
}
unset($this->queue[$i]);
if ($exception) {
throw $exception;
}
}
$this->queue = [];
}
}
| <?php
namespace React\Promise\Internal;
/**
* @internal
*/
final class CancellationQueue
{
private $started = false;
private $queue = [];
public function __invoke(): void
{
if ($this->started) {
return;
}
$this->started = true;
$this->drain();
}
public function enqueue($cancellable): void
{
if (!\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) {
return;
}
$length = \array_push($this->queue, $cancellable);
if ($this->started && 1 === $length) {
$this->drain();
}
}
private function drain(): void
{
for ($i = \key($this->queue); isset($this->queue[$i]); $i++) {
$cancellable = $this->queue[$i];
$exception = null;
try {
$cancellable->cancel();
} catch (\Throwable $exception) {
}
unset($this->queue[$i]);
if ($exception) {
throw $exception;
}
}
$this->queue = [];
}
}
|
Fix mailing all validators even when they have their students validated | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\ValidationRequest;
use App\Models\ValidatorInvite;
use App\Models\Company;
use App\Models\Validator;
use App\Models\Alert;
use App\Notifications\NewAlerts;
use App\Notifications\ValidationsPending;
class Cleanup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cleanup:all';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Does the cleanup and other daily tasks for Talented Europe entities';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
ValidationRequest::cleanup();
ValidatorInvite::cleanup();
$validators = Validator::whereHas('user', function ($query) {
$query->where('notify_me', true);
})->whereHas('validationRequest.student.user', function ($f) {
$f->where('valid', '!=', 'validated');
})->get();
$alerts = Alert::get();
foreach ($validators as $val) {
$val->user->notify(new ValidationsPending($val->user));
}
foreach ($alerts as $al) {
$al->target->notify(new NewAlerts($al->target));
}
}
}
| <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\ValidationRequest;
use App\Models\ValidatorInvite;
use App\Models\Company;
use App\Models\Validator;
use App\Models\Alert;
use App\Notifications\NewAlerts;
use App\Notifications\ValidationsPending;
class Cleanup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cleanup:all';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Does the cleanup and other daily tasks for Talented Europe entities';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
ValidationRequest::cleanup();
ValidatorInvite::cleanup();
$validators = Validator::whereHas('user', function ($query) {
$query->where('notify_me', true);
})->whereHas('validationRequest')->get();
$alerts = Alert::get();
foreach ($validators as $val) {
$val->user->notify(new ValidationsPending($val->user));
}
foreach ($alerts as $al) {
$al->target->notify(new NewAlerts($al->target));
}
}
}
|
Add convenience methods to get a client config. | package com.afrozaar.wordpress.wpapi.v2.util;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
public class ClientConfig {
Wordpress wordpress;
boolean debug;
public ClientConfig() {
}
private ClientConfig(boolean debug, Wordpress wordpress) {
this.debug = debug;
this.wordpress = wordpress;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public Wordpress getWordpress() {
return wordpress;
}
public void setWordpress(Wordpress wordpress) {
this.wordpress = wordpress;
}
public static ClientConfig load(InputStream inputStream) {
return new Yaml().loadAs(inputStream, ClientConfig.class);
}
public static ClientConfig of(String baseUrl, String username, String password, boolean debug) {
return new ClientConfig(debug, new Wordpress(baseUrl, username, password));
}
public static class Wordpress {
String username;
String password;
String baseUrl;
Wordpress() {
}
private Wordpress(String baseUrl, String username, String password) {
this.baseUrl = baseUrl;
this.password = password;
this.username = username;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
}
| package com.afrozaar.wordpress.wpapi.v2.util;
import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
public class ClientConfig {
Wordpress wordpress;
boolean debug;
public ClientConfig() {
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public Wordpress getWordpress() {
return wordpress;
}
public void setWordpress(Wordpress wordpress) {
this.wordpress = wordpress;
}
public static ClientConfig load(InputStream inputStream) {
return new Yaml().loadAs(inputStream, ClientConfig.class);
}
public static class Wordpress {
String username;
String password;
String baseUrl;
public Wordpress() {
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
}
|
Change 'password_reset_done' URL name to 'password_reset_complete'
The built-in password reset views use a different name for the last page in the
flow than we did before, and somehow we never noticed this until recently.
Trivial fix.
Fixes bug 3345. | from __future__ import unicode_literals
from django.conf.urls import patterns, url
from reviewboard.accounts.views import MyAccountView
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$',
MyAccountView.as_view(),
name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
| from __future__ import unicode_literals
from django.conf.urls import patterns, url
from reviewboard.accounts.views import MyAccountView
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$',
MyAccountView.as_view(),
name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
Store default value in root. | function Supersede (value) {
this._root = { '.value': value }
}
Supersede.prototype.set = function (path, value) {
var node = this._root
for (var i = 0, I = path.length; i < I; i++) {
if (!node[path[i]]) {
node[path[i]] = {}
}
node = node[path[i]]
}
node['.value'] = value
return value
}
Supersede.prototype.remove = function (path) {
var stop = path.length - 1
var unset = path[stop]
var value = this._value, parent = this._root, node, i = 0
while (i < stop && (node = parent[path[i]])) {
i++
parent = node
}
if (i == stop) {
if (unset == '*') {
for (var key in parent) {
if (key != '.value') {
delete parent[key]
}
}
} else {
delete parent[unset]
}
}
}
Supersede.prototype.get = function (path) {
var node = this._root, i = 0, value
do {
value = node['.value'] == null ? value : node['.value']
node = node[path[i++]]
} while (node)
return value
}
module.exports = Supersede
| function Supersede (value) {
this._root = {}
this._value = value
}
Supersede.prototype.set = function (path, value) {
var node = this._root
for (var i = 0, I = path.length; i < I; i++) {
if (!node[path[i]]) {
node[path[i]] = {}
}
node = node[path[i]]
}
node['.value'] = value
return value
}
Supersede.prototype.remove = function (path) {
var stop = path.length - 1
var unset = path[stop]
var value = this._value, parent = this._root, node, i = 0
while (i < stop && (node = parent[path[i]])) {
i++
parent = node
}
if (i == stop) {
if (unset == '*') {
for (var key in parent) {
if (key != '.value') {
delete parent[key]
}
}
} else {
delete parent[unset]
}
}
}
Supersede.prototype.get = function (path) {
var value = this._value, node = this._root, child, i = 0
while (child = node[path[i++]]) {
node = child
value = node['.value'] == null ? value : node['.value']
}
return value
}
module.exports = Supersede
|
Fix - namespace in test | <?php
use JakubOnderka\PhpVarDumpCheck;
class ZendTest extends PHPUnit_Framework_TestCase
{
protected $uut;
public function __construct()
{
$settings = new PhpVarDumpCheck\Settings();
$settings->functionsToCheck = array_merge($settings->functionsToCheck, array(
PhpVarDumpCheck\Settings::ZEND_DEBUG_DUMP,
PhpVarDumpCheck\Settings::ZEND_DEBUG_DUMP_2,
));
$this->uut = new PhpVarDumpCheck\Checker($settings);
}
public function testCheck_zendDebugDump()
{
$content = <<<PHP
<?php
Zend_Debug::dump(\$var);
PHP;
$result = $this->uut->check($content);
$this->assertCount(1, $result);
}
public function testCheck_zendDebugDumpReturn()
{
$content = <<<PHP
<?php
Zend_Debug::dump(\$var, null, false);
PHP;
$result = $this->uut->check($content);
$this->assertCount(1, $result);
}
/**
* Namespaces
*/
public function testCheck_zendNamespaceDump()
{
$content = <<<PHP
<?php
\\Zend\\Debug\\Debug::dump(\$form);
PHP;
$result = $this->uut->check($content);
$this->assertCount(1, $result);
}
}
| <?php
use JakubOnderka\PhpVarDumpCheck;
class ZendTest extends PHPUnit_Framework_TestCase
{
protected $uut;
public function __construct()
{
$settings = new PhpVarDumpCheck\Settings();
$settings->functionsToCheck = array_merge($settings->functionsToCheck, array(
PhpVarDumpCheck\Settings::ZEND_DEBUG_DUMP,
PhpVarDumpCheck\Settings::ZEND_DEBUG_DUMP_2,
));
$this->uut = new PhpVarDumpCheck\Checker($settings);
}
public function testCheck_zendDebugDump()
{
$content = <<<PHP
<?php
Zend_Debug::dump(\$var);
PHP;
$result = $this->uut->check($content);
$this->assertCount(1, $result);
}
public function testCheck_zendDebugDumpReturn()
{
$content = <<<PHP
<?php
Zend_Debug::dump(\$var, null, false);
PHP;
$result = $this->uut->check($content);
$this->assertCount(1, $result);
}
/**
* Namespaces
*/
public function testCheck_zendNamespaceDump()
{
$content = <<<PHP
<?php
\Zend\Debug\Debug::dump(\$form);
PHP;
$result = $this->uut->check($content);
$this->assertCount(1, $result);
}
}
|
IFS-5895: Add support for totals to other costs rows | package org.innovateuk.ifs.project.grantofferletter.viewmodel;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singletonList;
/*
* Holder of values for the other costs rows on GOL finance tables, which are handled differently
*/
public class OtherCostsRowModel {
private final String otherCostName;
private Map<String, List<BigDecimal>> otherCostValues;
public OtherCostsRowModel(String otherCostName,
Map<String, List<BigDecimal>> otherCostValues) {
this.otherCostName = otherCostName;
this.otherCostValues = otherCostValues;
}
public String getOtherCostName() {
return otherCostName;
}
public Map<String, List<BigDecimal>> getOtherCostValues() {
return otherCostValues;
}
public void addToCostValues(String orgName, BigDecimal cost) {
if(otherCostValues.keySet().contains(orgName)) {
otherCostValues.get(orgName).add(cost);
} else {
otherCostValues.put(orgName, singletonList(cost));
}
}
public Collection<String> getOrganisations() {
return otherCostValues.keySet();
}
public BigDecimal getCostValuesForOrg(String organisation) {
return otherCostValues.get(organisation)
.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public BigDecimal getTotal() {
return otherCostValues == null ?
BigDecimal.ZERO :
otherCostValues
.values()
.stream()
.flatMap(List::stream)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
| package org.innovateuk.ifs.project.grantofferletter.viewmodel;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static java.util.Collections.singletonList;
/*
* Holder of values for the other costs rows on GOL finance tables, which are handled differently
*/
public class OtherCostsRowModel {
private final String otherCostName;
private Map<String, List<BigDecimal>> otherCostValues;
public OtherCostsRowModel(String otherCostName,
Map<String, List<BigDecimal>> otherCostValues) {
this.otherCostName = otherCostName;
this.otherCostValues = otherCostValues;
}
public String getOtherCostName() {
return otherCostName;
}
public Map<String, List<BigDecimal>> getOtherCostValues() {
return otherCostValues;
}
public void addToCostValues(String orgName, BigDecimal cost) {
if(otherCostValues.keySet().contains(orgName)) {
otherCostValues.get(orgName).add(cost);
} else {
otherCostValues.put(orgName, singletonList(cost));
}
}
public Collection<String> getOrganisations() {
return otherCostValues.keySet();
}
public BigDecimal getCostValuesForOrg(String organisation) {
return otherCostValues.get(organisation)
.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
|
747: Handle setting values of '' and ' ' | from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation
SET value = 5
WHERE master_id = {master_id} AND value IN (NULL, "", " ");
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
| from __future__ import unicode_literals
from django.db import migrations, connection
def set_default_news_items(apps, schema_editor):
Plugin = apps.get_model("utils", "Plugin")
Journal = apps.get_model("journal", "Journal")
PluginSetting = apps.get_model("utils", "PluginSetting")
PluginSettingValue = apps.get_model("utils", "PluginSettingValue")
try:
plugin = Plugin.objects.get(name="News")
except Plugin.DoesNotExist:
pass
else:
journals = Journal.objects.all()
for journal in journals:
plugin_setting, c = PluginSetting.objects.get_or_create(
plugin=plugin,
name="number_of_articles"
)
plugin_setting_value, c = PluginSettingValue.objects.get_or_create(
setting=plugin_setting,
journal=journal
)
SQL = """
UPDATE utils_pluginsettingvalue_translation SET
value = 5 WHERE master_id = {master_id} AND value IS NULL;
""".format(master_id=plugin_setting_value.pk)
with connection.cursor() as cursor:
cursor.execute(SQL)
class Migration(migrations.Migration):
dependencies = [
('core', '0018_auto_20181116_1123'),
('utils', '0009_auto_20180808_1514'),
]
operations = [
migrations.RunPython(
set_default_news_items,
reverse_code=migrations.RunPython.noop
),
]
|
Annotate return types of Model properties | import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
from .system import System as _System
from .hamiltonian import Hamiltonian as _Hamiltonian
from .solver.solver_ex import SolverEx as _Solver
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self) -> _System:
sys = super().system
sys.__class__ = _System
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self) -> _Hamiltonian:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham
@property
def hamiltonian(self) -> _csrmatrix:
ham = super().hamiltonian
ham.__class__ = _Hamiltonian
return ham.matrix.to_scipy_csr()
@property
def solver(self) -> _Solver:
sol = super().solver
sol.__class__ = _Solver
sol.system = self.system
return sol
| import _pybinding
from scipy.sparse import csr_matrix as _csrmatrix
class Model(_pybinding.Model):
def __init__(self, *params):
super().__init__()
self.add(*params)
def add(self, *params):
for param in params:
if param is None:
continue
if isinstance(param, (tuple, list)):
self.add(*param)
else:
super().add(param)
def calculate(self, result):
self._calculate(result)
return result
@property
def system(self):
from .system import System as SystemEx
sys = super().system
sys.__class__ = SystemEx
sys.shape = self.shape
sys.lattice = self.lattice
return sys
@property
def _hamiltonian(self):
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham
@property
def hamiltonian(self) -> _csrmatrix:
from .hamiltonian import Hamiltonian as HamiltonianEx
ham = super().hamiltonian
ham.__class__ = HamiltonianEx
return ham.matrix.to_scipy_csr()
@property
def solver(self):
from .solver.solver_ex import SolverEx
sol = super().solver
sol.__class__ = SolverEx
sol.system = self.system
return sol
|
Fix bad comment on header | /**
+ * Korean translation for bootstrap-markdown
+ * WoongBi Kim <[email protected]>
+ */
;(function($){
$.fn.markdown.messages['kr'] = {
'Bold': "진하게",
'Italic': "이탤릭체",
'Heading': "머리글",
'URL/Link': "링크주소",
'Image': "이미지",
'List': "리스트",
'Preview': "미리보기",
'strong text': "강한 강조 텍스트",
'emphasized text': "강조 텍스트",
'heading text': "머리글 텍스트",
'enter link description here': "여기에 링크의 설명을 적으세요",
'Insert Hyperlink': "하이퍼링크 삽입",
'enter image description here': "여기세 이미지 설명을 적으세요",
'Insert Image Hyperlink': "이미지 링크 삽입",
'enter image title here': "여기에 이미지 제목을 적으세요",
'list text here': "리스트 텍스트"
};
}(jQuery))
| +/**
+ * Korean translation for bootstrap-markdown
+ * WoongBi Kim <[email protected]>
+ */
;(function($){
$.fn.markdown.messages['kr'] = {
'Bold': "진하게",
'Italic': "이탤릭체",
'Heading': "머리글",
'URL/Link': "링크주소",
'Image': "이미지",
'List': "리스트",
'Preview': "미리보기",
'strong text': "강한 강조 텍스트",
'emphasized text': "강조 텍스트",
'heading text': "머리글 텍스트",
'enter link description here': "여기에 링크의 설명을 적으세요",
'Insert Hyperlink': "하이퍼링크 삽입",
'enter image description here': "여기세 이미지 설명을 적으세요",
'Insert Image Hyperlink': "이미지 링크 삽입",
'enter image title here': "여기에 이미지 제목을 적으세요",
'list text here': "리스트 텍스트"
};
}(jQuery))
|
Fix constantine death on integers | Constants = (function() {
var CONSTANTS_URI = 'http://constantine.teaisaweso.me/json';
var gotConstants = new Bacon.Bus();
var constants = gotConstants.toProperty().skipDuplicates(_.isEqual);
var getAll = function(callback) {
constants.onValue(callback);
};
var reload = function() {
var rawConstants = $.get(CONSTANTS_URI);
var typeDecoders = {'string': function(x) { return x; },
'float': parseFloat,
'integer': parseFloat,
'boolean': function(x) { return x; }};
rawConstants.done(function(value) {
var baseValues = JSON.parse(value);
var actualConstants = {};
_.each(baseValues['constants'], function(tuple) {
actualConstants[tuple.name] = typeDecoders[tuple.type](tuple.value);
});
gotConstants.push(actualConstants);
});
};
var get = function(keys, callback) {
if (typeof keys === "string") {
keys = [keys];
}
var newStream = constants.map(function(x) {
return _.map(keys, function(y) { return x[y]; });
}).skipDuplicates(_.isEqual);
newStream.onValues(callback);
};
constants.onValue(function() {
console.log("Constants loaded.");
});
$(_.defer(reload));
// reload periodically, for dev
setInterval(reload, 2500);
return {'getAll': getAll,
'get': get,
'reload': reload};
}());
| Constants = (function() {
var CONSTANTS_URI = 'http://constantine.teaisaweso.me/json';
var gotConstants = new Bacon.Bus();
var constants = gotConstants.toProperty().skipDuplicates(_.isEqual);
var getAll = function(callback) {
constants.onValue(callback);
};
var reload = function() {
var rawConstants = $.get(CONSTANTS_URI);
var typeDecoders = {'string': function(x) { return x; },
'float': parseFloat,
'int': parseFloat,
'boolean': function(x) { return x; }};
rawConstants.done(function(value) {
var baseValues = JSON.parse(value);
var actualConstants = {};
_.each(baseValues['constants'], function(tuple) {
actualConstants[tuple.name] = typeDecoders[tuple.type](tuple.value);
});
gotConstants.push(actualConstants);
});
};
var get = function(keys, callback) {
if (typeof keys === "string") {
keys = [keys];
}
var newStream = constants.map(function(x) {
return _.map(keys, function(y) { return x[y]; });
}).skipDuplicates(_.isEqual);
newStream.onValues(callback);
};
constants.onValue(function() {
console.log("Constants loaded.");
});
$(_.defer(reload));
// reload periodically, for dev
setInterval(reload, 2500);
return {'getAll': getAll,
'get': get,
'reload': reload};
}());
|
Allow canary to fail without failing all tests | /*jshint node:true*/
module.exports = {
scenarios: [
{
name: 'default',
bower: {
dependencies: { }
}
},
{
name: 'ember-1.13',
bower: {
dependencies: {
'ember': '~1.13.0'
},
resolutions: {
'ember': '~1.13.0'
}
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
}
},
{
name: 'ember-canary',
allowedToFail: true,
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
}
]
};
| /*jshint node:true*/
module.exports = {
scenarios: [
{
name: 'default',
bower: {
dependencies: { }
}
},
{
name: 'ember-1.13',
bower: {
dependencies: {
'ember': '~1.13.0'
},
resolutions: {
'ember': '~1.13.0'
}
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
}
}
]
};
|
Use https ONLY in development | /**
* @file lib/index.js
* @description Runs a single server instance to run the application.
* @author Karim Alibhai
* @license MIT
* @copyright Karim Alibhai 2017
*/
import fs from 'fs'
import path from 'path'
import express from 'express'
import autocomplete from './search/autocomplete'
import nearby from './search/nearby'
const app = express()
, http = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV ?
require('https').createServer({
key: fs.readFileSync(path.resolve(__dirname, '..', 'ssl', 'server.key')),
cert: fs.readFileSync(path.resolve(__dirname, '..', 'ssl', 'server.crt'))
}, app) :
require('http').createServer(app)
, io = require('socket.io')(http)
app.use(require('morgan')('dev'))
app.use(express.static(path.join(__dirname, '..', 'public')))
io.on('connection', sock => {
sock.on('autocomplete', query =>
autocomplete(query)
.then(results =>
sock.emit(
'autocomplete:results',
results.filter(res => res.toLowerCase().startsWith(query.query.toLowerCase()))[0]
)
).catch(err => sock.emit('failure', err))
)
sock.on('nearby', query =>
nearby(query)
.then(results => sock.emit('nearby:results', results))
.catch(err => sock.emit('failure', err))
)
})
export default http | /**
* @file lib/index.js
* @description Runs a single server instance to run the application.
* @author Karim Alibhai
* @license MIT
* @copyright Karim Alibhai 2017
*/
import fs from 'fs'
import path from 'path'
import express from 'express'
import autocomplete from './search/autocomplete'
import nearby from './search/nearby'
const app = express()
, http = process.env.NODE_ENV === 'test' ?
require('https').createServer({
key: fs.readFileSync(path.resolve(__dirname, '..', 'ssl', 'server.key')),
cert: fs.readFileSync(path.resolve(__dirname, '..', 'ssl', 'server.crt'))
}, app) :
require('http').createServer(app)
, io = require('socket.io')(http)
app.use(require('morgan')('dev'))
app.use(express.static(path.join(__dirname, '..', 'public')))
io.on('connection', sock => {
sock.on('autocomplete', query =>
autocomplete(query)
.then(results =>
sock.emit(
'autocomplete:results',
results.filter(res => res.toLowerCase().startsWith(query.query.toLowerCase()))[0]
)
).catch(err => sock.emit('failure', err))
)
sock.on('nearby', query =>
nearby(query)
.then(results => sock.emit('nearby:results', results))
.catch(err => sock.emit('failure', err))
)
})
export default http |
Remove useless return in exec() callback | var fs = require('fs')
, findExec = require('find-exec')
, child_process = require('child_process')
, players = [
'mplayer',
'afplay',
'mpg123',
'mpg321',
'play'
]
function Play(opts){
opts = opts || {}
this.players = opts.players || players
this.player = opts.player || findExec(this.players)
var exec = child_process.exec
this.play = function(what, next){
next = next || function(){}
if (!what) return next(new Error("No audio file specified"));
try {
if (!fs.statSync(what).isFile()){
return next(new Error(what + " is not a file"));
}
} catch (err){
return next(new Error("File doesn't exist: " + what));
}
if (!this.player){
return next(new Error("Couldn't find a suitable audio player"))
}
exec(this.player + ' ' + what, function(err, stdout, stderr){
next(err);
})
}
this.test = function(next) { this.play('./assets/test.mp3', next) }
}
module.exports = function(opts){
return new Play(opts)
}
| var fs = require('fs')
, findExec = require('find-exec')
, child_process = require('child_process')
, players = [
'mplayer',
'afplay',
'mpg123',
'mpg321',
'play'
]
function Play(opts){
opts = opts || {}
this.players = opts.players || players
this.player = opts.player || findExec(this.players)
var exec = child_process.exec
this.play = function(what, next){
next = next || function(){}
if (!what) return next(new Error("No audio file specified"));
try {
if (!fs.statSync(what).isFile()){
return next(new Error(what + " is not a file"));
}
} catch (err){
return next(new Error("File doesn't exist: " + what));
}
if (!this.player){
return next(new Error("Couldn't find a suitable audio player"))
}
exec(this.player + ' ' + what, function(err, stdout, stderr){
return next(err);
})
}
this.test = function(next) { this.play('./assets/test.mp3', next) }
}
module.exports = function(opts){
return new Play(opts)
}
|
Add missing api key in product picker.
Fixes #6185 | $.fn.productAutocomplete = function (options) {
'use strict';
// Default options
options = options || {};
var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true;
this.select2({
minimumInputLength: 3,
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(','),
token: Spree.api_key
}, function (data) {
callback(multiple ? data.products : data.products[0]);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
| $.fn.productAutocomplete = function (options) {
'use strict';
// Default options
options = options || {};
var multiple = typeof(options.multiple) !== 'undefined' ? options.multiple : true;
this.select2({
minimumInputLength: 3,
multiple: multiple,
initSelection: function (element, callback) {
$.get(Spree.routes.product_search, {
ids: element.val().split(',')
}, function (data) {
callback(multiple ? data.products : data.products[0]);
});
},
ajax: {
url: Spree.routes.product_search,
datatype: 'json',
data: function (term, page) {
return {
q: {
name_cont: term,
sku_cont: term
},
m: 'OR',
token: Spree.api_key
};
},
results: function (data, page) {
var products = data.products ? data.products : [];
return {
results: products
};
}
},
formatResult: function (product) {
return product.name;
},
formatSelection: function (product) {
return product.name;
}
});
};
$(document).ready(function () {
$('.product_picker').productAutocomplete();
});
|
Enable fuzziness + AND phrases when searching text | const fp = require('lodash/fp')
const elastic = require('./index')
const toBody = message =>
fp.pick([
'timestamp',
'from',
'to',
'text',
], message)
const indexMessage = message => {
return elastic.index({
index: 'messages',
type: 'message',
id: message.id,
body: toBody(message),
})
}
const indexMessages = messages => {
return elastic.bulk({
body: fp.flatMap(message => [
{ index: { _index: 'messages', _type: 'message', _id: message.id }},
toBody(message),
], messages),
})
}
const searchMessages = async (channel, query, limit, afterTimestamp) => {
let body = {
size: limit,
sort: [{ timestamp: { order: 'desc' }}],
query: {
bool: {
filter: fp.concat(
{ term: { to: channel }},
!query.nick ? [] : { term: { from: query.nick }}
),
must: !query.text ? [] : [{
match: {
text: {
query: query.text,
operator: 'and',
fuzziness: 'auto',
}
},
}],
},
},
}
if (afterTimestamp) {
body.search_after = [+afterTimestamp]
}
const { hits } = await elastic.search({
index: 'messages',
type: 'message',
body,
})
return hits
}
module.exports = { indexMessage, indexMessages, searchMessages }
| const fp = require('lodash/fp')
const elastic = require('./index')
const toBody = message =>
fp.pick([
'timestamp',
'from',
'to',
'text',
], message)
const indexMessage = message => {
return elastic.index({
index: 'messages',
type: 'message',
id: message.id,
body: toBody(message),
})
}
const indexMessages = messages => {
return elastic.bulk({
body: fp.flatMap(message => [
{ index: { _index: 'messages', _type: 'message', _id: message.id }},
toBody(message),
], messages),
})
}
const searchMessages = async (channel, query, limit, afterTimestamp) => {
let body = {
size: limit,
sort: [{ timestamp: { order: 'desc' }}],
query: {
bool: {
filter: fp.concat(
{ term: { to: channel }},
!query.nick ? [] : { term: { from: query.nick }}
),
must: !query.text ? [] : [{
match: { text: query.text },
}],
},
},
}
if (afterTimestamp) {
body.search_after = [+afterTimestamp]
}
const { hits } = await elastic.search({
index: 'messages',
type: 'message',
body,
})
return hits
}
module.exports = { indexMessage, indexMessages, searchMessages }
|
Fix scope when setting up multiprocessing with coverage | import os
import sys
def patch_process_for_coverage():
# patch multiprocessing module to get coverage
# https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by
from coverage.collector import Collector
from coverage import coverage
import multiprocessing
# detect if coverage was running in forked process
if sys.version_info >= (3, 4):
klass = multiprocessing.process.BaseProcess
else:
klass = multiprocessing.Process
if Collector._collectors:
original = multiprocessing.Process._bootstrap
class ProcessWithCoverage(multiprocessing.Process):
def _bootstrap(self):
cov = coverage(
data_suffix=True,
config_file=os.getenv('COVERAGE_PROCESS_START', True)
)
cov.start()
try:
return original(self)
finally:
cov.stop()
cov.save()
if sys.version_info >= (3, 4):
klass._bootstrap = ProcessWithCoverage._bootstrap
else:
multiprocessing.Process = ProcessWithCoverage
if os.getenv('FULL_COVERAGE', 'false') == 'true':
try:
import coverage
coverage.process_startup()
patch_process_for_coverage()
except ImportError:
pass
| import os
import sys
def patch_process_for_coverage():
# patch multiprocessing module to get coverage
# https://bitbucket.org/ned/coveragepy/issue/117/enable-coverage-measurement-of-code-run-by
from coverage.collector import Collector
from coverage import coverage
import multiprocessing
# detect if coverage was running in forked process
if sys.version_info >= (3, 4):
klass = multiprocessing.process.BaseProcess
else:
klass = multiprocessing.Process
if Collector._collectors:
original = multiprocessing.Process._bootstrap
class ProcessWithCoverage(multiprocessing.Process):
def _bootstrap(self):
cov = coverage(
data_suffix=True,
config_file=os.getenv('COVERAGE_PROCESS_START', True)
)
cov.start()
try:
return original(self)
finally:
cov.stop()
cov.save()
if sys.version_info >= (3, 4):
klass._bootstrap = ProcessWithCoverage._bootstrap
else:
multiprocessing.Process = ProcessWithCoverage
if os.getenv('FULL_COVERAGE', 'false') == 'true':
try:
import coverage
coverage.process_startup()
patch_process_for_coverage()
except ImportError:
pass
|
Make timeout error an assertion error, not just any old exception
This means that timeout failures are considered to be test failures, where a specific assertion (i.e. 'this function takes less than N seconds') has failed, rather than being a random error in the test that may indicate a bug. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2012-2013 by PN.
:license: MIT, see LICENSE for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import signal
from functools import wraps
############################################################
# Timeout
############################################################
#http://www.saltycrane.com/blog/2010/04/using-python-timeout-decorator-uploading-s3/
class TimeoutError(AssertionError):
def __init__(self, value="Timed Out"):
self.value = value
def __str__(self):
return repr(self.value)
def timeout(seconds=None):
def decorate(f):
def handler(signum, frame):
raise TimeoutError()
@wraps(f)
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
new_seconds = kwargs['timeout'] if 'timeout' in kwargs else seconds
if new_seconds is None:
raise ValueError("You must provide a timeout value")
signal.alarm(new_seconds)
try:
result = f(*args, **kwargs)
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
return new_f
return decorate
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:copyright: (c) 2012-2013 by PN.
:license: MIT, see LICENSE for more details.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import signal
from functools import wraps
############################################################
# Timeout
############################################################
#http://www.saltycrane.com/blog/2010/04/using-python-timeout-decorator-uploading-s3/
class TimeoutError(Exception):
def __init__(self, value="Timed Out"):
self.value = value
def __str__(self):
return repr(self.value)
def timeout(seconds=None):
def decorate(f):
def handler(signum, frame):
raise TimeoutError()
@wraps(f)
def new_f(*args, **kwargs):
old = signal.signal(signal.SIGALRM, handler)
new_seconds = kwargs['timeout'] if 'timeout' in kwargs else seconds
if new_seconds is None:
raise ValueError("You must provide a timeout value")
signal.alarm(new_seconds)
try:
result = f(*args, **kwargs)
finally:
signal.signal(signal.SIGALRM, old)
signal.alarm(0)
return result
return new_f
return decorate
|
Watch task on *all* scss files now. | 'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
//gulp.task('sass', function () {
// gulp.src('./sass/**/*.scss')
// .pipe(sass().on('error', sass.logError))
// .pipe(gulp.dest('./css'));
//});
//gulp.task('sass:watch', function () {
// gulp.watch('./sass/**/*.scss', ['sass']);
//});
gulp.task('default', ['sass']);
gulp.task('sass', function(done) {
var generatedStyleFolder = './generated/';
gulp.src('./style/won.scss')
.pipe(sass({
errLogToConsole: true
}))
.pipe(autoprefixer({
browsers: ['last 3 versions'],
cascade: false
}))
.pipe(gulp.dest(generatedStyleFolder))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest(generatedStyleFolder))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch('./style/**/*.scss', ['sass']);
}); | 'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
//gulp.task('sass', function () {
// gulp.src('./sass/**/*.scss')
// .pipe(sass().on('error', sass.logError))
// .pipe(gulp.dest('./css'));
//});
//gulp.task('sass:watch', function () {
// gulp.watch('./sass/**/*.scss', ['sass']);
//});
gulp.task('default', ['sass']);
gulp.task('sass', function(done) {
var generatedStyleFolder = './generated/';
gulp.src('./style/won.scss')
.pipe(sass({
errLogToConsole: true
}))
.pipe(autoprefixer({
browsers: ['last 3 versions'],
cascade: false
}))
.pipe(gulp.dest(generatedStyleFolder))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest(generatedStyleFolder))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch('./style/won.scss', ['sass']);
}); |
Allow for switching to default context | if (browser.contextualIdentities !== undefined) {
browser.contextualIdentities.query({})
.then((contexts) => {
const parentId = chrome.contextMenus.create({
id: "moveContext",
title: "Move to context",
contexts: ["tab"]
});
const contextStore = contexts.reduce((store, context) => {
return Object.assign({}, store, {
[`contextPlus-${context.name}`]: context.cookieStoreId
});
}, {});
// Add a default context manually.
// Hope the name of the default cookieStore never changes :)
contextStore['contextPlus-default'] = 'firefox-default';
browser.contextMenus.create({
type: "normal",
title: "Default",
id: 'contextPlus-default',
parentId
});
contexts.forEach(context => {
chrome.contextMenus.create({
type: "normal",
title: context.name,
id: `contextPlus-${context.name}`,
parentId
});
});
browser.contextMenus.onClicked.addListener(function (info, tab) {
if (contextStore.hasOwnProperty(info.menuItemId)) {
const cookieStoreId = contextStore[info.menuItemId];
const newTabData = {
active,
index,
pinned,
url,
windowId
} = tab;
browser.tabs.create({
active,
cookieStoreId,
index,
pinned,
url,
windowId
}).then(() => browser.tabs.remove(tab.id));
}
});
});
}
| if (browser.contextualIdentities !== undefined) {
browser.contextualIdentities.query({})
.then((contexts) => {
const parentId = chrome.contextMenus.create({
id: "moveContext",
title: "Move to context",
contexts: ["tab"]
});
const contextStore = contexts.reduce((store, context) => {
return Object.assign({}, store, {
[`contextPlus-${context.name}`]: context.cookieStoreId
});
}, {});
contexts.forEach(context => {
chrome.contextMenus.create({
type: "normal",
title: context.name,
id: `contextPlus-${context.name}`,
parentId
});
});
browser.contextMenus.onClicked.addListener(function (info, tab) {
if (contextStore.hasOwnProperty(info.menuItemId)) {
const cookieStoreId = contextStore[info.menuItemId];
const newTabData = {
active,
index,
pinned,
url,
windowId
} = tab;
browser.tabs.create({
active,
cookieStoreId,
index,
pinned,
url,
windowId
}).then(() => browser.tabs.remove(tab.id));
}
});
});
}
|
Fix security context annotation return type | <?php
/**
*
* @author Andriy Oblivantsev <[email protected]>
* @copyright 19.02.2015 by WhereGroup GmbH & Co. KG
*/
namespace Mapbender\CoreBundle\Component;
use FOM\UserBundle\Entity\User;
/**
* Class SecurityContext
*
* @package FOM\UserBundle\Component
* @author Andriy Oblivantsev <[email protected]>
* @copyright 2015 by WhereGroup GmbH & Co. KG
*/
class SecurityContext extends \Symfony\Component\Security\Core\SecurityContext
{
/**
* Get current logged user by the token
*
* @return User
*/
public function getUser()
{
/** @var User $user */
$user = $this->getToken()->getUser();
if (!is_object($user) && is_string($user) && $user == 'anon.') {
$user = new User();
$user->setUsername("anon.");
}
return $user;
}
/**
* Get current user role list
*
* @return array Role name list
*/
public function getRolesAsArray()
{
$userRoles = $this->getToken()->getRoles();
$temp = array();
foreach ($userRoles as $role) {
$temp[] = $role->getRole();
}
return $temp;
}
} | <?php
/**
*
* @author Andriy Oblivantsev <[email protected]>
* @copyright 19.02.2015 by WhereGroup GmbH & Co. KG
*/
namespace Mapbender\CoreBundle\Component;
use FOM\UserBundle\Component\User\UserEntityInterface;
use FOM\UserBundle\Entity\User;
/**
* Class SecurityContext
*
* @package FOM\UserBundle\Component
* @author Andriy Oblivantsev <[email protected]>
* @copyright 2015 by WhereGroup GmbH & Co. KG
*/
class SecurityContext extends \Symfony\Component\Security\Core\SecurityContext
{
/**
* Get current logged user by the token
*
* @return UserEntityInterface
*/
public function getUser()
{
/** @var User $user */
$user = $this->getToken()->getUser();
if (!is_object($user) && is_string($user) && $user == 'anon.') {
$user = new User();
$user->setUsername("anon.");
}
return $user;
}
/**
* Get current user role list
*
* @return array Role name list
*/
public function getRolesAsArray()
{
$userRoles = $this->getToken()->getRoles();
$temp = array();
foreach ($userRoles as $role) {
$temp[] = $role->getRole();
}
return $temp;
}
} |
Fix issue with toggling in queries with dropdown menu | import { inject, bindable } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
@inject(EventAggregator, Element)
export class UiDropdownMenuItemCustomElement {
@bindable icon;
@bindable toggle;
@bindable toggleSource;
constructor(eventAggregator, element) {
this.isToggled = false;
this.ea = eventAggregator;
this.element = element;
this.setToggle = event => {
if (this.toggle) {
if (this.toggle in this.toggleSource) {
if (this.toggleSource[this.toggle] == 'True') {
this.toggleSource[this.toggle] = 'False';
this.isToggled = false;
} else {
this.toggleSource[this.toggle] = 'True';
this.isToggled = true;
}
// delete this.toggleSource[this.toggle];
} else {
this.toggleSource[this.toggle] = 'True';
this.isToggled = true;
}
this.ea.publish('queryChanged', {param: this.toggle, source: this.toggleSource});
}
};
}
attached() {
if (this.toggle && this.toggle in this.toggleSource) {
if (this.toggleSource[this.toggle] == 'False') {
this.isToggled = false;
} else {
this.isToggled = true;
}
}
this.element.addEventListener('click', this.setToggle);
}
detached() {
this.element.removeEventListener('click', this.setToggle);
}
}
| import { inject, bindable } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
@inject(EventAggregator, Element)
export class UiDropdownMenuItemCustomElement {
@bindable icon;
@bindable toggle;
@bindable toggleSource;
constructor(eventAggregator, element) {
this.isToggled = false;
this.ea = eventAggregator;
this.element = element;
this.setToggle = event => {
if (this.toggle) {
if (this.toggle in this.toggleSource) {
delete this.toggleSource[this.toggle];
this.isToggled = false;
} else {
this.toggleSource[this.toggle] = 'True';
this.isToggled = true;
}
this.ea.publish('queryChanged', {param: this.toggle, source: this.toggleSource});
}
};
}
attached() {
if (this.toggle && this.toggle in this.toggleSource) {
this.isToggled = true;
}
this.element.addEventListener('click', this.setToggle);
}
detached() {
this.element.removeEventListener('click', this.setToggle);
}
}
|
Improve the schema for classes to store hours and minutes separately | package com.satsumasoftware.timetable.db;
public final class ClassesSchema {
public static final String TABLE_NAME = "classes";
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME_HRS = "start_time_hrs";
public static final String COL_START_TIME_MINS = "start_time_mins";
public static final String COL_END_TIME_HRS = "end_time_hrs";
public static final String COL_END_TIME_MINS = "end_time_mins";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_HRS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME_MINS + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
protected static final String SQL_DELETE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
}
| package com.satsumasoftware.timetable.db;
public final class ClassesSchema {
public static final String TABLE_NAME = "classes";
public static final String COL_ID = "id";
public static final String COL_SUBJECT_ID = "subject_id";
public static final String COL_DAY = "day";
public static final String COL_START_TIME = "start_time";
public static final String COL_END_TIME = "end_time";
public static final String COL_ROOM = "room";
public static final String COL_TEACHER = "teacher";
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
COL_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_SUBJECT_ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_DAY + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_START_TIME + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_END_TIME + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_ROOM + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
COL_TEACHER + SchemaUtilsKt.TEXT_TYPE +
" )";
protected static final String SQL_DELETE =
"DROP TABLE IF EXISTS " + TABLE_NAME;
}
|
Remove GET options in url | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = message
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/recommender/', methods=['POST'])
def recommender():
content = request.get_json()
if content is not None:
doc = content.get('doc', {})
docs = content.get('docs', [])
if doc == {}:
msg = 'The parameter `doc` is missing or empty'
raise InvalidUsage(msg)
if len(docs) == 0:
msg = 'The parameter `docs` is missing or empty'
raise InvalidUsage(msg)
result = recommend(doc, docs)
return jsonify(result)
else:
msg = 'You need to send the parameters: doc and docs'
raise InvalidUsage(msg)
| from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = message
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/recommender/', methods=['GET', 'POST'])
def recommender():
content = request.get_json()
if content is not None:
doc = content.get('doc', {})
docs = content.get('docs', [])
if doc == {}:
msg = 'The parameter `doc` is missing or empty'
raise InvalidUsage(msg)
if len(docs) == 0:
msg = 'The parameter `docs` is missing or empty'
raise InvalidUsage(msg)
result = recommend(doc, docs)
return jsonify(result)
else:
msg = 'You need to send the parameters: doc and docs'
raise InvalidUsage(msg)
|
Use standardized S3 environment variables. | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. A "local" driver, as well as a variety of cloud
| based drivers are available for your choosing. Just store away!
|
| Supported: "local", "s3", "rackspace"
|
*/
'default' => env('STORAGE_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path().'/app',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY'),
'secret' => env('AWS_SECRET_KEY'),
'region' => 'us-east-1',
'bucket' => env('S3_BUCKET'),
],
],
];
| <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. A "local" driver, as well as a variety of cloud
| based drivers are available for your choosing. Just store away!
|
| Supported: "local", "s3", "rackspace"
|
*/
'default' => env('STORAGE_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => 's3',
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path().'/app',
],
's3' => [
'driver' => 's3',
'key' => env('S3_KEY'),
'secret' => env('S3_SECRET'),
'region' => 'us-east-1',
'bucket' => env('S3_BUCKET'),
],
],
];
|
Fix code to follow eslint rules | 'use babel';
/* global atom */
import { exec } from 'child-process-promise';
import { dirname } from 'path';
export default {
config: {
vhdlCompiler: {
title: 'VHDL Compiler',
description: 'Path to your vhdl compiler',
type: 'string',
default: 'ghdl',
},
},
provideLinter() {
return {
name: 'Vhdl Linter',
scope: 'file',
lintsOnChange: false,
grammarScopes: ['source.vhdl'],
lint: async (textEditor) => {
const errorRegex = /.*.vhd:([0-9]+):([0-9]+): (.*)/g;
const editorPath = textEditor.getPath();
const compiler = atom.config.get('linter-vhdl.vhdlCompiler');
const options = { cwd: dirname(editorPath) };
const results = [];
try {
await exec(`"${compiler}" -a "${editorPath}"`, options);
} catch ({ stderr }) {
let regexResult = errorRegex.exec(stderr);
while (regexResult !== null) {
const [, line, col, message] = regexResult;
const range = [[(+line) - 1, (+col) - 1], [(+line) - 1, 1000]];
results.push({
severity: 'error',
location: {
file: editorPath,
position: range,
},
excerpt: message,
description: message,
});
regexResult = errorRegex.exec(stderr);
}
}
return results;
},
};
},
};
| 'use babel';
/* global atom */
import { exec } from 'child-process-promise';
import { dirname } from 'path';
export default {
config: {
vhdlCompiler: {
title: 'VHDL Compiler',
description: 'Path to your vhdl compiler',
type: 'string',
default: 'ghdl',
},
},
provideLinter() {
return {
name: 'Vhdl Linter',
scope: 'file',
lintsOnChange: false,
grammarScopes: ['source.vhdl'],
lint: async (textEditor) => {
const errorRegex = /.*.vhd:([0-9]+):([0-9]+): (.*)/g;
const editorPath = textEditor.getPath();
const compiler = atom.config.get('linter-vhdl.vhdlCompiler');
const options = { cwd: dirname(editorPath) };
var results = [];
try {
await exec(`"${compiler}" -a "${editorPath}"`, options);
} catch ({ stderr }) {
var regexResult;
while ((regexResult = errorRegex.exec(stderr)) !== null) {
const [, line, col, message] = regexResult;
const range = [[(+line) - 1, (+col) - 1], [(+line) - 1, 1000]];
results.push({
severity: 'error',
location: {
file: editorPath,
position: range,
},
excerpt: message,
description: message,
});
}
}
return results;
},
};
},
};
|
Fix height checks by switching to use dirty flag instead of setting height -1 | import React from 'react';
import {shouldComponentUpdate} from 'react-addons-pure-render-mixin';
const ReactHeight = React.createClass({
propTypes: {
children: React.PropTypes.node.isRequired,
onHeightReady: React.PropTypes.func.isRequired,
hidden: React.PropTypes.bool
},
getDefaultProps() {
return {hidden: false};
},
componentWillMount() {
this.height = 0;
this.dirty = true;
},
componentDidMount() {
this.height = this.refs.wrapper.clientHeight;
this.dirty = false;
this.forceUpdate();
this.props.onHeightReady(this.height);
},
componentWillReceiveProps({children}) {
if (children !== this.props.children) {
this.dirty = true;
}
},
shouldComponentUpdate,
componentDidUpdate() {
if (this.refs.wrapper) {
this.dirty = false;
if (this.refs.wrapper.clientHeight !== this.height) {
this.height = this.refs.wrapper.clientHeight;
this.forceUpdate();
this.props.onHeightReady(this.height);
} else {
this.forceUpdate();
}
}
},
render() {
const {onHeightReady, hidden, children, ...props} = this.props;
if (!this.dirty) {
return hidden ? null : <div {...props}>{children}</div>;
}
return (
<div style={{height: 0, overflow: 'hidden'}}>
<div ref="wrapper" {...props}>{children}</div>
</div>
);
}
});
export default ReactHeight;
| import React from 'react';
import {shouldComponentUpdate} from 'react-addons-pure-render-mixin';
const ReactHeight = React.createClass({
propTypes: {
children: React.PropTypes.node.isRequired,
onHeightReady: React.PropTypes.func.isRequired,
hidden: React.PropTypes.bool
},
getDefaultProps() {
return {hidden: false};
},
componentWillMount() {
this.height = -1;
},
componentDidMount() {
this.height = this.refs.wrapper.clientHeight;
if (this.height > -1) {
this.forceUpdate();
return this.props.onHeightReady(this.height);
}
},
componentWillReceiveProps({children}) {
if (children !== this.props.children) {
this.height = -1;
}
},
shouldComponentUpdate,
componentDidUpdate() {
if (this.refs.wrapper) {
if (this.refs.wrapper.clientHeight !== this.height) {
this.height = this.refs.wrapper.clientHeight;
this.props.onHeightReady(this.height);
}
this.forceUpdate();
}
},
render() {
const {onHeightReady, hidden, children, ...props} = this.props;
if (this.height > -1) {
return hidden ? null : <div {...props}>{children}</div>;
}
return (
<div style={{height: 0, overflow: 'hidden'}}>
<div ref="wrapper" {...props}>{children}</div>
</div>
);
}
});
export default ReactHeight;
|
Trim to avoid // at home page domain redirect. | <?php
namespace Anomaly\RedirectsModule\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* Class RedirectDomains
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
*/
class RedirectDomains
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (!file_exists($domains = app_storage_path('redirects/domains.php'))) {
return $next($request);
}
if (!$domains = require $domains) {
return $next($request);
}
if ($redirect = array_get($domains, $request->getHttpHost())) {
return redirect(
($request->isSecure() ? 'https' : 'http') . '://' . array_get(
$redirect,
'to',
config('streams::system.domain')
) . '/' . trim($request->path(), '/'),
$redirect['status'],
[],
config('streams::system.force_ssl', false) ?: $redirect['secure']
);
}
return $next($request);
}
}
| <?php
namespace Anomaly\RedirectsModule\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* Class RedirectDomains
*
* @link http://pyrocms.com/
* @author PyroCMS, Inc. <[email protected]>
* @author Ryan Thompson <[email protected]>
*/
class RedirectDomains
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (!file_exists($domains = app_storage_path('redirects/domains.php'))) {
return $next($request);
}
if (!$domains = require $domains) {
return $next($request);
}
if ($redirect = array_get($domains, $request->getHttpHost())) {
return redirect(
($request->isSecure() ? 'https' : 'http') . '://' . array_get(
$redirect,
'to',
config('streams::system.domain')
) . '/' . $request->path(),
$redirect['status'],
[],
config('streams::system.force_ssl', false) ?: $redirect['secure']
);
}
return $next($request);
}
}
|
Use distinct() when getting section items | from django.db.models import Q
from .utils import get_section_relations, get_item_model_class
class ItemFilter(object):
manager_attr = 'objects'
def get_manager(self, model):
"""Return the desired manager for the item model."""
return getattr(model, self.manager_attr)
def get_section_relations(self, section):
return get_section_relations(section.__class__)
def filter_objects_by_section(self, rels, section):
"""Build a queryset containing all objects in the section subtree."""
subtree = section.get_descendants(include_self=True)
kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs in kwargs_list[1:]:
q |= Q(**kwargs)
return self.get_manager(get_item_model_class()).filter(q).distinct()
def process_items(self, items):
"""
Perform extra actions on the filtered items.
Example: Further filtering the items in the section to meet a
custom need.
"""
if hasattr(items, 'select_subclasses'):
items = items.select_subclasses()
return items
def __call__(self, section):
relations = self.get_section_relations(section)
items = self.filter_objects_by_section(relations, section)
return self.process_items(items)
find_related_models = ItemFilter()
| from django.db.models import Q
from .utils import get_section_relations, get_item_model_class
class ItemFilter(object):
manager_attr = 'objects'
def get_manager(self, model):
"""Return the desired manager for the item model."""
return getattr(model, self.manager_attr)
def get_section_relations(self, section):
return get_section_relations(section.__class__)
def filter_objects_by_section(self, rels, section):
"""Build a queryset containing all objects in the section subtree."""
subtree = section.get_descendants(include_self=True)
kwargs_list = [{'%s__in' % rel.field.name: subtree} for rel in rels]
q = Q(**kwargs_list[0])
for kwargs in kwargs_list[1:]:
q |= Q(**kwargs)
return self.get_manager(get_item_model_class()).filter(q)
def process_items(self, items):
"""
Perform extra actions on the filtered items.
Example: Further filtering the items in the section to meet a
custom need.
"""
if hasattr(items, 'select_subclasses'):
items = items.select_subclasses()
return items
def __call__(self, section):
relations = self.get_section_relations(section)
items = self.filter_objects_by_section(relations, section)
return self.process_items(items)
find_related_models = ItemFilter()
|
[MySQL] Use NUMERIC as a string generation strategy | package sqlancer.dbms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.Test;
import sqlancer.Main;
public class TestMySQL {
String mysqlAvailable = System.getenv("MYSQL_AVAILABLE");
boolean mysqlIsAvailable = mysqlAvailable != null && mysqlAvailable.equalsIgnoreCase("true");
@Test
public void testPQS() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
/*
* While the MySQL generation supports ALPHANUMERIC as string generation strategy, the Travis CI gate
* seems to fail due to special characters that are not supposed to be generated, and which cannot be
* reproduced locally.
*/
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--num-threads", "4", "--random-string-generation", "NUMERIC", "--database-prefix",
"pqsdb" /* Workaround for connections not being closed */, "--num-queries",
TestConfig.NUM_QUERIES, "mysql", "--oracle", "PQS" }));
}
@Test
public void testMySQL() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--max-expression-depth", "1", "--num-threads", "4", "--num-queries", TestConfig.NUM_QUERIES,
"mysql", "--oracle", "TLP_WHERE" }));
}
}
| package sqlancer.dbms;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.Test;
import sqlancer.Main;
public class TestMySQL {
String mysqlAvailable = System.getenv("MYSQL_AVAILABLE");
boolean mysqlIsAvailable = mysqlAvailable != null && mysqlAvailable.equalsIgnoreCase("true");
@Test
public void testPQS() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--num-threads", "4", "--random-string-generation", "ALPHANUMERIC", "--database-prefix",
"pqsdb" /* Workaround for connections not being closed */, "--num-queries",
TestConfig.NUM_QUERIES, "mysql", "--oracle", "PQS" }));
}
@Test
public void testMySQL() {
assumeTrue(mysqlIsAvailable);
assertEquals(0,
Main.executeMain(new String[] { "--random-seed", "0", "--timeout-seconds", TestConfig.SECONDS,
"--max-expression-depth", "1", "--num-threads", "4", "--num-queries", TestConfig.NUM_QUERIES,
"mysql", "--oracle", "TLP_WHERE" }));
}
}
|
Add speech to text and send text to server | const sendBtn = document.getElementById(`sendBtn`)
const input = document.getElementById(`input`)
const initSpeech = document.getElementById(`initSpeech`)
const speechOutput = document.getElementById(`speechOutput`)
let transcript = null
function postToServer(message) {
console.log(`Sending this: ` + message)
let request = new Request(`/api`, {
method: `POST`,
mode: `same-origin`, // alt. `cors`
redirect: `follow`,
body: JSON.stringify({
message: message
}),
headers: new Headers({
"Content-Type": `application/json`
})
})
fetch(request)
.then((response) => {
return response.json()
})
.then((response) => {
console.log(`Server: ` + response.message)
})
}
function recordSpeech(event) {
let recognition = new webkitSpeechRecognition();
// Speech recognition config
recognition.lang = `sv` // Swedish for best recognition of swedish accents
// Consider enabling for richer feedback to user
// recognition.interimResults = true
recognition.onresult = (event) => {
console.log(event.results[0][0].transcript)
transcript = event.results[0][0].transcript
speechOutput.value = transcript
postToServer(transcript)
}
recognition.start()
}
initSpeech.addEventListener(`mouseup`, recordSpeech,false)
| const sendBtn = document.getElementById(`sendBtn`)
const input = document.getElementById(`input`)
const initSpeech = document.getElementById(`initSpeech`)
function sendPost(event) {
event.preventDefault()
var message = input.value
console.log(`Sending to server: ` + message)
var request = new Request(`/api`, {
method: `POST`,
mode: `same-origin`, // alt. `cors`
redirect: `follow`,
body: JSON.stringify({
message: message
}),
headers: new Headers({
"Content-Type": `application/json`
})
})
fetch(request)
.then((response) => {
// console.log(`Success!`)
return response.json();
})
.then((response) => {
console.log(`From server: ` + response.message);
})
}
sendBtn.addEventListener(`click`, sendPost, false)
function startRec(event) {
var recognition = new webkitSpeechRecognition()
// Speech Recognition Config
recognition.lang = `sv` // Swedish is best for
// recognition.continuous = true
recognition.onresult = (event) => {
var textarea = document.getElementById(`speechOutput`)
console.log(event.results[0][0].transcript)
textarea.value += event.results[0][0].transcript
// for (var i = event.resultIndex; i < event.results.length; ++i) {
// console.log(event.results)
// if (event.results[i].isFinal) {
// console.log(event.results[i][0].transcript)
// }
// }
}
recognition.start()
}
initSpeech.addEventListener(`mouseup`, startRec, false) |
Fix required Django version (doesnt support 1.8 yet) | from setuptools import setup
setup(
name='django-simpleimages',
version='1.2.0',
author='Saul Shanabrook',
author_email='[email protected]',
packages=[
'simpleimages',
'simpleimages.management',
'simpleimages.management.commands',
],
url='https://www.github.com/saulshanabrook/django-simpleimages',
license=open('LICENSE.txt').read(),
description='Opinionated Django image transforms on models',
long_description=open('README.rst').read(),
install_requires=[
"Django>=1.5,<1.8",
"six",
"Pillow",
'clint',
],
zip_safe=False, # so that django finds management commands,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
| from setuptools import setup
setup(
name='django-simpleimages',
version='1.2.0',
author='Saul Shanabrook',
author_email='[email protected]',
packages=[
'simpleimages',
'simpleimages.management',
'simpleimages.management.commands',
],
url='https://www.github.com/saulshanabrook/django-simpleimages',
license=open('LICENSE.txt').read(),
description='Opinionated Django image transforms on models',
long_description=open('README.rst').read(),
install_requires=[
"Django>=1.5,<=1.8",
"six",
"Pillow",
'clint',
],
zip_safe=False, # so that django finds management commands,
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
],
)
|
Implement a write test for Locket. | #!/usr/bin/env node
var Locket = require('../')
var cadence = require('cadence')
var path = require('path')
var crypto = require('crypto')
var seedrandom = require('seedrandom')
var random = (function () {
var random = seedrandom(0)
return function (max) {
return Math.floor(random() * max)
}
})()
cadence(function (step) {
var locket = new Locket(path.join(path.join(__dirname, '../tmp'), 'put'))
step(function () {
locket.open({ createIfMissing: true }, step())
}, function () {
var entries = []
var type, sha, buffer, value
for (var i = 0; i < 1024; i++) {
var value = random(10000)
sha = crypto.createHash('sha1')
buffer = new Buffer(4)
buffer.writeUInt32BE(value, 0)
sha.update(buffer)
entries.push({
key: sha.digest('binary'),
value: value,
type: !! random(1)
})
}
console.log('here', entries.length)
locket.batch(entries, step())
})(7)
})(function (error) {
if (error) throw error
})
| #!/usr/bin/env node
var Locket = require('../')
var cadence = require('cadence')
var path = require('path')
var crypto = require('crypto')
var seedrandom = require('seedrandom')
function pseudo (max) {
var random = seedrandom()()
while (random > max) {
random = seedrandom()()
}
return random
}
cadence(function (step) {
var locket = new Locket(path.join(path.join(__dirname, '../tmp'), 'put'))
step(function () {
locket.open({ createIfMissing: true }, step())
}, function () {
var entries = []
var max = 10000
var type, sha, entry, val = seedrandom(0)()
for (var i = 0; i < 1024; i++) {
type = (pseudo(2) % 2 == 0)
sha = crypto.createHash('sha1')
entry = new Buffer(4)
entry.writeFloatLE(val, 0)
sha.update(entry)
entries.push({
type: type,
key: sha.digest('binary'),
value: val
})
val = pseudo(max)
}
locket.batch(entries, step())
}, function () {
sha = crypto.createHash('sha1')
first_key = new Buffer(4)
first_key.writeFloatLE(seedrandom(0)(), 0)
sha.update(first_key)
locket.get(sha.digest('binary'), function (_, value) {
console.log(value)
})
// ^^^ no idea what's going on here.
})
})(function (error) {
if (error) throw error
})
|
Apply consistent code style as used in other tests. | <?php
namespace Tests\Feature;
use App\Actions\VerifyDependencies;
use Exception;
use Symfony\Component\Process\ExecutableFinder;
use Tests\TestCase;
class VerifyDependenciesTest extends TestCase
{
private $executableFinder;
public function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->executableFinder = $this->mock(ExecutableFinder::class);
}
/** @test */
function it_checks_that_required_dependencies_are_available()
{
$this->executableFinder->shouldReceive('find')
->with('dependencyA')
->once()
->andReturn('/path/to/dependencyA');
$this->executableFinder->shouldReceive('find')
->with('dependencyB')
->once()
->andReturn('/path/to/dependencyB');
app(VerifyDependencies::class)(['dependencyA', 'dependencyB']);
}
/** @test */
function it_throws_and_exception_if_a_required_dependency_is_missing_missing()
{
$this->executableFinder->shouldReceive('find')
->with('dependencyA')
->once()
->andReturn('/path/to/dependencyA');
$this->executableFinder->shouldReceive('find')
->with('missingDependency')
->once()
->andReturn(null);
$this->expectException(Exception::class);
app(VerifyDependencies::class)(['dependencyA', 'missingDependency']);
}
}
| <?php
namespace Tests\Feature;
use App\Actions\VerifyDependencies;
use Exception;
use Symfony\Component\Process\ExecutableFinder;
use Tests\TestCase;
class VerifyDependenciesTest extends TestCase
{
/** @test */
function it_checks_that_required_dependencies_are_available()
{
$this->mock(ExecutableFinder::class, function ($mock) {
$mock->shouldReceive('find')
->with('dependencyA')
->once()
->andReturn('/path/to/dependencyA');
$mock->shouldReceive('find')
->with('dependencyB')
->once()
->andReturn('/path/to/dependencyB');
});
app(VerifyDependencies::class)(['dependencyA', 'dependencyB']);
}
/** @test */
function it_throws_and_exception_if_a_required_dependency_is_missing_missing()
{
$this->mock(ExecutableFinder::class, function ($mock) {
$mock->shouldReceive('find')
->with('dependencyA')
->once()
->andReturn('/path/to/dependencyA');
$mock->shouldReceive('find')
->with('missingDependency')
->once()
->andReturn(null);
});
$this->expectException(Exception::class);
app(VerifyDependencies::class)(['dependencyA', 'missingDependency']);
}
}
|
Rename variable elephpant as druplicon | <?php
/**
* @file
* Contains \Drupal\Console\Command\Autowire\ElephpantCommand.
*/
namespace Drupal\Console\Command\Autowire;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\Command;
use Symfony\Component\Finder\Finder;
class DrupliconCommand extends Command
{
protected function configure()
{
$this
->setName('druplicon')
->setDescription($this->trans('application.commands.druplicon.description'));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$renderer = $this->getRenderHelper();
$directory = sprintf(
'%stemplates/core/druplicon/',
$this->getApplication()->getDirectoryRoot()
);
$finder = new Finder();
$finder->files()
->name('*.twig')
->in($directory);
$templates = [];
foreach ($finder as $template) {
$templates[] = $template->getRelativePathname();
}
$druplicon = $renderer->render(
sprintf(
'core/druplicon/%s',
$templates[array_rand($templates)]
)
);
$output->writeln($druplicon);
}
}
| <?php
/**
* @file
* Contains \Drupal\Console\Command\Autowire\ElephpantCommand.
*/
namespace Drupal\Console\Command\Autowire;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\Command;
use Symfony\Component\Finder\Finder;
class DrupliconCommand extends Command
{
protected function configure()
{
$this
->setName('druplicon')
->setDescription($this->trans('application.commands.druplicon.description'));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$renderer = $this->getRenderHelper();
$directory = sprintf(
'%stemplates/core/druplicon/',
$this->getApplication()->getDirectoryRoot()
);
$finder = new Finder();
$finder->files()
->name('*.twig')
->in($directory);
$templates = [];
foreach ($finder as $template) {
$templates[] = $template->getRelativePathname();
}
$elephpant = $renderer->render(
sprintf(
'core/druplicon/%s',
$templates[array_rand($templates)]
)
);
$output->writeln($elephpant);
}
}
|
Fix comment in sort example | import React from 'react';
import { TacoTable, DataType, SortDirection, Formatters } from 'react-taco-table';
import cellLinesData from '../data/cell_lines.json';
/**
* An example demonstrating sort configurations
*/
const columns = [
{
id: 'name',
type: DataType.String,
value: rowData => rowData.cellLine.label,
header: 'String',
},
{
id: 'value',
type: DataType.Number,
header: 'First sort descending',
renderer: Formatters.decFormat(1),
firstSortDirection: SortDirection.Descending,
},
{
id: 'level-str',
type: DataType.String,
value: rowData => rowData.level,
header: 'Number as string',
firstSortDirection: SortDirection.Descending,
},
{
id: 'level-num',
type: DataType.Number,
value: rowData => rowData.level,
header: 'Number as number',
firstSortDirection: SortDirection.Descending,
},
{
id: 'name-length',
type: DataType.String,
sortType: DataType.Number,
value: rowData => rowData.cellLine.label,
sortValue: cellData => cellData.length,
header: 'String as number',
},
];
class ExampleFormatters extends React.Component {
render() {
return (
<TacoTable
columns={columns}
data={cellLinesData}
initialSortDirection={SortDirection.Ascending}
initialSortColumnId={'name'}
/>
);
}
}
export default ExampleFormatters;
| import React from 'react';
import { TacoTable, DataType, SortDirection, Formatters } from 'react-taco-table';
import cellLinesData from '../data/cell_lines.json';
/**
* An example demonstrating various formatters
*/
const columns = [
{
id: 'name',
type: DataType.String,
value: rowData => rowData.cellLine.label,
header: 'String',
},
{
id: 'value',
type: DataType.Number,
header: 'First sort descending',
renderer: Formatters.decFormat(1),
firstSortDirection: SortDirection.Descending,
},
{
id: 'level-str',
type: DataType.String,
value: rowData => rowData.level,
header: 'Number as string',
firstSortDirection: SortDirection.Descending,
},
{
id: 'level-num',
type: DataType.Number,
value: rowData => rowData.level,
header: 'Number as number',
firstSortDirection: SortDirection.Descending,
},
{
id: 'name-length',
type: DataType.String,
sortType: DataType.Number,
value: rowData => rowData.cellLine.label,
sortValue: cellData => cellData.length,
header: 'String as number',
},
];
class ExampleFormatters extends React.Component {
render() {
return (
<TacoTable
columns={columns}
data={cellLinesData}
initialSortDirection={SortDirection.Ascending}
initialSortColumnId={'name'}
/>
);
}
}
export default ExampleFormatters;
|
:art: Refactor & remove workaround for extends-before-declaration rule | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'extends-before-declarations',
'defaults': {},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('block', function (block) {
var lastDeclaration = null;
block.forEach(function (item, j) {
if (item.is('include') || item.is('extend')) {
if (item.contains('atkeyword')) {
var atkeyword = item.first('atkeyword');
if (atkeyword.contains('ident')) {
var ident = atkeyword.first('ident');
if (ident.content === 'extend') {
if (j > lastDeclaration && lastDeclaration !== null) {
error = {
'ruleId': parser.rule.name,
'line': item.start.line,
'column': item.start.column,
'message': 'Extends should come before declarations',
'severity': parser.severity
};
result = helpers.addUnique(result, error);
}
}
}
}
}
if (item.is('declaration')) {
lastDeclaration = j;
}
});
lastDeclaration = null;
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'extends-before-declarations',
'defaults': {},
'detect': function (ast, parser) {
var result = [],
error;
ast.traverseByType('block', function (block) {
var lastDeclaration = null;
block.forEach(function (item, j) {
// TODO: Remove tempory fix - atrule type is work around for issue:
// https://github.com/tonyganch/gonzales-pe/issues/147
if ((item.is('include') || item.is('extend') || item.is('atrule')) &&
item.first('atkeyword')) {
if (item.first('atkeyword').first('ident').content === 'extend') {
if (j > lastDeclaration && lastDeclaration !== null) {
error = {
'ruleId': parser.rule.name,
'line': item.start.line,
'column': item.start.column,
'message': 'Extends should come before declarations',
'severity': parser.severity
};
result = helpers.addUnique(result, error);
}
}
}
if (item.is('declaration')) {
lastDeclaration = j;
}
});
lastDeclaration = null;
});
return result;
}
};
|
Add a name to the runner | package wumpus;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import wumpus.Environment.*;
/**
* The iteration of plays that the player can take until reaches its end.
*/
public class Runner implements Iterable<Player>, Iterator<Player> {
private static final int DEFAULT_MAX_ITERATIONS = 200;
private final World world;
private final String name;
private int iterations = 0;
/**
* The runner constructor.
* @param world The world instance.
*/
public Runner(String name, World world) {
this.name = name;
this.world = world;
}
/**
* Returns the iterator that can be user in a loop.
* @return Itself
*/
public Iterator<Player> iterator() {
return this;
}
/**
* Check if the game has ended.
* @return
*/
public boolean hasNext() {
Player player = world.getPlayer();
return iterations < DEFAULT_MAX_ITERATIONS &&
player.isAlive() && player.getResult() != Result.WIN;
}
/**
* Get player instance to calculate the next iteration.
* @return The current player instance
*/
public Player next() {
if (!hasNext()) throw new NoSuchElementException();
iterations++;
return world.getPlayer();
}
/**
* Operation not supported, throws an error.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Get how many iterations have been made so far.
* @return The amount of iterations
*/
public int getDepth() {
return iterations;
}
}
| package wumpus;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import wumpus.Environment.*;
/**
* The iteration of plays that the player can take until reaches its end.
*/
public class Runner implements Iterable<Player>, Iterator<Player> {
private static final int DEFAULT_MAX_ITERATIONS = 200;
private final World world;
private int iterations = 0;
/**
* The runner constructor.
* @param world The world instance.
*/
public Runner(World world) {
this.world = world;
}
/**
* Returns the iterator that can be user in a loop.
* @return Itself
*/
public Iterator<Player> iterator() {
return this;
}
/**
* Check if the game has ended.
* @return
*/
public boolean hasNext() {
Player player = world.getPlayer();
return iterations < DEFAULT_MAX_ITERATIONS &&
player.isAlive() && player.getResult() != Result.WIN;
}
/**
* Get player instance to calculate the next iteration.
* @return The current player instance
*/
public Player next() {
if (!hasNext()) throw new NoSuchElementException();
iterations++;
return world.getPlayer();
}
/**
* Operation not supported, throws an error.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Get how many iterations have been made so far.
* @return The amount of iterations
*/
public int getDepth() {
return iterations;
}
}
|
Fix for Cannot read property 'excludeFinished' of null | angular.module('14all', ['ui.bootstrap','ngAnimate',
'auth',
/* Modules */
'manga','movie','serie','anime','game','book',
'14all.templates'])
.config(['RestangularProvider',function(RestangularProvider){
RestangularProvider.setRestangularFields({
id: "_id"
});
RestangularProvider.setBaseUrl('/api');
}])
.controller('AppCtrl',['$scope','$location','authService','$store',function($scope,$location,authService,$store){
// FIX SETTINGS
var tempSettings = $store.get('settings');
if(angular.isDefined(tempSettings) && angular.isDefined(tempSettings.excludeFinished)){
$store.remove('settings');
}
// FIX SETTINGS
$scope.isLoggedIn = authService.isLoggedIn;
$scope.logout = authService.logout;
$scope.settings = $store.bind($scope,'settings',{
filter:{
stats:{
finished: false,
dropped: false
},
orderBy:{
predicate:'',
reverse:false
},
keyword:{}
}
});
$scope.orderBy = $scope.settings.filter.orderBy;
$scope.focus = {search:true};
$scope.$on("$routeChangeStart",function(event,next,current){
$scope.focus.search = false;
});
$scope.$on("$routeChangeSuccess",function(event,next,current){
$scope.focus.search = true;
});
}]);
| angular.module('14all', ['ui.bootstrap','ngAnimate',
'auth',
/* Modules */
'manga','movie','serie','anime','game','book',
'14all.templates'])
.config(['RestangularProvider',function(RestangularProvider){
RestangularProvider.setRestangularFields({
id: "_id"
});
RestangularProvider.setBaseUrl('/api');
}])
.controller('AppCtrl',['$scope','$location','authService','$store',function($scope,$location,authService,$store){
// FIX SETTINGS
var tempSettings = $store.get('settings');
if(angular.isDefined(tempSettings.excludeFinished)){
$store.remove('settings');
}
// FIX SETTINGS
$scope.isLoggedIn = authService.isLoggedIn;
$scope.logout = authService.logout;
$scope.settings = $store.bind($scope,'settings',{
filter:{
stats:{
finished: false,
dropped: false
},
orderBy:{
predicate:'',
reverse:false
},
keyword:{}
}
});
$scope.orderBy = $scope.settings.filter.orderBy;
$scope.focus = {search:true};
$scope.$on("$routeChangeStart",function(event,next,current){
$scope.focus.search = false;
});
$scope.$on("$routeChangeSuccess",function(event,next,current){
$scope.focus.search = true;
});
}]);
|
Use client_name instead of schema_name | import json
from rest_framework.authtoken.models import Token
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
class Command(BaseCommand):
help = 'Export tenants, so that we can import them into the accounting app'
def add_arguments(self, parser):
parser.add_argument('--file', type=str, default=None, action='store')
def handle(self, *args, **options):
results = []
for client in Client.objects.all():
properties.set_tenant(client)
with LocalTenant(client, clear_tenant=True):
ContentType.objects.clear_cache()
accounts = []
for merchant in properties.MERCHANT_ACCOUNTS:
if merchant['merchant'] == 'docdata':
accounts.append(
{
'service_type': 'docdata',
'username': merchant['merchant_name']
}
)
api_key = Token.objects.get(user__username='accounting').key
results.append({
"name": client.client_name,
"domain": properties.TENANT_MAIL_PROPERTIES['website'],
"api_key": api_key,
"accounts": accounts
})
if options['file']:
text_file = open(options['file'], "w")
text_file.write(json.dumps(results))
text_file.close()
else:
print json.dumps(results)
| import json
from rest_framework.authtoken.models import Token
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
class Command(BaseCommand):
help = 'Export tenants, so that we can import them into the accounting app'
def add_arguments(self, parser):
parser.add_argument('--file', type=str, default=None, action='store')
def handle(self, *args, **options):
results = []
for client in Client.objects.all():
properties.set_tenant(client)
with LocalTenant(client, clear_tenant=True):
ContentType.objects.clear_cache()
accounts = []
for merchant in properties.MERCHANT_ACCOUNTS:
if merchant['merchant'] == 'docdata':
accounts.append(
{
'service_type': 'docdata',
'username': merchant['merchant_name']
}
)
api_key = Token.objects.get(user__username='accounting').key
results.append({
"name": client.schema_name,
"domain": properties.TENANT_MAIL_PROPERTIES['website'],
"api_key": api_key,
"accounts": accounts
})
if options['file']:
text_file = open(options['file'], "w")
text_file.write(json.dumps(results))
text_file.close()
else:
print json.dumps(results)
|
Set the byline to either the display name or the username
We don't need both in the comment email. We'd rather have the display
name, but if it's not available, then the username is fine. | <?php
class TalkCommentEmailService extends EmailBaseService
{
protected $talk;
protected $comment;
public function __construct($config, $recipients, $talk, $comment)
{
// set up the common stuff first
parent::__construct($config, $recipients);
// this email needs talk and comment info
$this->talk = $talk['talks'][0];
$this->comment = $comment['comments'][0];
}
public function sendEmail()
{
$this->setSubject("New feedback on " . $this->talk['talk_title']);
$byLine = '';
if (isset($this->comment['user_display_name'])) {
$byLine = ' by ' . $this->comment['user_display_name'];
}
if (empty($byLine) && isset($this->comment['username'])) {
$byLine = ' by' . $this->comment['username'];
}
$replacements = array(
"title" => $this->talk['talk_title'],
"rating" => $this->comment['rating'],
"comment" => $this->comment['comment'],
"url" => $this->talk['website_uri'],
"byline" => $byLine
);
$messageBody = $this->parseEmail("commentTalk.md", $replacements);
$messageHTML = $this->markdownToHtml($messageBody);
$this->setBody($this->htmlToPlainText($messageHTML));
$this->setHtmlBody($messageHTML);
$this->dispatchEmail();
}
}
| <?php
class TalkCommentEmailService extends EmailBaseService
{
protected $talk;
protected $comment;
public function __construct($config, $recipients, $talk, $comment)
{
// set up the common stuff first
parent::__construct($config, $recipients);
// this email needs talk and comment info
$this->talk = $talk['talks'][0];
$this->comment = $comment['comments'][0];
}
public function sendEmail()
{
$this->setSubject("New feedback on " . $this->talk['talk_title']);
$byLine = '';
if(isset($this->comment['user_display_name'])) {
$byLine = ' by ' . $this->comment['user_display_name'];
if(isset($this->comment['username'])) {
$byLine .= ' (' . $this->comment['username'] . ')';
}
}
$replacements = array(
"title" => $this->talk['talk_title'],
"rating" => $this->comment['rating'],
"comment" => $this->comment['comment'],
"url" => $this->talk['website_uri'],
"byline" => $byLine
);
$messageBody = $this->parseEmail("commentTalk.md", $replacements);
$messageHTML = $this->markdownToHtml($messageBody);
$this->setBody($this->htmlToPlainText($messageHTML));
$this->setHtmlBody($messageHTML);
$this->dispatchEmail();
}
}
|
Make codes being close to React style | var ContribBox = React.createClass({
handleLoad: function(user) {
alert(user);
},
render: function() {
return <div>asdf</div>;
}
});
var SearchBox = React.createClass({
getInitialState: function() {
return {
user: this.props.user || ''
};
},
submit: function(e) {
var uri = '/' + this.state.user;
e.preventDefault();
var ps = window.history.pushState ? 1 : 0;
[function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps]();
this.props.onSubmit(this.state.user);
},
updateUser: function(e) {
this.setState({
user: e.target.value
});
},
componentDidMount: function() {
this.props.onSubmit(this.state.user);
},
render: function() {
return (
<form className="ui" onSubmit={this.submit}>
<div className="ui action center aligned input">
<input type="text" placeholder="나무위키 아이디 입력" defaultValue={this.props.user} onChange={this.updateUser} />
<button className="ui teal button">조회</button>
</div>
</form>
);
}
});
| var ContribBox = React.createClass({
render: function() {
return <div />;
}
});
var SearchBox = React.createClass({
getInitialState: function () {
console.log(this.props);
return {
user: this.props.user || ''
};
},
handleSubmit: function() {
},
submit: function(e) {
var uri = '/' + this.state.user;
e.preventDefault();
var ps = window.history.pushState ? 1 : 0;
[function(){location.replace(uri)},function(){window.history.pushState(null,null,uri)}][ps]();
this.handleSubmit();
},
updateUser: function(e) {
this.setState({
user: e.target.value
});
},
render: function() {
return (
<form className="ui" onSubmit={this.submit}>
<div className="ui action center aligned input">
<input type="text" placeholder="나무위키 아이디 입력" defaultValue={this.props.user} onChange={this.updateUser} />
<button className="ui teal button">조회</button>
</div>
</form>
);
}
});
|
Return the command array in createCommand | <?php
namespace BryanCrowe;
class Growl
{
public function __construct() {}
public function growl($message = null, $options = []) {}
public function createCommand()
{
switch (PHP_OS) {
case 'Darwin':
if (exec('which growlnotify')) {
return [
'pkg' => 'growlnotify',
'msg' => '-m'
];
} else {
return [
'pkg' => 'terminal-notifier',
'msg' => '-message'
];
}
break;
case 'Linux':
if (exec('which growl')) {
return [
'pkg' => 'growl',
'msg' => '-m'
];
} else {
return [
'pkg' => 'notify-send',
'msg' => ''
];
}
break;
case 'WINNT':
return [
'pkg' => 'growlnotify',
'msg' => ''
];
break;
}
}
}
| <?php
namespace BryanCrowe;
class Growl
{
public function __construct() {}
public function growl($message = null, $options = []) {}
public function createCommand()
{
switch (PHP_OS) {
case 'Darwin':
if (exec('which growlnotify')) {
$command = [
'pkg' => 'growlnotify',
'msg' => '-m'
];
} else {
$command = [
'pkg' => 'terminal-notifier',
'msg' => '-message'
];
}
break;
case 'Linux':
if (exec('which growl')) {
$command = [
'pkg' => 'growl',
'msg' => '-m'
];
} else {
$command = [
'pkg' => 'notify-send',
'msg' => ''
];
}
break;
case 'WINNT':
$command = [
'pkg' => 'growlnotify',
'msg' => ''
];
break;
return $command;
}
}
}
|
Add missing save statement in update script
without this save nothing at all will be updated | <?php
class Kwc_List_ChildPages_Teaser_Update_20150309Legacy00002 extends Kwf_Update
{
public function postUpdate()
{
$cmps = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass('Kwc_List_ChildPages_Teaser_Component',
array('ignoreVisible'=>true)
);
$num = 0;
foreach ($cmps as $cmp) {
$num++;
if (count($cmps) > 20) echo "updating List ChildPages [$num/".count($cmps)."]...\n";
Kwf_Model_Abstract::getInstance('Kwc_List_ChildPages_Teaser_Model')->updatePages($cmp);
$s = new Kwf_Model_Select();
$s->whereEquals('component_id', $cmp->dbId);
foreach (Kwf_Model_Abstract::getInstance('Kwc_List_ChildPages_Teaser_Model')->getRows($s) as $row) {
$childPage = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row->target_page_id, array('ignoreVisible'=>true, 'limit'=>1));
$row->visible = isset($childPage->row) && isset($childPage->row->visible) ? $childPage->row->visible : true;
$row->save();
}
Kwf_Model_Abstract::clearAllRows();
}
}
}
| <?php
class Kwc_List_ChildPages_Teaser_Update_20150309Legacy00002 extends Kwf_Update
{
public function postUpdate()
{
$cmps = Kwf_Component_Data_Root::getInstance()
->getComponentsByClass('Kwc_List_ChildPages_Teaser_Component',
array('ignoreVisible'=>true)
);
$num = 0;
foreach ($cmps as $cmp) {
$num++;
if (count($cmps) > 20) echo "updating List ChildPages [$num/".count($cmps)."]...\n";
Kwf_Model_Abstract::getInstance('Kwc_List_ChildPages_Teaser_Model')->updatePages($cmp);
$s = new Kwf_Model_Select();
$s->whereEquals('component_id', $cmp->dbId);
foreach (Kwf_Model_Abstract::getInstance('Kwc_List_ChildPages_Teaser_Model')->getRows($s) as $row) {
$childPage = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row->target_page_id, array('ignoreVisible'=>true, 'limit'=>1));
$row->visible = isset($childPage->row) && isset($childPage->row->visible) ? $childPage->row->visible : true;
}
Kwf_Model_Abstract::clearAllRows();
}
}
}
|
Check mtime to see if we need to write out new db file. | #!/usr/bin/python
# Edit an AES encrypted json/pickle file.
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
mtime = os.path.getmtime(f.name)
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
if os.path.getmtime(f.name) == mtime:
print "Not updated"
break
try:
f.seek(0)
db = json.load(f)
filetype.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
# Over-write our temp file
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
| #!/usr/bin/python
# Edit an AES encrypted json/pickle file.
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, password)
f = tempfile.NamedTemporaryFile()
json.dump(db, f, indent=2)
f.flush()
while True:
subprocess.call([os.getenv("EDITOR") or "editor", f.name])
try:
f.seek(0)
db = json.load(f)
filetype.dump(fn, db, password)
break
except Exception, e:
print "Error in json"
print e
print "Try again (y/n)? ",
input = raw_input()
if not input.lower().startswith("y"):
break
f.seek(0,2)
len = f.tell()
f.seek(0)
f.write(" " * len)
f.flush()
f.close()
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(1)
fn = sys.argv[1]
password = getpass.getpass()
editfile(fn, password)
|
Remove imports in Orange, except data | from __future__ import absolute_import
from importlib import import_module
try:
from .import version
# Always use short_version here (see PEP 386)
__version__ = version.short_version
__git_revision__ = version.git_revision
except ImportError:
__version__ = "unknown"
__git_revision__ = "unknown"
ADDONS_ENTRY_POINT = 'orange.addons'
import warnings
import pkg_resources
alreadyWarned = False
disabledMsg = "Some features will be disabled due to failing modules\n"
def _import(name):
global alreadyWarned
try:
import_module(name, package='Orange')
except ImportError as err:
warnings.warn("%sImporting '%s' failed: %s" %
(disabledMsg if not alreadyWarned else "", name, err),
UserWarning, 2)
alreadyWarned = True
def import_all():
import Orange
for name in ["classification", "clustering", "data", "distance",
"evaluation", "feature", "misc", "regression", "statistics"]:
Orange.__dict__[name] = import_module('Orange.' + name, package='Orange')
# Alternatives:
# global classification
# import Orange.classification as classification
# or
# import Orange.classification as classification
# globals()['clasification'] = classification
_import(".data")
del _import
del alreadyWarned
del disabledMsg
| from __future__ import absolute_import
from importlib import import_module
try:
from .import version
# Always use short_version here (see PEP 386)
__version__ = version.short_version
__git_revision__ = version.git_revision
except ImportError:
__version__ = "unknown"
__git_revision__ = "unknown"
ADDONS_ENTRY_POINT = 'orange.addons'
import warnings
import pkg_resources
alreadyWarned = False
disabledMsg = "Some features will be disabled due to failing modules\n"
def _import(name):
global alreadyWarned
try:
import_module(name, package='Orange')
except ImportError as err:
warnings.warn("%sImporting '%s' failed: %s" %
(disabledMsg if not alreadyWarned else "", name, err),
UserWarning, 2)
alreadyWarned = True
def import_all():
import Orange
for name in ["classification", "clustering", "data", "distance",
"evaluation", "feature", "misc", "regression", "statistics"]:
Orange.__dict__[name] = import_module('Orange.' + name, package='Orange')
# Alternatives:
# global classification
# import Orange.classification as classification
# or
# import Orange.classification as classification
# globals()['clasification'] = classification
_import(".data")
_import(".distance")
_import(".feature")
_import(".feature.discretization")
_import(".data.discretization")
del _import
del alreadyWarned
del disabledMsg
|
Drop the wrapper, clone the element and apply the class instead | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import { ButtonGroup } from '../button';
import cx from 'classnames';
import theme from './theme.css';
class Message extends PureComponent {
static propTypes = {
className: PropTypes.string,
children: PropTypes.any.isRequired,
image: PropTypes.element,
imagePositioning: PropTypes.oneOf(['center', 'left', 'right']),
button: PropTypes.element,
link: PropTypes.element,
};
static defaultProps = {
imagePositioning: 'left',
};
render() {
const { className, children, image, imagePositioning, button, link, ...others } = this.props;
const classNames = cx(theme['message'], theme[`is-image-${imagePositioning}`], className);
const hasAction = Boolean(button || link);
return (
<Box data-teamleader-ui="message" className={classNames} {...others}>
{image && <div className={theme['image']}>{image}</div>}
<div className={theme['content']}>
{children}
{hasAction && (
<ButtonGroup className={theme['actions']} marginTop={4}>
{button && React.cloneElement(button, { className: theme['button'] })}
{link}
</ButtonGroup>
)}
</div>
</Box>
);
}
}
export default Message;
| import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import { ButtonGroup } from '../button';
import cx from 'classnames';
import theme from './theme.css';
class Message extends PureComponent {
static propTypes = {
className: PropTypes.string,
children: PropTypes.any.isRequired,
image: PropTypes.element,
imagePositioning: PropTypes.oneOf(['center', 'left', 'right']),
button: PropTypes.element,
link: PropTypes.element,
};
static defaultProps = {
imagePositioning: 'left',
};
render() {
const { className, children, image, imagePositioning, button, link, ...others } = this.props;
const classNames = cx(theme['message'], theme[`is-image-${imagePositioning}`], className);
const hasAction = Boolean(button || link);
return (
<Box data-teamleader-ui="message" className={classNames} {...others}>
{image && <div className={theme['image']}>{image}</div>}
<div className={theme['content']}>
{children}
{hasAction && (
<ButtonGroup className={theme['actions']} marginTop={4}>
{button && <span className={theme['button']}>{button}</span>}
{link}
</ButtonGroup>
)}
</div>
</Box>
);
}
}
export default Message;
|
Remove ACME bundle (default one in symfony) | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Hermes\ReportBundle\HermesReportBundle(),
new Hermes\ModelBundle\HermesModelBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Hermes\ReportBundle\HermesReportBundle(),
new Hermes\ModelBundle\HermesModelBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
Include dummy filter value to the config | /**
* Storage (save data to localStorage)
*/
var config = {};
var storage = {
set : function (key, value, stringify) {
var isChanged = config.hasOwnProperty(key) && (config[key] !== value);
if(isChanged) {
config[key] = value;
value = stringify ? JSON.stringify(value) : value;
localStorage.setItem(key, value);
}
},
get : function (key, type) {
var value;
if(!config.hasOwnProperty(key)) {
value = localStorage.getItem(key);
switch(type) {
case 'boolean':
value = value === 'true' ? true : false;
break;
case 'object':
value = JSON.parse(val);
break;
}
config[key] = value;
}
return config[key];
},
setFile : function (file) {
if(!file || !file.path) return;
config.file = file.path;
},
getFile : function () {
return config.file;
},
rmFile : function () {
config.file = null;
},
formConfig : function () {
return extend(config, { filter : '1' });
}
};
module.exports = storage;
/**
* Simple extend function for key-value pairs
*/
function extend(a, b) {
var obj = {};
Object.getOwnPropertyNames(a).forEach(function (prop) {
obj[prop] = a[prop];
});
Object.getOwnPropertyNames(b).forEach(function (prop) {
obj[prop] = b[prop];
});
return obj;
}
| /**
* Storage (save data to localStorage)
*/
var config = {};
var storage = {
set : function (key, value, stringify) {
var isChanged = config.hasOwnProperty(key) && (config[key] !== value);
if(isChanged) {
config[key] = value;
value = stringify ? JSON.stringify(value) : value;
localStorage.setItem(key, value);
}
},
get : function (key, type) {
var value;
if(!config.hasOwnProperty(key)) {
value = localStorage.getItem(key);
switch(type) {
case 'boolean':
value = value === 'true' ? true : false;
break;
case 'object':
value = JSON.parse(val);
break;
}
config[key] = value;
}
return config[key];
},
setFile : function (file) {
if(!file || !file.path) return;
config.file = file.path;
},
getFile : function () {
return config.file;
},
rmFile : function () {
config.file = null;
},
formConfig : function () {
return extend(config, {});
}
};
module.exports = storage;
/**
* Simple extend function for key-value pairs
*/
function extend(a, b) {
var obj = {};
Object.getOwnPropertyNames(a).forEach(function (prop) {
obj[prop] = a[prop];
});
Object.getOwnPropertyNames(b).forEach(function (prop) {
obj[prop] = b[prop];
});
return obj;
}
|
Replace deprecated share method with singleton | <?php
namespace Alexpechkarev\GoogleGeocoder;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;
class GoogleGeocoderServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
AliasLoader::getInstance()->alias('Geocoder','Alexpechkarev\GoogleGeocoder\Facades\GoogleGeocoderFacade');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
#$this->app['GoogleGeocoder'] = $this->app->share(function($app)
$this->app['GoogleGeocoder'] = $this->app->singleton('GoogleGeocoder', function($app)
{
$config = array();
$config['applicationKey'] = Config::get('google-geocoder.applicationKey');
$config['requestUrl'] = Config::get('google-geocoder.requestUrl');
// Throw an error if request URL is empty
if (empty($config['requestUrl'])) {
throw new \InvalidArgumentException('Request URL is empty, please check your config file.');
}
return new GoogleGeocoder($config);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
| <?php
namespace Alexpechkarev\GoogleGeocoder;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config;
class GoogleGeocoderServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
AliasLoader::getInstance()->alias('Geocoder','Alexpechkarev\GoogleGeocoder\Facades\GoogleGeocoderFacade');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['GoogleGeocoder'] = $this->app->share(function($app)
{
$config = array();
$config['applicationKey'] = Config::get('google-geocoder.applicationKey');
$config['requestUrl'] = Config::get('google-geocoder.requestUrl');
// Throw an error if request URL is empty
if (empty($config['requestUrl'])) {
throw new \InvalidArgumentException('Request URL is empty, please check your config file.');
}
return new GoogleGeocoder($config);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array();
}
}
|
Fix the namespace of Exception | <?php
namespace Pum\Bundle\TypeExtraBundle\Model;
/**
* The value of a coordinate object should NEVER change. You should instead use
* new objects.
*/
class Coordinate
{
protected $lat;
protected $lng;
public function __construct($lat = null, $lng = null)
{
$this->lat = $lat;
$this->lng = $lng;
}
/**
* @see self::__construct
*
* @return Coordinate
*/
static public function createFromString($string)
{
$coordinateData = explode(",", $string);
if (count($coordinateData) !== 2 || (!is_numeric($coordinateData[0]) || !is_numeric($coordinateData[1]))) {
throw new \Exception('Please provide a valid coordinate string : "latitude,longitude"');
}
return new self($coordinateData[0], $coordinateData[1]);
}
/**
* @return string
*/
public function getLat()
{
return $this->lat;
}
/**
* @return Coordinate
*/
public function setLat($lat)
{
return new self($lat, $this->getLng());
}
/**
* @return string
*/
public function getLng()
{
return $this->lng;
}
/**
* @return Coordinate
*/
public function setLng($lng)
{
return new self($this->getLat(), $lng);
}
/**
* @return string
*/
public function __toString()
{
return $this->lat.','.$this->lng;
}
}
| <?php
namespace Pum\Bundle\TypeExtraBundle\Model;
/**
* The value of a coordinate object should NEVER change. You should instead use
* new objects.
*/
class Coordinate
{
protected $lat;
protected $lng;
public function __construct($lat = null, $lng = null)
{
$this->lat = $lat;
$this->lng = $lng;
}
/**
* @see self::__construct
*
* @return Coordinate
*/
static public function createFromString($string)
{
$coordinateData = explode(",", $string);
if (count($coordinateData) !== 2 || (!is_numeric($coordinateData[0]) || !is_numeric($coordinateData[1]))) {
throw new Exception('Please provide a valid coordinate string : "latitude,longitude"');
}
return new self($coordinateData[0], $coordinateData[1]);
}
/**
* @return string
*/
public function getLat()
{
return $this->lat;
}
/**
* @return Coordinate
*/
public function setLat($lat)
{
return new self($lat, $this->getLng());
}
/**
* @return string
*/
public function getLng()
{
return $this->lng;
}
/**
* @return Coordinate
*/
public function setLng($lng)
{
return new self($this->getLat(), $lng);
}
/**
* @return string
*/
public function __toString()
{
return $this->lat.','.$this->lng;
}
}
|
Add parallel capability for running the map | '''
Read in a vm map file. The map file contains a mapping of profiles to names
allowing for individual vms to be created in a more stateful way
'''
# Import python libs
import os
import copy
import multiprocessing
# Import salt libs
import saltcloud.cloud
import salt.client
# Import third party libs
import yaml
class Map(object):
'''
Create a vm stateful map execution object
'''
def __init__(self, opts):
self.opts = opts
self.cloud = saltcloud.cloud.Cloud(self.opts)
self.map = self.read()
def read(self):
'''
Read in the specified map file and return the map structure
'''
if not self.opts['map']:
return {}
if not os.path.isfile(self.opts['map']):
return {}
try:
with open(self.opts['map'], 'rb') as fp_:
map_ = yaml.loads(fb_.read())
except Exception:
return {}
if 'include' in map_:
map_ = salt.config.include_config(map_, self.opts['map'])
return map_
def run_map(self):
'''
Execute the contents of the vm map
'''
for profile in self.map:
for name in self.map[profile]:
if not profile in self.opts['vm']:
continue
vm_ = copy.deepcopy(self.opts['vm'][profile])
vm_['name'] = name
if self.opts['parallel']:
multiprocessing.Process(
target=self.cloud.create(vm_)
).start()
else:
self.cloud.create(vm_)
| '''
Read in a vm map file. The map file contains a mapping of profiles to names
allowing for individual vms to be created in a more stateful way
'''
# Import python libs
import os
import copy
# Import salt libs
import saltcloud.cloud
import salt.client
# Import third party libs
import yaml
class Map(object):
'''
Create a vm stateful map execution object
'''
def __init__(self, opts):
self.opts = opts
self.cloud = saltcloud.cloud.Cloud(self.opts)
self.map = self.read()
def read(self):
'''
Read in the specified map file and return the map structure
'''
if not self.opts['map']:
return {}
if not os.path.isfile(self.opts['map']):
return {}
try:
with open(self.opts['map'], 'rb') as fp_:
map_ = yaml.loads(fb_.read())
except Exception:
return {}
if 'include' in map_:
map_ = salt.config.include_config(map_, self.opts['map'])
return map_
def run_map(self):
'''
Execute the contents of the vm map
'''
for profile in self.map:
for name in self.map[profile]:
if not profile in self.opts['vm']:
continue
vm_ = copy.deepcopy(self.opts['vm'][profile])
vm_['name'] = name
self.cloud.create(vm_)
|
Set Mocha timout to 5 seconds | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
node: true,
globals: {},
white: true,
indent: 2,
camelcase: true,
eqeqeq: true,
eqnull: true,
quotmark: true,
expr: true,
latedef: true
}
},
mochaTest: {
test: {
options: {
reporter: 'spec',
timeout: 5000
},
src: ['test/**/*.js']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('default', ['jshint', 'mochaTest']);
}; | module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
node: true,
globals: {},
white: true,
indent: 2,
camelcase: true,
eqeqeq: true,
eqnull: true,
quotmark: true,
expr: true,
latedef: true
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/**/*.js']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
grunt.registerTask('default', ['jshint', 'mochaTest']);
}; |
Disable notification test for now | require.config({
baseUrl: '.',
paths: {
jquery: 'js/vendor/jquery',
underscore: 'js/vendor/underscore',
backbone: 'js/vendor/backbone',
localstorage: 'js/vendor/backbone.localStorage',
foundation: 'js/vendor/foundation',
reveal: 'js/vendor/foundation.reveal',
d3: 'js/vendor/d3',
modernizr: 'js/vendor/modernizr'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
d3: {
exports: 'd3'
},
modernizr: {
exports: 'Modernizr'
},
foundation: ['jquery'],
reveal: ['foundation']
}
});
require(['js/app', 'jquery', 'modernizr', 'reveal'], function(App, $, Modernizr) {
var checkCompatibility = function() {
var requiredApis = ['inlinesvg', 'audio', 'localstorage'];
var missingApi = false;
for (var i = 0 ; i < requiredApis.length && !missingApi ; i++) {
missingApi = !Modernizr[requiredApis[i]];
}
if (missingApi) {
$('#compatibility-alert').show();
}
};
checkCompatibility();
var app = new App();
app.run();
$(document).foundation();
});
| require.config({
baseUrl: '.',
paths: {
jquery: 'js/vendor/jquery',
underscore: 'js/vendor/underscore',
backbone: 'js/vendor/backbone',
localstorage: 'js/vendor/backbone.localStorage',
foundation: 'js/vendor/foundation',
reveal: 'js/vendor/foundation.reveal',
d3: 'js/vendor/d3',
modernizr: 'js/vendor/modernizr'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
d3: {
exports: 'd3'
},
modernizr: {
exports: 'Modernizr'
},
foundation: ['jquery'],
reveal: ['foundation']
}
});
require(['js/app', 'jquery', 'modernizr', 'reveal'], function(App, $, Modernizr) {
var checkCompatibility = function() {
var requiredApis = ['inlinesvg', 'audio', 'localstorage', 'notification'];
var missingApi = false;
for (var i = 0 ; i < requiredApis.length && !missingApi ; i++) {
missingApi = !Modernizr[requiredApis[i]];
}
if (missingApi) {
$('#compatibility-alert').show();
}
};
checkCompatibility();
var app = new App();
app.run();
$(document).foundation();
});
|
Update smoke test compiler pass | <?php
namespace Smartbox\Integration\FrameworkBundle\DependencyInjection\CompilerPasses;
use Smartbox\Integration\FrameworkBundle\Tools\SmokeTests\ConnectivityCheckSmokeTest;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class SmokeTestConnectivityCompilerPass.
*/
class SmokeTestConnectivityCompilerPass implements CompilerPassInterface
{
/**
* @param ContainerBuilder $container
*
* @api
*/
public function process(ContainerBuilder $container)
{
$smokeTestCommand = $container->getDefinition('smartcore.command.smoke_test');
$connectivityCheckSmokeTestClass = $container->getParameter('smartesb.smoke_test.connectivity_check.class');
$connectivityCheckSmokeTestItems = $container->findTaggedServiceIds(ConnectivityCheckSmokeTest::TAG_TEST_CONNECTIVITY);
foreach ($connectivityCheckSmokeTestItems as $serviceName => $tags) {
$testServiceName = $serviceName.'.connectivity_smoke_test';
$container->register($testServiceName, $connectivityCheckSmokeTestClass)
->setArguments([
'Connectivity check for '.$serviceName,
[$testServiceName => new Reference($serviceName)],
])
;
$labels = [];
foreach ($tags as $tag => $attr) {
if (array_key_exists('labels', $attr)) {
$labels = explode(',', $attr['labels']);
}
}
$smokeTestCommand->addMethodCall('addTest', [$testServiceName, new Reference($testServiceName), 'run', 'getDescription', $labels]);
}
}
}
| <?php
namespace Smartbox\Integration\FrameworkBundle\DependencyInjection\CompilerPasses;
use Smartbox\Integration\FrameworkBundle\Tools\SmokeTests\ConnectivityCheckSmokeTest;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Class SmokeTestConnectivityCompilerPass.
*/
class SmokeTestConnectivityCompilerPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*
* @api
*/
public function process(ContainerBuilder $container)
{
$smokeTestCommand = $container->getDefinition('smartcore.command.smoke_test');
$connectivityCheckSmokeTestClass = $container->getParameter('smartesb.smoke_test.connectivity_check.class');
$connectivityCheckSmokeTestItems = $container->findTaggedServiceIds(ConnectivityCheckSmokeTest::TAG_TEST_CONNECTIVITY);
foreach ($connectivityCheckSmokeTestItems as $serviceName => $tags) {
$testServiceName = $serviceName.'.connectivity_smoke_test';
$container->register($testServiceName, $connectivityCheckSmokeTestClass)
->setArguments([
'Connectivity check for '.$serviceName,
[$testServiceName => new Reference($serviceName)],
])
;
$smokeTestCommand->addMethodCall('addTest', [$testServiceName, new Reference($testServiceName)]);
}
}
}
|
Change imports in user registration test. | from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from factory import fuzzy
from faker import Faker
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
EMAIL = Faker().email()
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL)
| from factory import Faker, fuzzy
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
class UserRegistrationTestCase(TestCase):
def test_registration_view(self):
"""Verify that user registration view loads properly."""
response = self.client.get(reverse("account_signup"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "account/signup.html")
def test_user_registration(self):
"""Ensure that user registration works properly."""
EMAIL = Faker("email").generate()
PASSWORD = fuzzy.FuzzyText(length=16)
test_user_data = {
"password1": PASSWORD,
"password2": PASSWORD,
"email": EMAIL,
"email2": EMAIL,
}
# Verify that POSTing user data to the registration view
# succeeds / returns the right HTTP status code.
response = self.client.post(
reverse("account_signup"), test_user_data)
# Successful form submission will cause the HTTP status code
# to be "302 Found", not "200 OK".
self.assertEqual(response.status_code, 302)
# Verify that a User has been successfully created.
user_model = get_user_model()
user_model.objects.get(email=EMAIL)
|
Fix pinging in chat throwing errors | import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
.format(note.user, note.from_user))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False
| import logging
from notify.models import Notification
logger = logging.getLogger(__name__)
def ping_filter(message, users, sending_user, notify_text, notify_type,
notify_url=None):
for user in users:
if username_in_message(message, user.username):
# Create notification
if user == sending_user:
continue
note = Notification(
text='{} {}: {}'.format(
sending_user.username, notify_text, message),
user=user,
from_user=sending_user,
type=notify_type,
link=notify_url)
note.save()
logger.info("Created notification for user {} from {}"
.format(note))
return message
def username_in_message(message, username):
message = message.lower()
username = username.lower()
# Check if @username in message. Edge case for username at the end of
# the message.
if '@' + username + ' ' in message.lower():
return True
try:
return (message.index('@' + username) ==
len(message.lower()) - len('@' + username))
except ValueError:
return False |
Update notes migration to use examiner and startDate | var config = require('../config.js');
var nano = require('nano')(config.couchAuthDbURL);
var maindb = nano.use('main');
var uuid = require('node-uuid');
var recordsToUpdate = [];
maindb.list({startkey: 'visit_', endkey: 'visit_\uffff', include_docs: true}, function(err, results) {
if (!err) {
results.rows.forEach(function(result) {
var visitDoc = result.doc.data;
if (visitDoc !== null && visitDoc.notes && !visitDoc.patientNotes) {
var noteUuid = uuid.v4();
var visitId = result.doc._id.substr(8);
var patientNote = {
_id: 'patientNote_2_' + noteUuid,
data: {
content: visitDoc.notes,
createdBy: visitDoc.examiner || '',
date: visitDoc.startDate,
noteType: 'General',
patient: visitDoc.patient,
visit: visitId
}
};
recordsToUpdate.push(patientNote);
result.doc.data.patientNotes = [noteUuid];
recordsToUpdate.push(result.doc);
}
});
if (recordsToUpdate.length > 0) {
maindb.bulk({ docs: recordsToUpdate}, function(err, results) {
if (err) {
console.log('Error updating patient notes records.', err);
} else {
console.log('Success updating patient notes records.', JSON.stringify(results, null, 2));
}
});
}
} else {
console.log('ERROR fetching visit records', err);
}
});
| var config = require('../config.js');
var nano = require('nano')(config.couchAuthDbURL);
var maindb = nano.use('main');
var uuid = require('node-uuid');
var recordsToUpdate = [];
maindb.list({startkey: 'visit_', endkey: 'visit_\uffff', include_docs: true}, function(err, results) {
if (!err) {
results.rows.forEach(function(result) {
var visitDoc = result.doc.data;
if (visitDoc !== null && visitDoc.notes && !visitDoc.patientNotes) {
var noteUuid = uuid.v4();
var visitId = result.doc._id.substr(8);
var patientNote = {
_id: 'patientNote_2_' + noteUuid,
data: {
content: visitDoc.notes,
createdBy: 'system',
date: new Date(),
noteType: 'General',
patient: visitDoc.patient,
visit: visitId
}
};
recordsToUpdate.push(patientNote);
result.doc.data.patientNotes = [noteUuid];
recordsToUpdate.push(result.doc);
}
});
if (recordsToUpdate.length > 0) {
maindb.bulk({ docs: recordsToUpdate}, function(err, results) {
if (err) {
console.log('Error updating patient notes records.', err);
} else {
console.log('Success updating patient notes records.', JSON.stringify(results, null, 2));
}
});
}
} else {
console.log('ERROR fetching visit records', err);
}
});
|
Fix scope issues in CommentsRetriever | "use strict";
angular.module('arethusa.comments').factory('CommentsRetriever', [
'configurator',
'idHandler',
function(configurator, idHandler) {
var comments = {};
var alreadyLoaded;
function splitIdAndComment(comment) {
var regexp = new RegExp('^##(.*?)##\n\n(.*)$');
var match = regexp.exec(comment);
return match ? match.slice(1, 3) : ['noId', comment];
}
function addComments(id, comment) {
var arr = arethusaUtil.getProperty(comments, id);
if (!arr) {
arr = [];
arethusaUtil.setProperty(comments, id, arr);
}
arr.push(comment);
}
function parseComments(res) {
angular.forEach(res, function(commentObj, i) {
var comment = commentObj.comment;
var extracted = splitIdAndComment(comment);
commentObj.comment = extracted[1];
addComments(extracted[0], commentObj);
});
}
return function(conf) {
var self = this;
var resource = configurator.provideResource(conf.resource);
this.getData = function(chunkId, callback) {
if (alreadyLoaded) {
callback(comments[chunkId]);
} else {
resource.get().then(function(res) {
parseComments(res.data);
callback(comments[chunkId]);
});
alreadyLoaded = true;
}
};
};
}
]);
| "use strict";
angular.module('arethusa.comments').factory('CommentsRetriever', [
'configurator',
'idHandler',
function(configurator, idHandler) {
var comments = {};
function splitIdAndComment(comment) {
var regexp = new RegExp('^##(.*?)##\n\n(.*)$');
var match = regexp.exec(comment);
return match ? match.slice(1, 3) : ['noId', comment];
}
function addComments(id, comment) {
var arr = arethusaUtil.getProperty(comments, id);
if (!arr) {
arr = [];
arethusaUtil.setProperty(comments, id, arr);
}
arr.push(comment);
}
function parseComments(res) {
angular.forEach(res, function(commentObj, i) {
var comment = commentObj.comment;
var extracted = splitIdAndComment(comment);
commentObj.comment = extracted[1];
addComments(extracted[0], commentObj);
});
}
return function(conf) {
var self = this;
var resource = configurator.provideResource(conf.resource);
var alreadyLoaded;
this.getData = function(chunkId, callback) {
if (alreadyLoaded) {
callback(comments[chunkId]);
} else {
resource.get().then(function(res) {
parseComments(res.data);
alreadyLoaded = true;
callback(comments[chunkId]);
});
}
};
};
}
]);
|
Move of autoload into on_start | <?php
namespace Concrete\Package\CommunityStoreStripe;
use Package;
use Whoops\Exception\ErrorException;
use \Concrete\Package\CommunityStore\Src\CommunityStore\Payment\Method as PaymentMethod;
defined('C5_EXECUTE') or die(_("Access Denied."));
class Controller extends Package
{
protected $pkgHandle = 'community_store_stripe';
protected $appVersionRequired = '5.7.2';
protected $pkgVersion = '1.0.2';
public function on_start()
{
require 'vendor/autoload.php';
}
public function getPackageDescription()
{
return t("Stripe Payment Method for Community Store");
}
public function getPackageName()
{
return t("Stripe Payment Method");
}
public function install()
{
$installed = Package::getInstalledHandles();
if(!(is_array($installed) && in_array('community_store',$installed)) ) {
throw new ErrorException(t('This package requires that Community Store be installed'));
} else {
$pkg = parent::install();
$pm = new PaymentMethod();
$pm->add('community_store_stripe','Stripe',$pkg);
}
}
public function uninstall()
{
$pm = PaymentMethod::getByHandle('community_store_stripe');
if ($pm) {
$pm->delete();
}
$pkg = parent::uninstall();
}
}
?> | <?php
namespace Concrete\Package\CommunityStoreStripe;
use Package;
use Whoops\Exception\ErrorException;
use \Concrete\Package\CommunityStore\Src\CommunityStore\Payment\Method as PaymentMethod;
defined('C5_EXECUTE') or die(_("Access Denied."));
require 'vendor/autoload.php';
class Controller extends Package
{
protected $pkgHandle = 'community_store_stripe';
protected $appVersionRequired = '5.7.2';
protected $pkgVersion = '1.0.2';
public function getPackageDescription()
{
return t("Stripe Payment Method for Community Store");
}
public function getPackageName()
{
return t("Stripe Payment Method");
}
public function install()
{
$installed = Package::getInstalledHandles();
if(!(is_array($installed) && in_array('community_store',$installed)) ) {
throw new ErrorException(t('This package requires that Community Store be installed'));
} else {
$pkg = parent::install();
$pm = new PaymentMethod();
$pm->add('community_store_stripe','Stripe',$pkg);
}
}
public function uninstall()
{
$pm = PaymentMethod::getByHandle('community_store_stripe');
if ($pm) {
$pm->delete();
}
$pkg = parent::uninstall();
}
}
?> |
Add comments about what other elements need support. | <?php
namespace ComplexPie\RSS20;
class Item extends \ComplexPie\XML\Entry
{
protected static $static_ext = array();
protected static $aliases = array(
'summary' => 'description',
'published' => 'pubDate',
);
protected static $elements = array(
// XXX: author
// XXX: category
// XXX: comments
'description' => array(
'element' => 'description',
'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
'single' => true
),
// XXX: enclosure
// XXX: guid
'link' => array(
'element' => 'link',
'contentConstructor' => 'ComplexPie\\Content\\IRINode',
'single' => true
),
'pubDate' => array(
'element' => 'pubDate',
'contentConstructor' => 'ComplexPie\\Content::from_date_in_textcontent',
'single' => true
),
// XXX: source
'title' => array(
'element' => 'title',
'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
'single' => true
),
);
protected static $element_namespaces = array(
);
}
Item::add_static_extension('get', '\\ComplexPie\\RSS20\\links', ~PHP_INT_MAX);
| <?php
namespace ComplexPie\RSS20;
class Item extends \ComplexPie\XML\Entry
{
protected static $static_ext = array();
protected static $aliases = array(
'summary' => 'description',
'published' => 'pubDate',
);
protected static $elements = array(
'description' => array(
'element' => 'description',
'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
'single' => true
),
'link' => array(
'element' => 'link',
'contentConstructor' => 'ComplexPie\\Content\\IRINode',
'single' => true
),
'title' => array(
'element' => 'title',
'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
'single' => true
),
'pubDate' => array(
'element' => 'pubDate',
'contentConstructor' => 'ComplexPie\\Content::from_date_in_textcontent',
'single' => true
),
);
protected static $element_namespaces = array(
);
}
Item::add_static_extension('get', '\\ComplexPie\\RSS20\\links', ~PHP_INT_MAX);
|
Resolve concurency on the same object. | package benchmarking;
import converters.JsonConverter;
import datamodel.PerformanceSelfMonitoring;
import mongo.MongoManager;
public class Monitoring {
CpuMonitoring cpuMonitor = new CpuMonitoring();
long startTime = -1, endTime = -1, totalTime = -1;
public void startMonitoring() {
cpuMonitor.startMonitoring();
startTime = System.currentTimeMillis();
}
public void stopMonitoring() {
cpuMonitor.stopMonitoring();
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
}
public PerformanceSelfMonitoring getResults(long pid) {
PerformanceSelfMonitoring perfSelf = new PerformanceSelfMonitoring();
perfSelf.setCpuUsageResults(cpuMonitor.parseForPid(pid));
perfSelf.setExecutionTime(totalTime);
return perfSelf;
}
public void saveResultsInDb (long pid, MongoManager mm) {
Thread writeRestuls = new Thread(new Runnable() {
@Override
public void run() {
PerformanceSelfMonitoring perfSelf = new PerformanceSelfMonitoring();
perfSelf.setCpuUsageResults(cpuMonitor.parseForPid(pid));
perfSelf.setExecutionTime(totalTime);
mm.pushJson(JsonConverter.objectToJsonString(perfSelf), "selfPerformance"); }
});
writeRestuls.start();
}
}
| package benchmarking;
import converters.JsonConverter;
import datamodel.PerformanceSelfMonitoring;
import mongo.MongoManager;
public class Monitoring {
CpuMonitoring cpuMonitor = new CpuMonitoring();
long startTime = -1, endTime = -1, totalTime = -1;
private PerformanceSelfMonitoring perfSelf = new PerformanceSelfMonitoring();
public void startMonitoring() {
cpuMonitor.startMonitoring();
startTime = System.currentTimeMillis();
}
public void stopMonitoring() {
cpuMonitor.stopMonitoring();
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
}
public PerformanceSelfMonitoring getResults(long pid) {
perfSelf.setCpuUsageResults(cpuMonitor.parseForPid(pid));
perfSelf.setExecutionTime(totalTime);
return perfSelf;
}
public void saveResultsInDb (long pid, MongoManager mm) {
Thread writeRestuls = new Thread(new Runnable() {
@Override
public void run() {
perfSelf.setCpuUsageResults(cpuMonitor.parseForPid(pid));
perfSelf.setExecutionTime(totalTime);
mm.pushJson(JsonConverter.objectToJsonString(perfSelf), "selfPerformance"); }
});
writeRestuls.start();
}
}
|
Fix typo - XML<->YAML configuration | """ Plugin manager is Checker's main module.
Plugin Manager is using Yapsy to find and load plugins from
a directory and loads them via PluginRunner.
"""
from yapsy.PluginManager import PluginManager
from pluginRunner import PluginRunner
from configLoader import ConfigLoader
from down import Scraper
import logging
import sys
def main():
""" Load configuration, find plugins, run plugin runner.
"""
if len(sys.argv) == 2:
# load configuration
cl = ConfigLoader()
cl.load(sys.argv[1])
# download initial transactions
s = Scraper(cl.getDbconf())
s.scrap(cl.getEntryPoints())
logging.getLogger("yapsy").addHandler(logging.StreamHandler())
# load plugins
manager = PluginManager()
manager.setPluginPlaces(["checker/plugin"])
manager.collectPlugins()
plugins = []
for pluginInfo in manager.getAllPlugins():
print(pluginInfo.name)
plugins.append(pluginInfo.plugin_object)
if len(plugins) == 0:
print("No plugins found")
runner = PluginRunner(cl.getDbconf(), cl.getUriAcceptor(),
cl.getTypeAcceptor(), cl.getMaxDepth())
# verify
runner.run(plugins)
else:
print("Usage: "+sys.argv[0]+" <configuration YAML file>")
if __name__ == "__main__":
main()
| """ Plugin manager is Checker's main module.
Plugin Manager is using Yapsy to find and load plugins from
a directory and loads them via PluginRunner.
"""
from yapsy.PluginManager import PluginManager
from pluginRunner import PluginRunner
from configLoader import ConfigLoader
from down import Scraper
import logging
import sys
def main():
""" Load configuration, find plugins, run plugin runner.
"""
if len(sys.argv) == 2:
# load configuration
cl = ConfigLoader()
cl.load(sys.argv[1])
# download initial transactions
s = Scraper(cl.getDbconf())
s.scrap(cl.getEntryPoints())
logging.getLogger("yapsy").addHandler(logging.StreamHandler())
# load plugins
manager = PluginManager()
manager.setPluginPlaces(["checker/plugin"])
manager.collectPlugins()
plugins = []
for pluginInfo in manager.getAllPlugins():
print(pluginInfo.name)
plugins.append(pluginInfo.plugin_object)
if len(plugins) == 0:
print("No plugins found")
runner = PluginRunner(cl.getDbconf(), cl.getUriAcceptor(),
cl.getTypeAcceptor(), cl.getMaxDepth())
# verify
runner.run(plugins)
else:
print("Usage: "+sys.argv[0]+" <configuration XML file>")
if __name__ == "__main__":
main()
|
Change log level to warning | import logging
import time
from functools import wraps
from . import compat
compat.patch() # monkey-patch time.perf_counter
log = logging.getLogger('amqpy')
def synchronized(lock_name):
"""Decorator for automatically acquiring and releasing lock for method call
This decorator accesses the `lock_name` :class:`threading.Lock` attribute of the instance that
the wrapped method is bound to. The lock is acquired (blocks indefinitely) before the method is
called. After the method has executed, the lock is released.
Decorated methods should not be long-running operations, since the lock is held for the duration
of the method's execution.
:param lock_name: name of :class:`threading.Lock` object
"""
def decorator(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
lock = getattr(self, lock_name)
acquired = lock.acquire(False)
if not acquired:
# log.debug('> Wait to acquire lock for [{}]'.format(f.__qualname__))
start_time = time.perf_counter()
lock.acquire()
tot_time = time.perf_counter() - start_time
if tot_time > 10:
# only log if waited for more than 10s to acquire lock
log.warn('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time))
try:
retval = f(self, *args, **kwargs)
finally:
lock.release()
return retval
return wrapper
return decorator
| import logging
import time
from functools import wraps
from . import compat
compat.patch() # monkey-patch time.perf_counter
log = logging.getLogger('amqpy')
def synchronized(lock_name):
"""Decorator for automatically acquiring and releasing lock for method call
This decorator accesses the `lock_name` :class:`threading.Lock` attribute of the instance that
the wrapped method is bound to. The lock is acquired (blocks indefinitely) before the method is
called. After the method has executed, the lock is released.
Decorated methods should not be long-running operations, since the lock is held for the duration
of the method's execution.
:param lock_name: name of :class:`threading.Lock` object
"""
def decorator(f):
@wraps(f)
def wrapper(self, *args, **kwargs):
lock = getattr(self, lock_name)
acquired = lock.acquire(False)
if not acquired:
# log.debug('> Wait to acquire lock for [{}]'.format(f.__qualname__))
start_time = time.perf_counter()
lock.acquire()
tot_time = time.perf_counter() - start_time
if tot_time > 10:
# only log if waited for more than 10s to acquire lock
log.debug('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time))
try:
retval = f(self, *args, **kwargs)
finally:
lock.release()
return retval
return wrapper
return decorator
|
Make sudo pfctl error check Python 3 compatible
In Python 3, subprocess.check_output() returns a sequence of bytes. This change ensures that it will be converted to a string, so the substring test for the sudo error message does not raise a TypeError. This fixes the code in Python 3 while remaining compatible with Python 2. | import subprocess
from . import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output.decode(errors="replace"):
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt.decode(errors="replace")
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
| import subprocess
from . import pf
"""
Doing this the "right" way by using DIOCNATLOOK on the pf device turns out
to be a pain. Apple has made a number of modifications to the data
structures returned, and compiling userspace tools to test and work with
this turns out to be a pain in the ass. Parsing pfctl output is short,
simple, and works.
Note: Also Tested with FreeBSD 10 pkgng Python 2.7.x.
Should work almost exactly as on Mac OS X and except with some changes to
the output processing of pfctl (see pf.py).
"""
class Resolver(object):
STATECMD = ("sudo", "-n", "/sbin/pfctl", "-s", "state")
def original_addr(self, csock):
peer = csock.getpeername()
try:
stxt = subprocess.check_output(self.STATECMD, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if "sudo: a password is required" in e.output:
insufficient_priv = True
else:
raise RuntimeError("Error getting pfctl state: " + repr(e))
else:
insufficient_priv = "sudo: a password is required" in stxt
if insufficient_priv:
raise RuntimeError(
"Insufficient privileges to access pfctl. "
"See http://docs.mitmproxy.org/en/latest/transparent/osx.html for details.")
return pf.lookup(peer[0], peer[1], stxt)
|
Change note trigger to tell, and make it reply | # -*- coding: utf-8 -*-
# vim: set ts=4 et
import sqlite3
from plugin import *
class Plugin(BasePlugin):
def on_load(self, reloading):
self.db = sqlite3.connect('data/notes.db')
c = self.db.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS notes
(channel text, sender text, recipient text, message text)''')
self.db.commit()
def on_unload(self, reloading):
self.db.close()
@hook
def tell_trigger(self, msg, args, argstr):
if not msg.channel:
return
data = {'channel': msg.param[0], 'sender': msg.nick}
data['recipient'], data['message'] = argstr.split(None, 1)
c = self.db.cursor()
c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data)
self.db.commit()
msg.reply("Aye aye!")
@hook
def privmsg_command(self, msg):
if not msg.channel:
return
c = self.db.cursor()
criteria = {'channel': msg.param[0], 'recipient': msg.nick}
c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria)
rows = c.fetchall()
if rows:
for row in rows:
msg.reply("Note: <%s> %s" % row)
c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria)
self.db.commit()
| # -*- coding: utf-8 -*-
# vim: set ts=4 et
import sqlite3
from plugin import *
class Plugin(BasePlugin):
def on_load(self, reloading):
self.db = sqlite3.connect('data/notes.db')
c = self.db.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS notes
(channel text, sender text, recipient text, message text)''')
self.db.commit()
def on_unload(self, reloading):
self.db.close()
@hook
def note_trigger(self, msg, args, argstr):
if not msg.channel:
return
data = {'channel': msg.param[0], 'sender': msg.nick}
data['recipient'], data['message'] = argstr.split(None, 1)
c = self.db.cursor()
c.execute('INSERT INTO notes VALUES (:channel, :sender, :recipient, :message)', data)
self.db.commit()
@hook
def privmsg_command(self, msg):
if not msg.channel:
return
c = self.db.cursor()
criteria = {'channel': msg.param[0], 'recipient': msg.nick}
c.execute('SELECT sender, message FROM notes WHERE channel=:channel AND recipient=:recipient', criteria)
rows = c.fetchall()
if rows:
for row in rows:
msg.reply("Note: <%s> %s" % row)
c.execute('DELETE FROM notes WHERE channel=:channel AND recipient=:recipient', criteria)
self.db.commit()
|
[FIX] hw_drivers: Fix issue with printer device-id
When we print a ticket status with a thermal printer we need printer's device-id
But if we add manually a printer this device-id doesn't exist
So now we update de devices list with a supported = True if
printer are manually added
closes odoo/odoo#53043
Signed-off-by: Quentin Lejeune (qle) <[email protected]> | from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.controllers.driver import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_delay = 120
connection_type = 'printer'
def get_devices(self):
printer_devices = {}
with cups_lock:
printers = conn.getPrinters()
devices = conn.getDevices()
for printer in printers:
path = printers.get(printer).get('device-uri', False)
if path and path in devices:
devices.get(path).update({'supported': True}) # these printers are automatically supported
for path in devices:
if 'uuid=' in path:
identifier = sub('[^a-zA-Z0-9_]', '', path.split('uuid=')[1])
elif 'serial=' in path:
identifier = sub('[^a-zA-Z0-9_]', '', path.split('serial=')[1])
else:
identifier = sub('[^a-zA-Z0-9_]', '', path)
devices[path]['identifier'] = identifier
devices[path]['url'] = path
printer_devices[identifier] = devices[path]
return printer_devices
| from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.controllers.driver import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_delay = 120
connection_type = 'printer'
def get_devices(self):
printer_devices = {}
with cups_lock:
printers = conn.getPrinters()
for printer in printers:
printers[printer]['supported'] = True # these printers are automatically supported
printers[printer]['device-make-and-model'] = printers[printer]['printer-make-and-model']
if 'usb' in printers[printer]['device-uri']:
printers[printer]['device-class'] = 'direct'
else:
printers[printer]['device-class'] = 'network'
devices = conn.getDevices()
if printers:
devices.update(printers)
for path in devices:
if 'uuid=' in path:
identifier = sub('[^a-zA-Z0-9_]', '', path.split('uuid=')[1])
elif 'serial=' in path:
identifier = sub('[^a-zA-Z0-9_]', '', path.split('serial=')[1])
else:
identifier = sub('[^a-zA-Z0-9_]', '', path)
devices[path]['identifier'] = identifier
devices[path]['url'] = path
printer_devices[identifier] = devices[path]
return printer_devices
|
Allow "Home" to be active menu item | from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks for "%s"' % name
@register.inclusion_tag('minicms/menu.html', takes_context=True)
def show_menu(context, name='menu'):
request = context['request']
menu = []
try:
for line in Block.objects.get(name=name).content.splitlines():
line = line.rstrip()
try:
title, url = line.rsplit(' ', 1)
except:
continue
menu.append({'title': title.strip(), 'url': url})
except Block.DoesNotExist:
pass
# Mark the best-matching URL as active
active = None
active_len = 0
# Normalize path
path = request.path.rstrip('/') + '/'
for item in menu:
# Normalize path
url = item['url'].rstrip('/') + '/'
# Root is only active if you have a "Home" link
if path != '/' and url == '/':
continue
if path.startswith(url) and len(url) > active_len:
active = item
active_len = len(url)
if active is not None:
active['active'] = True
return {'menu': menu}
| from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks for "%s"' % name
@register.inclusion_tag('minicms/menu.html', takes_context=True)
def show_menu(context, name='menu'):
request = context['request']
menu = []
try:
for line in Block.objects.get(name=name).content.splitlines():
line = line.rstrip()
try:
title, url = line.rsplit(' ', 1)
except:
continue
menu.append({'title': title.strip(), 'url': url})
except Block.DoesNotExist:
pass
# Mark the best-matching URL as active
if request.path != '/':
active = None
active_len = 0
# Normalize path
path = request.path.rstrip('/') + '/'
for item in menu:
# Normalize path
url = item['url'].rstrip('/') + '/'
if path.startswith(url) and len(url) > active_len:
active = item
active_len = len(url)
if active is not None:
active['active'] = True
return {'menu': menu}
|
Fix error from removed api after upgrading jquery |
define([], function() {
'use strict';
return withAsyncQueue;
function withAsyncQueue() {
this.before('initialize', function() {
var self = this,
deferreds = {},
stacks = {};
this.setupAsyncQueue = function(name) {
var stack = stacks[name] = [],
objectData;
self[name + 'Ready'] = function(callback) {
if (callback) {
// Legacy non-promise
if (objectData) {
callback.call(self, objectData);
} else {
stack.push(callback);
}
} else {
return deferreds[name] || (deferreds[name] = $.Deferred());
}
};
self[name + 'IsReady'] = function() {
if (deferreds[name]) {
return deferreds[name].state() == 'resolved';
}
return objectData !== undefined;
};
self[name + 'MarkReady'] = function(data) {
if (!data) throw "No object passed to " + name + "MarkReady";
if (deferreds[name]) {
deferreds[name].resolve(data);
} else {
deferreds[name] = $.Deferred();
deferreds[name].resolve(data);
}
objectData = data;
stack.forEach(function(c) {
c.call(self, objectData);
});
stack.length = 0;
};
self[name + 'Unload'] = function() {
deferreds[name] = null;
objectData = null;
};
};
});
}
});
|
define([], function() {
'use strict';
return withAsyncQueue;
function withAsyncQueue() {
this.before('initialize', function() {
var self = this,
deferreds = {},
stacks = {};
this.setupAsyncQueue = function(name) {
var stack = stacks[name] = [],
objectData;
self[name + 'Ready'] = function(callback) {
if (callback) {
// Legacy non-promise
if (objectData) {
callback.call(self, objectData);
} else {
stack.push(callback);
}
} else {
return deferreds[name] || (deferreds[name] = $.Deferred());
}
};
self[name + 'IsReady'] = function() {
if (deferreds[name]) {
return deferreds[name].isResolved();
}
return objectData !== undefined;
};
self[name + 'MarkReady'] = function(data) {
if (!data) throw "No object passed to " + name + "MarkReady";
if (deferreds[name]) {
deferreds[name].resolve(data);
} else {
deferreds[name] = $.Deferred();
deferreds[name].resolve(data);
}
objectData = data;
stack.forEach(function(c) {
c.call(self, objectData);
});
stack.length = 0;
};
self[name + 'Unload'] = function() {
deferreds[name] = null;
objectData = null;
};
};
});
}
});
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.