text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Allow for 1 arg in a list | """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list):
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
| """ Auxiliary functions for models """
def unpack_args(args, layer_no, layers_max):
""" Return layer parameters """
new_args = {}
for arg in args:
if isinstance(args[arg], list) and layers_max > 1:
if len(args[arg]) >= layers_max:
arg_value = args[arg][layer_no]
else:
arg_value = args[arg]
else:
arg_value = args[arg]
new_args.update({arg: arg_value})
return new_args
def unpack_fn_from_config(param, config=None):
""" Return params from config """
par = config.get(param)
if par is None:
return None, {}
if isinstance(par, (tuple, list)):
if len(par) == 0:
par_name = None
elif len(par) == 1:
par_name, par_args = par[0], {}
elif len(par) == 2:
par_name, par_args = par
else:
par_name, par_args = par[0], par[1:]
elif isinstance(par, dict):
par = par.copy()
par_name, par_args = par.pop('name', None), par
else:
par_name, par_args = par, {}
return par_name, par_args
|
Fix blocking all options except OptionValues | <?php
namespace WP_Migrations\OptionVersions;
class Provider
{
protected $repository;
public function __construct(Repository $optionVersionRepository)
{
$this->repository = $optionVersionRepository;
}
public function init()
{
add_action('updated_option', [$this, 'updated_option'], 1, 3);
add_action('admin_menu', [$this, 'optionversions_menu']);
}
public function updated_option($option,$old_value, $new_value)
{
if ($option[0] == '_') {
return;
}
if ('wp-migrations-plugin-options' === $option) {
return;
}
$serialized_option = maybe_serialize( $new_value );
$this->repository->log($option,$serialized_option,get_current_user_id());
}
public function optionversions_menu(){
$title = __("Option Versions",'wp-migrations');
add_management_page( $title, $title, 'manage_options', 'optionversions', [$this,'toolsPage'] );
}
public function toolsPage(){
if( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
$listTable = new ListTable();
$listTable->prepare_items();
include('assets/toolspage.php');
}
} | <?php
namespace WP_Migrations\OptionVersions;
class Provider
{
protected $repository;
public function __construct(Repository $optionVersionRepository)
{
$this->repository = $optionVersionRepository;
}
public function init()
{
add_action('updated_option', [$this, 'updated_option'], 1, 3);
add_action('admin_menu', [$this, 'optionversions_menu']);
}
public function updated_option($option,$old_value, $new_value)
{
if ($option[0] == '_') {
return;
}
if ('wp-migrations-plugin-options' !== $option) {
return;
}
$serialized_option = maybe_serialize( $new_value );
$this->repository->log($option,$serialized_option,get_current_user_id());
}
public function optionversions_menu(){
$title = __("Option Versions",'wp-migrations');
add_management_page( $title, $title, 'manage_options', 'optionversions', [$this,'toolsPage'] );
}
public function toolsPage(){
if( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
$listTable = new ListTable();
$listTable->prepare_items();
include('assets/toolspage.php');
}
} |
Add mixin to put the username in context | import urlparse
from functools import wraps
from django.conf import settings
from django.utils.decorators import available_attrs, method_decorator
from django.contrib.auth import REDIRECT_FIELD_NAME
from privileges.forms import GrantForm
from privileges.models import Grant
def owner_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
if request.user.username == kwargs["username"] or \
request.user.is_superuser:
return view_func(request, *args, **kwargs)
path = request.build_absolute_uri()
login_scheme, login_netloc = urlparse.urlparse(settings.LOGIN_URL)[:2]
current_scheme, current_netloc = urlparse.urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(path, redirect_field_name=REDIRECT_FIELD_NAME)
return _wrapped_view
def cbv_decorator(decorator):
def _decorator(cls):
cls.dispatch = method_decorator(decorator)(cls.dispatch)
return cls
return _decorator
class UsernameContextMixin(object):
def get_context_data(self, **kwargs):
context = super(UsernameContextMixin, self).get_context_data(**kwargs)
context.update({
"username": self.kwargs.get("username")
})
return context
| import urlparse
from functools import wraps
from django.conf import settings
from django.utils.decorators import available_attrs, method_decorator
from django.contrib.auth import REDIRECT_FIELD_NAME
from privileges.forms import GrantForm
from privileges.models import Grant
def owner_required(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
if request.user.username == kwargs["username"] or \
request.user.is_superuser:
return view_func(request, *args, **kwargs)
path = request.build_absolute_uri()
login_scheme, login_netloc = urlparse.urlparse(settings.LOGIN_URL)[:2]
current_scheme, current_netloc = urlparse.urlparse(path)[:2]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(path, redirect_field_name=REDIRECT_FIELD_NAME)
return _wrapped_view
def cbv_decorator(decorator):
def _decorator(cls):
cls.dispatch = method_decorator(decorator)(cls.dispatch)
return cls
return _decorator
|
Add a services filter to the API | <?php
/**
* @author Kirk Mayo <[email protected]>
*
* A controller class for handling API requests
*/
class SocialAPI extends Controller
{
private static $allowed_actions = array(
'countsfor'
);
private static $url_handlers = array(
'countsfor/$SERVICE/$FILTER'
=> 'countsFor'
);
public function countsFor() {
$urls = explode(',',$this->request->getVar('urls'));
// queue all urls to be checked
foreach ($urls as $url) {
$result = SocialQueue::queueURL($url);
}
$urlObjs = SocialURL::get()
->filter(array(
'URL' => $urls,
'Active' => 1
));
if (!$urlObjs->count()) {
return json_encode(array());
}
$result = array();
// do we need to filter the results any further
$service = $this->getRequest()->param('SERVICE');
if ($service && $service == 'service') {
$filter = $this->getRequest()->param('FILTER');
}
foreach ($urlObjs as $urlObj) {
foreach ($urlObj->Statistics() as $statistic) {
if ($filter) {
if (strtoupper($statistic->Service) == strtoupper($filter)) {
$results['results'][$urlObj->URL][$statistic->Service][] = array(
$statistic->Action => $statistic->Count
);
}
} else {
$results['results'][$urlObj->URL][$statistic->Service][] = array(
$statistic->Action => $statistic->Count
);
}
}
}
return json_encode($results);
}
}
| <?php
/**
* @author Kirk Mayo <[email protected]>
*
* A controller class for handling API requests
*/
class SocialAPI extends Controller
{
private static $allowed_actions = array(
'countsfor'
);
private static $url_handlers = array(
'countsfor'
=> 'countsfor'
);
public function countsfor() {
$urls = explode(',',$this->request->getVar('pageUrl'));
// queue all urls to be checked
foreach ($urls as $url) {
$result = SocialQueue::queueURL($url);
}
$urlObjs = SocialURL::get()
->filter(array(
'URL' => $urls,
'Active' => 1
));
if (!$urlObjs->count()) {
return json_encode(array());
}
$result = array();
foreach ($urlObjs as $urlObj) {
foreach ($urlObj->Statistics() as $statistic) {
$results['results'][$urlObj->URL][$statistic->Service][] = array(
$statistic->Action => $statistic->Count
);
}
}
return json_encode($results);
}
}
|
Fix URL pattern for validating OAuth2 tokens | # Copyright (C) 2014 Universidad Politecnica de Madrid
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.fiware_oauth2 import views
# NOTE(garcianavalon) following
# https://github.com/ging/fi-ware-idm/wiki/Using-the-FI-LAB-instance
urlpatterns = patterns(
'fiware_oauth2.views',
url(r"^oauth2/authorize/$", views.AuthorizeView.as_view(),
name='fiware_oauth2_authorize'),
url(r"^oauth2/authorize/cancel/$", views.cancel_authorize,
name='fiware_oauth2_cancel_authorize'),
url(r"^oauth2/token$", views.AccessTokenView.as_view(),
name='fiware_oauth2_access_token'),
url(r"^user$", views.UserInfoView.as_view(),
name='fiware_oauth2_user_info'),
) | # Copyright (C) 2014 Universidad Politecnica de Madrid
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.fiware_oauth2 import views
# NOTE(garcianavalon) following
# https://github.com/ging/fi-ware-idm/wiki/Using-the-FI-LAB-instance
urlpatterns = patterns(
'fiware_oauth2.views',
url(r"^oauth2/authorize/$", views.AuthorizeView.as_view(),
name='fiware_oauth2_authorize'),
url(r"^oauth2/authorize/cancel/$", views.cancel_authorize,
name='fiware_oauth2_cancel_authorize'),
url(r"^oauth2/token$", views.AccessTokenView.as_view(),
name='fiware_oauth2_access_token'),
url(r"^user", views.UserInfoView.as_view(),
name='fiware_oauth2_user_info'),
) |
Disable non-functional create service button | import React, { Component } from 'react';
import {observer} from 'mobx-react';
import Services from '../components/Services';
import Tasks from '../components/Tasks';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router';
const styles = {
button: {
margin: 0.6 + 'rem'
}
};
const Dashboard = observer(
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
selectedServices: []
};
}
onServiceSelection(selectedServices) {
this.setState({
selectedServices: selectedServices
});
}
render() {
const {nodeStore} = this.props.route;
/*
<FlatButton
label="Create Service"
containerElement={<Link to="/services/create" />}
primary={true}
style={styles.button}
icon={<i className="material-icons">add</i>}
/>
*/
return (
<div>
<Services
services={nodeStore.services}
onSelection={this.onServiceSelection.bind(this)}
selectedServices={this.state.selectedServices}/>
<Tasks
tasks={nodeStore.tasks}
selectedServices={this.state.selectedServices}/>
</div>
);
}
}
);
export default Dashboard;
| import React, { Component } from 'react';
import {observer} from 'mobx-react';
import Services from '../components/Services';
import Tasks from '../components/Tasks';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router';
const styles = {
button: {
margin: 0.6 + 'rem'
}
};
const Dashboard = observer(
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
selectedServices: []
};
}
onServiceSelection(selectedServices) {
this.setState({
selectedServices: selectedServices
});
}
render() {
const {nodeStore} = this.props.route;
return (
<div>
<FlatButton
label="Create Service"
containerElement={<Link to="/services/create" />}
primary={true}
style={styles.button}
icon={<i className="material-icons">add</i>}
/>
<Services
services={nodeStore.services}
onSelection={this.onServiceSelection.bind(this)}
selectedServices={this.state.selectedServices}/>
<Tasks
tasks={nodeStore.tasks}
selectedServices={this.state.selectedServices}/>
</div>
);
}
}
);
export default Dashboard;
|
refactor: Save currentTimePeriod passed to component to variable
Prevents bubbling | import Ember from 'ember';
import moment from 'npm:moment';
export default Ember.Component.extend({
btnActive: false,
didReceiveAttrs () {
let timePeriodChanged = {
year: this.get('currentDate').year,
month: this.get('currentDate').month
};
if (!this.get('timePeriods').length) {
this.get('timePeriods').push([
moment().format('YYYY'),
moment().format('MM')
]);
}
this.set('timePeriodChanged', timePeriodChanged);
},
init () {
this._super();
this.get('userSettings').timePeriods().then(response => {
// Sort by latest on top
this.set('timePeriods', response.sortBy('begins').reverse());
// Create array of years
this.set('years', response.uniqBy('year'));
});
actions: {
monthSelected (value) {
this.timePeriodBtn(true);
this.set('timePeriodChanged.month', parseInt(value));
},
yearSelected (value) {
this.timePeriodBtn(true);
this.set('timePeriodChanged.year', parseInt(value));
},
changeTimePeriod () {
this.timePeriodBtn(false);
const timePeriod = this.get('timePeriodChanged');
if (moment(`${timePeriod.year}-${timePeriod.month}`, 'YYYY-MM').isSame(moment().format('YYYY-MM'))) {
timePeriod.isInPast = false;
} else {
timePeriod.isInPast = true;
}
this.sendAction('action', timePeriod);
}
},
timePeriodBtn (boolean) {
// Run only if value differs
if (this.get('btnActive') !== boolean) {
this.set('btnActive', boolean);
}
}
});
| import Ember from 'ember';
import moment from 'npm:moment';
export default Ember.Component.extend({
btnActive: false,
didReceiveAttrs () {
this.set('timePeriodChanged', this.get('currentDate'));
},
init () {
this._super();
this.get('userSettings').timePeriods().then(response => {
// Sort by latest on top
this.set('timePeriods', response.sortBy('begins').reverse());
// Create array of years
this.set('years', response.uniqBy('year'));
});
actions: {
monthSelected (value) {
this.timePeriodBtn(true);
this.set('timePeriodChanged.month', parseInt(value));
},
yearSelected (value) {
this.timePeriodBtn(true);
this.set('timePeriodChanged.year', parseInt(value));
},
changeTimePeriod () {
this.timePeriodBtn(false);
const timePeriod = this.get('timePeriodChanged');
if (moment(`${timePeriod.year}-${timePeriod.month}`, 'YYYY-MM').isSame(moment().format('YYYY-MM'))) {
timePeriod.isInPast = false;
} else {
timePeriod.isInPast = true;
}
this.sendAction('action', timePeriod);
}
},
timePeriodBtn (boolean) {
// Run only if value differs
if (this.get('btnActive') !== boolean) {
this.set('btnActive', boolean);
}
}
});
|
Put config back in thing | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
'''
Executables
########################
Exa provides two executables; "exa" and "exw". For the graphical user interface,
built on top of the Jupyter notebook environment, run "exa" on the command line.
'''
import argparse
import subprocess
from exa._config import set_update, config
def notebook():
'''
Start the exa notebook gui (a Jupyter notebook environment).
'''
subprocess.Popen(['jupyter notebook'], shell=True, cwd=config['paths']['notebooks'])
def workflow(wkflw):
'''
Args:
wkflw: Path to workflow script or instance of workflow class.
'''
raise NotImplementedError('Workflows are currently unsupported.')
def main():
'''
Main entry point for the application.
'''
parser = argparse.ArgumentParser(description=None)
parser.add_argument(
'-u',
'--update',
action='store_true',
help='Update static data and extensions (updates will occur on next import).'
)
parser.add_argument(
'-w',
'--workflow',
type=str,
help='Workflow not implemented',
required=False,
default=None
)
args = parser.parse_args()
if args.update == True:
set_update()
elif args.workflow is None:
notebook()
else:
workflow(args.workflow)
if __name__ == '__main__':
main()
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
'''
Executables
########################
Exa provides two executables; "exa" and "exw". For the graphical user interface,
built on top of the Jupyter notebook environment, run "exa" on the command line.
'''
import argparse
import subprocess
from exa._config import set_update
def notebook():
'''
Start the exa notebook gui (a Jupyter notebook environment).
'''
subprocess.Popen(['jupyter notebook'], shell=True, cwd=config['paths']['notebooks'])
def workflow(wkflw):
'''
Args:
wkflw: Path to workflow script or instance of workflow class.
'''
raise NotImplementedError('Workflows are currently unsupported.')
def main():
'''
Main entry point for the application.
'''
parser = argparse.ArgumentParser(description=None)
parser.add_argument(
'-u',
'--update',
action='store_true',
help='Update static data and extensions (updates will occur on next import).'
)
parser.add_argument(
'-w',
'--workflow',
type=str,
help='Workflow not implemented',
required=False,
default=None
)
args = parser.parse_args()
if args.update == True:
set_update()
elif args.workflow is None:
notebook()
else:
workflow(args.workflow)
if __name__ == '__main__':
main()
|
Add timer and remove confirm buttonk, overall cleanup for better ux | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data },
beforeSend: customBlockUi(this)
}).done(function(response) {
swal({
title: "Great!",
text: "You have set up a tutoring availability!",
confirmButtonColor: "#FFFFFF",
showConfirmButton: false,
allowOutsideClick: true,
timer: 1500,
type: "success"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function(response) {
swal({
title: "Oops...",
text: response.responseJSON.errors,
confirmButtonColor: "#EF5350",
type: "error"
});
});
})
})
var createDate = function() {
var date = $('.timepicker').val();
var time = $('.datepicker').val();
var dateTime = date + " " + time;
return (new Date(dateTime));
}
// Timeslot New Button
var makeNewTimeslotbutton = function(){
$('#modal_new_timeslot').modal({ show: true });
} | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data },
beforeSend: customBlockUi(this)
}).done(function(response) {
swal({
title: "Great!",
text: "You have set up a tutoring availability!",
confirmButtonColor: "#66BB6A",
type: "success"
});
$('#tutor-cal').fullCalendar('refetchEvents');
}).fail(function(response) {
swal({
title: "Oops...",
text: response.responseJSON.errors,
confirmButtonColor: "#EF5350",
type: "error"
});
});
})
})
var createDate = function() {
var date = $('.timepicker').val();
var time = $('.datepicker').val();
var dateTime = date + " " + time;
return (new Date(dateTime));
}
// Timeslot New Button
var makeNewTimeslotbutton = function(){
$('#modal_new_timeslot').modal({ show: true });
} |
Fix translations for non present gas load and heat load
Fixes: #1538 | var D3CarrierLoadChart = (function () {
'use strict';
D3CarrierLoadChart.prototype = $.extend({}, D3LoadChart.prototype, {
emptyMessage: function () {
return $(this.chartClass).parent().find(".empty");
},
chartDataCallback: function (chartData) {
if (chartData) {
$(this.chartClass).removeClass("hidden");
this.emptyMessage().addClass("hidden");
} else {
this.displayEmptyMessage(this.lastRequestedData.name);
}
},
displayEmptyMessage: function (name) {
var carrier,
empty = this.emptyMessage(),
context = empty.find("span.context");
if (this.settings.view_as === 'total') {
context.text("");
} else {
carrier = this.settings.view_carrier.replace(/_[a-z]+$/, '');
context.text(I18n.t("carriers." + carrier).toLowerCase());
}
empty.find("span.node").text(name);
$(this.chartClass).addClass("hidden");
empty.removeClass("hidden");
}
});
function D3CarrierLoadChart(chartClass, curveType, settings) {
D3LoadChart.call(this, chartClass, curveType, settings);
};
return D3CarrierLoadChart;
}());
| var D3CarrierLoadChart = (function () {
'use strict';
D3CarrierLoadChart.prototype = $.extend({}, D3LoadChart.prototype, {
emptyMessage: function () {
return $(this.chartClass).parent().find(".empty");
},
chartDataCallback: function (chartData) {
if (chartData) {
$(this.chartClass).removeClass("hidden");
this.emptyMessage().addClass("hidden");
} else {
this.displayEmptyMessage(this.lastRequestedData.name);
}
},
displayEmptyMessage: function (name) {
var empty = this.emptyMessage(),
context = empty.find("span.context");
if (this.settings.view_as === 'total') {
context.text("");
} else {
context.text(
I18n.t(
"carriers." + this.settings.view_carrier
).toLowerCase()
);
}
empty.find("span.node").text(name);
$(this.chartClass).addClass("hidden");
empty.removeClass("hidden");
}
});
function D3CarrierLoadChart(chartClass, curveType, settings) {
D3LoadChart.call(this, chartClass, curveType, settings);
};
return D3CarrierLoadChart;
}());
|
Fix file name for Linux / case-sensitive file systems
On Linux, when running trying to run the editor, globalRootRegistry.js could not be found:
Error /home/dali/src/dreem2-dev/lib/dr/globals/globalRootRegistry.js In teemserver.js request handling. File not found, returning 404 | /** Allows a node to act as a "root" for a node hierarchy.
Events:
onready:boolean Fired when the root node has been
completely instantiated.
Attributes:
ready:boolean Indicates that this root node is now ready for use. This
starts as undefined and gets set to true when dr.notifyReady is
called.
*/
define(function(require, exports, module) {
var dr = require('$LIB/dr/dr.js'),
JS = require('$LIB/jsclass.js'),
globalRootRegistry = require('$LIB/dr/globals/GlobalRootRegistry.js');
require('$LIB/dr/view/View.js');
module.exports = dr.RootNode = new JS.Module('RootNode', {
// Life Cycle //////////////////////////////////////////////////////////////
initNode: function(parent, attrs) {
this.callSuper(parent, attrs);
globalRootRegistry.addRoot(this);
},
/** @overrides dr.View */
destroyAfterOrphaning: function() {
globalRootRegistry.removeRoot(this);
this.callSuper();
},
// Accessors ///////////////////////////////////////////////////////////////
set_ready: function(v) {
if (this.setActual('ready', v, 'boolean', false)) {
// Notify all descendants in a depth first manner since
// initialization is now done.
if (this.ready) this.walk(null, function(node) {node.notifyReady();});
}
},
set_classroot: function(v) {
this.setSimpleActual('classroot', this);
}
});
});
| /** Allows a node to act as a "root" for a node hierarchy.
Events:
onready:boolean Fired when the root node has been
completely instantiated.
Attributes:
ready:boolean Indicates that this root node is now ready for use. This
starts as undefined and gets set to true when dr.notifyReady is
called.
*/
define(function(require, exports, module) {
var dr = require('$LIB/dr/dr.js'),
JS = require('$LIB/jsclass.js'),
globalRootRegistry = require('$LIB/dr/globals/globalRootRegistry.js');
require('$LIB/dr/view/View.js');
module.exports = dr.RootNode = new JS.Module('RootNode', {
// Life Cycle //////////////////////////////////////////////////////////////
initNode: function(parent, attrs) {
this.callSuper(parent, attrs);
globalRootRegistry.addRoot(this);
},
/** @overrides dr.View */
destroyAfterOrphaning: function() {
globalRootRegistry.removeRoot(this);
this.callSuper();
},
// Accessors ///////////////////////////////////////////////////////////////
set_ready: function(v) {
if (this.setActual('ready', v, 'boolean', false)) {
// Notify all descendants in a depth first manner since
// initialization is now done.
if (this.ready) this.walk(null, function(node) {node.notifyReady();});
}
},
set_classroot: function(v) {
this.setSimpleActual('classroot', this);
}
});
});
|
Make the tractor beam louder | package uk.co.alynn.games.ld30;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
public class AudioEngine {
private final Map<String, Sound> m_fx = new HashMap<String, Sound>();
private static AudioEngine s_sharedEngine = null;
public AudioEngine() {
loadEffect("shoot", "kick.wav");
loadEffect("hit", "snare.wav");
loadEffect("invader-warn", "meepmerp.wav");
loadEffect("tractor", "tractor.wav");
loadEffect("invader-shoot", "dink.wav");
loadEffect("invader-hit-planet", "dop.wav");
loadEffect("game-over", "tish.wav");
}
private void loadEffect(String name, String file) {
Sound effect = Gdx.audio.newSound(Gdx.files.internal("sfx/" + file));
m_fx.put(name, effect);
}
public void play(String effect) {
Sound fx = m_fx.get(effect);
if (effect.equals("tractor")) {
fx.play(0.6f);
} else {
fx.play();
}
}
public void stopAll(String effect) {
Sound fx = m_fx.get(effect);
fx.stop();
}
public static AudioEngine get() {
if (s_sharedEngine == null) {
s_sharedEngine = new AudioEngine();
}
return s_sharedEngine;
}
}
| package uk.co.alynn.games.ld30;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
public class AudioEngine {
private final Map<String, Sound> m_fx = new HashMap<String, Sound>();
private static AudioEngine s_sharedEngine = null;
public AudioEngine() {
loadEffect("shoot", "kick.wav");
loadEffect("hit", "snare.wav");
loadEffect("invader-warn", "meepmerp.wav");
loadEffect("tractor", "tractor.wav");
loadEffect("invader-shoot", "dink.wav");
loadEffect("invader-hit-planet", "dop.wav");
loadEffect("game-over", "tish.wav");
}
private void loadEffect(String name, String file) {
Sound effect = Gdx.audio.newSound(Gdx.files.internal("sfx/" + file));
m_fx.put(name, effect);
}
public void play(String effect) {
Sound fx = m_fx.get(effect);
if (effect.equals("tractor")) {
fx.play(0.1f);
} else {
fx.play();
}
}
public void stopAll(String effect) {
Sound fx = m_fx.get(effect);
fx.stop();
}
public static AudioEngine get() {
if (s_sharedEngine == null) {
s_sharedEngine = new AudioEngine();
}
return s_sharedEngine;
}
}
|
Stop validation error notification stack
closes #3383
- Calls closePassive() if a new validation error is thrown to display
only the latest validation error | /* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
actions: {
submit: function () {
var self = this,
data = self.getProperties('email');
this.toggleProperty('submitting');
this.validate({ format: false }).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'POST',
data: {
passwordreset: [{
email: data.email
}]
}
}).then(function (resp) {
self.toggleProperty('submitting');
self.notifications.showSuccess('Please check your email for instructions.');
self.transitionToRoute('signin');
}).catch(function (resp) {
self.toggleProperty('submitting');
self.notifications.closePassive();
self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.');
});
}).catch(function (errors) {
self.toggleProperty('submitting');
self.notifications.closePassive();
self.notifications.showErrors(errors);
});
}
}
});
export default ForgottenController;
| /* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';
var ForgottenController = Ember.Controller.extend(ValidationEngine, {
email: '',
submitting: false,
// ValidationEngine settings
validationType: 'forgotten',
actions: {
submit: function () {
var self = this,
data = self.getProperties('email');
this.toggleProperty('submitting');
this.validate({ format: false }).then(function () {
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'POST',
data: {
passwordreset: [{
email: data.email
}]
}
}).then(function (resp) {
self.toggleProperty('submitting');
self.notifications.showSuccess('Please check your email for instructions.');
self.transitionToRoute('signin');
}).catch(function (resp) {
self.toggleProperty('submitting');
self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.');
});
}).catch(function (errors) {
self.toggleProperty('submitting');
self.notifications.showErrors(errors);
});
}
}
});
export default ForgottenController;
|
Make progress bar visible by default. | from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
self.value = value
def startup(self):
self._impl = NSProgressIndicator.new()
self._impl.setStyle_(NSProgressIndicatorBarStyle)
self._impl.setDisplayedWhenStopped_(True)
if self.max:
self._impl.setIndeterminate_(False)
self._impl.setMaxValue_(self.max)
else:
self._impl.setIndeterminate_(True)
# Disable all autolayout functionality
self._impl.setTranslatesAutoresizingMaskIntoConstraints_(False)
self._impl.setAutoresizesSubviews_(False)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
self._running = self._value is not None
if value is not None:
self._impl.setDoubleValue_(value)
def start(self):
if self._impl and not self._running:
self._impl.startAnimation_(self._impl)
self._running = True
def stop(self):
if self._impl and self._running:
self._impl.stopAnimation_(self._impl)
self._running = False
| from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
self.value = value
def startup(self):
self._impl = NSProgressIndicator.new()
self._impl.setStyle_(NSProgressIndicatorBarStyle)
self._impl.setDisplayedWhenStopped_(False)
if self.max:
self._impl.setIndeterminate_(False)
self._impl.setMaxValue_(self.max)
else:
self._impl.setIndeterminate_(True)
# Disable all autolayout functionality
self._impl.setTranslatesAutoresizingMaskIntoConstraints_(False)
self._impl.setAutoresizesSubviews_(False)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
self._running = self._value is not None
if value is not None:
self._impl.setDoubleValue_(value)
def start(self):
if self._impl and not self._running:
self._impl.startAnimation_(self._impl)
self._running = True
def stop(self):
if self._impl and self._running:
self._impl.stopAnimation_(self._impl)
self._running = False
|
Fix qs error in history | import logging
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from pytz import timezone
from dojo.filters import LogEntryFilter
from dojo.utils import get_page_items, add_breadcrumb
localtz = timezone(settings.TIME_ZONE)
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] %(message)s',
datefmt='%d/%b/%Y %H:%M:%S',
filename=settings.DOJO_ROOT + '/../django_app.log',
)
logger = logging.getLogger(__name__)
def action_history(request, cid, oid):
from django.contrib.contenttypes.models import ContentType
from auditlog.models import LogEntry
try:
ct = ContentType.objects.get_for_id(cid)
obj = ct.get_object_for_this_type(pk=oid)
except KeyError:
raise Http404()
history = LogEntry.objects.filter(content_type=ct, object_pk=obj.id).order_by('-timestamp')
history = LogEntryFilter(request.GET, queryset=history)
paged_history = get_page_items(request, history.qs, 25)
add_breadcrumb(parent=obj, title="Action History", top_level=False, request=request)
return render(request, 'dojo/action_history.html',
{"history": paged_history,
"filtered": history,
"obj": obj,
})
| import logging
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from pytz import timezone
from dojo.filters import LogEntryFilter
from dojo.utils import get_page_items, add_breadcrumb
localtz = timezone(settings.TIME_ZONE)
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] %(message)s',
datefmt='%d/%b/%Y %H:%M:%S',
filename=settings.DOJO_ROOT + '/../django_app.log',
)
logger = logging.getLogger(__name__)
def action_history(request, cid, oid):
from django.contrib.contenttypes.models import ContentType
from auditlog.models import LogEntry
try:
ct = ContentType.objects.get_for_id(cid)
obj = ct.get_object_for_this_type(pk=oid)
except KeyError:
raise Http404()
history = LogEntry.objects.filter(content_type=ct, object_pk=obj.id).order_by('-timestamp')
history = LogEntryFilter(request.GET, queryset=history)
paged_history = get_page_items(request, history, 25)
add_breadcrumb(parent=obj, title="Action History", top_level=False, request=request)
return render(request, 'dojo/action_history.html',
{"history": paged_history,
"filtered": history,
"obj": obj,
})
|
Add error logging to nagios wrapper | import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
| import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(pluginCommandLineList, stdout=subprocess.PIPE)
out, err = p.communicate()
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
Fix : fix unit test | 'use strict';
describe('Navbar directive', function() {
var scope, element;
beforeEach(module('talend.widget'));
beforeEach(module('htmlTemplates'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<talend-navbar>' +
' <a href="javascript:void(0)" class="navigation-menu-button">MENU</a>' +
' <nav role="navigation">' +
' <ul class="navigation-menu show">' +
' <li class="nav-link"><a href="javascript:void(0)" class="icon t-top-bar_notification"></a></li>' +
' <li class="nav-link more"><a href="javascript:void(0)" class="icon t-top-bar_profile nomore"></a>' +
' <ul class="submenu">' +
' <li><a href="javascript:void(0)">Logout</a></li>' +
' <li class="divider"></li>' +
' <li><a href="javascript:void(0)">Edit profil</a></li>' +
' </ul>' +
' </li>' +
' </ul>' +
' </nav>' +
'</talend-navbar>');
$compile(element)(scope);
scope.$digest();
}));
it('should remove navigation-menu "show" class', function() {
//then
expect(element.find('.navigation-menu').hasClass('show')).toBe(false);
});
}); | 'use strict';
describe('Navbar directive', function() {
var scope, element;
beforeEach(module('talend.widget'));
beforeEach(module('htmlTemplates'));
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<talend-navbar>' +
' <a href="javascript:void(0)" class="navigation-menu-button">MENU</a>' +
' <nav role="navigation">' +
' <ul class="navigation-menu show">' +
' <li class="nav-link"><a href="javascript:void(0)" class="icon t-top-bar_notification"></a></li>' +
' <li class="nav-link more"><a href="javascript:void(0)" class="icon t-top-bar_profile nomore"></a>' +
' <ul class="submenu">' +
' <li><a href="javascript:void(0)">Logout</a></li>' +
' <li class="divider"></li>' +
' <li><a href="javascript:void(0)">Edit profil</a></li>' +
' </ul>' +
' </li>' +
' </ul>' +
' </nav>' +
'</talend-navbar>');
$compile(element)(scope);
scope.$digest();
}));
it('should remove navigation-menu \'show\' class', function() {
//then
expect(element.find('.navigation-menu').hasClass()).toBe(false);
});
}); |
:bug: Fix error when files are not found
Using include syntax with a wrong path resulted in a crash without emitting an error message. | var aglio = require('aglio');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function (options) {
'use strict';
// Mixes in default options.
options = defaults(options || {}, {
compress: false,
paths: []
});
function transform(file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file); // pass along
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-aglio', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
// Clones the options object.
var opts = defaults({
theme: 'default'
}, options);
// Injects the path of the current file.
opts.filename = file.path;
// Inject includePath for relative includes
opts.includePath = opts.includePath || path.dirname(opts.filename);
try {
aglio.render(str, opts, function (err, html) {
if (err) {
self.emit('error', new PluginError('gulp-aglio', err));
} else {
file.contents = new Buffer(html);
file.path = gutil.replaceExtension(file.path, '.html');
self.push(file);
}
next();
});
} catch(err) {
self.emit("error", new PluginError("gulp-aglio", err));
}
}
return through2.obj(transform);
};
| var aglio = require('aglio');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
var defaults = require('lodash.defaults');
var path = require('path');
module.exports = function (options) {
'use strict';
// Mixes in default options.
options = defaults(options || {}, {
compress: false,
paths: []
});
function transform(file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file); // pass along
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-aglio', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
// Clones the options object.
var opts = defaults({
theme: 'default'
}, options);
// Injects the path of the current file.
opts.filename = file.path;
// Inject includePath for relative includes
opts.includePath = opts.includePath || path.dirname(opts.filename);
aglio.render(str, opts, function (err, html) {
if (err) {
self.emit('error', new PluginError('gulp-aglio', err));
} else {
file.contents = new Buffer(html);
file.path = gutil.replaceExtension(file.path, '.html');
self.push(file);
}
next();
});
}
return through2.obj(transform);
};
|
Format description to multiple lines using RawTextHelpFormatter.
Reference:
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text | #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
# http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text
import argparse
from argparse import RawTextHelpFormatter
def main():
'''
Read arguments from command line or from a file.
'''
parser = argparse.ArgumentParser(description=''' For help, use argument -h
$ ./arg-reader.py -h
To specify an argument, prefix with -
$ ./arg-reader.py -animalbig hippo -animalsmall fly
To read arguments from a file, prefix file name with @
$ ./arg-reader.py @args2.txt
To specify arguments from command line and from a file
$ ./arg-reader.py @args.txt -animalbig hippo''',
fromfile_prefix_chars='@',
formatter_class=RawTextHelpFormatter,
)
parser.add_argument('-animalbig', action="store", dest="animalbig",
help = 'name of a big animal')
parser.add_argument('-animalsmall', action="store", dest="animalsmall",
help = 'name of a small animal')
arguments = parser.parse_args()
print(arguments)
print(arguments.animalbig)
print(arguments.animalsmall)
if __name__ == "__main__": main()
| #!/usr/bin/env python3
# References:
# http://docs.python.org/3.3/library/argparse.html?highlight=argparse#argparse
# http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html
import argparse
def main():
'''
For help, use argument -h
$ ./arg-reader.py -h
To specify an argument, prefix with -
$ ./arg-reader.py -animalbig hippo -animalsmall fly
To read arguments from a file, prefix file name with @
$ ./arg-reader.py @args2.txt
To specify arguments from command line and from a file
$ ./arg-reader.py @args.txt -animalbig hippo
'''
parser = argparse.ArgumentParser(description='To read arguments from a file, prefix file name with @ e.g. $ ./arg-reader.py @args.txt -animalbig hippo',
fromfile_prefix_chars='@',
)
parser.add_argument('-animalbig', action="store", dest="animalbig",
help = 'name of a big animal')
parser.add_argument('-animalsmall', action="store", dest="animalsmall",
help = 'name of a small animal')
arguments = parser.parse_args()
print(arguments)
print(arguments.animalbig)
print(arguments.animalsmall)
if __name__ == "__main__": main()
|
Make the shouldSkipProperty code more readable | <?php
/*
* Copyright 2011 Johannes M. Schmitt <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\SerializerBundle\Serializer\Exclusion;
use JMS\SerializerBundle\Metadata\ClassMetadata;
use JMS\SerializerBundle\Metadata\PropertyMetadata;
class GroupsExclusionStrategy implements ExclusionStrategyInterface
{
private $groups = array();
public function __construct(array $groups)
{
foreach ($groups as $group) {
$this->groups[$group] = true;
}
}
public function shouldSkipClass(ClassMetadata $metadata)
{
return false;
}
/**
* {@inheritDoc}
*/
public function shouldSkipProperty(PropertyMetadata $property)
{
if (!$property->groups) {
return true;
}
foreach ($property->groups as $group) {
if (isset($this->groups[$group])) {
return false;
}
}
return true;
}
} | <?php
/*
* Copyright 2011 Johannes M. Schmitt <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace JMS\SerializerBundle\Serializer\Exclusion;
use JMS\SerializerBundle\Metadata\ClassMetadata;
use JMS\SerializerBundle\Metadata\PropertyMetadata;
class GroupsExclusionStrategy implements ExclusionStrategyInterface
{
private $groups = array();
public function __construct(array $groups)
{
foreach ($groups as $group) {
$this->groups[$group] = true;
}
}
public function shouldSkipClass(ClassMetadata $metadata)
{
return false;
}
/**
* {@inheritDoc}
*/
public function shouldSkipProperty(PropertyMetadata $property)
{
if ($this->groups && $property->groups) {
foreach ($property->groups as $group) {
if (isset($this->groups[$group])) {
return false;
}
}
}
return true;
}
} |
Remove phone-number and email from facilities | <div class="container">
<h2 class="headline">Liste der Hilfsgruppen in Berlin</h2>
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Homepage</th>
<th class="text-center">Adresse</th>
<th class="text-center">Öffnungszeiten</th>
<th class="text-center">Bedarfsliste</th>
</tr>
</thead>
<tbody>
<?php foreach($facilities as $facility): ?>
<tr>
<td><?= $facility->organisation; ?></td>
<td>
<?php if($facility->homepage): ?>
<a target="_blank" href="<?= $facility->homepage; ?>">Link</a>
<?php endif; ?>
</td>
<td>
<?= $facility->address; ?><br />
<?= $facility->zip; ?> <?= $facility->city; ?>
</td>
<td><?= opening_hours($facility->opening_hours); ?></td>
<td><a href="<?= base_url('/stocklist/public_pdf/' . $facility->facility_id) ?>">Download</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
| <h2 class="headline">Liste der Hilfsgruppen in Berlin</h2>
<div class="table-responsive">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Homepage</th>
<th class="text-center">Email</th>
<th class="text-center">Telefon</th>
<th class="text-center">Adresse</th>
<th class="text-center">Öffnungszeiten</th>
<th class="text-center">Bedarfsliste</th>
</tr>
</thead>
<tbody>
<?php foreach($facilities as $facility): ?>
<tr>
<td><?= $facility->organisation; ?></td>
<td>
<?php if($facility->homepage): ?>
<a target="_blank" href="<?= $facility->homepage; ?>">Link</a>
<?php endif; ?>
</td>
<td>
<?php if($facility->email): ?>
<a href="mailto:<?= $facility->email; ?>">Email</a>
<?php endif; ?>
</td>
<td><?= $facility->phone; ?></td>
<td>
<?= $facility->address; ?><br />
<?= $facility->zip; ?> <?= $facility->city; ?>
</td>
<td><?= opening_hours($facility->opening_hours); ?></td>
<td><a href="<?= base_url('/stocklist/public_pdf/' . $facility->facility_id) ?>">Download</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
|
Save modal dialog now correctly imports html template
Error as a result of shufling file structure, not updating paths | import templateUrl from './save-modal-dialog.html';
/** @ngInject */
export function SaveModalDialogFactory($uibModal) {
var modalSaveDialog = {
showModal: showModal,
};
return modalSaveDialog;
function showModal(saveCallback, doNotSaveCallback, cancelCallback, okToSave) {
var modalOptions = {
templateUrl,
controller: SaveModalDialogController,
controllerAs: 'vm',
resolve: {
saveCallback: resolveSave,
doNotSaveCallback: resolveDoNotSave,
cancelCallback: resolveCancel,
okToSave: resolveOkToSave,
},
};
function resolveSave() {
return saveCallback;
}
function resolveDoNotSave() {
return doNotSaveCallback;
}
function resolveCancel() {
return cancelCallback;
}
function resolveOkToSave() {
return okToSave;
}
var modal = $uibModal.open(modalOptions);
return modal.result;
}
}
/** @ngInject */
function SaveModalDialogController(saveCallback, doNotSaveCallback, cancelCallback, okToSave, $uibModalInstance) {
var vm = this;
vm.save = save;
vm.doNotSave = doNotSave;
vm.cancel = cancel;
vm.okToSave = okToSave;
function save() {
saveCallback();
$uibModalInstance.close();
}
function doNotSave() {
doNotSaveCallback();
$uibModalInstance.close();
}
function cancel() {
cancelCallback();
$uibModalInstance.close();
}
}
| /** @ngInject */
export function SaveModalDialogFactory($uibModal) {
var modalSaveDialog = {
showModal: showModal,
};
return modalSaveDialog;
function showModal(saveCallback, doNotSaveCallback, cancelCallback, okToSave) {
var modalOptions = {
templateUrl: 'app/components/save-modal-dialog/save-modal-dialog.html',
controller: SaveModalDialogController,
controllerAs: 'vm',
resolve: {
saveCallback: resolveSave,
doNotSaveCallback: resolveDoNotSave,
cancelCallback: resolveCancel,
okToSave: resolveOkToSave,
},
};
function resolveSave() {
return saveCallback;
}
function resolveDoNotSave() {
return doNotSaveCallback;
}
function resolveCancel() {
return cancelCallback;
}
function resolveOkToSave() {
return okToSave;
}
var modal = $uibModal.open(modalOptions);
return modal.result;
}
}
/** @ngInject */
function SaveModalDialogController(saveCallback, doNotSaveCallback, cancelCallback, okToSave, $uibModalInstance) {
var vm = this;
vm.save = save;
vm.doNotSave = doNotSave;
vm.cancel = cancel;
vm.okToSave = okToSave;
function save() {
saveCallback();
$uibModalInstance.close();
}
function doNotSave() {
doNotSaveCallback();
$uibModalInstance.close();
}
function cancel() {
cancelCallback();
$uibModalInstance.close();
}
}
|
Add --inline autorefreshing to webpack dev server | const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
home: path.join(__dirname, 'app/src/home'),
},
module: {
loaders: [
{
test: /\.sass$/,
loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: 'node_modules',
query: { presets: ['es2015'] },
},
{
test: /\.(ttf|woff|woff2)$/,
loader: 'file',
query: { name: 'fonts/[name].[ext]' },
},
{
test: /\.png$/,
loader: 'file',
},
{
test: /\.html$/,
loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader',
},
],
},
output: {
path: path.join(__dirname, 'app/build'),
publicPath: '/',
filename: '[name].js',
},
plugins: [
new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }),
],
// --------------------------------------------------------------------------
devServer: {
contentBase: path.join(__dirname, 'app/build'),
inline: true,
},
};
| const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: {
home: path.join(__dirname, 'app/src/home'),
},
module: {
loaders: [
{
test: /\.sass$/,
loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: 'node_modules',
query: { presets: ['es2015'] },
},
{
test: /\.(ttf|woff|woff2)$/,
loader: 'file',
query: { name: 'fonts/[name].[ext]' },
},
{
test: /\.png$/,
loader: 'file',
},
{
test: /\.html$/,
loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader',
},
],
},
output: {
path: path.join(__dirname, 'app/build'),
publicPath: '/',
filename: '[name].js',
},
plugins: [
new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: { warnings: false } }),
],
// --------------------------------------------------------------------------
devServer: {
contentBase: path.join(__dirname, 'app/build'),
},
};
|
Switch yaml CLI argument from file to file path. | """
ydf/cli
~~~~~~~
Defines the command-line interface.
"""
import click
import sys
from ydf import templating, yaml_ext
@click.command('ydf')
@click.argument('yaml',
type=click.Path(dir_okay=False))
@click.option('-v', '--variables',
type=click.Path(dir_okay=False),
help='YAML file containing variables to be exposed to YAML file and template during rendering')
@click.option('-t', '--template',
type=str,
default=templating.DEFAULT_TEMPLATE_NAME,
help='Name of Jinja2 template used to build Dockerfile')
@click.option('-s', '--search-path',
type=click.Path(file_okay=False),
default=templating.DEFAULT_TEMPLATE_PATH,
help='File system paths to search for templates')
@click.option('-o', '--output',
type=click.File('w'),
help='Dockerfile generated from translation',
default=sys.stdout)
def main(yaml, variables, template, search_path, output):
"""
YAML to Dockerfile
"""
yaml = yaml_ext.load(yaml.read())
env = templating.environ(search_path)
rendered = env.get_template(template).render(templating.render_vars(yaml))
output.write(rendered)
if __name__ == '__main__':
main()
| """
ydf/cli
~~~~~~~
Defines the command-line interface.
"""
import click
import sys
from ydf import templating, yaml_ext
@click.command('ydf')
@click.argument('yaml',
type=click.File('r'))
@click.option('-v', '--variables',
type=click.Path(dir_okay=False),
help='YAML file containing variables to be exposed to YAML file and template during rendering')
@click.option('-t', '--template',
type=str,
default=templating.DEFAULT_TEMPLATE_NAME,
help='Name of Jinja2 template used to build Dockerfile')
@click.option('-s', '--search-path',
type=click.Path(file_okay=False),
default=templating.DEFAULT_TEMPLATE_PATH,
help='File system paths to search for templates')
@click.option('-o', '--output',
type=click.File('w'),
help='Dockerfile generated from translation',
default=sys.stdout)
def main(yaml, variables, template, search_path, output):
"""
YAML to Dockerfile
"""
yaml = yaml_ext.load(yaml.read())
env = templating.environ(search_path)
rendered = env.get_template(template).render(templating.render_vars(yaml))
output.write(rendered)
if __name__ == '__main__':
main()
|
Make mobile streaming dialog easier to understand | package de.danoeh.antennapod.dialog;
import android.content.Context;
import androidx.appcompat.app.AlertDialog;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.playback.Playable;
import de.danoeh.antennapod.core.util.playback.PlaybackServiceStarter;
public class StreamingConfirmationDialog {
private final Context context;
private final Playable playable;
public StreamingConfirmationDialog(Context context, Playable playable) {
this.context = context;
this.playable = playable;
}
public void show() {
new AlertDialog.Builder(context)
.setTitle(R.string.stream_label)
.setMessage(R.string.confirm_mobile_streaming_notification_message)
.setPositiveButton(R.string.stream_label, (dialog, which) -> stream())
.setNegativeButton(R.string.confirm_mobile_streaming_button_always, (dialog, which) -> {
UserPreferences.setAllowMobileStreaming(true);
stream();
})
.setNeutralButton(R.string.cancel_label, null)
.show();
}
private void stream() {
new PlaybackServiceStarter(context, playable)
.callEvenIfRunning(true)
.startWhenPrepared(true)
.shouldStream(true)
.shouldStreamThisTime(true)
.start();
}
}
| package de.danoeh.antennapod.dialog;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import androidx.appcompat.app.AlertDialog;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;
import de.danoeh.antennapod.core.util.playback.Playable;
import de.danoeh.antennapod.core.util.playback.PlaybackServiceStarter;
public class StreamingConfirmationDialog {
private final Context context;
private final Playable playable;
public StreamingConfirmationDialog(Context context, Playable playable) {
this.context = context;
this.playable = playable;
}
public void show() {
View view = View.inflate(context, R.layout.checkbox_do_not_show_again, null);
CheckBox checkDoNotShowAgain = view.findViewById(R.id.checkbox_do_not_show_again);
new AlertDialog.Builder(context)
.setTitle(R.string.stream_label)
.setMessage(R.string.confirm_mobile_streaming_notification_message)
.setView(view)
.setPositiveButton(R.string.stream_label, (dialog, which) -> {
if (checkDoNotShowAgain.isChecked()) {
UserPreferences.setAllowMobileStreaming(true);
}
new PlaybackServiceStarter(context, playable)
.callEvenIfRunning(true)
.startWhenPrepared(true)
.shouldStream(true)
.shouldStreamThisTime(true)
.start();
})
.setNegativeButton(R.string.cancel_label, null)
.show();
}
}
|
Use eq function to ge element by index. | import cheerio from 'cheerio';
import moment from 'moment-timezone';
const originalTimeZone = 'Europe/Kiev';
const skiLiftDateFormat = 'DD.MM.YYYY HH:mm:ss';
export default function proceed(data) {
if (data.error) {
return {
errors: Object.values(data.error),
lifts: []
};
}
const cardNumber = data.success;
const $ = cheerio.load(data.html);
const dataTables = $('table');
const orginalPurchaseDate = dataTables.eq(0).find('#order_info_header_white:nth-child(1) > span').text();
return {
cardNumber: cardNumber,
purchaseDate: getAdoptedDateString(orginalPurchaseDate),
lifts: getLifts(dataTables.eq(1))
};
function getLifts($tableNode) {
return $tableNode
.find('tr')
// skip first row,
// because it is table header
.slice(1)
.map((index, element) => {
var columns = $(element).find('td');
return {
skiLiftId: columns.eq(0).text(),
date: getAdoptedDateString(columns.eq(1).text()),
initialLift: Number.parseInt(columns.eq(2).text()),
liftsLeft: Number.parseInt(columns.eq(3).text())
}
})
.toArray();
}
function getAdoptedDateString(date) {
return moment.tz(date, skiLiftDateFormat, originalTimeZone).local().format('L LTS');
}
} | import cheerio from 'cheerio';
import moment from 'moment-timezone';
const originalTimeZone = 'Europe/Kiev';
const skiLiftDateFormat = 'DD.MM.YYYY HH:mm:ss';
export default function proceed(data) {
if (data.error) {
return {
errors: Object.values(data.error),
lifts: []
};
}
const cardNumber = data.success;
const $ = cheerio.load(data.html);
const dataTables = $('table');
const orginalPurchaseDate = dataTables.eq(0).find('#order_info_header_white:nth-child(1) > span').text();
return {
cardNumber: cardNumber,
purchaseDate: getAdoptedDateString(orginalPurchaseDate),
lifts: getLifts(dataTables.eq(1))
};
function getLifts($tableNode) {
return $tableNode
.find('tr')
// skip first row,
// because it is table header
.slice(1)
.map((index, element) => {
var columns = $(element).find('td');
return {
skiLiftId: $(columns[0]).text(),
date: getAdoptedDateString($(columns[1]).text()),
initialLift: Number.parseInt($(columns[2]).text()),
liftsLeft: Number.parseInt($(columns[3]).text())
}
})
.toArray();
}
function getAdoptedDateString(date) {
return moment.tz(date, skiLiftDateFormat, originalTimeZone).local().format('L LTS');
}
} |
Create directories for output if they don't already exist
Especially the downloader should do this to allow for easier
scripting. | package com.holmsted.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.annotation.Nonnull;
public class FileWriter {
public static void writeFile(String filename, String contents) {
File dataFile = new File(filename);
mkdirsForFile(dataFile);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(dataFile);
Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(contents);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeFile(String filename, InputStream inputStream) {
File dataFile = new File(filename);
mkdirsForFile(dataFile);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(dataFile);
byte[] buffer = new byte[4096];
int readBytes;
while ((readBytes = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void mkdirsForFile(@Nonnull File file) {
File path = new File(file.getParent());
if (!path.exists() && !path.mkdirs()) {
throw new IllegalArgumentException(
"Path did not exist and could not be created: '" + path.getAbsolutePath() + "'");
}
}
}
| package com.holmsted.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class FileWriter {
public static void writeFile(String filename, String contents) {
File dataFile = new File(filename);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(dataFile);
Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(contents);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeFile(String filename, InputStream inputStream) {
File dataFile = new File(filename);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(dataFile);
byte[] buffer = new byte[4096];
int readBytes;
while ((readBytes = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
Copy prototype memebers on extend | 'use strict';
var extendPrototypeWithThese = function (prototype, extendThese) {
/*
Helper method to implement a simple inheritance model for object prototypes.
*/
var outp = prototype;
if (extendThese) {
for (var i = extendThese.length - 1; i >= 0; i--) {
// I need to create the object in order to copy the prototype functions
var tmpObj = extendThese[i].prototype;
for (var key in tmpObj) {
if (key == '_implements') {
// Implements should be extended with later coming before earlier
// TODO: Filer so we remove duplicates from existing list (order makes difference)
outp.prototype._implements = tmpObj._implements.concat(outp.prototype._implements);
} else {
// All others added and lower indexes override higher
outp.prototype[key] = tmpObj[key];
}
}
}
}
return outp;
}
module.exports.extendPrototypeWithThese = extendPrototypeWithThese;
var addMembers = function (outp, params) {
/*
Helper method to add each item in params dictionary to the prototype of outp.
*/
for (var key in params) {
if (params.hasOwnProperty(key)) {
outp.prototype[key] = params[key];
}
}
return outp;
}
module.exports.addMembers = addMembers; | 'use strict';
var extendPrototypeWithThese = function (prototype, extendThese) {
/*
Helper method to implement a simple inheritance model for object prototypes.
*/
var outp = prototype;
if (extendThese) {
for (var i = extendThese.length - 1; i >= 0; i--) {
// I need to create the object in order to copy the prototype functions
var tmpObj = new extendThese[i]();
for (var key in tmpObj) {
if (key == '_implements') {
// Implements should be extended with later coming before earlier
// TODO: Filer so we remove duplicates from existing list (order makes difference)
outp.prototype._implements = tmpObj._implements.concat(outp.prototype._implements);
} else {
// All others added and lower indexes override higher
outp.prototype[key] = tmpObj[key];
}
}
}
}
return outp;
}
module.exports.extendPrototypeWithThese = extendPrototypeWithThese;
var addMembers = function (outp, params) {
/*
Helper method to add each item in params dictionary to the prototype of outp.
*/
for (var key in params) {
if (params.hasOwnProperty(key)) {
outp.prototype[key] = params[key];
}
}
return outp;
}
module.exports.addMembers = addMembers; |
Fix search result image sizes | import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { GEODATA_API_URL } from '@env'
const Thumbnail = ({ recordId, thumbnails, t }) => {
const hasThumbnail = thumbnails && thumbnails.length > 0
const thumbnail = hasThumbnail
? `${GEODATA_API_URL}/records/${recordId}/thumbnails/${thumbnails[0].originalUrlHash}`
: '/static/images/datasets/default-thumbnail.svg'
return (
<div>
<img src={thumbnail} alt='' />
<style jsx>{`
div {
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
overflow: hidden;
height: 180px;
width: 180px;
@media (max-width: 767px) {
width: 100%;
${!hasThumbnail && (`
display: none;
`)}
}
}
img {
display: flex;
max-height: 100%;
@media (max-width: 767px) {
max-width: 100%;
max-height: none;
height: auto;
margin: auto;
}
}
`}</style>
</div>
)
}
Thumbnail.propTypes = {
thumbnails: PropTypes.arrayOf(PropTypes.shape({
originalUrlHash: PropTypes.isRequired
})),
recordId: PropTypes.string.isRequired,
t: PropTypes.func.isRequired
}
export default translate('search')(Thumbnail)
| import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { GEODATA_API_URL } from '@env'
const Thumbnail = ({ recordId, thumbnails, t }) => {
const hasThumbnail = thumbnails && thumbnails.length > 0
const thumbnail = hasThumbnail
? `${GEODATA_API_URL}/records/${recordId}/thumbnails/${thumbnails[0].originalUrlHash}`
: '/static/images/datasets/default-thumbnail.svg'
return (
<div>
<img src={thumbnail} alt='' />
<style jsx>{`
div {
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
overflow: hidden;
height: 180px;
width: 180px;
@media (max-width: 767px) {
width: 100%;
${!hasThumbnail && (`
display: none;
`)}
}
}
img {
display: flex;
height: 100%;
@media (max-width: 767px) {
max-width: 100%;
height: auto;
margin: auto;
}
}
`}</style>
</div>
)
}
Thumbnail.propTypes = {
thumbnails: PropTypes.arrayOf(PropTypes.shape({
originalUrlHash: PropTypes.isRequired
})),
recordId: PropTypes.string.isRequired,
t: PropTypes.func.isRequired
}
export default translate('search')(Thumbnail)
|
Clear the console when script loads | (() => {
let log = console.debug; // Can change to console.log if needed
console.clear();
let init = () => {
// The Socket.io script tag has loaded
window.ioconn = window.io.connect;
window.io.connect = function() { // The moomoo.io game client uses io.connect to establish a socket.io connection
if (!arguments[1] || !arguments[1]["query"]) {
// The client always makes a connection with a query string, and this connection doesn't supply one.
return ioconn.apply(this, arguments);
} else {
// The game client is attempting to connect to the Socket.io server
var s = ioconn.apply(this, arguments);
var socketEmit = s.emit;
// Capture outgoing traffic
s.emit = function() {
var packetType = arguments[0];
var mainData = arguments[1];
// There are also other arguments that are supplied based on the packet being sent...
switch (packetType) {
case "1":
// Spawn packet
log("Player spawn detected. name:", mainData.name);
break;
default:
log("Unknown outgoing packet with args", arguments);
break;
}
return socketEmit.apply(this, arguments); // Call the real emit
}
// Capture incoming traffic
s.on('ch', (sid, msg) => {
// Chat message
log('Player with sid', sid, 'send message:', msg);
});
// TODO: capture more incoming traffic
}
}
}
window.addEventListener('load', init);
})(); | (() => {
let log = console.debug; // Can change to console.log if needed
let init = () => {
// The Socket.io script tag has loaded
window.ioconn = window.io.connect;
window.io.connect = function() { // The moomoo.io game client uses io.connect to establish a socket.io connection
if (!arguments[1] || !arguments[1]["query"]) {
// The client always makes a connection with a query string, and this connection doesn't supply one.
return ioconn.apply(this, arguments);
} else {
// The game client is attempting to connect to the Socket.io server
var s = ioconn.apply(this, arguments);
var socketEmit = s.emit;
// Capture outgoing traffic
s.emit = function() {
var packetType = arguments[0];
var mainData = arguments[1];
// There are also other arguments that are supplied based on the packet being sent...
switch (packetType) {
case "1":
// Spawn packet
log("Player spawn detected. name:", mainData.name);
break;
default:
log("Unknown outgoing packet with args", arguments);
break;
}
return socketEmit.apply(this, arguments); // Call the real emit
}
// Capture incoming traffic
s.on('ch', (sid, msg) => {
// Chat message
log('Player with sid', sid, 'send message:', msg);
});
// TODO: capture more incoming traffic
}
}
}
window.addEventListener('load', init);
})(); |
Add debug.html to build script | var historyApiFallback = require("connect-history-api-fallback");
var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest,
middleware: [historyApiFallback()]
}
},
js: {
src: src + '/js/app.js'
},
templates: {
src: src + '/templates/**/*.html'
},
css: {
src: src + "/js/vendor/highlight.js/styles/docco.css",
dest: dest
},
sass: {
src: src + "/sass/**/*.scss",
dest: dest,
settings: {
outputStyle: "compressed",
indentedSyntax: false, // Disable .sass syntax!
imagePath: 'img' // Used by the image-url helper
}
},
images: {
src: src + "/img/**",
dest: dest + "/img"
},
markup: {
src: src + "/{index.html,debug.html,favicon.ico,/platform/**,/resources/**}",
dest: dest
},
browserify: {
bundleConfigs: [{
entries: src + '/js/app.js',
dest: dest,
outputName: 'worker_ui.js',
extensions: [],
transform: ["ractivate"]
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
}
}; | var historyApiFallback = require("connect-history-api-fallback");
var dest = "./build";
var src = './src';
module.exports = {
browserSync: {
server: {
// Serve up our build folder
baseDir: dest,
middleware: [historyApiFallback()]
}
},
js: {
src: src + '/js/app.js'
},
templates: {
src: src + '/templates/**/*.html'
},
css: {
src: src + "/js/vendor/highlight.js/styles/docco.css",
dest: dest
},
sass: {
src: src + "/sass/**/*.scss",
dest: dest,
settings: {
outputStyle: "compressed",
indentedSyntax: false, // Disable .sass syntax!
imagePath: 'img' // Used by the image-url helper
}
},
images: {
src: src + "/img/**",
dest: dest + "/img"
},
markup: {
src: src + "/{index.html,favicon.ico,/platform/**,/resources/**}",
dest: dest
},
browserify: {
bundleConfigs: [{
entries: src + '/js/app.js',
dest: dest,
outputName: 'worker_ui.js',
extensions: [],
transform: ["ractivate"]
}]
},
production: {
cssSrc: dest + '/*.css',
jsSrc: dest + '/*.js',
dest: dest
}
}; |
Update minimun zoom to 24 hours | /* global console, Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 86400000,
editable: {
add: false,
updateTime: true,
updateGroup: false,
remove: true
},
groupOrder: function (a, b) {
if (a.id === "Demos") {
return -1;
}
if (b.id === "Demos") {
return 1;
}
var groups = [a.id, b.id];
groups.sort();
if (a.id === groups[0]) {
return -1;
} else {
return 1;
}
}
});
$(document).ready(function(){
$('.vis-center>.vis-content').on('scroll', function () {
$('.vis-left>.vis-content').scrollTop($(this).scrollTop());
});
$('.vis-left>.vis-content').on('scroll', function () {
$('.vis-center>.vis-content').scrollTop($(this).scrollTop());
});
});
})(); | /* global console, Calendar, vis */
(function() {
"use strict";
var calendar = new Calendar();
calendar.init(document.getElementById('visualization'),
{
height: "100vh",
orientation: "top",
zoomKey: 'shiftKey',
zoomMax: 315360000000,
zoomMin: 600000,
editable: {
add: false,
updateTime: true,
updateGroup: false,
remove: true
},
groupOrder: function (a, b) {
if (a.id === "Demos") {
return -1;
}
if (b.id === "Demos") {
return 1;
}
var groups = [a.id, b.id];
groups.sort();
if (a.id === groups[0]) {
return -1;
} else {
return 1;
}
}
});
$(document).ready(function(){
$('.vis-center>.vis-content').on('scroll', function () {
$('.vis-left>.vis-content').scrollTop($(this).scrollTop());
});
$('.vis-left>.vis-content').on('scroll', function () {
$('.vis-center>.vis-content').scrollTop($(this).scrollTop());
});
});
})(); |
Fix usage of `url_title` in TeamAdmin. | from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Person, Team
@admin.register(Person)
class PersonAdmin(SearchMetaBaseAdmin):
prepopulated_fields = {"url_title": ("first_name", "last_name",)}
filter_horizontal = ("teams",)
fieldsets = (
(None, {
"fields": (
"page",
)
}),
('Name information', {
'fields': (
"title",
"first_name",
"middle_name",
"last_name",
"url_title",
)
}),
('Additional information', {
'fields': (
"photo",
"job_title",
"bio",
"teams",
"order",
)
}),
('Contact details', {
'fields': (
"email",
"linkedin_username",
"skype_username",
"twitter_username",
)
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Team)
class TeamAdmin(PageBaseAdmin):
prepopulated_fields = {
"slug": ("title",)
}
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
| from cms.admin import PageBaseAdmin, SearchMetaBaseAdmin
from django.contrib import admin
from .models import Person, Team
@admin.register(Person)
class PersonAdmin(SearchMetaBaseAdmin):
prepopulated_fields = {"url_title": ("first_name", "last_name",)}
filter_horizontal = ("teams",)
fieldsets = (
(None, {
"fields": (
"page",
)
}),
('Name information', {
'fields': (
"title",
"first_name",
"middle_name",
"last_name",
"url_title",
)
}),
('Additional information', {
'fields': (
"photo",
"job_title",
"bio",
"teams",
"order",
)
}),
('Contact details', {
'fields': (
"email",
"linkedin_username",
"skype_username",
"twitter_username",
)
}),
SearchMetaBaseAdmin.PUBLICATION_FIELDS,
SearchMetaBaseAdmin.SEO_FIELDS,
)
@admin.register(Team)
class TeamAdmin(PageBaseAdmin):
prepopulated_fields = {"url_title": ("title",)}
fieldsets = (
PageBaseAdmin.TITLE_FIELDS,
("Content", {
"fields": ("content_primary",),
}),
PageBaseAdmin.PUBLICATION_FIELDS,
PageBaseAdmin.NAVIGATION_FIELDS,
PageBaseAdmin.SEO_FIELDS,
)
|
Use enum instead of conditional | "use babel";
// @flow
import type { PlanConfig } from "../../PlanConfigurationFeature/Types/types.js.flow";
import path from "path";
import FlowDiagnostic from "./Presenters/FlowDiagnostic.js";
export default {
infos: {
name: "flow",
iconUri:
"atom://molecule-dev-environment/.storybook/public/devtool-icon-flow.png",
},
configSchema: {
type: "object",
schemas: {
binary: {
type: "enum",
label: "binary",
enum: [
{ value: "local", description: "local" },
{ value: "global", description: "global" },
],
},
},
},
getStrategyForPlan(plan: PlanConfig) {
let binaryPath;
let cmd;
const options = "--stdio";
if (plan.config.binary == "local")
binaryPath = `${path.join(
path.dirname(plan.packageInfos.path),
"node_modules",
".bin",
"flow-language-server",
)}`;
else binaryPath = "flow-language-server";
cmd = `${binaryPath} ${options}`;
return {
strategy: {
type: "shell",
command: cmd,
cwd: path.dirname(plan.packageInfos.path),
lsp: true,
},
controller: {},
};
},
DiagnosticView: FlowDiagnostic,
isPackage: ".flowconfig",
};
| "use babel";
// @flow
import type { PlanConfig } from "../../PlanConfigurationFeature/Types/types.js.flow";
import path from "path";
import FlowDiagnostic from "./Presenters/FlowDiagnostic.js";
export default {
infos: {
name: "flow",
iconUri:
"atom://molecule-dev-environment/.storybook/public/devtool-icon-flow.png",
},
configSchema: {
type: "object",
schemas: {
binary: {
type: "conditional",
expression: {
type: "enum",
label: "binary",
enum: [
{ value: "local", description: "local" },
{ value: "global", description: "global" },
],
},
cases: {
local: null,
global: null,
},
},
},
},
getStrategyForPlan(plan: PlanConfig) {
let binaryPath;
let cmd;
const options = "--stdio";
if (plan.config.binary.expressionValue == "local")
binaryPath = `${path.join(
path.dirname(plan.packageInfos.path),
"node_modules",
".bin",
"flow-language-server",
)}`;
else binaryPath = "flow-language-server";
cmd = `${binaryPath} ${options}`;
return {
strategy: {
type: "shell",
command: cmd,
cwd: path.dirname(plan.packageInfos.path),
lsp: true,
},
controller: {},
};
},
DiagnosticView: FlowDiagnostic,
isPackage: ".flowconfig",
};
|
Remove the doc that describes the setup. Setup is automated now | import mysql.connector
from luigi.contrib.mysqldb import MySqlTarget
import unittest
host = 'localhost'
port = 3306
database = 'luigi_test'
username = None
password = None
table_updates = 'table_updates'
def _create_test_database():
con = mysql.connector.connect(user=username,
password=password,
host=host,
port=port,
autocommit=True)
con.cursor().execute('CREATE DATABASE IF NOT EXISTS %s' % database)
_create_test_database()
target = MySqlTarget(host, database, username, password, '', 'update_id')
class MySqlTargetTest(unittest.TestCase):
def test_touch_and_exists(self):
drop()
self.assertFalse(target.exists(),
'Target should not exist before touching it')
target.touch()
self.assertTrue(target.exists(),
'Target should exist after touching it')
def drop():
con = target.connect(autocommit=True)
con.cursor().execute('DROP TABLE IF EXISTS %s' % table_updates)
| '''
$ mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 211
Server version: 5.6.15 Homebrew
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> create database luigi;
Query OK, 1 row affected (0.00 sec)
'''
import mysql.connector
from luigi.contrib.mysqldb import MySqlTarget
import unittest
host = 'localhost'
port = 3306
database = 'luigi_test'
username = None
password = None
table_updates = 'table_updates'
def _create_test_database():
con = mysql.connector.connect(user=username,
password=password,
host=host,
port=port,
autocommit=True)
con.cursor().execute('CREATE DATABASE IF NOT EXISTS %s' % database)
_create_test_database()
target = MySqlTarget(host, database, username, password, '', 'update_id')
class MySqlTargetTest(unittest.TestCase):
def test_touch_and_exists(self):
drop()
self.assertFalse(target.exists(),
'Target should not exist before touching it')
target.touch()
self.assertTrue(target.exists(),
'Target should exist after touching it')
def drop():
con = target.connect(autocommit=True)
con.cursor().execute('DROP TABLE IF EXISTS %s' % table_updates)
|
Add region in the new API route | <?php
namespace CodeDay\Clear\ModelContracts;
use \CodeDay\Clear\Models;
class Grant extends ModelContract
{
public static function getFields()
{
return [
'id' => [
'name' => 'ID',
'description' => 'The ID of the grant. Numeric.',
'example' => '1',
'value' => function($model) { return $model->id; }
],
'username' => [
'name' => 'Username',
'description' => 'Username of the user that this grant belongs to.',
'example' => 'tylermenezes',
'value' => function($model) { return $model->username; }
],
'event' => [
'name' => 'Event',
'description' => 'The event that this grant gave the user access to.',
'type' => 'Event',
'rich' => true,
'value' => function($model, $permissions) { return new Event($model->event, $permissions, true); }
],
'region' => [
'name' => 'Event',
'description' => 'The region of the event that this grant gave the user access to.',
'type' => 'Event',
'rich' => true,
'value' => function($model, $permissions) { return new Region($model->event->region, $permissions, true); }
]
];
}
}
| <?php
namespace CodeDay\Clear\ModelContracts;
use \CodeDay\Clear\Models;
class Grant extends ModelContract
{
public static function getFields()
{
return [
'id' => [
'name' => 'ID',
'description' => 'The ID of the grant. Numeric.',
'example' => '1',
'value' => function($model) { return $model->id; }
],
'username' => [
'name' => 'Username',
'description' => 'Username of the user that this grant belongs to.',
'example' => 'tylermenezes',
'value' => function($model) { return $model->username; }
],
'event' => [
'name' => 'Event',
'description' => 'The event that this grant gave the user access to.',
'type' => 'Event',
'rich' => true,
'value' => function($model, $permissions) { return new Event($model->event, $permissions, true); }
]
];
}
}
|
Adjust which log messages can be filtered out | package io.quarkus.runtime.logging;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.jboss.logging.Logger;
public class LogCleanupFilter implements Filter {
private Map<String, LogCleanupFilterElement> filterElements = new HashMap<>();
public LogCleanupFilter(List<LogCleanupFilterElement> filterElements) {
for (LogCleanupFilterElement element : filterElements) {
this.filterElements.put(element.getLoggerName(), element);
}
}
@Override
public boolean isLoggable(LogRecord record) {
// Only allow filtering messages of warning level and lower
if (record.getLevel().intValue() > Level.WARNING.intValue()) {
return true;
}
LogCleanupFilterElement filterElement = filterElements.get(record.getLoggerName());
if (filterElement != null) {
for (String messageStart : filterElement.getMessageStarts()) {
if (record.getMessage().startsWith(messageStart)) {
record.setLevel(org.jboss.logmanager.Level.DEBUG);
return Logger.getLogger(record.getLoggerName()).isDebugEnabled();
}
}
}
return true;
}
}
| package io.quarkus.runtime.logging;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.jboss.logging.Logger;
public class LogCleanupFilter implements Filter {
private Map<String, LogCleanupFilterElement> filterElements = new HashMap<>();
public LogCleanupFilter(List<LogCleanupFilterElement> filterElements) {
for (LogCleanupFilterElement element : filterElements) {
this.filterElements.put(element.getLoggerName(), element);
}
}
@Override
public boolean isLoggable(LogRecord record) {
if (record.getLevel().intValue() != Level.INFO.intValue()
&& record.getLevel().intValue() != Level.WARNING.intValue()) {
return true;
}
LogCleanupFilterElement filterElement = filterElements.get(record.getLoggerName());
if (filterElement != null) {
for (String messageStart : filterElement.getMessageStarts()) {
if (record.getMessage().startsWith(messageStart)) {
record.setLevel(org.jboss.logmanager.Level.DEBUG);
return Logger.getLogger(record.getLoggerName()).isDebugEnabled();
}
}
}
// System.err.println("isLoggable: "+record.getLoggerName());
// System.err.println("isLoggable: "+record.getMessage());
return true;
}
}
|
Remove ref to dead Config class | import sys
import argparse
import os
import mediachain.reader.api
def main(arguments=None):
if arguments == None:
arguments = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='mediachain-reader',
description='Mediachain Reader CLI'
)
parser.add_argument('-h', '--host',
type=str,
required=True,
dest='host')
parser.add_argument('-p', '--port',
type=int,
required=True,
dest='port')
subparsers = parser.add_subparsers(help='Mediachain Reader SubCommands',
dest='subcommand')
get_parser = subparsers.add_parser(
'get',
help='Get a revision chain for a given artefact/entity id'
)
get_parser.add_argument('object_id',
type=str,
help='The id of the artefact/entity to fetch')
SUBCOMMANDS={
'get': 'get_chain_head'
}
ns = parser.parse_args(arguments)
fn = getattr(mediachain.reader.api, SUBCOMMANDS[ns.subcommand])
fn(ns)
if __name__ == "__main__":
main()
| import sys
import argparse
import os
import mediachain.reader.api
from mediachain.reader.api import Config
def main(arguments=None):
if arguments == None:
arguments = sys.argv[1:]
parser = argparse.ArgumentParser(
prog='mediachain-reader',
description='Mediachain Reader CLI'
)
parser.add_argument('-h', '--host',
type=str,
required=True,
dest='host')
parser.add_argument('-p', '--port',
type=int,
required=True,
dest='port')
subparsers = parser.add_subparsers(help='Mediachain Reader SubCommands',
dest='subcommand')
get_parser = subparsers.add_parser(
'get',
help='Get a revision chain for a given artefact/entity id'
)
get_parser.add_argument('object_id',
type=str,
help='The id of the artefact/entity to fetch')
SUBCOMMANDS={
'get': 'get_chain_head'
}
ns = parser.parse_args(arguments)
cfg = Config(host=ns.host, port=ns.port)
fn = getattr(mediachain.reader.api, SUBCOMMANDS[ns.subcommand])
fn(ns)
if __name__ == "__main__":
main()
|
Fix a hard-coded api root in the image viewer. | import { apiRoot, restRequest } from 'girder/rest';
import View from 'girder/views/View';
var ImageViewerWidget = View.extend({
initialize: function (settings) {
this.itemId = settings.itemId;
restRequest({
type: 'GET',
path: 'item/' + this.itemId + '/tiles'
}).done((resp) => {
this.levels = resp.levels;
this.tileWidth = resp.tileWidth;
this.tileHeight = resp.tileHeight;
this.sizeX = resp.sizeX;
this.sizeY = resp.sizeY;
this.render();
this.trigger('g:imageRendered', this);
});
},
/**
* Return a url for a specific tile. This can also be used to generate a
* template url if the level, x, and y parameters are template strings
* rather than integers.
*
* @param {number|string} level: the tile level or a template string.
* @param {number|string} x: the tile x position or a template string.
* @param {number|string} y: the tile y position or a template string.
* @param {object} [query]: optional query parameters to add to the url.
*/
_getTileUrl: function (level, x, y, query) {
var url = apiRoot + '/item/' + this.itemId + '/tiles/zxy/' +
level + '/' + x + '/' + y;
if (query) {
url += '?' + $.param(query);
}
return url;
}
});
export default ImageViewerWidget;
| import { restRequest } from 'girder/rest';
import View from 'girder/views/View';
var ImageViewerWidget = View.extend({
initialize: function (settings) {
this.itemId = settings.itemId;
restRequest({
type: 'GET',
path: 'item/' + this.itemId + '/tiles'
}).done((resp) => {
this.levels = resp.levels;
this.tileWidth = resp.tileWidth;
this.tileHeight = resp.tileHeight;
this.sizeX = resp.sizeX;
this.sizeY = resp.sizeY;
this.render();
this.trigger('g:imageRendered', this);
});
},
/**
* Return a url for a specific tile. This can also be used to generate a
* template url if the level, x, and y parameters are template strings
* rather than integers.
*
* @param {number|string} level: the tile level or a template string.
* @param {number|string} x: the tile x position or a template string.
* @param {number|string} y: the tile y position or a template string.
* @param {object} [query]: optional query parameters to add to the url.
*/
_getTileUrl: function (level, x, y, query) {
var url = '/api/v1/item/' + this.itemId + '/tiles/zxy/' +
level + '/' + x + '/' + y;
if (query) {
url += '?' + $.param(query);
}
return url;
}
});
export default ImageViewerWidget;
|
Make outlook emit single files | import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
class OutlookPSTIngestor(Ingestor, TempFileSupport, OLESupport, ShellSupport):
MIME_TYPES = ['application/vnd.ms-outlook']
EXTENSIONS = ['pst', 'ost', 'pab']
BASE_SCORE = 5
COMMAND_TIMEOUT = 12 * 60 * 60
def ingest(self, file_path, entity):
entity.schema = model.get('Package')
self.extract_ole_metadata(file_path, entity)
temp_dir = self.make_empty_directory()
try:
self.exec_command('readpst',
'-e', # make subfolders, files per message
'-S', # single files
'-D', # include deleted
# '-r', # recursive structure
'-8', # utf-8 where possible
'-cv', # export vcards
# '-q', # quiet
'-o', temp_dir,
file_path)
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
except Exception:
log.exception("Failed to unpack PST.")
# Handle partially extracted archives.
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
raise
| import logging
from followthemoney import model
from ingestors.ingestor import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
log = logging.getLogger(__name__)
class OutlookPSTIngestor(Ingestor, TempFileSupport, OLESupport, ShellSupport):
MIME_TYPES = ['application/vnd.ms-outlook']
EXTENSIONS = ['pst', 'ost', 'pab']
BASE_SCORE = 5
COMMAND_TIMEOUT = 12 * 60 * 60
def ingest(self, file_path, entity):
entity.schema = model.get('Package')
self.extract_ole_metadata(file_path, entity)
temp_dir = self.make_empty_directory()
try:
self.exec_command('readpst',
'-e', # make subfolders, files per message
'-D', # include deleted
'-r', # recursive structure
'-8', # utf-8 where possible
'-b',
'-q', # quiet
'-o', temp_dir,
file_path)
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
except Exception:
log.exception("Failed to unpack PST.")
# Handle partially extracted archives.
self.manager.delegate(DirectoryIngestor, temp_dir, entity)
raise
|
Fix exception when required options are missing
Options can be on command line and in config file, so we check in merged
dictionary after getting from both sources. | from sys import exit
import argparse
from .commands import dispatch, choices
from .config import get_config
from .utils import merge, error
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--base-url',
dest='url',
metavar='https://redmine.example.com',
help='Base URL of your Redmine installation.')
parser.add_argument('-S', '--no-ssl-verify', dest='ssl_verify',
action='store_const', const=False)
parser.add_argument('-k', '--api-key',
dest='key',
help='Your Redmine API key.')
parser.add_argument('-C', '--config-file',
help='Override default config path.')
parser.add_argument('cmd',
choices=choices,
help='Command to execute.')
parser.add_argument('args',
nargs=argparse.REMAINDER,
help='Arguments to command. Use --help to get '
'command-specific help.')
args = vars(parser.parse_args())
conf = get_config(args.pop('config_file'))
cmd = args.pop('cmd')
cmd_args = args.pop('args')
merged_conf = merge(conf, args)
required = ['url', 'key']
missing = lambda x: bool(merged_conf.get(x))
if not all(map(missing, required)):
error('fatal: base_url and api_key are required')
return 1
return dispatch(cmd, cmd_args, merged_conf)
if __name__ == '__main__':
exit(main())
| from sys import exit
import argparse
from .commands import dispatch, choices
from .config import get_config
from .utils import merge
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--base-url',
metavar='https://redmine.example.com',
help='Base URL of your Redmine installation.')
parser.add_argument('-S', '--no-ssl-verify', dest='ssl_verify',
action='store_const', const=False)
parser.add_argument('-k', '--api-key',
help='Your Redmine API key.')
parser.add_argument('-C', '--config-file',
help='Override default config path.')
parser.add_argument('cmd',
choices=choices,
help='Command to execute.')
parser.add_argument('args',
nargs=argparse.REMAINDER,
help='Arguments to command. Use --help to get '
'command-specific help.')
args = vars(parser.parse_args())
conf = get_config(args.pop('config_file'))
cmd = args.pop('cmd')
cmd_args = args.pop('args')
merged_conf = merge(conf, args)
return dispatch(cmd, cmd_args, merged_conf)
if __name__ == '__main__':
exit(main())
|
Change default language : en | 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
window.i18next.use(window.i18nextXHRBackend)
window.i18next.init({
debug: true,
lng: 'en', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
useCookie: false,
useLocalStorage: false
}, function (err, t) {
console.log('resources loaded')
})
})
| 'use strict'
angular
.module('serinaApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngMaterial'
])
.config(function ($routeProvider) {
$routeProvider
.when('/hub', {
templateUrl: 'views/hub/hub.html',
controller: 'HubCtrl'
})
.when('/lang/:lang', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.when('/lang/:lang/:group*', {
templateUrl: 'views/lang/lang.html',
controller: 'LangCtrl'
})
.otherwise({
redirectTo: '/hub'
})
})
.run(function ($rootScope, $mdSidenav) {
$rootScope.endPoint = 'http://localhost:3000/api'
$rootScope.toggleLeft = buildToggler('left')
function buildToggler (componentId) {
return function () {
$mdSidenav(componentId).toggle()
}
}
window.i18next.use(window.i18nextXHRBackend)
window.i18next.init({
debug: true,
lng: 'fr', // If not given, i18n will detect the browser language.
fallbackLng: '', // Default is dev
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
useCookie: false,
useLocalStorage: false
}, function (err, t) {
console.log('resources loaded')
})
})
|
Terminate the interactive prompt upon completion | import path from 'path';
import {assign} from 'bound-native-methods/object';
import Vorpal from 'vorpal';
import JSONFilePlus from 'json-file-plus';
const cli = Vorpal();
cli.command('config', 'Configures this project.')
.action(function (args, callback) {
const {log, prompt} = this;
log();
prompt(
[{
name: 'name',
message: 'Enter the package name: '
}, {
name: 'description',
message: 'Enter the package description: '
}, {
name: 'url',
message: 'Enter the URL of the repository: '
}, {
type: 'confirm',
name: 'private',
message: 'Is the project private?'
}],
async ({url, ...answers}) => {
const file = await JSONFilePlus(path.join(process.cwd(), 'package.json'));
file.set(answers::assign({
repository: {url}
}));
log();
try {
await file.save();
log('Configuration was successfully saved.');
} catch (error) {
log(`Error while saving the configuration! ${error}`);
}
log();
cli.ui.cancel();
}
);
});
cli.delimiter('backtier>').show().exec('config');
| import path from 'path';
import {assign} from 'bound-native-methods/object';
import Vorpal from 'vorpal';
import JSONFilePlus from 'json-file-plus';
const cli = Vorpal();
cli.command('config', 'Configures this project.')
.action(function (args, callback) {
const {log, prompt} = this;
log();
prompt(
[{
name: 'name',
message: 'Enter the package name: '
}, {
name: 'description',
message: 'Enter the package description: '
}, {
name: 'url',
message: 'Enter the URL of the repository: '
}, {
type: 'confirm',
name: 'private',
message: 'Is the project private?'
}],
async ({url, ...answers}) => {
const file = await JSONFilePlus(path.join(process.cwd(), 'package.json'));
file.set(answers::assign({
repository: {url}
}));
log();
try {
await file.save(callback);
log('Configuration was successfully saved.');
} catch (error) {
log(`Error while saving the configuration! ${error}`);
}
log();
}
);
});
cli.delimiter('backtier>').show().exec('config');
|
Tweak to migration in order to accomodate old names for data fields and allow for if data fields were not present | import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
"""
def handle(self, *args, **options):
org_groups = GroupProfile.objects.filter(group_type='organization')
for org in org_groups:
data = json.loads(org.data)
name = org.name
display_name = data.get('display_name', name)
contact_name = data.get('contact_name', None)
contact_email = data.get('email', None)
if contact_email is None:
contact_email = data.get('contact_email', None)
contact_phone = data.get('phone', None)
if contact_phone is None:
contact_phone = data.get('contact_phone', None)
migrated_org = Organization.objects.create(
name=name,
display_name=display_name,
contact_name=contact_name,
contact_email=contact_email,
contact_phone=contact_phone
)
group = Group.objects.get(groupprofile=org.id)
users = group.user_set.all()
for user in users:
migrated_org.users.add(user)
linked_groups = group.grouprelationship.get_linked_group_relationships()
for linked_group in linked_groups:
if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
migrated_org.groups.add(actual_group)
| import json
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from api_manager.models import GroupProfile, Organization
class Command(BaseCommand):
"""
Migrates legacy organization data and user relationships from older Group model approach to newer concrete Organization model
"""
def handle(self, *args, **options):
org_groups = GroupProfile.objects.filter(group_type='organization')
for org in org_groups:
data = json.loads(org.data)
migrated_org = Organization.objects.create(
name=data['name'],
display_name=data['display_name'],
contact_name=data['contact_name'],
contact_email=data['contact_email'],
contact_phone=data['contact_phone']
)
group = Group.objects.get(groupprofile=org.id)
users = group.user_set.all()
for user in users:
migrated_org.users.add(user)
linked_groups = group.grouprelationship.get_linked_group_relationships()
for linked_group in linked_groups:
if linked_group.to_group_relationship_id is not org.id: # Don't need to carry the symmetrical component
actual_group = Group.objects.get(id=linked_group.to_group_relationship_id)
migrated_org.groups.add(actual_group)
|
Replace the hard coded dictionary path with a variable. | <?php
namespace TuxOne\ValidationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @Annotation
*/
class NotContainsBadWordsValidator extends ConstraintValidator
{
private $dictionaryPath;
public function __construct($dictionaryPath)
{
$this->dictionaryPath = $dictionaryPath;
}
public function validate($value, Constraint $constraint)
{
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$stringValue = (string) $value;
// Load blacklist
$blacklist = $this->getBlackListArray();
// Split input value into words
$words = $this->getWordsArray($stringValue);
// Search for bad words
$match = array_intersect($words, $blacklist);
if ( count($match) > 0 ) {
$this->context->addViolation($constraint->message, array('%string%' => reset($match)));
}
}
private function getBlackListArray()
{
return file($this->dictionaryPath, FILE_IGNORE_NEW_LINES);
}
private function getWordsArray($text)
{
$text = strtolower($text);
$text = preg_replace("/[^a-z0-9 ]/", ' ', $text);
$words = explode(' ', $text);
$words = array_unique($words);
return $words;
}
}
| <?php
namespace TuxOne\ValidationBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @Annotation
*/
class NotContainsBadWordsValidator extends ConstraintValidator
{
private $dictionaryPath;
public function __construct($dictionaryPath)
{
$this->dictionaryPath = $dictionaryPath;
}
public function validate($value, Constraint $constraint)
{
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$stringValue = (string) $value;
// Load blacklist
$blacklist = $this->getBlackListArray();
// Split input value into words
$words = $this->getWordsArray($stringValue);
// Search for bad words
$match = array_intersect($words, $blacklist);
if ( count($match) > 0 ) {
$this->context->addViolation($constraint->message, array('%string%' => reset($match)));
}
}
private function getBlackListArray()
{
return file(__DIR__."/../../Dictionaries/list.txt", FILE_IGNORE_NEW_LINES);
}
private function getWordsArray($text)
{
$text = strtolower($text);
$text = preg_replace("/[^a-z0-9 ]/", ' ', $text);
$words = explode(' ', $text);
$words = array_unique($words);
return $words;
}
}
|
Add optional text to display | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
3. (optional) Text to display (without color)
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x':
col_char = '3'
cols_limit = 78
code = '' # No code provided - only yellow bar
else:
if code == 'y':
col_char = '3'
else:
value = int(code)
if value:
col_char = '1'
else:
col_char = '2'
cols_limit = int(sys.argv[2])
if len(sys.argv) >= 4:
start_text = sys.argv[3] + ' '
else:
start_text = ''
esc = chr(27)
print (''.join((
start_text,
esc,
'[4',
col_char,
'm',
' ' * (cols_limit - 2 - len(code) - len(start_text)),
code,
esc,
'[0m',
)))
else:
print ('''
Usage: %(prog_name)s status_code number_of_columns
1. status code: 0 - OK (green color), other values - BAD (red color)
2. number of columns: the width of text console
3. (optional) Text to display
''' % dict(
prog_name=sys.argv[0],
))
| #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x':
col_char = '3'
cols_limit = 78
code = '' # No code provided - only yellow bar
else:
if code == 'y':
col_char = '3'
else:
value = int(code)
if value:
col_char = '1'
else:
col_char = '2'
cols_limit = int(sys.argv[2])
esc = chr(27)
print (''.join((
esc,
'[4',
col_char,
'm',
' ' * (cols_limit - 2 - len(code)),
code,
esc,
'[0m',
)))
else:
print ('''
Usage: %(prog_name)s status_code number_of_columns
1. status code: 0 - OK (green color), other values - BAD (red color)
2. number of columns: the width of text console
''' % dict(
prog_name=sys.argv[0],
))
|
Add functionality to print list of parseable files | # -*- coding: utf-8 -*-
import os
import argparse
import fs_utils
from pybtex.database.input import bibtex
def main():
"""
Command-line interface
"""
parser = argparse.ArgumentParser(description="Manage BibTeX files")
parser.add_argument("-t", "--test",
action="store_true",
help="Test parseability of BibTeX file(s)",)
parser.add_argument("-v", "--verbose",
action="store_true",
help="Verbose output",)
parser.add_argument("paths_args",
nargs="*",
default="*.bib",
help="File(s) to test parseability",
metavar="files")
args = parser.parse_args()
test(args)
def test(args):
"""
Implement "test" command-line functionality
"""
paths = fs_utils.handle_files_args(*args.paths_args)
bibs_paths_dict = fs_utils.import_bib_files(*paths)
parseables = []
parseables_msg = "The following files are parseable:"
unparseables = []
unparseables_msg = "The following files are unparseable:"
for key in bibs_paths_dict.keys():
if bibs_paths_dict[key] is None:
unparseables.append(key)
unparseables_msg += "\n\t" + str(key.resolve())
else:
parseables.append(key)
parseables_msg += "\n\t" + str(key.resolve())
if args.verbose:
print(parseables_msg)
print("\r")
print(unparseables_msg)
if __name__ == '__main__':
main()
| # -*- coding: utf-8 -*-
import os
import argparse
import fs_utils
from pybtex.database.input import bibtex
def main():
"""
Command-line interface
"""
parser = argparse.ArgumentParser(description="Manage BibTeX files")
parser.add_argument("-t", "--test",
action="store_true",
help="Test parseability of BibTeX file(s)",)
parser.add_argument("-v", "--verbose",
action="store_true",
help="Verbose output",)
parser.add_argument("paths_args",
nargs="*",
default="*.bib",
help="File(s) to test parseability",
metavar="files")
args = parser.parse_args()
test(args)
def test(args):
"""
Implement "test" command-line functionality
"""
paths = fs_utils.handle_files_args(*args.paths_args)
bibs_paths_dict = fs_utils.import_bib_files(*paths)
parseables = []
unparseables = []
for key in bibs_paths_dict.keys():
if bibs_paths_dict[key] is None:
unparseables.append(key)
else:
parseables.append(key)
print("The following files are unparseable:")
for unparseable in unparseables:
print("\t" + str(unparseable.resolve()))
if __name__ == '__main__':
main()
|
Use proper syntax for User-Agent header | <?php
namespace Kyranb\Footprints;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
class Footprinter implements FootprinterInterface
{
protected Request $request;
protected string $random;
public function __construct()
{
$this->random = Str::random(20); // Will only be set once during requests since this class is a singleton
}
/** @inheritDoc */
public function footprint(Request $request): string
{
$this->request = $request;
if ($request->hasCookie(config('footprints.cookie_name'))) {
return $request->cookie(config('footprints.cookie_name'));
}
// This will add the cookie to the response
Cookie::queue(
config('footprints.cookie_name'),
$footprint = $this->fingerprint(),
config('footprints.attribution_duration'),
null,
config('footprints.cookie_domain')
);
return $footprint;
}
/**
* This method will generate a fingerprint for the request based on the configuration.
*
* If relying on cookies then the logic of this function is not important, but if cookies are disabled this value
* will be used to link previous requests with one another.
*
* @return string
*/
protected function fingerprint()
{
// This is highly inspired from the $request->fingerprint() method
return sha1(implode('|', array_filter([
$this->request->ip(),
$this->request->header('User-Agent'),
config('footprints.uniqueness') ? $this->random : null,
])));
}
}
| <?php
namespace Kyranb\Footprints;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
class Footprinter implements FootprinterInterface
{
protected Request $request;
protected string $random;
public function __construct()
{
$this->random = Str::random(20); // Will only be set once during requests since this class is a singleton
}
/** @inheritDoc */
public function footprint(Request $request): string
{
$this->request = $request;
if ($request->hasCookie(config('footprints.cookie_name'))) {
return $request->cookie(config('footprints.cookie_name'));
}
// This will add the cookie to the response
Cookie::queue(
config('footprints.cookie_name'),
$footprint = $this->fingerprint(),
config('footprints.attribution_duration'),
null,
config('footprints.cookie_domain')
);
return $footprint;
}
/**
* This method will generate a fingerprint for the request based on the configuration.
*
* If relying on cookies then the logic of this function is not important, but if cookies are disabled this value
* will be used to link previous requests with one another.
*
* @return string
*/
protected function fingerprint()
{
// This is highly inspired from the $request->fingerprint() method
return sha1(implode('|', array_filter([
$this->request->ip(),
$this->request->header('user-agent'),
config('footprints.uniqueness') ? $this->random : null,
])));
}
}
|
Fix default legend type detection | from .legend import Legend
from .constants import SINGLE_LEGEND
class LegendList:
"""LegendList
Args:
legends (list, Legend): List of legends for a layer.
"""
def __init__(self, legends=None, default_legend=None, geom_type=None):
self._legends = self._init_legends(legends, default_legend, geom_type)
def _init_legends(self, legends, default_legend, layer_type):
if isinstance(legends, list):
legend_list = []
for legend in legends:
if isinstance(legend, Legend):
if legend._type == 'basic':
legend._type = _get_simple_legend_geometry_type(layer_type)
elif legend._type == 'default' and default_legend:
legend._type = default_legend._type
legend._prop = default_legend._prop
legend_list.append(legend)
else:
raise ValueError('Legends list contains invalid elements')
return legend_list
else:
return []
def get_info(self):
legends_info = []
for legend in self._legends:
if legend:
legends_info.append(legend.get_info())
return legends_info
def _get_simple_legend_geometry_type(layer_type):
return SINGLE_LEGEND + '-' + layer_type
| from .legend import Legend
from .constants import SINGLE_LEGEND
class LegendList:
"""LegendList
Args:
legends (list, Legend): List of legends for a layer.
"""
def __init__(self, legends=None, default_legend=None, geom_type=None):
self._legends = self._init_legends(legends, default_legend, geom_type)
def _init_legends(self, legends, default_legend, layer_type):
if isinstance(legends, list):
legend_list = []
for legend in legends:
if isinstance(legend, Legend):
if legend._type == 'default' or legend._type == 'basic':
legend._type = _get_simple_legend_geometry_type(layer_type)
if legend._type == 'default' and default_legend:
legend._prop = default_legend._prop
legend_list.append(legend)
else:
raise ValueError('Legends list contains invalid elements')
return legend_list
else:
return []
def get_info(self):
legends_info = []
for legend in self._legends:
if legend:
legends_info.append(legend.get_info())
return legends_info
def _get_simple_legend_geometry_type(layer_type):
return SINGLE_LEGEND + '-' + layer_type
|
Add mention of Python 3.6 support | #!/usr/bin/env python
# coding=utf-8
import sys
import os
import re
from setuptools import setup
from setuptools.command.test import test as TestCommand
HERE = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = 'mailjet_rest'
VERSION = 'v1.2.2'
setup(
name=PACKAGE_NAME,
version=VERSION,
author='starenka',
author_email='[email protected]',
maintainer='Guillaume Badi',
maintainer_email='[email protected]',
download_url='https://github.com/mailjet/mailjet-apiv3-python/releases/tag/v1.2.2',
url='https://github.com/mailjet/mailjet-apiv3-python',
description=('Mailjet V3 API wrapper'),
classifiers=['Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Utilities'],
license='GPLv3',
keywords='mailjet api wrapper email client',
include_package_data=True,
install_requires=['requests>=2.4.3'],
tests_require=['unittest'],
entry_points={},
packages=['mailjet_rest'],
)
| #!/usr/bin/env python
# coding=utf-8
import sys
import os
import re
from setuptools import setup
from setuptools.command.test import test as TestCommand
HERE = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = 'mailjet_rest'
VERSION = 'v1.2.2'
setup(
name=PACKAGE_NAME,
version=VERSION,
author='starenka',
author_email='[email protected]',
maintainer='Guillaume Badi',
maintainer_email='[email protected]',
download_url='https://github.com/mailjet/mailjet-apiv3-python/releases/tag/v1.2.2',
url='https://github.com/mailjet/mailjet-apiv3-python',
description=('Mailjet V3 API wrapper'),
classifiers=['Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities'],
license='GPLv3',
keywords='mailjet api wrapper email client',
include_package_data=True,
install_requires=['requests>=2.4.3'],
tests_require=['unittest'],
entry_points={},
packages=['mailjet_rest'],
)
|
Remove Ember 2.12 from Ember Try config | 'use strict';
const getChannelURL = require('ember-source-channel-url');
module.exports = function() {
return Promise.all([
getChannelURL('release'),
getChannelURL('beta'),
getChannelURL('canary')
]).then((urls) => {
return {
scenarios: [
{
name: 'ember-lts-2.16',
npm: {
devDependencies: {
'ember-source': '~2.16.0'
}
}
},
{
name: 'ember-lts-2.18',
npm: {
devDependencies: {
'ember-source': '~2.18.0'
}
}
},
{
name: 'ember-release',
npm: {
devDependencies: {
'ember-source': urls[0]
}
}
},
{
name: 'ember-beta',
npm: {
devDependencies: {
'ember-source': urls[1]
}
}
},
{
name: 'ember-canary',
npm: {
devDependencies: {
'ember-source': urls[2]
}
}
},
{
name: 'ember-default',
npm: {
devDependencies: {}
}
}
]
};
});
};
| 'use strict';
const getChannelURL = require('ember-source-channel-url');
module.exports = function() {
return Promise.all([
getChannelURL('release'),
getChannelURL('beta'),
getChannelURL('canary')
]).then((urls) => {
return {
scenarios: [
{
name: 'ember-lts-2.12',
npm: {
devDependencies: {
'ember-source': '~2.12.0'
}
}
},
{
name: 'ember-lts-2.16',
npm: {
devDependencies: {
'ember-source': '~2.16.0'
}
}
},
{
name: 'ember-lts-2.18',
npm: {
devDependencies: {
'ember-source': '~2.18.0'
}
}
},
{
name: 'ember-release',
npm: {
devDependencies: {
'ember-source': urls[0]
}
}
},
{
name: 'ember-beta',
npm: {
devDependencies: {
'ember-source': urls[1]
}
}
},
{
name: 'ember-canary',
npm: {
devDependencies: {
'ember-source': urls[2]
}
}
},
{
name: 'ember-default',
npm: {
devDependencies: {}
}
}
]
};
});
};
|
Use analysis base class form helper and form building blocks | from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import InlineField
from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from analyses.forms import (
AbstractAnalysisCreateForm,
AnalysisCommonLayout,
AnalysisFormActions,
Include,
)
from .models import RNASeqModel
class RNASeqCreateForm(AbstractAnalysisCreateForm):
class Meta(AbstractAnalysisCreateForm.Meta):
model = RNASeqModel
fields = '__all__'
widgets = {
**AbstractAnalysisCreateForm.Meta.widgets,
}
@cached_property
def helper(self):
helper = super().helper
helper.layout = Layout(
AnalysisCommonLayout(analysis_type="RNA-Seq"),
Fieldset(
'Quality Check',
HTML(
"<p>Examine and process the quality of the sequencing "
"reads.</p>"
),
Field('quality_check'),
Field('trim_adapter'),
Field('rm_duplicate'),
),
AnalysisFormActions(),
)
return helper
| from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, Field, Fieldset, HTML, Layout, Submit
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from analyses.forms import AbstractAnalysisCreateForm, AnalysisCommonLayout
from .models import RNASeqModel
class RNASeqCreateForm(AbstractAnalysisCreateForm):
class Meta(AbstractAnalysisCreateForm.Meta):
model = RNASeqModel
fields = (
*AbstractAnalysisCreateForm.Meta.fields,
'quality_check', 'trim_adapter', 'rm_duplicate',
)
widgets = {
**AbstractAnalysisCreateForm.Meta.widgets,
}
@cached_property
def helper(self):
helper = FormHelper()
helper.layout = Layout(
AnalysisCommonLayout(analysis_type="RNA-Seq"),
Fieldset(
'Quality Check',
HTML(
"<p>Examine and process the quality of the sequencing "
"reads.</p>"
),
Field('quality_check'),
Field('trim_adapter'),
Field('rm_duplicate'),
),
FormActions(
Submit(
'save', _('Create New Analysis'), css_class='btn-lg',
)
)
)
helper.include_media = False
return helper
|
Use io.open with UTF-8 encoding to avoid UnicodeDecodeError | import io
import os
import re
from setuptools import setup, find_packages
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read())
if version:
return version.group(1)
else:
raise RuntimeError("Unable to find version string.")
with io.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name='auth0-python',
version=find_version(),
description='Auth0 Python SDK',
long_description=long_description,
author='Auth0',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=['requests'],
extras_require={'test': ['mock']},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
url='https://github.com/auth0/auth0-python',
)
| import io
import os
import re
from setuptools import setup, find_packages
def find_version():
file_dir = os.path.dirname(__file__)
with io.open(os.path.join(file_dir, 'auth0', '__init__.py')) as f:
version = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', f.read())
if version:
return version.group(1)
else:
raise RuntimeError("Unable to find version string.")
with open('README.rst') as f:
long_description = f.read()
setup(
name='auth0-python',
version=find_version(),
description='Auth0 Python SDK',
long_description=long_description,
author='Auth0',
author_email='[email protected]',
license='MIT',
packages=find_packages(),
install_requires=['requests'],
extras_require={'test': ['mock']},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
url='https://github.com/auth0/auth0-python',
)
|
Fix expensive transform tests by increasing timeouts to 5000ms. | import assert from "assert";
import { join } from "path";
import {
readdirSync,
readFileSync,
statSync,
} from "fs";
import { compile, transform } from "../lib/compiler.js";
import { prettyPrint } from "recast";
var jsFiles = Object.create(null);
function walk(dir) {
readdirSync(dir).forEach(function (item) {
var absPath = join(dir, item);
var stat = statSync(absPath);
if (stat.isDirectory()) {
walk(absPath);
} else if (item.endsWith(".js") &&
stat.isFile()) {
jsFiles[absPath] = readFileSync(absPath, "utf8");
}
});
}
walk(__dirname);
describe("compiler.transform", function () {
function check(options) {
Object.keys(jsFiles).forEach(function (absPath) {
var code = jsFiles[absPath];
assert.strictEqual(
prettyPrint(compile(code, options).ast).code,
prettyPrint(transform(options.parse(code), options)).code,
"Transform mismatch for " + absPath
);
});
}
it("gives the same results as compile with babylon", function () {
check({
ast: true,
parse: require("../lib/parsers/babylon.js").parse
});
}).timeout(5000);
it("gives the same results as compile with acorn", function () {
check({
ast: true,
parse: require("../lib/parsers/acorn.js").parse
});
}).timeout(5000);
});
| import assert from "assert";
import { join } from "path";
import {
readdirSync,
readFileSync,
statSync,
} from "fs";
import { compile, transform } from "../lib/compiler.js";
import { prettyPrint } from "recast";
var jsFiles = Object.create(null);
function walk(dir) {
readdirSync(dir).forEach(function (item) {
var absPath = join(dir, item);
var stat = statSync(absPath);
if (stat.isDirectory()) {
walk(absPath);
} else if (item.endsWith(".js") &&
stat.isFile()) {
jsFiles[absPath] = readFileSync(absPath, "utf8");
}
});
}
walk(__dirname);
describe("compiler.transform", function () {
function check(options) {
Object.keys(jsFiles).forEach(function (absPath) {
var code = jsFiles[absPath];
assert.strictEqual(
prettyPrint(compile(code, options).ast).code,
prettyPrint(transform(options.parse(code), options)).code,
"Transform mismatch for " + absPath
);
});
}
it("gives the same results as compile with babylon", function () {
check({
ast: true,
parse: require("../lib/parsers/babylon.js").parse
});
});
it("gives the same results as compile with acorn", function () {
check({
ast: true,
parse: require("../lib/parsers/acorn.js").parse
});
});
});
|
Add logging to keyword data migration | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-02 15:46
from __future__ import unicode_literals
from django.db import migrations, models
def forward(apps, schema_editor):
Keyword = apps.get_model('events', 'Keyword')
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None):
n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count()
if n_events != keyword.n_events:
print("Updating event number for " + str(keyword.name))
keyword.n_events = n_events
keyword.save(update_fields=("n_events",))
class Migration(migrations.Migration):
dependencies = [
('events', '0034_add_keyword_deprecated'),
]
operations = [
migrations.AddField(
model_name='keyword',
name='n_events',
field=models.IntegerField(db_index=True, default=0, editable=False, help_text='number of events with this keyword', verbose_name='event count'),
),
migrations.AlterField(
model_name='event',
name='audience',
field=models.ManyToManyField(blank=True, related_name='audience_events', to='events.Keyword'),
),
migrations.AlterField(
model_name='event',
name='keywords',
field=models.ManyToManyField(related_name='events', to='events.Keyword'),
),
migrations.RunPython(forward, migrations.RunPython.noop)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-02 15:46
from __future__ import unicode_literals
from django.db import migrations, models
def forward(apps, schema_editor):
Keyword = apps.get_model('events', 'Keyword')
for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None):
n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count()
if n_events != keyword.n_events:
keyword.n_events = n_events
keyword.save(update_fields=("n_events",))
class Migration(migrations.Migration):
dependencies = [
('events', '0034_add_keyword_deprecated'),
]
operations = [
migrations.AddField(
model_name='keyword',
name='n_events',
field=models.IntegerField(db_index=True, default=0, editable=False, help_text='number of events with this keyword', verbose_name='event count'),
),
migrations.AlterField(
model_name='event',
name='audience',
field=models.ManyToManyField(blank=True, related_name='audience_events', to='events.Keyword'),
),
migrations.AlterField(
model_name='event',
name='keywords',
field=models.ManyToManyField(related_name='events', to='events.Keyword'),
),
migrations.RunPython(forward, migrations.RunPython.noop)
]
|
Remove last references to flatpage so it doesnt show up on admin page | # -*- encoding: UTF-8 -*-
from core import settings as stCore
from django import forms
from django.conf import settings as st
from flatpages_i18n.forms import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
| # -*- encoding: UTF-8 -*-
from core import settings as stCore
from django import forms
from django.conf import settings as st
from django.contrib.flatpages.admin import FlatpageForm
from django.contrib.sites.models import Site
from django.forms.widgets import HiddenInput, MultipleHiddenInput
class PageForm(FlatpageForm):
url = forms.CharField(label='', max_length=100, required=False)
sites = forms.ModelMultipleChoiceField(queryset=Site.objects.all(),
required=False, label='')
def __init__(self, *args, **kwargs):
super(FlatpageForm, self).__init__(*args, **kwargs)
self.fields['url'].initial = stCore.BASE_URL_FLATPAGES
self.fields['url'].widget = HiddenInput()
self.fields['sites'].widget = MultipleHiddenInput()
def clean_url(self):
return True
def save(self, commit=True):
flatpage = super(PageForm, self).save(commit=False)
flatpage.save()
flatpage.url = stCore.BASE_URL_FLATPAGES + str(flatpage.id) + '/'
flatpage.sites.add(Site.objects.get(id=st.SITE_ID))
return flatpage
class Meta:
widgets = {
'content': forms.widgets.Textarea(),
}
class Media:
js = (st.TINYMCE_JS_URL, st.TINYMCE_JS_TEXTAREA)
|
FIX Import missing namespace for RunBuildTaskJob | <?php
use Heyday\Elastica\ReindexTask;
use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Jobs\RunBuildTaskJob;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;
/**
* These regular updates run as often as is practical.
* They seem to take 2-3 hours at the moment, so we run them 4 times per day.
*/
class SilverStripeElasticaReindexCron implements CronTask
{
/**
* Run every 6 hours
*
* @return string
*/
public function getSchedule()
{
return "0 */6 * * *";
}
/**
* Run the build task SilverStripeElasticaReindexTask
* @return void
*/
public function process()
{
$taskClasses = [
[UpdateSilverStripeVersionsTask::class, null],
[UpdateAddonsTask::class, null],
[ReindexTask::class, 'reindex=1'],
];
foreach ($taskClasses as $taskInfo) {
list($taskClass, $taskQuerystring) = $taskInfo;
$job = new RunBuildTaskJob($taskClass, $taskQuerystring);
$jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job);
echo 'Added ' . $taskClass . ' to job queue (job ID ' . $jobID . ")\n";
}
}
}
| <?php
use Heyday\Elastica\ReindexTask;
use SilverStripe\Core\Injector\Injector;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\CronTask\Interfaces\CronTask;
/**
* These regular updates run as often as is practical.
* They seem to take 2-3 hours at the moment, so we run them 4 times per day.
*/
class SilverStripeElasticaReindexCron implements CronTask
{
/**
* Run every 6 hours
*
* @return string
*/
public function getSchedule()
{
return "0 */6 * * *";
}
/**
* Run the build task SilverStripeElasticaReindexTask
* @return void
*/
public function process()
{
$taskClasses = [
[UpdateSilverStripeVersionsTask::class, null],
[UpdateAddonsTask::class, null],
[ReindexTask::class, 'reindex=1'],
];
foreach ($taskClasses as $taskInfo) {
list($taskClass, $taskQuerystring) = $taskInfo;
$job = new RunBuildTaskJob($taskClass, $taskQuerystring);
$jobID = Injector::inst()->get(QueuedJobService::class)->queueJob($job);
echo 'Added ' . $taskClass . ' to job queue (job ID ' . $jobID . ")\n";
}
}
}
|
Fix most umd export name
See https://unpkg.com/[email protected]/dist/most.js | /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget: 'umd',
},
externals: {
most: {
root: 'most',
commonjs2: 'most',
commonjs: 'most',
amd: 'most',
},
redux: {
root: 'Redux',
commonjs2: 'redux',
commonjs: 'redux',
amd: 'redux',
},
},
resolve: {
extensions: ['.js'],
mainFields: ['module', 'main', 'jsnext:main'],
},
}
const devConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'development'
}),
],
}
const prodConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.min.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'production'
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
comments: false,
}),
],
}
module.exports = [devConfig, prodConfig]
| /* eslint-disable import/no-commonjs */
const webpack = require('webpack')
const baseConfig = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader'],
exclude: /node_modules/,
},
],
},
output: {
library: 'ReduxMost',
libraryTarget: 'umd',
},
externals: {
most: {
root: 'Most',
commonjs2: 'most',
commonjs: 'most',
amd: 'most',
},
redux: {
root: 'Redux',
commonjs2: 'redux',
commonjs: 'redux',
amd: 'redux',
},
},
resolve: {
extensions: ['.js'],
mainFields: ['module', 'main', 'jsnext:main'],
},
}
const devConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'development'
}),
],
}
const prodConfig = {
...baseConfig,
output: {
...baseConfig.output,
filename: './dist/redux-most.min.js',
},
plugins: [
new webpack.EnvironmentPlugin({
'NODE_ENV': 'production'
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
comments: false,
}),
],
}
module.exports = [devConfig, prodConfig]
|
Add the command that failed to the error log and the error email to help debug problems where the error produces no output. | import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
boto.log.error('Error running command: "%s". Output: "%s"' % (command, self.last_command.output))
if notify:
self.notify('Error encountered', \
'Error running the following command:\n\t%s\n\nCommand output:\n\t%s' % \
(command, self.last_command.output))
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
| import os, sys, time, traceback
import smtplib
from boto.utils import ShellCommand, get_ts
import boto
import boto.utils
class ScriptBase:
def __init__(self, config_file=None):
self.instance_id = boto.config.get('Instance', 'instance-id', 'default')
self.name = self.__class__.__name__
self.ts = get_ts()
if config_file:
boto.config.read(config_file)
def notify(self, subject, body=''):
boto.utils.notify(subject, body)
def mkdir(self, path):
if not os.path.isdir(path):
try:
os.mkdir(path)
except:
boto.log.error('Error creating directory: %s' % path)
def umount(self, path):
if os.path.ismount(path):
self.run('umount %s' % path)
def run(self, command, notify=True, exit_on_error=False):
self.last_command = ShellCommand(command)
if self.last_command.status != 0:
boto.log.error(self.last_command.output)
if notify:
self.notify('Error encountered', self.last_command.output)
if exit_on_error:
sys.exit(-1)
return self.last_command.status
def main(self):
pass
|
Update coverage thresholds to current values | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 97,
statements: 98
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
} | 'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
allFiles: ['Gruntfile.js', 'lib/**/*.js', 'test/**/*.js', 'index.js'],
options: {
jshintrc: '.jshintrc',
}
},
mochacli: {
all: ['test/**/*.js'],
options: {
reporter: 'spec',
ui: 'tdd'
}
},
'mocha_istanbul': {
coveralls: {
src: [ 'test/lib', 'test/lib/utils' ],
options: {
coverage: true,
legend: true,
check: {
lines: 85,
statements: 84
},
root: './lib',
reportFormats: ['lcov']
}
}
}
})
grunt.event.on('coverage', function(lcov, done){
require('coveralls').handleInput(lcov, function(error) {
if (error) {
console.log(error)
return done(error)
}
done()
})
})
// Load the plugins
grunt.loadNpmTasks('grunt-contrib-jshint')
grunt.loadNpmTasks('grunt-mocha-cli')
grunt.loadNpmTasks('grunt-mocha-istanbul')
// Configure tasks
grunt.registerTask('coveralls', ['mocha_istanbul:coveralls'])
grunt.registerTask('default', ['test'])
grunt.registerTask('test', ['mochacli', 'jshint', 'coveralls'])
} |
Include the uuid with the user attributes | <?php
namespace Sil\SilAuth\saml;
class User
{
public static function convertToSamlFieldNames(
string $employeeId,
string $firstName,
string $lastName,
string $username,
string $email,
string $uuid,
string $idpDomainName,
$passwordExpirationDate,
array $mfa
) {
return [
'eduPersonPrincipalName' => [
$username . '@' . $idpDomainName,
],
/**
* Misspelled version of eduPersonTargetedID.
* @deprecated
*/
'eduPersonTargetID' => (array)$uuid, // Incorrect, deprecated
/**
* NOTE: Do NOT include eduPersonTargetedID. If you need it, use the core:TargetedID module, ideally at the
* Hub, to generate an eduPersonTargetedID.
*/
'sn' => (array)$lastName,
'givenName' => (array)$firstName,
'mail' => (array)$email,
'employeeNumber' => (array)$employeeId,
'cn' => (array)$username,
'schacExpiryDate' => (array)$passwordExpirationDate,
'mfa' => $mfa,
'uuid' => (array)$uuid,
];
}
}
| <?php
namespace Sil\SilAuth\saml;
class User
{
public static function convertToSamlFieldNames(
string $employeeId,
string $firstName,
string $lastName,
string $username,
string $email,
string $uuid,
string $idpDomainName,
$passwordExpirationDate,
array $mfa
) {
return [
'eduPersonPrincipalName' => [
$username . '@' . $idpDomainName,
],
/**
* Misspelled version of eduPersonTargetedID.
* @deprecated
*/
'eduPersonTargetID' => (array)$uuid, // Incorrect, deprecated
/**
* NOTE: Do NOT include eduPersonTargetedID. If you need it, use the core:TargetedID module, ideally at the
* Hub, to generate an eduPersonTargetedID.
*/
'sn' => (array)$lastName,
'givenName' => (array)$firstName,
'mail' => (array)$email,
'employeeNumber' => (array)$employeeId,
'cn' => (array)$username,
'schacExpiryDate' => (array)$passwordExpirationDate,
'mfa' => $mfa,
];
}
}
|
Work around issue with coveralls lib. | /*
* grunt-contrib-jshint
* http://gruntjs.com/
*
* Copyright (c) 2015 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'tasks/**/*.js', 'test/**/*.js'],
options: {
jshintrc: true
}
},
mocha_istanbul: {
coverage: {
src: 'test/**/*.spec.js',
options: {
coverageFolder: 'build/coverage',
reportFormats: ['lcov'],
}
}
},
lcovMerge: {
options: {
emitters: ['file', 'event'],
outputFile: 'out.lcov'
},
files: ['build/coverage/*.info', 'build/coverage/**/*.info']
}
});
grunt.event.on('coverage', function(lcov, done) {
// Coveralls uses argv to set the basePath
var oldArgv = process.argv[2];
process.argv[2] = '';
require('coveralls').handleInput(lcov, function(err) {
process.argv[2] = oldArgv;
if (err) {
return done(err);
}
done();
});
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-istanbul');
grunt.registerTask('ci', ['jshint', 'mocha_istanbul', 'lcovMerge']);
grunt.registerTask('default', ['jshint', 'mocha_istanbul']);
}; | /*
* grunt-contrib-jshint
* http://gruntjs.com/
*
* Copyright (c) 2015 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'tasks/**/*.js', 'test/**/*.js'],
options: {
jshintrc: true
}
},
mocha_istanbul: {
coverage: {
src: 'test/**/*.spec.js',
options: {
coverageFolder: 'build/coverage',
reportFormats: ['lcov'],
}
}
},
lcovMerge: {
options: {
emitters: ['event']
},
files: ['build/coverage/*.info', 'build/coverage/**/*.info']
}
});
grunt.event.on('coverage', function(lcov, done) {
require('coveralls').handleInput(lcov, function(err) {
if (err) {
return done(err);
}
done();
});
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-istanbul');
grunt.registerTask('ci', ['jshint', 'mocha_istanbul', 'lcovMerge']);
grunt.registerTask('default', ['jshint', 'mocha_istanbul']);
}; |
Enable task addition to the database | angular.module('MainApp')
.controller('FabControl', ($mdToast, $mdDialog, $scope, addToDB) => {
$scope.addNew = (ev) => {
$mdDialog.show({
controller: DialogController,
templateUrl: 'templates/newTaskDialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
closeTo: {
top: 520,
left: 0,
width: 40,
height: 30
}
})
.then(task => {
addToDB(task);
$mdToast.show(
$mdToast.simple()
.textContent('Task added.')
.position('bottom start')
);
}, () => {
console.log('Empty task. Ignoring.');
});
}
function DialogController($scope, $mdDialog) {
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.add = function(task) {
if (task) {
$mdDialog.hide(task);
}
};
}
});
| angular.module('MainApp')
.controller('FabControl', ($mdToast, $mdDialog, $scope, addToDB) => {
$scope.addNew = (ev) => {
$mdDialog.show({
controller: DialogController,
templateUrl: 'templates/newTaskDialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
closeTo: {
top: 520,
left: 0,
width: 40,
height: 30
}
})
.then(task => {
// addToDB(task);
// $mdToast.show(
// $mdToast.simple()
// .textContent('Task added.')
// .position('bottom start')
// );
}, () => {
console.log('Empty task. Ignoring.');
});
}
function DialogController($scope, $mdDialog) {
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.add = function(task) {
if (task) {
$mdDialog.hide(task);
}
};
}
});
|
Fix unable to revert resolving of SQLinjection
[1] Revert back code for replaceAll
[2] Revert 2 resolve strings one by one |
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
return this.stringConcat('0', dateTimeNumber);
}
}
return dateTimeNumber;
};
this.replaceAll = function replaceAll(string, stringToReplace, replacement) {
return string.replace(new RegExp(stringToReplace, 'g'), replacement);
};
this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) {
return stringToReplace.replace(/["\\]/g, (char) => {
switch (char) {
case '"':
case '\\':
return `\\${char}`; // prepends a backslash to backslash, percent,
// and double/single quotes
default:
return char;
}
});
};
this.revertSQLInjections = function revertSQLInjections(stringToReplace) {
stringToReplace = this.replaceAll(stringToReplace, '\\\\"', '"');
stringToReplace = this.replaceAll(stringToReplace, '\\\\\\\\', '\\');
return stringToReplace;
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) {
const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash
return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder);
};
}
|
export default function stringManipulation() {
this.stringConcat = function stringConcat(...stringToConcat) {
return stringToConcat.join('');
};
this.stringDateTime00Format = function stringDateTime00Format(dateTimeNumber) {
if (typeof dateTimeNumber == 'number') {
if (dateTimeNumber < 10) {
return this.stringConcat('0', dateTimeNumber);
}
}
return dateTimeNumber;
};
this.resolveSQLInjections = function resolveSQLInjections(stringToReplace) {
return stringToReplace.replace(/["'\\]/g, (char) => {
switch (char) {
case '"':
case '\\':
return `\\${char}`; // prepends a backslash to backslash, percent,
// and double/single quotes
default:
return char;
}
});
};
this.revertSQLInjections = function revertSQLInjections(stringToReplace) {
return stringToReplace.replace(/[\\\\"\\\\\\\\]/g, (char) => {
switch (char) {
case '\\\\"':
return '"';
case '\\\\\\\\':
return '\\'; // prepends a backslash to backslash, percent,
// and double/single quotes
default:
return char;
}
});
};
this.getPreviousPath = function getPreviousPath(fullPath, lastFolderName) {
const lengthOfExtraCurrentFolder = lastFolderName.length + 1; // extra slash
return fullPath.substring(0, fullPath.length - lengthOfExtraCurrentFolder);
};
}
|
Add require statement for api | var api = require('./api');
module.exports = {
login(username, password, callback) {
api.login(username, password)
.then((response) => {
if(response.status === 400){
if(callback) {
callback(false);
}
} else if (response.status === 200) {
console.log("$$$$$$$$", document.cookie);
response.json()
.then(function(body) {
localStorage.token = true;
if(callback) {
callback(true);
}
});
}
})
.catch((err) => {
console.error('Error with login' + err);
});
},
logout(callback) {
delete localStorage.token;
api.logout()
.then(() => {
if (callback) {
callback();
}
});
},
loggedIn() {
return !!localStorage.token
},
checkForSession(next) {
delete localStorage.token;
return api.checkForSession()
.then((response) => {
if(response.status === 200) {
response.json().then((data) => {
if(data) {
localStorage.token = true;
}
next(data);
});
}
})
.catch((err) => {
console.error('Error checking session', err);
next(false);
});
// send api request to protected route
// if response.status === 401, i don't have access
// return false;
// else,
// localStorage.token = true;
// it will return userID / login data
}
} |
module.exports = {
login(username, password, callback) {
api.login(username, password)
.then((response) => {
if(response.status === 400){
if(callback) {
callback(false);
}
} else if (response.status === 200) {
console.log("$$$$$$$$", document.cookie);
response.json()
.then(function(body) {
localStorage.token = true;
if(callback) {
callback(true);
}
});
}
})
.catch((err) => {
console.error('Error with login' + err);
});
},
logout(callback) {
delete localStorage.token;
api.logout()
.then(() => {
if (callback) {
callback();
}
});
},
loggedIn() {
return !!localStorage.token
},
checkForSession(next) {
delete localStorage.token;
return api.checkForSession()
.then((response) => {
if(response.status === 200) {
response.json().then((data) => {
if(data) {
localStorage.token = true;
}
next(data);
});
}
})
.catch((err) => {
console.error('Error checking session', err);
next(false);
});
// send api request to protected route
// if response.status === 401, i don't have access
// return false;
// else,
// localStorage.token = true;
// it will return userID / login data
}
} |
Add link explaining why componentWillMount is used. | import './app.styl';
import * as state from '../state';
import Component from '../components/component.react';
import Footer from './footer.react';
import Menu from './menu.react';
import React from 'react';
import persistState from './persiststate.react';
import {RouteHandler} from 'react-router';
// Remember to import all app stores here.
import '../auth/store';
import '../todos/store';
import '../users/store';
class App extends Component {
constructor(props) {
super(props);
this.state = this.getState();
}
getState() {
return {
auth: state.authCursor(),
pendingActions: state.pendingActionsCursor(),
todos: state.todosCursor(),
users: state.usersCursor(),
viewer: state.usersCursor().get('viewer')
};
}
// https://github.com/steida/este/issues/274
componentWillMount() {
if (!process.env.IS_BROWSER) return;
state.state.on('change', () => {
if ('production' !== process.env.NODE_ENV)
console.time('app render'); // eslint-disable-line no-console
this.setState(this.getState(), () => {
if ('production' !== process.env.NODE_ENV)
console.timeEnd('app render'); // eslint-disable-line no-console
});
});
}
render() {
return (
<div className="page">
<Menu viewer={this.state.viewer} />
<RouteHandler {...this.state} />
<Footer />
</div>
);
}
}
App = persistState(App);
export default App;
| import './app.styl';
import * as state from '../state';
import Component from '../components/component.react';
import Footer from './footer.react';
import Menu from './menu.react';
import React from 'react';
import persistState from './persiststate.react';
import {RouteHandler} from 'react-router';
// Remember to import all app stores here.
import '../auth/store';
import '../todos/store';
import '../users/store';
class App extends Component {
constructor(props) {
super(props);
this.state = this.getState();
}
getState() {
return {
auth: state.authCursor(),
pendingActions: state.pendingActionsCursor(),
todos: state.todosCursor(),
users: state.usersCursor(),
viewer: state.usersCursor().get('viewer')
};
}
componentWillMount() {
if (!process.env.IS_BROWSER) return;
state.state.on('change', () => {
if ('production' !== process.env.NODE_ENV)
console.time('app render'); // eslint-disable-line no-console
this.setState(this.getState(), () => {
if ('production' !== process.env.NODE_ENV)
console.timeEnd('app render'); // eslint-disable-line no-console
});
});
}
render() {
return (
<div className="page">
<Menu viewer={this.state.viewer} />
<RouteHandler {...this.state} />
<Footer />
</div>
);
}
}
App = persistState(App);
export default App;
|
Use play scene if no show scene for filtering in admin | "use strict";
let Schedule = require('models/schedule');
module.exports = function(router) {
router.get('/', function (req, res, next) {
if (!req.filter) return next();
let filter = req.filter;
Schedule.findOne(filter)
.populate('shows.theatre shows.scene shows.play')
.exec(function (err, schedule) {
if (err) return next(err);
if (schedule) {
schedule.shows = filterScheduleShows(schedule, req);
}
let viewFilter = req.query;
viewFilter.month = viewFilter.month || schedule.monthKey;
res.render('admin/schedule/view', {
title: 'Управление — Расписание',
schedule: schedule,
filter: viewFilter,
theatres: req.options.theatres,
scenes: req.options.scenes,
months: req.options.months,
versions: req.options.versions,
});
});
});
function filterScheduleShows(schedule, req) {
return schedule.shows.filter(function (show) {
const scene = show.scene || show.play.scene;
return (!req.query.theatre || req.query.theatre === String(show.theatre.id)) &&
(!req.query.scene || req.query.scene === String(scene.id))
});
}
}; | "use strict";
let Schedule = require('models/schedule');
module.exports = function(router) {
router.get('/', function (req, res, next) {
if (!req.filter) return next();
let filter = req.filter;
Schedule.findOne(filter)
.populate('shows.theatre shows.scene shows.play')
.exec(function (err, schedule) {
if (err) return next(err);
if (schedule) {
schedule.shows = filterScheduleShows(schedule, req);
}
let viewFilter = req.query;
viewFilter.month = viewFilter.month || schedule.monthKey;
res.render('admin/schedule/view', {
title: 'Управление — Расписание',
schedule: schedule,
filter: viewFilter,
theatres: req.options.theatres,
scenes: req.options.scenes,
months: req.options.months,
versions: req.options.versions,
});
});
});
function filterScheduleShows(schedule, req) {
return schedule.shows.filter(function (show) {
return (!req.query.theatre || req.query.theatre === String(show.theatre.id)) &&
(!req.query.scene || req.query.scene === String(show.scene.id))
});
}
}; |
Use [job.title] as genealogy of input_handler.save while submit job. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions.
"""
# built-in modules
import json
# 3rd-party modules
from botocore.client import Config
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
if scheduler != 'swf':
raise UnsupportedScheduler(scheduler)
from mass.scheduler.swf import config
import boto3
client = boto3.client(
'swf',
region_name=config.REGION,
config=Config(connect_timeout=config.CONNECT_TIMEOUT,
read_timeout=config.READ_TIMEOUT))
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
genealogy=[job.title]
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions.
"""
# built-in modules
import json
# 3rd-party modules
from botocore.client import Config
# local modules
from mass.exception import UnsupportedScheduler
from mass.input_handler import InputHandler
def submit(job, protocol=None, priority=1, scheduler='swf'):
"""Submit mass job to SWF with specific priority.
"""
if scheduler != 'swf':
raise UnsupportedScheduler(scheduler)
from mass.scheduler.swf import config
import boto3
client = boto3.client(
'swf',
region_name=config.REGION,
config=Config(connect_timeout=config.CONNECT_TIMEOUT,
read_timeout=config.READ_TIMEOUT))
handler = InputHandler(protocol)
res = client.start_workflow_execution(
domain=config.DOMAIN,
workflowId=job.title,
workflowType=config.WORKFLOW_TYPE_FOR_JOB,
taskList={'name': config.DECISION_TASK_LIST},
taskPriority=str(priority),
input=json.dumps({
'protocol': protocol,
'body': handler.save(
data=job,
job_title=job.title,
task_title=job.title
)
}),
executionStartToCloseTimeout=str(config.WORKFLOW_EXECUTION_START_TO_CLOSE_TIMEOUT),
tagList=[job.title],
taskStartToCloseTimeout=str(config.DECISION_TASK_START_TO_CLOSE_TIMEOUT),
childPolicy=config.WORKFLOW_CHILD_POLICY)
return job.title, res['runId']
|
Add output of command in hex | #!/usr/bin/env python
# Copyright 2014 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from subprocess import Popen,PIPE
import shlex
import logging
class ExecProc:
def __init__(self):
self.command = None
self.debug = False
def setDebug(self,debug):
self.debug = debug
def setCommand(self,command):
if type(command) != str:
raise ValueError
self.command = command
def execute(self):
if self.command == None:
raise ValueError
# Remove Carriage Returns
command = self.command.strip('\r')
args = shlex.split(command)
if self.debug == True:
logging.info("command=\"%s\"",args)
p = Popen(args,stdout=PIPE)
o,e = p.communicate()
if self.debug == True:
logging.info("output=\"%s\"",o)
logging.info(':'.join(x.encode('hex') for x in o))
return o
| #!/usr/bin/env python
# Copyright 2014 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from subprocess import Popen,PIPE
import shlex
import logging
class ExecProc:
def __init__(self):
self.command = None
self.debug = False
def setDebug(self,debug):
self.debug = debug
def setCommand(self,command):
if type(command) != str:
raise ValueError
self.command = command
def execute(self):
if self.command == None:
raise ValueError
args = shlex.split(self.command)
if self.debug == True:
logging.info("command=\"%s\"",self.command)
p = Popen(args,stdout=PIPE)
o,e = p.communicate()
if self.debug == True:
logging.info("output=\"%s\"",o)
return o |
Remove promise where not needed | (function(){
var mod = angular.module('caspy.api', ['ngResource', 'caspy.server']);
mod.config(['$resourceProvider',
function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]
);
mod.factory('caspyAPI',
['$q', '$http', '$resource', 'Constants',
function($q, $http, $resource, Constants) {
var api = {
root: null
, resources: {}
, resolve: function(name) {
var d = $q.defer();
if (typeof api.root[name] === 'undefined') {
d.reject(new Error(name + ' endpoint not available'));
}
else {
d.resolve(api.root[name]);
}
return d.promise;
}
, get_endpoint: function(name) {
if (api.root)
return api.resolve(name);
return $http.get(Constants.apiRootUrl)
.then(function(response) {
api.root = response.data;
return api.resolve(name);
})
}
, get_resource: function(name) {
return api.get_endpoint(name)
.then(api.build_resource);
}
, build_resource: function(endpoint) {
return $resource(endpoint + ':item/');
}
};
return api;
}]
);
})();
| (function(){
var mod = angular.module('caspy.api', ['ngResource', 'caspy.server']);
mod.config(['$resourceProvider',
function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]
);
mod.factory('caspyAPI',
['$q', '$http', '$resource', 'Constants',
function($q, $http, $resource, Constants) {
var api = {
root: null
, resources: {}
, resolve: function(name) {
var d = $q.defer();
if (typeof api.root[name] === 'undefined') {
d.reject(new Error(name + ' endpoint not available'));
}
else {
d.resolve(api.root[name]);
}
return d.promise;
}
, get_endpoint: function(name) {
if (api.root)
return api.resolve(name);
return $http.get(Constants.apiRootUrl)
.then(function(response) {
api.root = response.data;
return api.resolve(name);
})
}
, get_resource: function(name) {
return api.get_endpoint(name)
.then(api.build_resource);
}
, build_resource: function(endpoint) {
var d = $q.defer();
d.resolve($resource(endpoint + ':item/'));
return d.promise;
}
};
return api;
}]
);
})();
|
Enable remote, rmessage and rnotify plugins by default | # Module: defaults
# Date: 14th May 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""defaults - System Defaults
This module contains default configuration and sane defaults for various
parts of the system. These defaults are used by the environment initially
when no environment has been created.
"""
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
"remote.*": "enabled",
"rmessage.*": "enabled",
"rnotify.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
| # Module: defaults
# Date: 14th May 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""defaults - System Defaults
This module contains default configuration and sane defaults for various
parts of the system. These defaults are used by the environment initially
when no environment has been created.
"""
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
|
Clone the attribution link, which is alreaady an <a> in order to get the correct link. | "use strict";
angular.module("hikeio").
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
var context = {
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
var attributionLink = this.element.attr("data-attribution-link");
if (attributionLink) {
var anchor = $(".attribution-link").clone();
anchor.attr("href", attributionLink);
anchor.click(function(event) {
event.stopPropagation();
});
$(".fancybox-inner").append(anchor);
}
},
afterClose: function(current, previous) {
$rootScope.$broadcast("fancyboxClosed");
},
padding : 2,
nextEffect : "none",
prevEffect : "none",
closeEffect : "none",
closeBtn : true,
arrows : false,
keys : true,
nextClick : true
};
scope.$on("$routeChangeStart", function () {
$.fancybox.close();
});
scope.$on("fancyboxClose", function () {
$.fancybox.close();
});
scope.$on("$destroy", function () {
context.afterLoad = null;
context.afterClose = null;
});
$(element).find(attrs.fancybox).fancybox(context);
}
};
}]); | "use strict";
angular.module("hikeio").
directive("fancybox", ["$rootScope", function($rootScope) {
return {
link: function (scope, element, attrs) {
var context = {
afterLoad: function(current, previous) {
$rootScope.$broadcast("fancyboxLoaded");
var attributionLink = this.element.attr("data-attribution-link");
if (attributionLink) {
var anchor = $("<a href='" + attributionLink + "'>");
anchor.append($(".attribution-link").clone());
anchor.click(function(event) {
event.stopPropagation();
});
$(".fancybox-inner").append(anchor);
}
},
afterClose: function(current, previous) {
$rootScope.$broadcast("fancyboxClosed");
},
padding : 2,
nextEffect : "none",
prevEffect : "none",
closeEffect : "none",
closeBtn : true,
arrows : false,
keys : true,
nextClick : true
};
scope.$on("$routeChangeStart", function () {
$.fancybox.close();
});
scope.$on("fancyboxClose", function () {
$.fancybox.close();
});
scope.$on("$destroy", function () {
context.afterLoad = null;
context.afterClose = null;
});
$(element).find(attrs.fancybox).fancybox(context);
}
};
}]); |
Make slide start and end optional | <?php
namespace Zeropingheroes\Lanager\Requests;
class StoreSlideRequest extends Request
{
use LaravelValidation;
/**
* Whether the request is valid
*
* @return bool
*/
public function valid(): bool
{
$this->validationRules = [
'lan_id' => ['required', 'numeric', 'exists:lans,id'],
'name' => ['required', 'max:255'],
'content' => ['required'],
'position' => ['integer', 'min:0', 'max:127'],
'duration' => ['integer', 'min:0', 'max:32767'],
'start' => ['nullable', 'date_format:Y-m-d H:i:s', 'before:end'],
'end' => ['nullable', 'date_format:Y-m-d H:i:s', 'after:start'],
'published' => ['boolean'],
];
if (!$this->laravelValidationPasses()) {
return $this->setValid(false);
}
return $this->setValid(true);
}
} | <?php
namespace Zeropingheroes\Lanager\Requests;
class StoreSlideRequest extends Request
{
use LaravelValidation;
/**
* Whether the request is valid
*
* @return bool
*/
public function valid(): bool
{
$this->validationRules = [
'lan_id' => ['required', 'numeric', 'exists:lans,id'],
'name' => ['required', 'max:255'],
'content' => ['required'],
'position' => ['integer', 'min:0', 'max:127'],
'duration' => ['integer', 'min:0', 'max:32767'],
'start' => ['required', 'date_format:Y-m-d H:i:s', 'before:end'],
'end' => ['required', 'date_format:Y-m-d H:i:s', 'after:start'],
'published' => ['boolean'],
];
if (!$this->laravelValidationPasses()) {
return $this->setValid(false);
}
return $this->setValid(true);
}
} |
Support only python >= 3.4 | import os
import re
import sys
from setuptools import setup, find_packages
PY_VER = sys.version_info
if PY_VER >= (3, 4):
pass
else:
raise RuntimeError("Only support Python version >= 3.4")
def get_version():
with open(os.path.join(os.path.dirname(__file__), 'gitlab_mr.py')) as f:
for line in f.readlines():
m = re.match(r"__version__ = '(.*?)'", line)
if m:
return m.group(1)
raise ValueError('Cannot find version')
def parse_requirements(req_file_path):
with open(req_file_path) as f:
return f.readlines()
setup(
name="gitlab-merge-request",
version=get_version(),
author="Alexander Koval",
author_email="[email protected]",
description=("Console utility to create gitlab merge requests."),
license="Apache License 2.0",
keywords="git gitlab merge-request",
url="https://github.com/anti-social/gitlab-merge-request",
py_modules=[
'gitlab_mr',
],
entry_points = {
'console_scripts': ['gitlab-mr = gitlab_mr:main'],
},
install_requires=parse_requirements('requirements.txt'),
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Environment :: Console",
"Topic :: Software Development :: Version Control",
"Topic :: Utilities",
],
)
| import os
import re
from setuptools import setup, find_packages
def get_version():
with open(os.path.join(os.path.dirname(__file__), 'gitlab_mr.py')) as f:
for line in f.readlines():
m = re.match(r"__version__ = '(.*?)'", line)
if m:
return m.group(1)
raise ValueError('Cannot find version')
def parse_requirements(req_file_path):
with open(req_file_path) as f:
return f.readlines()
setup(
name="gitlab-merge-request",
version=get_version(),
author="Alexander Koval",
author_email="[email protected]",
description=("Console utility to create gitlab merge requests."),
license="Apache License 2.0",
keywords="git gitlab merge-request",
url="https://github.com/anti-social/gitlab-merge-request",
py_modules=[
'gitlab_mr',
],
entry_points = {
'console_scripts': ['gitlab-mr = gitlab_mr:main'],
},
install_requires=parse_requirements('requirements.txt'),
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Environment :: Console",
"Topic :: Software Development :: Version Control",
"Topic :: Utilities",
],
)
|
Correct docs on RabbitMQ crash source. | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
"""An iterable of crashes from RabbitMQ"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
"""Return an iterator over crashes from RabbitMQ.
Each crash is a tuple of the ``(args, kwargs)`` variety. The lone arg
is a crash ID, and the kwargs contain only a callback function which
the FTS app will call to send an ack to Rabbit after processing is
complete.
"""
for a_crash_id in self.crash_store.new_crashes():
yield (
(a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
| # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from configman import Namespace, RequiredConfig
from configman.converters import class_converter
from functools import partial
#==============================================================================
class RMQNewCrashSource(RequiredConfig):
"""this class is a refactoring of the iteratior portion of the legacy
Socorro processor. It isolates just the part of fetching the ooids of
jobs to be processed"""
required_config = Namespace()
required_config.source.add_option(
'crashstorage_class',
doc='the source storage class',
default='socorro.external.rabbitmq.crashstorage.RabbitMQCrashStorage',
from_string_converter=class_converter
)
#--------------------------------------------------------------------------
def __init__(self, config, processor_name, quit_check_callback=None):
self.config = config
self.crash_store = config.crashstorage_class(config)
#--------------------------------------------------------------------------
def close(self):
pass
#--------------------------------------------------------------------------
def __iter__(self):
"""an adapter that allows this class can serve as an iterator in a
fetch_transform_save app"""
for a_crash_id in self.crash_store.new_crashes():
yield (
(a_crash_id,),
{'finished_func': partial(
self.crash_store.ack_crash,
a_crash_id
)}
)
#--------------------------------------------------------------------------
def __call__(self):
return self.__iter__()
|
Fix name of index created for tests. | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)], stderr=subprocess.STDOUT)
try:
yield 'http://localhost:{}'.format(port)
finally:
subprocess.check_output(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)], stderr=subprocess.STDOUT)
finally:
shutil.rmtree(server_dir)
@contextlib.contextmanager
def devpi_index(server_url, user, index):
"""
Creates the given user and index, and cleans it afterwards.
Yields of tuple of index-url and password. The index is created without an upstream.
"""
password = 'foo'
with devpi.Client(server_url) as devpi_client:
devpi_client._execute('user', '-c', user, 'password=' + password)
devpi_client._execute('login', user, '--password=' + password)
devpi_client._execute('index', '-c', index, 'bases=')
yield '{}/{}/{}'.format(server_url, user, index), password
devpi_client._execute('index', '--delete', '/{}/{}'.format(user, index))
devpi_client._execute('user', user, '--delete')
| # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--start', '--serverdir={}'.format(server_dir), '--port={}'.format(port)], stderr=subprocess.STDOUT)
try:
yield 'http://localhost:{}'.format(port)
finally:
subprocess.check_output(['devpi-server', '--stop', '--serverdir={}'.format(server_dir)], stderr=subprocess.STDOUT)
finally:
shutil.rmtree(server_dir)
@contextlib.contextmanager
def devpi_index(server_url, user, index):
"""
Creates the given user and index, and cleans it afterwards.
Yields of tuple of index-url and password. The index is created without an upstream.
"""
password = 'foo'
with devpi.Client(server_url) as devpi_client:
devpi_client._execute('user', '-c', user, 'password=' + password)
devpi_client._execute('login', user, '--password=' + password)
devpi_client._execute('index', '-c', 'wheels', 'bases=')
yield '{}/{}/{}'.format(server_url, user, index), password
devpi_client._execute('index', '--delete', '/{}/{}'.format(user, index))
devpi_client._execute('user', user, '--delete')
|
Replace "question" with "step" in Newtrip buttons | function set_correct_origin(prev, last) {
$(last).find("input[id*='origin_auto']").prop("disabled", true).val($(prev).find("input[id*='destination_auto']").val());
$(last).find("input[type='number'][id*='origin']").val($(prev).find("input[type='number'][id*='destination']").val());
}
$(function () {
$(".inline." + formset_prefix).formset({
prefix: formset_prefix, // The form prefix for your django formset
addCssClass: "btn btn-success btn-block step-add", // CSS class applied to the add link
deleteCssClass: "btn btn-success btn-block step-delete", // CSS class applied to the delete link
addText: 'Add another step', // Text for the add link
deleteText: 'Remove step above', // Text for the delete link
formCssClass: 'inline-form', // CSS class applied to each form in a formset
added: function (row) {
add_autocomplete(row);
var forms = $(".inline." + formset_prefix);
var prev_form = forms.get(forms.length - 2);
set_correct_origin(prev_form, row);
},
removed: function (row) {
var forms = $(".inline." + formset_prefix);
forms.first().find("input").prop("disabled", false);
if ($('#id_' + formset_prefix + '-TOTAL_FORMS').val() != 1) {
set_correct_origin(forms.get(forms.length - 2), forms.get(forms.length - 1));
}
}
})
}); | function set_correct_origin(prev, last) {
$(last).find("input[id*='origin_auto']").prop("disabled", true).val($(prev).find("input[id*='destination_auto']").val());
$(last).find("input[type='number'][id*='origin']").val($(prev).find("input[type='number'][id*='destination']").val());
}
$(function () {
$(".inline." + formset_prefix).formset({
prefix: formset_prefix, // The form prefix for your django formset
addCssClass: "btn btn-success btn-block step-add", // CSS class applied to the add link
deleteCssClass: "btn btn-success btn-block step-delete", // CSS class applied to the delete link
addText: 'Add another question', // Text for the add link
deleteText: 'Remove question above', // Text for the delete link
formCssClass: 'inline-form', // CSS class applied to each form in a formset
added: function (row) {
add_autocomplete(row);
var forms = $(".inline." + formset_prefix);
var prev_form = forms.get(forms.length - 2);
set_correct_origin(prev_form, row);
},
removed: function (row) {
var forms = $(".inline." + formset_prefix);
forms.first().find("input").prop("disabled", false);
if ($('#id_' + formset_prefix + '-TOTAL_FORMS').val() != 1) {
set_correct_origin(forms.get(forms.length - 2), forms.get(forms.length - 1));
}
}
})
}); |
Make the cookie only add pages lazily | /* Collapse remember
* Use a cookie to "remember" the state of bootstrap collapse divs
* use the 'collapse-remember' class to get this functionality
*/
$(document).ready(function () {
const state_cookie_c = 'collapse-remember';
var page = window.location.pathname;
var state = Cookies.getJSON(state_cookie_c);
if (state === undefined) {
state = {};
Cookies.set(state_cookie_c, state);
}
if (state.hasOwnProperty(page)) {
Object.keys(state[page]).forEach(function (collapse_id) {
if (state[page][collapse_id]) {
console.log('showing: '+collapse_id);
$('#'+collapse_id).addClass('show');
}
});
}
$(".collapse-remember").on('shown.bs.collapse', function () {
state = Cookies.getJSON(state_cookie_c);
if (state[page] === undefined) {
state[page] = {};
}
var id = $(this).attr('id');
console.log('Shown: ' + id);
state[page][id] = true;
Cookies.set(state_cookie_c, state);
});
$(".collapse-remember").on('hidden.bs.collapse', function () {
state = Cookies.getJSON(state_cookie_c);
if (state[page] === undefined) {
state[page] = {};
}
var id = $(this).attr('id');
console.log('Hidden: ' + id);
state[page][id] = false;
Cookies.set(state_cookie_c, state);
});
});
| /* Collapse remember
* Use a cookie to "remember" the state of bootstrap collapse divs
* use the 'collapse-remember' class to get this functionality
*/
$(document).ready(function () {
const state_cookie_c = 'collapse-remember';
var page = window.location.pathname;
var state = Cookies.getJSON(state_cookie_c);
if (state === undefined) {
state = {};
Cookies.set(state_cookie_c, state);
}
if (state[page] === undefined) {
state[page] = {};
Cookies.set(state_cookie_c, state);
}
Object.keys(state[page]).forEach(function (collapse_id) {
if (state[page][collapse_id]) {
console.log('showing: '+collapse_id);
$('#'+collapse_id).addClass('show');
}
});
$(".collapse-remember").on('shown.bs.collapse', function () {
var id = $(this).attr('id');
console.log('Shown: ' + id);
state = Cookies.getJSON(state_cookie_c);
state[page][id] = true;
Cookies.set(state_cookie_c, state);
});
$(".collapse-remember").on('hidden.bs.collapse', function () {
var id = $(this).attr('id');
console.log('Hidden: ' + id);
state = Cookies.getJSON(state_cookie_c);
state[page][id] = false;
Cookies.set(state_cookie_c, state);
});
});
|
Fix bad habit caused by c++ programming | package com.skelril.aurora.prayer.PrayerFX;
import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Author: Turtle9598
*/
public class InventoryFX extends AbstractPrayer {
private int type, amount;
public InventoryFX() {
super();
this.type = BlockID.DIRT;
this.amount = 1;
}
public InventoryFX(int type, int amount) {
super();
this.type = type;
this.amount = amount;
}
@Override
public PrayerType getType() {
return PrayerType.INVENTORY;
}
@Override
public void add(Player player) {
ItemStack held = player.getItemInHand().clone();
ItemStack stack = new ItemStack(type, ChanceUtil.getRandom(amount));
if (held != null && held.getTypeId() != BlockID.AIR && !held.isSimilar(stack)) {
Item item = player.getWorld().dropItem(player.getLocation(), held);
item.setPickupDelay(20 * 5);
}
player.setItemInHand(stack);
}
@Override
public void clean(Player player) {
// Nothing to do here
}
}
| package com.skelril.aurora.prayer.PrayerFX;
import com.sk89q.worldedit.blocks.BlockID;
import com.skelril.aurora.prayer.PrayerType;
import com.skelril.aurora.util.ChanceUtil;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Author: Turtle9598
*/
public class InventoryFX extends AbstractPrayer {
int type, amount;
public InventoryFX() {
super();
this.type = BlockID.DIRT;
this.amount = 1;
}
public InventoryFX(int type, int amount) {
super();
this.type = type;
this.amount = amount;
}
@Override
public PrayerType getType() {
return PrayerType.INVENTORY;
}
@Override
public void add(Player player) {
ItemStack held = player.getItemInHand().clone();
ItemStack stack = new ItemStack(type, ChanceUtil.getRandom(amount));
if (held != null && held.getTypeId() != BlockID.AIR && !held.isSimilar(stack)) {
Item item = player.getWorld().dropItem(player.getLocation(), held);
item.setPickupDelay(20 * 5);
}
player.setItemInHand(stack);
}
@Override
public void clean(Player player) {
// Nothing to do here
}
}
|
Make the alarm list in Vitrage Topology view related to the selected entity
Change-Id: I1de754ada13262ffa0f7a76de2c1b390f31a36f6
story: #2004725
task: # 28763 | angular
.module('horizon.dashboard.project.vitrage')
.directive('hzAlarms', hzAlarms);
function hzAlarms() {
var directive = {
templateUrl: STATIC_URL + 'dashboard/project/components/alarms/alarms.html',
restrict: 'E',
scope: {
selected: '='
},
controller: AlarmsController,
controllerAs: 'alarmsCtrl'
};
AlarmsController.$inject = ['$scope', 'modalSrv', 'timeSrv', 'vitrageTopologySrv'];
return directive;
function AlarmsController($scope, modalSrv, timeSrv, vitrageTopologySrv) {
var alarmsCtrl = this;
alarmsCtrl.timezone = timeSrv.getHorizonTimezone();
alarmsCtrl.dateFormat = timeSrv.longDateFormat;
$scope.$watch('selected', function(newData, oldData) {
if (newData != oldData) {
console.log('selected ', newData);
var config = {vitrage_id: newData.vitrage_id};
vitrageTopologySrv.getAlarms(config).then(function(result) {
alarmsCtrl.computeAlarms = result.data;
});
}
});
alarmsCtrl.onAlarmClick = function(alarm) {
var modalOptions = {
animation: true,
templateUrl: STATIC_URL + 'dashboard/project/components/rca/rcaContainer.html',
controller: 'RcaContainerController',
windowClass: 'app-modal-window',
resolve: {alarm: function() {
return alarm;
}}
};
modalSrv.show(modalOptions);
}
}
}
| angular
.module('horizon.dashboard.project.vitrage')
.directive('hzAlarms', hzAlarms);
function hzAlarms() {
var directive = {
templateUrl: STATIC_URL + 'dashboard/project/components/alarms/alarms.html',
restrict: 'E',
scope: {
selected: '='
},
controller: AlarmsController,
controllerAs: 'alarmsCtrl'
};
AlarmsController.$inject = ['$scope', 'modalSrv', 'timeSrv', 'vitrageTopologySrv'];
return directive;
function AlarmsController($scope, modalSrv, timeSrv, vitrageTopologySrv) {
var alarmsCtrl = this;
alarmsCtrl.timezone = timeSrv.getHorizonTimezone();
alarmsCtrl.dateFormat = timeSrv.longDateFormat;
$scope.$watch('selected', function(newData, oldData) {
if (newData != oldData) {
console.log('selected ', newData);
vitrageTopologySrv.getAlarms(newData.vitrage_id).then(function(result) {
alarmsCtrl.computeAlarms = result.data;
});
}
});
alarmsCtrl.onAlarmClick = function(alarm) {
var modalOptions = {
animation: true,
templateUrl: STATIC_URL + 'dashboard/project/components/rca/rcaContainer.html',
controller: 'RcaContainerController',
windowClass: 'app-modal-window',
resolve: {alarm: function() {
return alarm;
}}
};
modalSrv.show(modalOptions);
}
}
}
|
Return all most frequent subsequences | import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
import numpy as np
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# Most frequent sub-sequence
OccurrenceNb = np.array(OccurrenceNb)
subseq = np.array(subseq)
result = list(subseq[OccurrenceNb == OccurrenceNb.max()])
return result
| import re
class dna():
"""Instantiate a DNA object"""
def __init__(self):
self.sequence = ""
def genSequence(self, N):
"""Generate a DNA sequence of length N in the subset [G-A-T-C]"""
import random
self.sequence = ""
for i in range(N):
self.sequence += random.choice(["G", "A", "T", "C"])
return self.sequence
def querySubSequence(self, subseq):
"""Return True if the string argument `subseq` is contained inside the `sequence` property"""
# Search for sub-sequence
p = re.compile(subseq)
m = p.search(self.sequence)
if m == None:
found = False
else:
found = True
return found
def getMostFrequentSubSeq(self, m):
"""Returns the most frequent sub-sequence of length m contained in the `sequence` property"""
# Create a set of every possible unique subsequence
subseq = set()
i = 0
while i <= len(self.sequence) - m:
subseq.add(self.sequence[i:i+m])
i += 1
subseq = list(subseq)
# Get the occurrence number of each subsequence
OccurrenceNb = []
for i in subseq:
p = re.compile(i)
OccurrenceNb.append(len(p.findall(self.sequence)))
# First most frequent sub-sequence
result = subseq[OccurrenceNb.index(max(OccurrenceNb))]
return result
|
Use the ECMASCRIPT5_STRICT flag otherwise AngularJS dies |
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
from django.core.exceptions import ImproperlyConfigured
class ClosureCompiler(Processor):
def modify_expected_output_filenames(self, filenames):
return filenames
def process(self, inputs):
if not hasattr(settings, "CLOSURE_COMPILER_BINARY"):
raise ImproperlyConfigured("Please set the CLOSURE_COMPILER_BINARY setting")
from subprocess import Popen, PIPE
outputs = OrderedDict()
compressor = settings.CLOSURE_COMPILER_BINARY
try:
for filename, contents in inputs.items():
cmd = Popen([
'java', '-jar', compressor, "--language_in", "ECMASCRIPT5_STRICT"],
stdin=PIPE, stdout=PIPE, stderr=PIPE,
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
file_out = StringIO.StringIO()
file_out.write(output)
file_out.seek(0)
outputs[filename] = file_out
except Exception, e:
raise ValueError("Failed to execute Java VM or closure. "
"Please make sure that you have installed Java "
"and that it's in your PATH and that you've configured "
"CLOSURE_COMPILER_BINARY in your settings correctly.\n"
"Error was: %s" % e)
return outputs
|
from collections import OrderedDict
import os
import StringIO
from django.conf import settings
from django.utils.encoding import smart_str
from ..base import Processor
from django.core.exceptions import ImproperlyConfigured
class ClosureCompiler(Processor):
def modify_expected_output_filenames(self, filenames):
return filenames
def process(self, inputs):
if not hasattr(settings, "CLOSURE_COMPILER_BINARY"):
raise ImproperlyConfigured("Please set the CLOSURE_COMPILER_BINARY setting")
from subprocess import Popen, PIPE
outputs = OrderedDict()
compressor = settings.CLOSURE_COMPILER_BINARY
try:
for filename, contents in inputs.items():
cmd = Popen([
'java', '-jar', compressor],
stdin=PIPE, stdout=PIPE, stderr=PIPE,
universal_newlines=True
)
output, error = cmd.communicate(smart_str(contents.read()))
file_out = StringIO.StringIO()
file_out.write(output)
file_out.seek(0)
outputs[filename] = file_out
except Exception, e:
raise ValueError("Failed to execute Java VM or closure. "
"Please make sure that you have installed Java "
"and that it's in your PATH and that you've configured "
"CLOSURE_COMPILER_BINARY in your settings correctly.\n"
"Error was: %s" % e)
return outputs
|
Reset search results on new search | (function () {
'use strict';
angular
.module('app')
.controller('MenuController', MenuController);
MenuController.$inject = ['$scope', 'UserService', '$rootScope', 'SearchService', 'TranslateService'];
function MenuController($scope, UserService, $rootScope, SearchService, TranslateService) {
initController();
function initController() {
$scope.search_expression = null;
$scope.results = [];
$scope.displaySearchResults = false;
$scope.languages = [];
TranslateService.GetLanguages().then(function(response) {
if (response.success) {
$scope.languages = response.data;
}
});
}
$scope.setSearchResults = function(value) {
if (value === false) {
$scope.results = [];
}
$scope.displaySearchResults = value;
}
$scope.search = function() {
$scope.resetSearch();
SearchService.Search($scope.search_expression, {'services': ['UserService', 'NewsService'], 'length': '2', 'offset': '0'}).then(function(response) {
if (response.success === true && response.data.length > 0) {
angular.forEach(response.data, function(res, id) {
if (res.success === true) {
$scope.results.push(res.data);
}
});
}
});
}
$scope.resetSearch = function() {
$scope.results = [];
}
}
})(); | (function () {
'use strict';
angular
.module('app')
.controller('MenuController', MenuController);
MenuController.$inject = ['$scope', 'UserService', '$rootScope', 'SearchService', 'TranslateService'];
function MenuController($scope, UserService, $rootScope, SearchService, TranslateService) {
initController();
function initController() {
$scope.search_expression = null;
$scope.results = [];
$scope.displaySearchResults = false;
$scope.languages = [];
TranslateService.GetLanguages().then(function(response) {
if (response.success) {
$scope.languages = response.data;
}
});
}
$scope.setSearchResults = function(value) {
if (value === false) {
$scope.results = [];
}
$scope.displaySearchResults = value;
}
$scope.search = function() {
SearchService.Search($scope.search_expression, {'services': ['UserService', 'NewsService'], 'length': '2', 'offset': '0'}).then(function(response) {
if (response.success === true && response.data.length > 0) {
angular.forEach(response.data, function(res, id) {
if (res.success === true) {
$scope.results.push(res.data);
}
});
}
});
}
}
})(); |
Fix typos and grammar errors | {
"%d unread message": {
"one": "%d непрочитане повідомлення",
"other": "%d непрочитаних повідомлень"
},
"Unread messages in %%s, %%s and one other": {
"one": "Непрочитані повідомлення в %%s, %%s і ще одному каналі",
"other": "Непрочитані повідомлення в %%s, %%s і в %d інших каналах"
},
"Unread messages in %s": "Непрочитані повідомлення в %s",
"Unread messages in %s and %s": "Непрочитані повідомлення в %s і %s",
"Unread messages from %s": "Непрочитані повідомлення від %s",
"Unread messages from %s and %s": "Непрочитані повідомлення від %s і %s",
"Unread messages from %%s, %%s and one other": {
"one": "Непрочитані повідомлення від %%s, %%s і ще одного",
"other": "Непрочитані повідомлення від %%s, %%s і %d інших"
}
}
| {
"%d unread message": {
"one": "%d непрочитане повідомлення",
"other": "%d непрочитаних пвідомлень"
},
"Unread messages in %%s, %%s and one other": {
"one": "Непрочитані повідомлення в %%s, %%s і ще одному",
"other": "Непрочитані повідомлення в %%s, %%s і в %d інших"
},
"Unread messages in %s": "Непрочитані повідомлення в %s",
"Unread messages in %s and %s": "Непрочитані повідомлення в %s і %s",
"Unread messages from %s": "Непрочитані повідомлення від %s",
"Unread messages from %s and %s": "Непрочитані повідомлення від %s і %s",
"Unread messages from %%s, %%s and one other": {
"one": "Непрочитані повідомлення від %%s, %%s і ще одного",
"other": "Непрочитані повідомлення від %%s, %%s і %d інших"
}
}
|
Exclude tests and include sql files in cnx-authoring package
Remove include_package_data=True as it looks for MANIFEST.in instead of
using the package_data that we specified in setup.py.
Tested by running:
```bash
rm -rf cnx_authoring.egg-info dist
python setup.py sdist
```
Close #51 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='[email protected]',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(exclude=['*.tests', '*.tests.*']),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
install_requires = (
'cnx-epub',
'cnx-query-grammar',
'colander',
'openstax-accounts>=0.5',
'PasteDeploy',
'pyramid',
'psycopg2>=2.5',
'requests',
'tzlocal',
'waitress',
)
tests_require = (
'mock', # only required for python2
'WebTest',
)
setup(
name='cnx-authoring',
version='0.1',
author='Connexions team',
author_email='[email protected]',
url='https://github.com/connexions/cnx-authoring',
license='LGPL, See also LICENSE.txt',
description='Unpublished repo',
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
package_data={
'cnxauthoring.storage': ['sql/*.sql', 'sql/*/*.sql'],
},
include_package_data=True,
entry_points={
'paste.app_factory': [
'main = cnxauthoring:main',
],
'console_scripts': [
'cnx-authoring-initialize_db = cnxauthoring.scripts.initializedb:main'
]
},
test_suite='cnxauthoring.tests',
zip_safe=False,
)
|
fix: Update correct snapper when options change | angular.module('snap')
.directive('snapContent', ['snapRemote', function (snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = {
element: element[0]
};
angular.extend(snapOptions, snapRemote.globalOptions);
var snapId = attrs.snapId;
if(!!snapId) {
snapId = scope.$eval(attrs.snapId);
}
// override snap options if some provided in snap-options attribute
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
angular.extend(snapOptions, scope.$eval(attrs.snapOptions));
}
snapRemote.register(new window.Snap(snapOptions), snapId);
// watch snapOptions for updates
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
scope.$watch(attrs.snapOptions, function(newSnapOptions) {
snapRemote.getSnapper(snapId).then(function(snapper) {
snapper.settings(newSnapOptions);
});
}, true);
}
scope.$on('$destroy', function() {
snapRemote.unregister(snapId);
});
}
};
}]);
| angular.module('snap')
.directive('snapContent', ['snapRemote', function (snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = {
element: element[0]
};
angular.extend(snapOptions, snapRemote.globalOptions);
var snapId = attrs.snapId;
if(!!snapId) {
snapId = scope.$eval(attrs.snapId);
}
// override snap options if some provided in snap-options attribute
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
angular.extend(snapOptions, scope.$eval(attrs.snapOptions));
}
snapRemote.register(new window.Snap(snapOptions), snapId);
// watch snapOptions for updates
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
scope.$watch(attrs.snapOptions, function(newSnapOptions) {
snapRemote.getSnapper().then(function(snapper) {
snapper.settings(newSnapOptions);
});
}, true);
}
scope.$on('$destroy', function() {
snapRemote.unregister(snapId);
});
}
};
}]);
|
Change load date to be constant per loading event | 'use strict';
var through = require('through2');
var formatAddress = require('../lib/formatAddress');
var loadDate = Date.now();
module.exports = function(addr, city, state, zip){
if(!addr) throw new Error('Must provide address at minimum.');
var args = [addr, city, state, zip];
var prefix = '';
var suffix = '';
//Chunk is a GeoJSON feature
function transform(chunk, enc, cb){
chunk = JSON.parse(chunk);
var props = chunk.properties;
var payload;
try{
var vals = args.map(function(arg){
if(typeof arg === 'function') return arg(props);
return props[arg];
});
payload = {
type: "Feature",
properties: {
address: formatAddress(
vals[0],
vals[1],
vals[2],
vals[3]
),
alt_address: "",
load_date: loadDate
//Source<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
},
geometry: {
type: "Point",
coordinates: chunk.geometry.coordinates
}
};
}catch(e){
//possibly log the error
return cb();
}
//Elaticsearch bulk wants newline separated values
this.push(prefix + JSON.stringify(payload) + suffix);
cb();
}
return function(pre, suf){
if(pre) prefix = pre;
if(suf) suffix = suf;
return through(transform);
}
};
| 'use strict';
var through = require('through2');
var formatAddress = require('../lib/formatAddress');
module.exports = function(addr, city, state, zip){
if(!addr) throw new Error('Must provide address at minimum.');
var args = [addr, city, state, zip];
var prefix = '';
var suffix = '';
//Chunk is a GeoJSON feature
function transform(chunk, enc, cb){
chunk = JSON.parse(chunk);
var props = chunk.properties;
var payload;
try{
var vals = args.map(function(arg){
if(typeof arg === 'function') return arg(props);
return props[arg];
});
payload = {
type: "Feature",
properties: {
address: formatAddress(
vals[0],
vals[1],
vals[2],
vals[3]
),
alt_address: "",
load_date: Date.now()
//Source<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
},
geometry: {
type: "Point",
coordinates: chunk.geometry.coordinates
}
};
}catch(e){
//possibly log the error
return cb();
}
//Elaticsearch bulk wants newline separated values
this.push(prefix + JSON.stringify(payload) + suffix);
cb();
}
return function(pre, suf){
if(pre) prefix = pre;
if(suf) suffix = suf;
return through(transform);
}
};
|
Use more descriptive test constant names | import chai from 'chai';
import React from 'react';
import {
findRenderedDOMComponentWithTag,
renderIntoDocument
} from 'react-addons-test-utils';
import ReactSVG from '../src';
chai.should();
describe('react-svg', () => {
describe('while rendering', () => {
it('should add the className to the rendered component', () => {
const reactSVG = renderIntoDocument(
<ReactSVG
className={'not-vml'}
path={'http://localhost:9876/base/test/fixtures/atomic.svg'}
/>
);
findRenderedDOMComponentWithTag(reactSVG, 'img').className
.should.eql('not-vml');
});
it('should add the path to the rendered component', () => {
const reactSVG = renderIntoDocument(
<ReactSVG
className={'not-vml'}
path={'http://localhost:9876/base/test/fixtures/atomic.svg'}
/>
);
findRenderedDOMComponentWithTag(reactSVG, 'img').dataset.src
.should.eql('http://localhost:9876/base/test/fixtures/atomic.svg');
});
});
describe('after mounting', () => {
it('should run the callback when the SVGInjector has finished', (done) => {
renderIntoDocument(
<ReactSVG
className={'not-vml'}
path={'http://localhost:9876/base/test/fixtures/atomic.svg'}
callback={(svg) => {
svg.classList.contains('not-vml').should.be.true;
done();
}}
/>
);
});
});
});
| import chai from 'chai';
import React from 'react';
import {
findRenderedDOMComponentWithTag,
renderIntoDocument
} from 'react-addons-test-utils';
import ReactSVG from '../src';
chai.should();
describe('react-svg', () => {
describe('while rendering', () => {
it('should add the className to the rendered component', () => {
const component = renderIntoDocument(
<ReactSVG
className={'not-vml'}
path={'http://localhost:9876/base/test/fixtures/atomic.svg'}
/>
);
findRenderedDOMComponentWithTag(component, 'img').className
.should.eql('not-vml');
});
it('should add the path to the rendered component', () => {
const component = renderIntoDocument(
<ReactSVG
className={'not-vml'}
path={'http://localhost:9876/base/test/fixtures/atomic.svg'}
/>
);
findRenderedDOMComponentWithTag(component, 'img').dataset.src
.should.eql('http://localhost:9876/base/test/fixtures/atomic.svg');
});
});
describe('after mounting', () => {
it('should run the callback when the SVGInjector has finished', (done) => {
renderIntoDocument(
<ReactSVG
className={'not-vml'}
path={'http://localhost:9876/base/test/fixtures/atomic.svg'}
callback={(svg) => {
svg.classList.contains('not-vml').should.be.true;
done();
}}
/>
);
});
});
});
|
Check if all sequences are of the same length | import logging
__author__ = "Antonio J. Nebro"
__license__ = "GPL"
__version__ = "1.0-SNAPSHOT"
__status__ = "Development"
__email__ = "[email protected]"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Score:
""" Class representing MSA (Multiple Sequence Alignment) scores
A msa has to be a Python list containing pairs of (identifier, sequence), as in this example:
((id1, SSSBA), (id2, HHALK), (id3, -HLGS), etc))
Requirements:
- All the sequences in an msa must be aligned
- The gap character is '-'
"""
def compute(self, msa) -> float:
""" Compute the score
:param msa
:return: the value of the score
"""
pass
def get_seqs_from_list_of_pairs(self, msa):
""" Get the sequences from an msa.
:param msa: Python list containing pairs of (identifier, sequence)
:return: List of sequences (i.e. "('AB', 'CD', 'EF' )") if all sequences are of the same length.
"""
sequences = []
logger.debug('List of pairs: {0}'.format(msa))
for i in range(len(msa)):
sequences.append(msa[i][1])
logger.debug('List of sequences: {0}'.format(sequences))
return sequences \
if all(len(sequences[0]) == len(seq) for seq in sequences) \
else self._raiser('Sequences are not of the same length.')
def _raiser(self, e): raise Exception(e) | import logging
__author__ = "Antonio J. Nebro"
__license__ = "GPL"
__version__ = "1.0-SNAPSHOT"
__status__ = "Development"
__email__ = "[email protected]"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class Score:
""" Class representing MSA (Multiple Sequence Alignment) scores
A msa has to be a Python list containing pairs of (identifier, sequence), as in this example:
((id1, SSSBA), (id2, HHALK), (id3, -HLGS), etc))
Requirements:
- All the sequences in an msa must be aligned
- The gap character is '-'
"""
def compute(self, msa) -> float:
""" Compute the score
:param msa
:return: the value of the score
"""
pass
def get_seqs_from_list_of_pairs(self, msa):
""" Get the sequences from an msa.
:param msa: Python list containing pairs of (identifier, sequence)
:return: List of sequences (i.e. "('AB', 'CD', 'EF' )").
"""
sequences = []
logger.debug('List of pairs: {0}'.format(msa))
for i in range(len(msa)):
sequences.append(msa[i][1])
logger.debug('List of sequences: {0}'.format(sequences))
return sequences |
Fix grunt errors in node > 6 | /*global module:false*/
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
exec: {
removeDocs: "rm -rf docs/*",
createDocs: 'coddoc -f multi-html -d ./lib --dir ./docs'
},
jshint: {
file: "./lib/*.js",
options: {
jshintrc: '.jshintrc',
reporterOutput: '',
}
},
it: {
all: {
src: 'test/**/*.test.js',
options: {
timeout: 3000, // not fully supported yet
reporter: 'spec'
}
}
},
'gh-pages': {
options: {
base: 'docs'
},
src: ['**']
}
});
// Default task.
grunt.registerTask('default', ['jshint', 'it', "exec"]);
grunt.loadNpmTasks('grunt-it');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-exec');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.registerTask("benchmark", "run benchmarks", function () {
var done = this.async();
require("./benchmark/benchmark")(function (err) {
if (err) {
grunt.log.error(err.stack);
done(false)
} else {
grunt.log.ok("Done running benchmarks");
done();
}
});
});
};
| /*global module:false*/
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
exec: {
removeDocs: "rm -rf docs/*",
createDocs: 'coddoc -f multi-html -d ./lib --dir ./docs'
},
jshint: {
file: "./lib/*.js",
options: {
jshintrc: '.jshintrc'
}
},
it: {
all: {
src: 'test/**/*.test.js',
options: {
timeout: 3000, // not fully supported yet
reporter: 'spec'
}
}
},
'gh-pages': {
options: {
base: 'docs'
},
src: ['**']
}
});
// Default task.
grunt.registerTask('default', ['jshint', 'it', "exec"]);
grunt.loadNpmTasks('grunt-it');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-exec');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.registerTask("benchmark", "run benchmarks", function () {
var done = this.async();
require("./benchmark/benchmark")(function (err) {
if (err) {
grunt.log.error(err.stack);
done(false)
} else {
grunt.log.ok("Done running benchmarks");
done();
}
});
});
};
|
Disable Admin controller user acl | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/
public function indexAction()
{
// if user is not logged in, redirect to login page
$securityContext = $this->container->get('security.authorization_checker');
if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('fos_user_security_login');
}
// Load the data for the current user into an object
$user = $this->getUser();
// continue only if user has Admin access, else redirect to Home
// if ($user->getEmail() !== '[email protected]') {
// return $this->redirectToRoute('home');
// }
// Get an instance of the Entity Manager
$em = $this->getDoctrine()->getManager();
$tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
->findOneById(12);
$dataUpdatesManager = $this->get('app.data_updates.manager');
$dataUpdatesManager->setEntityManager($em);
$dataUpdatesManager->updateTeamsByTournament($tournament);
// $dataUpdatesManager->updateFixtures();
return $this->redirectToRoute('home');
}
}
| <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/
public function indexAction()
{
// if user is not logged in, redirect to login page
$securityContext = $this->container->get('security.authorization_checker');
if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('fos_user_security_login');
}
// Load the data for the current user into an object
$user = $this->getUser();
var_dump($user->getEmail());die;
// continue only if user has Admin access, else redirect to Home
if ($user->getEmail() !== '[email protected]') {
return $this->redirectToRoute('home');
}
// Get an instance of the Entity Manager
$em = $this->getDoctrine()->getManager();
$tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
->findOneById(12);
$dataUpdatesManager = $this->get('app.data_updates.manager');
$dataUpdatesManager->setEntityManager($em);
$dataUpdatesManager->updateTeamsByTournament($tournament);
// $dataUpdatesManager->updateFixtures();
return $this->redirectToRoute('home');
}
}
|
Fix eslint ts override tsx matching | module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
"prefer-spread": ["warn"],
"one-var": ["warn"],
"padded-blocks": ["warn"],
"no-extend-native": ["warn"],
"camelcase": ["warn"],
"no-multi-spaces": ["error", { "ignoreEOLComments": true }],
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always",
}],
"arrow-parens": "off",
"prefer-promise-reject-errors": "off",
"quotes": "off",
"indent": "off",
"no-constant-condition": "off",
"no-async-promise-executor": "off",
},
overrides: [{
"files": ["src/**/*.ts"],
"extends": ["matrix-org/ts"],
"rules": {
// While we're converting to ts we make heavy use of this
"@typescript-eslint/no-explicit-any": "off",
"quotes": "off",
},
}],
};
| module.exports = {
extends: ["matrix-org"],
plugins: [
"babel",
],
env: {
browser: true,
node: true,
},
rules: {
"no-var": ["warn"],
"prefer-rest-params": ["warn"],
"prefer-spread": ["warn"],
"one-var": ["warn"],
"padded-blocks": ["warn"],
"no-extend-native": ["warn"],
"camelcase": ["warn"],
"no-multi-spaces": ["error", { "ignoreEOLComments": true }],
"space-before-function-paren": ["error", {
"anonymous": "never",
"named": "never",
"asyncArrow": "always",
}],
"arrow-parens": "off",
"prefer-promise-reject-errors": "off",
"quotes": "off",
"indent": "off",
"no-constant-condition": "off",
"no-async-promise-executor": "off",
},
overrides: [{
"files": ["src/**/*.{ts, tsx}"],
"extends": ["matrix-org/ts"],
"rules": {
// While we're converting to ts we make heavy use of this
"@typescript-eslint/no-explicit-any": "off",
"quotes": "off",
},
}],
};
|
Fix another bug related to logging dataset errors
OIPA-612 / #589 | import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(location)
xmlschema_doc = etree.parse(xsd_data)
xsd_data.close()
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_errors = None
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as e:
xml_errors = e
pass
if xml_errors:
for error in xml_errors.error_log:
element = error.message[
(findnth_occurence_in_string(
error.message, '\'', 0
) + 1):findnth_occurence_in_string(
error.message, '\'', 1
)
]
attribute = '-'
if 'attribute' in error.message:
attribute = error.message[
(findnth_occurence_in_string(
error.message, '\'', 2
) + 1):findnth_occurence_in_string(
error.message, '\'', 3
)
]
iati_parser.append_error(
'XsdValidationError',
element,
attribute,
error.message.split(':')[0],
error.line,
error.message.split(':')[1],
'unkown for XSD validation errors')
| import os
import os.path
from lxml import etree
from common.util import findnth_occurence_in_string
def validate(iati_parser, xml_etree):
base = os.path.dirname(os.path.abspath(__file__))
location = base + "/../schemas/" + iati_parser.VERSION \
+ "/iati-activities-schema.xsd"
xsd_data = open(location)
xmlschema_doc = etree.parse(xsd_data)
xsd_data.close()
xmlschema = etree.XMLSchema(xmlschema_doc)
xml_errors = None
try:
xmlschema.assertValid(xml_etree)
except etree.DocumentInvalid as xml_errors:
pass
if xml_errors:
for error in xml_errors.error_log:
element = error.message[
(findnth_occurence_in_string(
error.message, '\'', 0
) + 1):findnth_occurence_in_string(
error.message, '\'', 1
)
]
attribute = '-'
if 'attribute' in error.message:
attribute = error.message[
(findnth_occurence_in_string(
error.message, '\'', 2
) + 1):findnth_occurence_in_string(
error.message, '\'', 3
)
]
iati_parser.append_error(
'XsdValidationError',
element,
attribute,
error.message.split(':')[0],
error.line,
error.message.split(':')[1],
'unkown for XSD validation errors')
|
Fix "Missing translation key for 'null'" | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { get } from '../../store';
import { areWeFunYet, translate as $t } from '../../helpers';
import ExternalLink from './external-link.js';
import DisplayIf from './display-if';
let showLicense = areWeFunYet();
export const LoadingMessage = props => {
let message = props.message || $t('client.spinner.generic');
return (
<div className="loading-message">
<h3>{$t('client.spinner.title')}</h3>
<div>
<div className="spinner" />
<div>{message}</div>
<DisplayIf condition={showLicense}>
<div>
{$t('client.spinner.license')}
<ExternalLink href="https://liberapay.com/Kresus">Kresus</ExternalLink>
</div>
</DisplayIf>
</div>
</div>
);
};
LoadingMessage.propTypes = {
// Message indicating why we're doing background loading (and the UI is
// frozen).
message: PropTypes.string
};
export const LoadingOverlay = connect(state => {
return {
processingReason: get.backgroundProcessingReason(state)
};
})(props => {
if (!props.processingReason) {
return null;
}
return (
<div id="loading-overlay">
<LoadingMessage message={$t(props.processingReason)} />
</div>
);
});
| import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { get } from '../../store';
import { areWeFunYet, translate as $t } from '../../helpers';
import ExternalLink from './external-link.js';
import DisplayIf from './display-if';
let showLicense = areWeFunYet();
export const LoadingMessage = props => {
let message = props.message || $t('client.spinner.generic');
return (
<div className="loading-message">
<h3>{$t('client.spinner.title')}</h3>
<div>
<div className="spinner" />
<div>{message}</div>
<DisplayIf condition={showLicense}>
<div>
{$t('client.spinner.license')}
<ExternalLink href="https://liberapay.com/Kresus">Kresus</ExternalLink>
</div>
</DisplayIf>
</div>
</div>
);
};
LoadingMessage.propTypes = {
// Message indicating why we're doing background loading (and the UI is
// frozen).
message: PropTypes.string
};
export const LoadingOverlay = connect(state => {
return {
processingReason: get.backgroundProcessingReason(state)
};
})(props => {
return (
<DisplayIf condition={props.processingReason !== null}>
<div id="loading-overlay">
<LoadingMessage message={$t(props.processingReason)} />
</div>
</DisplayIf>
);
});
|
Add option for adding a callback | 'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
var sendMinified = function (callback) {
// No callbak specified, just minify and send to client.
if (typeof callback === 'undefined') {
return function (err, html) {
if (err) {
console.error(err)
if (opts.displayErrors === true) {
res.send('Rendering error: ' + err.message);
} else {
res.sendStatus(500);
}
} else {
html = minify(html, opts.htmlMinifier);
res.send(html);
}
}
} else {
// Custom callback specified by user, use that one
return function (err, html) {
html = minify(html, opts.htmlMinifier);
callback(err, html);
}
}
};
if (opts.override === false) {
res.renderMin = function (view, renderOpts, callback) {
this.render(view, renderOpts, sendMinified(callback));
}
} else {
res.oldRender = res.render;
res.render = function (view, renderOpts, callback) {
this.oldRender(view, renderOpts, sendMinified(callback));
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML;
| 'use strict';
var minify = require('html-minifier').minify;
function minifyHTML(opts) {
if (!opts) opts = {};
function minifier(req, res, next) {
var sendMinified = function (err, html) {
if (err) {
console.error(err)
if (opts.displayErrors === true) {
res.send('Rendering error: ' + err.message);
} else {
res.sendStatus(500);
}
} else {
html = minify(html, opts.htmlMinifier);
res.send(html);
}
};
if (opts.override === false) {
res.renderMin = function (view, renderOpts) {
this.render(view, renderOpts, sendMinified);
}
} else {
res.oldRender = res.render;
res.render = function (view, renderOpts) {
this.oldRender(view, renderOpts, sendMinified);
};
}
return next();
}
return (minifier);
}
module.exports = minifyHTML;
|
Remove grant types form field | <?php
namespace App\Form\OAuth;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ClientType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('redirectUris', 'collection', array(
'type' => 'text',
'allow_add' => true,
'allow_delete'=>true
))
->add('preApproved', 'checkbox', array(
'required' => false,
))
->add('submit', 'submit')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\OAuth\Client'
));
}
/**
* @return string
*/
public function getName()
{
return 'app_oauth_client';
}
}
| <?php
namespace App\Form\OAuth;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ClientType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('allowedGrantTypes', 'choice', array(
'choices' => array(
'authorization_code' => 'authorization_code',
),
'multiple'=>true,
'expanded' => true,
))
->add('redirectUris', 'collection', array(
'type' => 'text',
'allow_add' => true,
'allow_delete'=>true
))
->add('preApproved', 'checkbox', array(
'required' => false,
))
->add('submit', 'submit')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'App\Entity\OAuth\Client'
));
}
/**
* @return string
*/
public function getName()
{
return 'app_oauth_client';
}
}
|
Support configuration with no hidden-layer | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chainer
from chainer import functions as F
from chainer import links as L
from chainer import cuda
class MLP(chainer.Chain):
"""Multi-Layer Perceptron"""
def __init__(self, in_size, out_size, hidden_sizes):
self.in_size = in_size
self.out_size = out_size
self.hidden_sizes = hidden_sizes
layers = {}
if hidden_sizes:
hidden_layers = []
hidden_layers.append(L.Linear(in_size, hidden_sizes[0]))
for hin, hout in zip(hidden_sizes, hidden_sizes[1:]):
hidden_layers.append(L.Linear(hin, hout))
layers['hidden_layers'] = chainer.ChainList(*hidden_layers)
layers['output'] = L.Linear(hidden_sizes[-1], out_size)
else:
layers['output'] = L.Linear(in_size, out_size)
super().__init__(**layers)
def __call__(self, x, test=False):
h = x
if self.hidden_sizes:
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
| from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import super
from builtins import range
from future import standard_library
standard_library.install_aliases()
import random
import numpy as np
import chainer
from chainer import functions as F
from chainer import links as L
from chainer import cuda
class MLP(chainer.Chain):
"""Multi-Layer Perceptron"""
def __init__(self, in_size, out_size, hidden_sizes):
self.in_size = in_size
self.out_size = out_size
self.hidden_sizes = hidden_sizes
layers = {}
if hidden_sizes:
hidden_layers = []
hidden_layers.append(L.Linear(in_size, hidden_sizes[0]))
for hin, hout in zip(hidden_sizes, hidden_sizes[1:]):
hidden_layers.append(L.Linear(hin, hout))
layers['hidden_layers'] = chainer.ChainList(*hidden_layers)
layers['output'] = L.Linear(hidden_sizes[-1], out_size)
else:
layers['output'] = L.Linear(in_size, out_size)
super().__init__(**layers)
def __call__(self, x, test=False):
h = x
for l in self.hidden_layers:
h = F.relu(l(h))
return self.output(h)
|
Fix error in UCB1 algorithm | package com.danisola.bandit;
public class Ucb1Algorithm extends AbstractBanditAlgorithm {
public Ucb1Algorithm(int numArms, UpdateStrategy updateStrategy) {
super(numArms, updateStrategy);
}
@Override
public int selectArm() {
int totalCount = 0;
for (int i = 0; i < counts.length; i++) {
int count = counts[i];
if (count == 0) {
return i;
}
totalCount += count;
}
double[] ucbValues = new double[numArms];
for (int i = 0; i < numArms; i++) {
double bonus = Math.sqrt((2 * Math.log(totalCount)) / counts[i]);
ucbValues[i] = values[i] + bonus;
}
int maxIndex = 0;
for (int i = 1; i < ucbValues.length; i++) {
double newValue = ucbValues[i];
if (newValue > ucbValues[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
@Override
public String toString() {
return "UCB1 {}";
}
}
| package com.danisola.bandit;
public class Ucb1Algorithm extends AbstractBanditAlgorithm {
public Ucb1Algorithm(int numArms, UpdateStrategy updateStrategy) {
super(numArms, updateStrategy);
}
@Override
public int selectArm() {
int totalCount = 0;
for (int i = 0; i < counts.length; i++) {
int count = counts[i];
if (count == 0) {
return i;
}
totalCount += count;
}
double[] ucbValues = new double[numArms];
for (int i = 0; i < numArms; i++) {
double bonus = Math.sqrt(2 * Math.log(totalCount / counts[i]));
ucbValues[i] = values[i] + bonus;
}
int maxIndex = 0;
for (int i = 1; i < ucbValues.length; i++) {
double newValue = ucbValues[i];
if (newValue > ucbValues[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
@Override
public String toString() {
return "UCB1 {}";
}
}
|
Add menu title to MenuWidget output | "use strict";
const Widget = require('../../layout/widget');
const Item = require('../../router/item');
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class menuWidget extends Widget {
constructor(data={}, engine) {
super(data);
this.engine = engine;
['id', 'title', 'description', 'showParentLinks', 'maxLevels', 'overrides'].map(v => this[v] = data[v]);
this.entries = [];
}
init(context, data) {
return co(function*(self, superInit){
yield superInit.call(self, context, data);
let content = '';
for (let entry of self.entries) {
let show = false;
for (let handler of entry.handlers) {
if (yield handler.showLink(entry.data.path, context)) {
show = true;
break;
}
}
if (show) {
content += `<a href="/${entry.data.path}">${entry.data.menu.text}</a><br />`;
}
}
merge(self.data, {
// TODO: Translate.
// TODO: Escape.
content: content ? `<div class="title">${self.title}</div>${content}` : '',
});
})(this, super.init);
}
addHandler(handler) {
let Router = this.engine.plugin.get('Router');
this.entries.push({
data: handler,
handlers: Router.router.collectHandlers(handler.path).filter(handler => handler.menu || handler.allowShowLink),
});
}
}
module.exports = menuWidget;
| "use strict";
const Widget = require('../../layout/widget');
const Item = require('../../router/item');
const merge = require('../../../util/merge');
const {coroutine: co} = require('bluebird');
class menuWidget extends Widget {
constructor(data={}, engine) {
super(data);
this.engine = engine;
['id', 'title', 'description', 'showParentLinks', 'maxLevels', 'overrides'].map(v => this[v] = data[v]);
this.entries = [];
}
init(context, data) {
return co(function*(self, superInit){
yield superInit.call(self, context, data);
let content = '';
for (let entry of self.entries) {
let show = false;
for (let handler of entry.handlers) {
if (yield handler.showLink(entry.data.path, context)) {
show = true;
break;
}
}
if (show) {
content += `<a href="/${entry.data.path}">${entry.data.menu.text}</a><br />`;
}
}
merge(self.data, {
content: content,
});
})(this, super.init);
}
addHandler(handler) {
let Router = this.engine.plugin.get('Router');
this.entries.push({
data: handler,
handlers: Router.router.collectHandlers(handler.path).filter(handler => handler.menu || handler.allowShowLink),
});
//console.log(this.id, handler);
}
}
module.exports = menuWidget;
|
Use OPENSSL_REFCNT instead of OPENSSL as our SSL provider when possible. | package com.relayrides.pushy.apns;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for choosing SSL providers.
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*
* @since 0.10
*/
class SslUtil {
private static final Logger log = LoggerFactory.getLogger(SslUtil.class);
/**
* Selects an SSL provider based on the availability of of an ALPN-capable native provider.
*
* @return an ALPN-capable native SSL provider if available, or else the JDK SSL provider
*/
public static SslProvider getSslProvider() {
final SslProvider sslProvider;
if (OpenSsl.isAvailable()) {
if (OpenSsl.isAlpnSupported()) {
log.info("Native SSL provider is available and supports ALPN; will use native provider.");
sslProvider = SslProvider.OPENSSL_REFCNT;
} else {
log.info("Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
sslProvider = SslProvider.JDK;
}
} else {
log.info("Native SSL provider not available; will use JDK SSL provider.");
sslProvider = SslProvider.JDK;
}
return sslProvider;
}
}
| package com.relayrides.pushy.apns;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class for choosing SSL providers.
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*
* @since 0.10
*/
class SslUtil {
private static final Logger log = LoggerFactory.getLogger(SslUtil.class);
/**
* Selects an SSL provider based on the availability of of an ALPN-capable native provider.
*
* @return an ALPN-capable native SSL provider if available, or else the JDK SSL provider
*/
public static SslProvider getSslProvider() {
final SslProvider sslProvider;
if (OpenSsl.isAvailable()) {
if (OpenSsl.isAlpnSupported()) {
log.info("Native SSL provider is available and supports ALPN; will use native provider.");
sslProvider = SslProvider.OPENSSL;
} else {
log.info("Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
sslProvider = SslProvider.JDK;
}
} else {
log.info("Native SSL provider not available; will use JDK SSL provider.");
sslProvider = SslProvider.JDK;
}
return sslProvider;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.