text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Add missing number case for traverser | /**
* Traverser for Intl AST.
*
* @param {object} ast Intl AST (from intl-messageformat-parser)
* @param {object} visitor Visitor object for traversal
*/
export const traverser = (ast, visitor) => {
function traverse(node, parent) {
/*jshint maxcomplexity:false*/
if (Array.isArray(node)) {
node.forEach(child => {
traverse(child, parent);
});
return;
}
const method = visitor[node.type];
if (method) {
method(node, parent);
}
switch (node.type) {
case 'messageFormatPattern':
traverse(node.elements, node);
break;
// No children.
case 'messageTextElement':
break;
case 'argumentElement':
if (node.format) {
traverse(node.format, node);
}
break;
// No children.
case 'simpleFormat':
case 'dateFormat':
case 'timeFormat':
case 'numberFormat':
break;
case 'pluralFormat':
traverse(node.options, node);
break;
case 'selectOrdinalFormat':
traverse(node.options, node);
break;
case 'selectFormat':
traverse(node.options, node);
break;
// No children.
case 'optionalFormatPattern':
break;
case 'pluralStyle':
traverse(node.options, node);
break;
default:
throw new TypeError(node.type);
}
}
traverse(ast, null);
};
| /**
* Traverser for Intl AST.
*
* @param {object} ast Intl AST (from intl-messageformat-parser)
* @param {object} visitor Visitor object for traversal
*/
export const traverser = (ast, visitor) => {
function traverse(node, parent) {
/*jshint maxcomplexity:false*/
if (Array.isArray(node)) {
node.forEach(child => {
traverse(child, parent);
});
return;
}
const method = visitor[node.type];
if (method) {
method(node, parent);
}
switch (node.type) {
case 'messageFormatPattern':
traverse(node.elements, node);
break;
// No children.
case 'messageTextElement':
break;
case 'argumentElement':
if (node.format) {
traverse(node.format, node);
}
break;
// No children.
case 'simpleFormat':
case 'dateFormat':
case 'timeFormat':
break;
case 'pluralFormat':
traverse(node.options, node);
break;
case 'selectOrdinalFormat':
traverse(node.options, node);
break;
case 'selectFormat':
traverse(node.options, node);
break;
// No children.
case 'optionalFormatPattern':
break;
case 'pluralStyle':
traverse(node.options, node);
break;
default:
throw new TypeError(node.type);
}
}
traverse(ast, null);
};
|
Check the model beig indexed | from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
if model.__name__.lower() != 'testmodel':
all_instances = model.objects.all()[0:3] \
if options.get('test') else model.objects.all()
[index_instance(obj) for obj in all_instances]
message = "Indexed {} {}".format(
all_instances.count(),
model._meta.verbose_name_plural.capitalize())
self.stdout.write(message)
else:
# relation "common_testmodel" does not exist
# Will be fixed
pass
self.stdout.write("Finished indexing")
| from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
action='store_true',
dest='test',
default=False,
help='Provide this if you want to create a test index')
def handle(self, *args, **options):
# optimize this to index in bulk
apps_lists = settings.LOCAL_APPS
for app_name in apps_lists:
app = get_app(app_name)
for model in get_models(app):
all_instances = model.objects.all()[0:3] \
if options.get('test') else model.objects.all()
[index_instance(obj) for obj in all_instances]
message = "Indexed {} {}".format(
all_instances.count(),
model._meta.verbose_name_plural.capitalize())
self.stdout.write(message)
self.stdout.write("Finished indexing")
|
Revert "set null soap parameters"
This reverts commit 0000599 | <?php
/**
* Created by PhpStorm.
* User: Administrador
* Date: 03/10/2017
* Time: 09:47 AM.
*/
namespace Greenter\Ws\Services;
use Greenter\Ws\Header\WSSESecurityHeader;
/**
* Class SoapClient.
*/
class SoapClient implements WsClientInterface
{
private $client;
/**
* SoapClient constructor.
*
* @param string $wsdl Url of WSDL
* @param array $parameters Soap's parameters
*/
public function __construct($wsdl = '', $parameters = [])
{
if (empty($wsdl)) {
$wsdl = WsdlProvider::getBillPath();
}
$this->client = new \SoapClient($wsdl, $parameters);
}
/**
* @param $user
* @param $password
*/
public function setCredentials($user, $password)
{
$this->client->__setSoapHeaders(new WSSESecurityHeader($user, $password));
}
/**
* Set Url of Service.
*
* @param string $url
*/
public function setService($url)
{
$this->client->__setLocation($url);
}
/**
* @param $function
* @param $arguments
*
* @return mixed
*/
public function call($function, $arguments)
{
return $this->client->__soapCall($function, $arguments);
}
}
| <?php
/**
* Created by PhpStorm.
* User: Administrador
* Date: 03/10/2017
* Time: 09:47 AM.
*/
namespace Greenter\Ws\Services;
use Greenter\Ws\Header\WSSESecurityHeader;
/**
* Class SoapClient.
*/
class SoapClient implements WsClientInterface
{
private $client;
/**
* SoapClient constructor.
*
* @param string $wsdl Url of WSDL
* @param array $parameters Soap's parameters
*/
public function __construct($wsdl = '', array $parameters = null)
{
if (empty($wsdl)) {
$wsdl = WsdlProvider::getBillPath();
}
$this->client = new \SoapClient($wsdl, $parameters);
}
/**
* @param $user
* @param $password
*/
public function setCredentials($user, $password)
{
$this->client->__setSoapHeaders(new WSSESecurityHeader($user, $password));
}
/**
* Set Url of Service.
*
* @param string $url
*/
public function setService($url)
{
$this->client->__setLocation($url);
}
/**
* @return \SoapClient
*/
public function getClient()
{
return $this->client;
}
/**
* @param $function
* @param $arguments
*
* @return mixed
*/
public function call($function, $arguments)
{
return $this->client->__soapCall($function, $arguments);
}
}
|
Fix typo in modal (CantMoveAttached) message. | define(function (require) {
var React = require('react/addons'),
BootstrapModalMixin = require('components/mixins/BootstrapModalMixin.react');
return React.createClass({
displayName: "CantMoveAttached",
mixins: [BootstrapModalMixin],
confirm: function () {
this.hide();
},
render: function () {
var content = (
<div>
<h4>You are trying to move attached resources</h4>
<p>An instance or volume cannot be moved while attached. To move these resources, please detach them by first selecting the attached volume and then selecting the dettach option on the top right.</p>
</div>
);
return (
<div className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h3>Resources Still Attached</h3>
</div>
<div className="modal-body">
{content}
</div>
<div className="modal-footer">
<button className="btn btn-primary" onClick={this.confirm} >OK</button>
</div>
</div>
</div>
</div>
);
}
});
});
| define(function (require) {
var React = require('react/addons'),
BootstrapModalMixin = require('components/mixins/BootstrapModalMixin.react');
return React.createClass({
displayName: "CantMoveAttached",
mixins: [BootstrapModalMixin],
confirm: function () {
this.hide();
},
render: function () {
var content = (
<div>
<h4>You are trying to move attached resources</h4>
<p>An instance or volume can not be moved while attached. To move these resources, please dettach them by first selecting the attached volume and then selecting the dettach option top right.</p>
</div>
);
return (
<div className="modal fade">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h3>Resources Still Attached</h3>
</div>
<div className="modal-body">
{content}
</div>
<div className="modal-footer">
<button className="btn btn-primary" onClick={this.confirm} >OK</button>
</div>
</div>
</div>
</div>
);
}
});
});
|
Mark all fields as read only in the dashboard | from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
readonly_fields = tuple(f.name for f in Reimbursement._meta.fields)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
| from django.contrib import admin
from jarbas.core.models import Reimbursement
class SuspiciousListFilter(admin.SimpleListFilter):
title = 'Is suspicious'
parameter_name = 'is_suspicions'
def lookups(self, request, model_admin):
return (
('yes', 'Yes'),
('no', 'No'),
)
def queryset(self, request, queryset):
return queryset.suspicions() if self.value() == 'yes' else queryset
class ReimbursementModelAdmin(admin.ModelAdmin):
list_display = (
'document_id',
'congressperson_name',
'year',
'subquota_description',
'supplier',
'cnpj_cpf',
'is_suspicious',
'total_net_value',
'available_in_latest_dataset',
)
search_fields = (
'applicant_id',
'cnpj_cpf',
'congressperson_name',
'document_id',
'party',
'state',
'supplier',
)
list_filter = (
SuspiciousListFilter,
'available_in_latest_dataset',
'year',
'state',
)
def is_suspicious(self, obj):
return obj.suspicions is not None
is_suspicious.short_description = 'Suspicious'
is_suspicious.boolean = True
admin.site.register(Reimbursement, ReimbursementModelAdmin)
|
Use php array sugar syntax | <?php
namespace Rezzza\RestApiBehatExtension;
abstract class ExpectationFailed extends \Exception
{
abstract public function getContextText();
/**
* Returns exception message with additional context info.
*
* @return string
*/
public function __toString()
{
try {
$contextText = $this->pipeString($this->trimString($this->getContextText())."\n");
$string = sprintf("%s\n\n%s", $this->getMessage(), $contextText);
} catch (\Exception $e) {
return $this->getMessage();
}
return $string;
}
/**
* Prepends every line in a string with pipe (|).
*
* @param string $string
*
* @return string
*/
protected function pipeString($string)
{
return '| '.strtr($string, ["\n" => "\n| "]);
}
/**
* Trims string to specified number of chars.
*
* @param string $string response content
* @param int $count trim count
*
* @return string
*/
protected function trimString($string, $count = 1000)
{
$string = trim($string);
if ($count < mb_strlen($string)) {
return mb_substr($string, 0, $count - 3).'...';
}
return $string;
}
}
| <?php
namespace Rezzza\RestApiBehatExtension;
abstract class ExpectationFailed extends \Exception
{
abstract function getContextText();
/**
* Returns exception message with additional context info.
*
* @return string
*/
public function __toString()
{
try {
$contextText = $this->pipeString($this->trimString($this->getContextText())."\n");
$string = sprintf("%s\n\n%s", $this->getMessage(), $contextText);
} catch (\Exception $e) {
return $this->getMessage();
}
return $string;
}
/**
* Prepends every line in a string with pipe (|).
*
* @param string $string
*
* @return string
*/
protected function pipeString($string)
{
return '| '.strtr($string, array("\n" => "\n| "));
}
/**
* Trims string to specified number of chars.
*
* @param string $string response content
* @param int $count trim count
*
* @return string
*/
protected function trimString($string, $count = 1000)
{
$string = trim($string);
if ($count < mb_strlen($string)) {
return mb_substr($string, 0, $count - 3).'...';
}
return $string;
}
}
|
Update NavLinks: use gatsby-link to avoid code chunks necessary for pages not being loaded. | import React from 'react'
import NavLink from 'gatsby-link'
import styles from './navigation.module.styl'
export default ({ sports }) => (
<nav>
<ol className={`${styles['sports-list']}`}>
{
sports.map(({ node }, idx) => (
<li key={idx} className={`${styles['sport-item']}`}>
<h3 className={styles['no-margin']}>
<NavLink
to={`/${node.name}`}
activeClassName={styles.active}
className={styles['nav-link']}>
{ node.name }
</NavLink>
</h3>
<ol className={`${styles['countries-list']}`}>
{
node.countries.map((country, idx) => (
<li key={idx} className={`${styles['country-item']}`}>
<h3 className={styles['no-margin']}>
<NavLink
to={`/${node.name}/${country.name}`}
activeClassName={styles.active}
className={styles['nav-link']}>
{ country.name }
</NavLink>
</h3>
</li>
))
}
</ol>
</li>
))
}
</ol>
</nav>
)
| import React from 'react'
import { NavLink } from 'react-router-dom'
import styles from './navigation.module.styl'
export default ({ sports }) => (
<nav>
<ol className={`${styles['sports-list']}`}>
{
sports.map(({ node }, idx) => (
<li key={idx} className={`${styles['sport-item']}`}>
<h3 className={styles['no-margin']}>
<NavLink
to={`/${node.name}`}
activeClassName={styles.active}
className={styles['nav-link']}>
{ node.name }
</NavLink>
</h3>
<ol className={`${styles['countries-list']}`}>
{
node.countries.map((country, idx) => (
<li key={idx} className={`${styles['country-item']}`}>
<h3 className={styles['no-margin']}>
<NavLink
to={`/${node.name}/${country.name}`}
activeClassName={styles.active}
className={styles['nav-link']}>
{ country.name }
</NavLink>
</h3>
</li>
))
}
</ol>
</li>
))
}
</ol>
</nav>
)
|
Call toString on action type before displaying | import React, { Component } from 'react';
import JSONTree from 'react-json-tree';
const styles = {
actionBar: {
paddingTop: 8,
paddingBottom: 7,
paddingLeft: 16
},
payload: {
margin: 0,
overflow: 'auto'
}
};
export default class LogMonitorAction extends Component {
renderPayload(payload) {
return (
<div style={{
...styles.payload,
backgroundColor: this.props.theme.base00
}}>
{ Object.keys(payload).length > 0 ?
<JSONTree theme={this.props.theme}
keyName={'action'}
data={payload}
expandRoot={this.props.expandActionRoot} /> : '' }
</div>
);
}
render() {
const { type, ...payload } = this.props.action;
return (
<div style={{
backgroundColor: this.props.theme.base02,
color: this.props.theme.base06,
...this.props.style
}}>
<div style={styles.actionBar}
onClick={this.props.onClick}>
{type.toString()}
</div>
{!this.props.collapsed ? this.renderPayload(payload) : ''}
</div>
);
}
}
| import React, { Component } from 'react';
import JSONTree from 'react-json-tree';
const styles = {
actionBar: {
paddingTop: 8,
paddingBottom: 7,
paddingLeft: 16
},
payload: {
margin: 0,
overflow: 'auto'
}
};
export default class LogMonitorAction extends Component {
renderPayload(payload) {
return (
<div style={{
...styles.payload,
backgroundColor: this.props.theme.base00
}}>
{ Object.keys(payload).length > 0 ?
<JSONTree theme={this.props.theme}
keyName={'action'}
data={payload}
expandRoot={this.props.expandActionRoot} /> : '' }
</div>
);
}
render() {
const { type, ...payload } = this.props.action;
return (
<div style={{
backgroundColor: this.props.theme.base02,
color: this.props.theme.base06,
...this.props.style
}}>
<div style={styles.actionBar}
onClick={this.props.onClick}>
{type}
</div>
{!this.props.collapsed ? this.renderPayload(payload) : ''}
</div>
);
}
}
|
Remove TODO for done thing
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1257 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.domain.delta;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
import javax.persistence.Column;
import java.util.Set;
import org.hibernate.validator.NotNull;
/**
* @author Rhett Sutphin
*/
@Entity
@DiscriminatorValue("add")
public class Add extends Change {
private Integer newChildId;
private Integer index;
@Override
@Transient
public ChangeAction getAction() { return ChangeAction.ADD; }
////// BEAN PROPERTIES
@Column (name = "new_value")
public Integer getNewChildId() {
return newChildId;
}
public void setNewChildId(Integer newChildId) {
this.newChildId = newChildId;
}
@Column (name = "attribute")
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append("[id=").append(getId()).append("; child id ").append(getNewChildId());
if (getIndex() != null) {
sb.append(" at index ").append(getIndex());
}
return sb.append(']').toString();
}
}
| package edu.northwestern.bioinformatics.studycalendar.domain.delta;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
import javax.persistence.Column;
import java.util.Set;
import org.hibernate.validator.NotNull;
/**
* @author Rhett Sutphin
*/
@Entity // TODO
@DiscriminatorValue("add")
public class Add extends Change {
private Integer newChildId;
private Integer index;
@Override
@Transient
public ChangeAction getAction() { return ChangeAction.ADD; }
////// BEAN PROPERTIES
@Column (name = "new_value")
public Integer getNewChildId() {
return newChildId;
}
public void setNewChildId(Integer newChildId) {
this.newChildId = newChildId;
}
@Column (name = "attribute")
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append("[id=").append(getId()).append("; child id ").append(getNewChildId());
if (getIndex() != null) {
sb.append(" at index ").append(getIndex());
}
return sb.append(']').toString();
}
}
|
Fix a brace syntax error | // ==UserScript==
// @name TwitchEmote4Facebook
// @description adds the Twitch emotes to the facebook chat
// @homepage https://github.com/Kiniamaro/TwitchEmote4Facebook
// @version 0.1.0
// @include https://www.facebook.com/*
// @match https://raw.githubusercontent.com/Kiniamaro/TwitchEmote4Facebook/master/emotes.js
// @grant none
// ==/UserScript==
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mut) {
var msglist = mut.target.getElementsByClassName('null');
for (var i = 0; i < msglist.length; i++) {
var msg = msglist[i];
console.log("went in");
textToEmote(msg);
}
});
});
function documentReady() {
var chatContainer = document.getElementById('ChatTabsPagelet');
observer.observe(chatContainer, {childList: true, subtree: true});
}
var readyStateChecker = setInterval(function () {
if (document.readyState === 'complete') {
documentReady();
clearInterval(readyStateChecker);
}
}, 100);
function textToEmote(message) {
console.log(emotes[0].name);
for(var i = 0; i < emotes.length; i ++) {
if (message.textContent.match(emotes[i].regex)){
message.textContent = message.textContent.replace(
emotes[i].regex, emotes[i].image);
}
}
}
| // ==UserScript==
// @name TwitchEmote4Facebook
// @description adds the Twitch emotes to the facebook chat
// @homepage https://github.com/Kiniamaro/TwitchEmote4Facebook
// @version 0.1.0
// @include https://www.facebook.com/*
// @match https://raw.githubusercontent.com/Kiniamaro/TwitchEmote4Facebook/master/emotes.js
// @grant none
// ==/UserScript==
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mut) {
var msglist = mut.target.getElementsByClassName('null');
for (var i = 0; i < msglist.length; i++) {
var msg = msglist[i];
console.log("went in");
textToEmote(msg);
}
}
});
});
function documentReady() {
var chatContainer = document.getElementById('ChatTabsPagelet');
observer.observe(chatContainer, {childList: true, subtree: true});
}
var readyStateChecker = setInterval(function () {
if (document.readyState === 'complete') {
documentReady();
clearInterval(readyStateChecker);
}
}, 100);
function textToEmote(message) {
console.log(emotes[0].name);
for(var i = 0; i < emotes.length; i ++) {
if (message.textContent.match(emotes[i].regex)){
message.textContent = message.textContent.replace(
emotes[i].regex, emotes[i].image);
}
}
}
|
Remove call to expandContentPanel action on slide edit URL/load | import {shortTitle} from '../../configs/general';
import slideIdTypeError from '../error/slideIdTypeError';
import { AllowedPattern } from '../error/util/allowedPattern';
import expandContentPanel from '../deckpagelayout/expandContentPanel';
import serviceUnavailable from '../error/serviceUnavailable';
const log = require('../log/clog');
export default function loadSlideEdit(context, payload, done) {
if (!(AllowedPattern.SLIDE_ID.test(payload.params.sid) || payload.params.sid === undefined)) {
context.executeAction(slideIdTypeError, payload, done);
return;
}
context.service.read('slide.content', payload, {timeout: 20 * 1000}, (err, res) => {
if (err) {
log.error(context, {filepath: __filename, err: err});
context.executeAction(serviceUnavailable, payload, done);
//context.dispatch('LOAD_SLIDE_EDIT_FAILURE', err);
} else {
//expand edit view collapsing TreeNode. Then dispatch LOAD_SLIDE_EDIT_SUCCESS
//revert for SWIK-1347 - Slide Edit view to display decktree (and right-hand panel)
//context.executeAction(expandContentPanel,{}, () => {
context.dispatch('LOAD_SLIDE_EDIT_SUCCESS', res);
//});
//TODO: do not allow editing title when on the edit slide mode
//context.dispatch('UNDO_RENAME_TREE_NODE_SUCCESS', payload.params);
}
let pageTitle = shortTitle + ' | Slide Edit | ' + payload.params.sid;
context.dispatch('UPDATE_PAGE_TITLE', {
pageTitle: pageTitle
});
done();
});
}
| import {shortTitle} from '../../configs/general';
import slideIdTypeError from '../error/slideIdTypeError';
import { AllowedPattern } from '../error/util/allowedPattern';
import expandContentPanel from '../deckpagelayout/expandContentPanel';
import serviceUnavailable from '../error/serviceUnavailable';
const log = require('../log/clog');
export default function loadSlideEdit(context, payload, done) {
if (!(AllowedPattern.SLIDE_ID.test(payload.params.sid) || payload.params.sid === undefined)) {
context.executeAction(slideIdTypeError, payload, done);
return;
}
context.service.read('slide.content', payload, {timeout: 20 * 1000}, (err, res) => {
if (err) {
log.error(context, {filepath: __filename, err: err});
context.executeAction(serviceUnavailable, payload, done);
//context.dispatch('LOAD_SLIDE_EDIT_FAILURE', err);
} else {
//expand edit view collapsing TreeNode. Then dispatch LOAD_SLIDE_EDIT_SUCCESS
context.executeAction(expandContentPanel,{}, () => {
context.dispatch('LOAD_SLIDE_EDIT_SUCCESS', res);
});
//TODO: do not allow editing title when on the edit slide mode
//context.dispatch('UNDO_RENAME_TREE_NODE_SUCCESS', payload.params);
}
let pageTitle = shortTitle + ' | Slide Edit | ' + payload.params.sid;
context.dispatch('UPDATE_PAGE_TITLE', {
pageTitle: pageTitle
});
done();
});
}
|
Use a more pleasant color for LineChart | import VisualizationComponent from './../resplendent';
import vcharts from 'vcharts';
export default class LineChart extends VisualizationComponent {
constructor (el, data) {
super(el);
let values = data.values.map((x) => x[1]);
let minY = Math.min(...values);
if (minY === -Infinity) {
minY = 0;
}
let maxY = Math.max(...values);
if (maxY === Infinity) {
maxY = 0;
}
maxY += (maxY - minY) * 0.20;
this.chart = vcharts.chart('xy', {
el: el,
series: [
{
name: 'series1',
values: data.values,
x: '0',
y: '1',
color: 'darkslategray',
line: true,
point: true
}
],
xAxis: {
title: 'X',
type: 'time'
},
yAxis: {
title: 'Y',
zoom: false,
pan: false,
domain: [minY, maxY]
},
padding: {
top: 100,
bottom: 100,
left: 100,
right: 100
}
});
}
render () {
this.chart.update();
}
}
export default LineChart;
| import VisualizationComponent from './../resplendent';
import vcharts from 'vcharts';
export default class LineChart extends VisualizationComponent {
constructor (el, data) {
super(el);
let values = data.values.map((x) => x[1]);
let minY = Math.min(...values);
if (minY === -Infinity) {
minY = 0;
}
let maxY = Math.max(...values);
if (maxY === Infinity) {
maxY = 0;
}
maxY += (maxY - minY) * 0.20;
this.chart = vcharts.chart('xy', {
el: el,
series: [
{
name: 'series1',
values: data.values,
x: '0',
y: '1',
color: 'blue',
line: true,
point: true
}
],
xAxis: {
title: 'X',
type: 'time'
},
yAxis: {
title: 'Y',
zoom: false,
pan: false,
domain: [minY, maxY]
},
padding: {
top: 100,
bottom: 100,
left: 100,
right: 100
}
});
}
render () {
this.chart.update();
}
}
export default LineChart;
|
Fix resolving of packup index.html template | var path = require('path');
var fs = require('fs');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function(options) {
return {
entry: [
'webpack-dev-server/client?http://localhost:' + options.port,
'webpack/hot/only-dev-server',
options.entryFile
],
output: {
path: path.resolve(options.root, 'build'),
filename: 'app.js',
pathinfo: true,
// contentBase: fs.existsSync(path.resolve(options.root, 'index.html')) ? path.resolve(options.root) : __dirname
contentBase: path.resolve(options.root)
},
devtool: '#eval-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin(options.globals),
new HtmlWebpackPlugin({
title: options.package.name,
template: fs.existsSync(path.resolve(options.root, 'index.html')) ? path.resolve(options.root, 'index.html') : path.resolve(__dirname, 'index.html'),
inject: 'body',
description: options.package.description,
version: options.package.version
})
],
// Packup-specific options, not directly used by webpack
port: options.port,
loaders: {
js: {
loaders: ['react-hot', 'babel']
}
}
};
}
| var path = require('path');
var fs = require('fs');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = function(options) {
return {
entry: [
'webpack-dev-server/client?http://localhost:' + options.port,
'webpack/hot/only-dev-server',
options.entryFile
],
output: {
path: path.resolve(options.root, 'build'),
filename: 'app.js',
pathinfo: true,
// contentBase: fs.existsSync(path.resolve(options.root, 'index.html')) ? path.resolve(options.root) : __dirname
contentBase: path.resolve(options.root)
},
devtool: '#eval-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.DefinePlugin(options.globals),
new HtmlWebpackPlugin({
title: options.package.name,
template: fs.existsSync(path.resolve(options.root, 'index.html')) ? path.resolve(options.root, 'index.html') :'index.html',
inject: 'body',
description: options.package.description,
version: options.package.version
})
],
// Packup-specific options, not directly used by webpack
port: options.port,
loaders: {
js: {
loaders: ['react-hot', 'babel']
}
}
};
}
|
Add error checking for missing json schema | var wrappedRequest = {}
_.each(_currentRequest._getAccessibleProperties(), function(property){
if(typeof _currentRequest[property] == 'function'){
wrappedRequest[property] = function(){
return _currentRequest[property](Array.prototype.slice.call(arguments))
}
}else{
wrappedRequest[property] = _currentRequest[property]
}
})
sandboxValidator(wrappedRequest)
//extra methods added to support validation
wrappedRequest.checkJsonSchema = function checkJsonSchema(filename){
// Initialize a JSON Schema validator.
if(typeof amanda != "function") throw new Error("Failed to load JSON Schema validator")
var jsonSchemaValidator = amanda('json')
// load request schema from cache
var schemaStr = nashornUtils.readFile("schemas/" + filename + ".json")
if(typeof schemaStr != "string") throw new Error("Failed to load json schema")
//if we have everything then validate
jsonSchemaValidator.validate(wrappedRequest.body, schemaStr, { singleError: false }, function(error) {
if(!error) return;
error = JSON.parse(error)
if (wrappedRequest._validationErrors === undefined) {
wrappedRequest._validationErrors = [];
}
for (var x=0; x < error.length; x++){
var validateError = {
param: error[x].property,
msg: error[x].message
}
wrappedRequest._validationErrors.push(validateError)
}
});
}
_matchedFunction.run(wrappedRequest, _currentResponse) | var wrappedRequest = {}
_.each(_currentRequest._getAccessibleProperties(), function(property){
if(typeof _currentRequest[property] == 'function'){
wrappedRequest[property] = function(){
return _currentRequest[property](Array.prototype.slice.call(arguments))
}
}else{
wrappedRequest[property] = _currentRequest[property]
}
})
sandboxValidator(wrappedRequest)
//extra methods added to support validation
wrappedRequest.checkJsonSchema = function checkJsonSchema(filename){
// Initialize a JSON Schema validator.
if(typeof amanda != "function") throw new Error("Failed to load JSON Schema validator")
var jsonSchemaValidator = amanda('json')
// load request schema from cache
var schemaStr = nashornUtils.readFile("schemas/" + filename + ".json")
//if we have everything then validate
jsonSchemaValidator.validate(wrappedRequest.body, schemaStr, { singleError: false }, function(error) {
if(!error) return;
error = JSON.parse(error)
if (wrappedRequest._validationErrors === undefined) {
wrappedRequest._validationErrors = [];
}
for (var x=0; x < error.length; x++){
var validateError = {
param: error[x].property,
msg: error[x].message
}
wrappedRequest._validationErrors.push(validateError)
}
});
}
_matchedFunction.run(wrappedRequest, _currentResponse) |
Fix new notifications on old subjects not appearing | <?php namespace Flarum\Core\Notifications;
use Flarum\Core\Users\User;
class NotificationRepository
{
/**
* Find a user's notifications.
*
* @param User $user
* @param int|null $limit
* @param int $offset
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findByUser(User $user, $limit = null, $offset = 0)
{
$primaries = Notification::select(
app('flarum.db')->raw('MAX(id) AS id'),
app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
)
->where('user_id', $user->id)
->whereIn('type', $user->getAlertableNotificationTypes())
->where('is_deleted', false)
->groupBy('type', 'subject_id')
->orderByRaw('MAX(time) DESC')
->skip($offset)
->take($limit);
return Notification::with('subject')
->select('notifications.*', 'p.unread_count')
->mergeBindings($primaries->getQuery())
->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', 'p.id')
->latest('time')
->get();
}
}
| <?php namespace Flarum\Core\Notifications;
use Flarum\Core\Users\User;
class NotificationRepository
{
/**
* Find a user's notifications.
*
* @param User $user
* @param int|null $limit
* @param int $offset
* @return \Illuminate\Database\Eloquent\Collection
*/
public function findByUser(User $user, $limit = null, $offset = 0)
{
$primaries = Notification::select(
app('flarum.db')->raw('MAX(id) AS id'),
app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
)
->where('user_id', $user->id)
->whereIn('type', $user->getAlertableNotificationTypes())
->where('is_deleted', false)
->groupBy('type', 'subject_id')
->latest('time')
->skip($offset)
->take($limit);
return Notification::with('subject')
->select('notifications.*', 'p.unread_count')
->mergeBindings($primaries->getQuery())
->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', 'p.id')
->latest('time')
->get();
}
}
|
Fix error in error log | import hashlib
from datapackage_pipelines.utilities.extended_json import json
from ..errors import SpecError
from .dependency_resolver import resolve_dependencies
class HashCalculator(object):
def __init__(self):
self.all_pipeline_ids = {}
def calculate_hash(self, spec):
cache_hash = None
if spec.pipeline_id in self.all_pipeline_ids:
message = 'Duplicate key {0} in {1}' \
.format(spec.pipeline_id, spec.path)
spec.errors.append(SpecError('Duplicate Pipeline Id', message))
else:
cache_hash = resolve_dependencies(spec, self.all_pipeline_ids)
if len(spec.errors) > 0:
return cache_hash
for step in spec.pipeline_details['pipeline']:
m = hashlib.md5()
m.update(cache_hash.encode('ascii'))
with open(step['executor'], 'rb') as f:
m.update(f.read())
m.update(json.dumps(step, ensure_ascii=True, sort_keys=True)
.encode('ascii'))
cache_hash = m.hexdigest()
step['_cache_hash'] = cache_hash
self.all_pipeline_ids[spec.pipeline_id] = spec
spec.cache_hash = cache_hash
| import hashlib
from datapackage_pipelines.utilities.extended_json import json
from ..errors import SpecError
from .dependency_resolver import resolve_dependencies
class HashCalculator(object):
def __init__(self):
self.all_pipeline_ids = {}
def calculate_hash(self, spec):
cache_hash = None
if spec.pipeline_id in self.all_pipeline_ids:
message = 'Duplicate key {0} in {1}' \
.format(spec.pipeline_id, spec.abspath)
spec.errors.append(SpecError('Duplicate Pipeline Id', message))
else:
cache_hash = resolve_dependencies(spec, self.all_pipeline_ids)
if len(spec.errors) > 0:
return cache_hash
for step in spec.pipeline_details['pipeline']:
m = hashlib.md5()
m.update(cache_hash.encode('ascii'))
with open(step['executor'], 'rb') as f:
m.update(f.read())
m.update(json.dumps(step, ensure_ascii=True, sort_keys=True)
.encode('ascii'))
cache_hash = m.hexdigest()
step['_cache_hash'] = cache_hash
self.all_pipeline_ids[spec.pipeline_id] = spec
spec.cache_hash = cache_hash
|
Add real plugin state tests for plugins that always work (meta, containers, services). | from contextlib import contextmanager
from os import path
from unittest import TestCase
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch
from canaryd_packages import six
from canaryd.plugin import get_plugin_by_name
class TestPluginRealStates(TestCase):
def run_plugin(self, plugin_name):
plugin = get_plugin_by_name(plugin_name)
plugin.get_state({})
def test_meta_plugin(self):
self.run_plugin('meta')
def test_services_plugin(self):
self.run_plugin('services')
def test_containers_plugin(self):
self.run_plugin('containers')
@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
jsontest_files = path.join('tests/plugins')
@contextmanager
def patch_commands(self, commands):
def handle_command(command, *args, **kwargs):
command = command[0]
if command not in commands:
raise ValueError('Broken tests: {0} not in commands: {1}'.format(
command, commands.keys(),
))
return '\n'.join(commands[command])
check_output_patch = patch(
'canaryd.subprocess.check_output',
handle_command,
)
check_output_patch.start()
yield
check_output_patch.stop()
def jsontest_function(self, test_name, test_data):
plugin = get_plugin_by_name(test_data['plugin'])
with self.patch_commands(test_data['commands']):
state = plugin.get_state({})
try:
self.assertEqual(state, test_data['state'])
except AssertionError:
print(list(diff(test_data['state'], state)))
raise
| from contextlib import contextmanager
from os import path
from unittest import TestCase
from canaryd_packages import six
from dictdiffer import diff
from jsontest import JsonTest
from mock import patch
from canaryd.plugin import get_plugin_by_name
@six.add_metaclass(JsonTest)
class TestPluginStates(TestCase):
jsontest_files = path.join('tests/plugins')
@contextmanager
def patch_commands(self, commands):
def handle_command(command, *args, **kwargs):
command = command[0]
if command not in commands:
raise ValueError(
'Broken tests: {0} not in commands'.format(command),
)
return '\n'.join(commands[command])
check_output_patch = patch(
'canaryd.subprocess.check_output',
handle_command,
)
check_output_patch.start()
yield
check_output_patch.stop()
def jsontest_function(self, test_name, test_data):
plugin = get_plugin_by_name(test_data['plugin'])
with self.patch_commands(test_data['commands']):
state = plugin.get_state({})
try:
self.assertEqual(state, test_data['state'])
except AssertionError:
print(list(diff(test_data['state'], state)))
raise
|
Fix typo in upgrade script
git-svn-id: eda3d06fcef731589ace1b284159cead3416df9b@1647 af82e41b-90c4-0310-8c96-b1721e28e2e2 | import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
name text PRIMARY KEY,
time integer,
description text
);
INSERT INTO version(name,time,description)
SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';
-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
name text PRIMARY KEY,
owner text,
description text
);
INSERT INTO component(name,owner,description)
SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""
def do_upgrade(env, ver, cursor):
cursor.execute(sql)
# Copy the new default wiki macros over to the environment
from trac.siteconfig import __default_macros_dir__ as macros_dir
for f in os.listdir(macros_dir):
if not f.endswith('.py'):
continue
src = os.path.join(macros_dir, f)
dst = os.path.join(env.path, 'wiki-macros', f)
if not os.path.isfile(dst):
shutil.copy2(src, dst)
| import os.path
import shutil
sql = """
-- Remove empty values from the milestone list
DELETE FROM milestone WHERE COALESCE(name,'')='';
-- Add a description column to the version table, and remove unnamed versions
CREATE TEMP TABLE version_old AS SELECT * FROM version;
DROP TABLE version;
CREATE TABLE version (
name text PRIMARY KEY,
time integer,
description text
);
INSERT INTO version(name,time,description)
SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>'';
-- Add a description column to the component table, and remove unnamed components
CREATE TEMP TABLE component_old AS SELECT * FROM component;
DROP TABLE component;
CREATE TABLE component (
name text PRIMARY KEY,
owner text,
description text
);
INSERT INTO component(name,owner,description)
SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>'';
"""
def do_upgrade(env, ver, cursor):
cursor.execute(sql)
# Copy the new default wiki macros over to the environment
from trac.siteconfig import __default_macro_dir__ as macro_dir
for f in os.listdir(macro_dir):
if not f.endswith('.py'):
continue
src = os.path.join(macro_dir, f)
dst = os.path.join(env.path, 'wiki-macros', f)
if not os.path.isfile(dst):
shutil.copy2(src, dst)
|
Add build history seeder to initial seed | <?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
try {
// Miscellaneous Data (e.g. counts)
$this->call(MiscSeeder::class);
// Users, Stats, Ranks
$this->call(UserSeeder::class);
// Beatmaps and sets
$this->call(BeatmapSeeder::class);
// Events
$this->call(EventSeeder::class);
// Scores
$this->call(ScoreSeeder::class);
// BanchoStats
$this->call(BanchoStatsSeeder::class);
// Forums, topics, posts etc
$this->call(ForumSeeder::class);
// Users Profile Data (Favourite maps, First place ranks, Playcounts)
$this->call(UserProfileSeeder::class);
// Store Products
$this->call(ProductSeeder::class);
// Build propagation history (user count data for each build in 30min intervals)
$this->call(BuildPropagationHistorySeeder::class);
} catch (ErrorException $er) {
$this->command->error($er->getMessage());
} catch (Exception $ex) {
$this->command->error($ex->getMessage());
} catch (\Illuminate\Database\QueryException $qe) {
$this->command->error($qe->getMessage());
}
}
}
| <?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
try {
// Miscellaneous Data (e.g. counts)
$this->call(MiscSeeder::class);
// Users, Stats, Ranks
$this->call(UserSeeder::class);
// Beatmaps and sets
$this->call(BeatmapSeeder::class);
// Events
$this->call(EventSeeder::class);
// Scores
$this->call(ScoreSeeder::class);
// BanchoStats
$this->call(BanchoStatsSeeder::class);
// Forums, topics, posts etc
$this->call(ForumSeeder::class);
// Users Profile Data (Favourite maps, First place ranks, Playcounts)
$this->call(UserProfileSeeder::class);
//Store Products
$this->call(ProductSeeder::class);
} catch (ErrorException $er) {
$this->command->error($er->getMessage());
} catch (Exception $ex) {
$this->command->error($ex->getMessage());
} catch (\Illuminate\Database\QueryException $qe) {
$this->command->error($qe->getMessage());
}
}
}
|
Fix minor typo in DownloaderHandlers comment | """Download handlers for different schemes"""
from twisted.internet import defer
from scrapy.exceptions import NotSupported, NotConfigured
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import load_object
from scrapy import signals
class DownloadHandlers(object):
def __init__(self, crawler):
self._handlers = {}
self._notconfigured = {}
handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE')
handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {}))
for scheme, clspath in handlers.iteritems():
# Allow to disable a handler just like any other
# component (extension, middleware, etc).
if clspath is None:
continue
cls = load_object(clspath)
try:
dh = cls(crawler.settings)
except NotConfigured as ex:
self._notconfigured[scheme] = str(ex)
else:
self._handlers[scheme] = dh
crawler.signals.connect(self._close, signals.engine_stopped)
def download_request(self, request, spider):
scheme = urlparse_cached(request).scheme
try:
handler = self._handlers[scheme].download_request
except KeyError:
msg = self._notconfigured.get(scheme, \
'no handler available for that scheme')
raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg))
return handler(request, spider)
@defer.inlineCallbacks
def _close(self, *_a, **_kw):
for dh in self._handlers.values():
if hasattr(dh, 'close'):
yield dh.close()
| """Download handlers for different schemes"""
from twisted.internet import defer
from scrapy.exceptions import NotSupported, NotConfigured
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.misc import load_object
from scrapy import signals
class DownloadHandlers(object):
def __init__(self, crawler):
self._handlers = {}
self._notconfigured = {}
handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE')
handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {}))
for scheme, clspath in handlers.iteritems():
# Allow to disable a handler just like any other
# component (extension, middlware, etc).
if clspath is None:
continue
cls = load_object(clspath)
try:
dh = cls(crawler.settings)
except NotConfigured as ex:
self._notconfigured[scheme] = str(ex)
else:
self._handlers[scheme] = dh
crawler.signals.connect(self._close, signals.engine_stopped)
def download_request(self, request, spider):
scheme = urlparse_cached(request).scheme
try:
handler = self._handlers[scheme].download_request
except KeyError:
msg = self._notconfigured.get(scheme, \
'no handler available for that scheme')
raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg))
return handler(request, spider)
@defer.inlineCallbacks
def _close(self, *_a, **_kw):
for dh in self._handlers.values():
if hasattr(dh, 'close'):
yield dh.close()
|
Allow overriding overflow for sticky table | /* eslint-disable react/prefer-stateless-function */
import React from 'react';
import { Body as TableBody } from 'reactabular-table';
class Body extends React.Component {
constructor(props) {
super(props);
this.ref = null;
}
render() {
const { style, tableHeader, onScroll, ...props } = this.props;
const tableHeaderWidth = tableHeader ? tableHeader.clientWidth : 0;
const tableBodyWidth = this.ref ? this.ref.clientWidth : 0;
const scrollOffset = tableHeaderWidth - tableBodyWidth || 0;
return React.createElement(
TableBody,
{
ref: (body) => {
this.ref = body && body.getRef();
},
style: {
display: 'block',
overflow: 'auto',
paddingRight: scrollOffset
...style || {},
},
// Expand onScroll as otherwise the logic won't work
onScroll: (e) => {
onScroll && onScroll(e);
const { target: { scrollLeft } } = e;
if (tableHeader) {
tableHeader.scrollLeft = scrollLeft;
}
},
...props
}
);
}
getRef() {
return this.ref;
}
}
Body.propTypes = {
style: React.PropTypes.any,
tableHeader: React.PropTypes.any,
onScroll: React.PropTypes.func
};
export default Body;
| /* eslint-disable react/prefer-stateless-function */
import React from 'react';
import { Body as TableBody } from 'reactabular-table';
class Body extends React.Component {
constructor(props) {
super(props);
this.ref = null;
}
render() {
const { style, tableHeader, onScroll, ...props } = this.props;
const tableHeaderWidth = tableHeader ? tableHeader.clientWidth : 0;
const tableBodyWidth = this.ref ? this.ref.clientWidth : 0;
const scrollOffset = tableHeaderWidth - tableBodyWidth || 0;
return React.createElement(
TableBody,
{
ref: (body) => {
this.ref = body && body.getRef();
},
style: {
...style || {},
display: 'block',
overflow: 'auto',
paddingRight: scrollOffset
},
// Expand onScroll as otherwise the logic won't work
onScroll: (e) => {
onScroll && onScroll(e);
const { target: { scrollLeft } } = e;
if (tableHeader) {
tableHeader.scrollLeft = scrollLeft;
}
},
...props
}
);
}
getRef() {
return this.ref;
}
}
Body.propTypes = {
style: React.PropTypes.any,
tableHeader: React.PropTypes.any,
onScroll: React.PropTypes.func
};
export default Body;
|
Allow overriding host/port of S3 service to connect to.
Hardcode non-vhost calling convention, at least for now.
(The host name overriding typically doesn't work with vhosts;
"BUCKET.localhost" is not very helpful.)
To use a local S3-compatible service, put something like
this in ~/.boto:
[Boto]
s3_host = localhost
s3_port = 7280
is_secure = no
TODO: Get a patch to uptream Boto to make this unnecessary. | import boto.s3.connection
import optparse
def main():
parser = optparse.OptionParser(
usage='%prog BUCKET [KEY]',
)
parser.add_option(
'--method',
default='GET',
help='HTTP method to use [default: %default]',
)
parser.add_option(
'--expiry',
type='int',
default=60*60*24,
help='seconds before expiry [default: %default]',
)
opts, args = parser.parse_args()
try:
(bucket, key) = args
except ValueError:
try:
(bucket,) = args
except ValueError:
parser.error('Unexpected arguments.')
else:
key = None
conn_kwargs = {}
host = boto.config.get('Boto', 's3_host')
if host is not None:
conn_kwargs['host'] = host
port = boto.config.getint('Boto', 's3_port')
if port is not None:
conn_kwargs['port'] = port
conn = boto.s3.connection.S3Connection(
calling_format=boto.s3.connection.OrdinaryCallingFormat(),
**conn_kwargs
)
kwargs = {}
if bucket is not None:
kwargs['bucket'] = bucket
if key is not None:
kwargs['key'] = key
url = conn.generate_url(
expires_in=opts.expiry,
method=opts.method,
**kwargs
)
print url
| import boto.s3.connection
import optparse
def main():
parser = optparse.OptionParser(
usage='%prog BUCKET [KEY]',
)
parser.add_option(
'--method',
default='GET',
help='HTTP method to use [default: %default]',
)
parser.add_option(
'--expiry',
type='int',
default=60*60*24,
help='seconds before expiry [default: %default]',
)
opts, args = parser.parse_args()
try:
(bucket, key) = args
except ValueError:
try:
(bucket,) = args
except ValueError:
parser.error('Unexpected arguments.')
else:
key = None
conn = boto.s3.connection.S3Connection(
# aws_access_key_id=cfg.get(section, 'access_key'),
# aws_secret_access_key=cfg.get(section, 'secret_key'),
# is_secure=cfg.getboolean(section, 'is_secure'),
# port=port,
# host=cfg.get(section, 'host'),
)
kwargs = {}
if bucket is not None:
kwargs['bucket'] = bucket
if key is not None:
kwargs['key'] = key
url = conn.generate_url(
expires_in=opts.expiry,
method=opts.method,
**kwargs
)
print url
|
Optimize formatting of main file | /*global
define,
require,
window,
console,
_
*/
/*jslint devel:true,
white: true
*/
define([
'jquery',
'underscore',
'./properties',
'./initialproperties',
'./lib/js/extensionUtils',
'text!./lib/css/style.css'
],
function ($, _, props, initProps, extensionUtils, cssContent) {
'use strict';
extensionUtils.addStyleToHeader(cssContent);
return {
definition: props,
initialProperties: initProps,
snapshot: { canTakeSnapshot: true },
resize : function( $element, layout ) {
//do nothing
},
// clearSelectedValues : function($element) {
//
// },
// Angular Support (uncomment to use)
//template: '',
// Angular Controller
//controller: ['$scope', function ($scope) {
//
//}],
// (Angular Controller)
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
console.info('$element:');
console.log($element);
console.info('layout:');
console.log(layout);
console.groupEnd();
$element.empty();
var $helloWorld = $(document.createElement('div'));
$helloWorld.addClass('hello-world');
$helloWorld.html('Hello World from the extension "<%= extensionName%>"');
$element.append($helloWorld);
}
};
});
| /*global
define,
require,
window,
console,
_
*/
/*jslint devel:true,
white: true
*/
define([
'jquery',
'underscore',
'./properties',
'./initialproperties',
'./lib/js/extensionUtils',
'text!./lib/css/style.css'
],
function ($, _, props, initProps, extensionUtils, cssContent) {
'use strict';
extensionUtils.addStyleToHeader(cssContent);
return {
definition: props,
initialProperties: initProps,
snapshot: { canTakeSnapshot: true },
resize : function( $element, layout ) {
//do nothing
},
// clearSelectedValues : function($element) {
//
// },
// Angular Template
//template: '',
// (Angular Template)
// Angular Controller
controller: ['$scope', function ($scope) {
}],
// (Angular Controller)
// Paint Method
paint: function ( $element, layout ) {
console.groupCollapsed('Basic Objects');
console.info('$element:');
console.log($element);
console.info('layout:');
console.log(layout);
console.groupEnd();
$element.empty();
var $helloWorld = $(document.createElement('div'));
$helloWorld.addClass('hello-world');
$helloWorld.html('Hello World from the extension "<%= extensionName%>"');
$element.append($helloWorld);
}
// (Paint Method)
};
});
|
Revert array_walk to foreach for php 5.3 compat | <?php
namespace OpenConext\EngineBlock\Logger\Formatter;
use EngineBlock_Exception;
use Monolog\Formatter\FormatterInterface;
use OpenConext\EngineBlock\Logger\Message\AdditionalInfo;
final class AdditionalInfoFormatter implements FormatterInterface
{
/**
* @var FormatterInterface
*/
private $formatter;
public function __construct(FormatterInterface $formatter)
{
$this->formatter = $formatter;
}
public function format(array $record)
{
return $this->formatter->format($this->addAdditionalInfoForEngineBlockExceptions($record));
}
public function formatBatch(array $records)
{
foreach ($records as &$value) {
$value = $this->addAdditionalInfoForEngineBlockExceptions($value);
};
return $this->formatter->formatBatch($records);
}
/**
* @param array $record
* @return array
*/
private function addAdditionalInfoForEngineBlockExceptions(array $record)
{
if (!isset($record['context']['exception'])) {
return $record;
}
$exception = $record['context']['exception'];
if (!$exception instanceof EngineBlock_Exception) {
return $record;
}
$record['context']['exception'] = AdditionalInfo::createFromException($exception)->toArray();
return $record;
}
}
| <?php
namespace OpenConext\EngineBlock\Logger\Formatter;
use EngineBlock_Exception;
use Monolog\Formatter\FormatterInterface;
use OpenConext\EngineBlock\Logger\Message\AdditionalInfo;
final class AdditionalInfoFormatter implements FormatterInterface
{
/**
* @var FormatterInterface
*/
private $formatter;
public function __construct(FormatterInterface $formatter)
{
$this->formatter = $formatter;
}
public function format(array $record)
{
return $this->formatter->format($this->addAdditionalInfoForEngineBlockExceptions($record));
}
public function formatBatch(array $records)
{
$self = $this;
array_walk($records, function (&$value) use ($self) {
$value = $self->addAdditionalInfoForEngineBlockExceptions($value);
});
return $this->formatter->formatBatch($records);
}
/**
* @param array $record
* @return array
*/
private function addAdditionalInfoForEngineBlockExceptions(array $record)
{
if (!isset($record['context']['exception'])) {
return $record;
}
$exception = $record['context']['exception'];
if (!$exception instanceof EngineBlock_Exception) {
return $record;
}
$record['context']['exception'] = AdditionalInfo::createFromException($exception)->toArray();
return $record;
}
}
|
Put the console command in the request scope | <?php
namespace Forex\Bundle\EmailBundle\Command;
use Forex\Bundle\EmailBundle\Entity\EmailMessage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Request;
class SendPendingEmailsCommand extends ContainerAwareCommand
{
protected $em;
protected $sender;
protected function configure()
{
$this
->setName('email:send-pending-emails')
->setDescription('Sends all pending emails')
;
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$request = new Request();
$container->set('request', $request);
$container->enterScope('request');
$this->em = $container->get('doctrine.orm.default_entity_manager');
$this->sender = $container->get('forex.email_sender');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$progress = $this->getHelperSet()->get('progress');
$pendingMessages = $this->em->getRepository('ForexEmailBundle:EmailMessage')->findPendingEmails();
$progress->start($output, count($pendingMessages));
foreach ($pendingMessages as $message) {
$this->sender->send($message);
$progress->advance();
}
$progress->finish();
$this->em->flush();
}
}
| <?php
namespace Forex\Bundle\EmailBundle\Command;
use Forex\Bundle\EmailBundle\Entity\EmailMessage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SendPendingEmailsCommand extends ContainerAwareCommand
{
protected $em;
protected $sender;
protected function configure()
{
$this
->setName('email:send-pending-emails')
->setDescription('Sends all pending emails')
;
}
protected function initialize(InputInterface $input, OutputInterface $output)
{
$container = $this->getContainer();
$this->em = $container->get('doctrine.orm.default_entity_manager');
$this->sender = $container->get('forex.email_sender');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$progress = $this->getHelperSet()->get('progress');
$pendingMessages = $this->em->getRepository('ForexEmailBundle:EmailMessage')->findPendingEmails();
$progress->start($output, count($pendingMessages));
foreach ($pendingMessages as $message) {
$this->sender->send($message);
$progress->advance();
}
$progress->finish();
$this->em->flush();
}
}
|
Verify the config file before use | <?php
namespace Craft;
class SyncCommand extends BaseCommand
{
public function actionPlugin()
{
echo "Synchronizing plugins\n";
if (!craft()->config->exists('activePlugins', 'plugins')) {
echo "You need to specify plugins in craft/config/plugins.php before using this functionality.\n";
}
$requiredPlugins = array_merge(['Console'], craft()->config->get('activePlugins', 'plugins'));
$currentPlugins = craft()->plugins->getPlugins(false);
foreach ($currentPlugins as $plugin) {
$pluginClassHandle = $plugin->getClassHandle();
if (in_array($pluginClassHandle, $requiredPlugins)) {
// This plugin should be activated
if (!$plugin->isInstalled) {
echo "Installing $pluginClassHandle plugin.\n";
craft()->plugins->installPlugin($pluginClassHandle);
} elseif (!$plugin->isEnabled) {
echo "Enabling $pluginClassHandle plugin.\n";
craft()->plugins->enablePlugin($pluginClassHandle);
} else {
echo "Plugin $pluginClassHandle is already active.\n";
}
} else {
// This plugin should be deactivated
if ($plugin->isEnabled) {
echo "Disabling $pluginClassHandle plugin.\n";
craft()->plugins->disablePlugin($pluginClassHandle);
}
}
}
}
}
| <?php
namespace Craft;
class SyncCommand extends BaseCommand
{
public function actionPlugin()
{
echo "Synchronizing plugins\n";
$requiredPlugins = array_merge(['Console'], craft()->config->get('activePlugins', 'plugins'));
$currentPlugins = craft()->plugins->getPlugins(false);
foreach ($currentPlugins as $plugin) {
$pluginClassHandle = $plugin->getClassHandle();
if (in_array($pluginClassHandle, $requiredPlugins)) {
// This plugin should be activated
if (!$plugin->isInstalled) {
echo "Installing $pluginClassHandle plugin.\n";
craft()->plugins->installPlugin($pluginClassHandle);
} elseif (!$plugin->isEnabled) {
echo "Enabling $pluginClassHandle plugin.\n";
craft()->plugins->enablePlugin($pluginClassHandle);
} else {
echo "Plugin $pluginClassHandle is already active.\n";
}
} else {
// This plugin should be deactivated
if ($plugin->isEnabled) {
echo "Disabling $pluginClassHandle plugin.\n";
craft()->plugins->disablePlugin($pluginClassHandle);
}
}
}
}
}
|
Include path in plugin info regardless of source. | var _ = require('lodash');
var fs = require('fs');
var path = require('path');
module.exports = {
filter: function(plugins) {
var toLoad = [];
_.forOwn(plugins, function(options, name) {
if(!options)
return;
if(options === true) {
toLoad.push({
name: name,
source: 'npm',
path: path.join('node_modules', name);
});
} else if(typeof(options) === "object") {
if(options.disabled)
return;
var source = options.path ? 'local' : 'npm';
var plPath = options.path || path.join('node_modules', name);
toLoad.push(_.merge({ source: source, name: name, path: plPath }, options, function(a, b) { return b ? b : a; }));
}
});
return toLoad;
},
enable: function(plugin) {
return plugin.enableAsync().then(function() {
plugin.enabled = true;
sails.emit('plugin:' + plugin.name + ':enabled');
plugin.log.info('Enabled plugin `' + plugin.name + '` at version ' + plugin.version + '.');
}).catch(function(err) {
plugin.log.error("Couldn't enable: " + err.message);
});
},
disable: function(plugin) {
return new Promise(function(resolve, reject) {
plugin.disable();
plugin.enabled = false;
sails.emit('plugin:' + plugin.name + ':disable');
plugin.log.info('Disabled plugin `' + plugin.name + '`.');
resolve(plugin);
});
}
};
| var _ = require('lodash');
var fs = require('fs');
var path = require('path');
module.exports = {
filter: function(plugins) {
var toLoad = [];
_.forOwn(plugins, function(options, name) {
if(!options)
return;
if(options === true) {
toLoad.push({
name: name,
source: 'npm'
});
} else if(typeof(options) === "object") {
if(options.disabled)
return;
var source = options.path ? 'local' : 'npm';
toLoad.push(_.merge({ source: source, name: name }, options, function(a, b) { return b ? b : a; }));
}
});
return toLoad;
},
enable: function(plugin) {
return plugin.enableAsync().then(function() {
plugin.enabled = true;
sails.emit('plugin:' + plugin.name + ':enabled');
plugin.log.info('Enabled plugin `' + plugin.name + '` at version ' + plugin.version + '.');
}).catch(function(err) {
plugin.log.error("Couldn't enable: " + err.message);
});
},
disable: function(plugin) {
return new Promise(function(resolve, reject) {
plugin.disable();
plugin.enabled = false;
sails.emit('plugin:' + plugin.name + ':disable');
plugin.log.info('Disabled plugin `' + plugin.name + '`.');
resolve(plugin);
});
}
};
|
Fix phpstan error with static call to instance method | <?php
/**
* Copyright (c) Qobo Ltd. (https://www.qobo.biz)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Qobo Ltd. (https://www.qobo.biz)
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Menu\View\Helper;
use Cake\Core\Configure;
use Cake\Routing\Router;
use Cake\Utility\Hash;
use Cake\View\Helper;
use Cake\View\View;
class MenuHelper extends Helper
{
/**
* Set the full base URL recursivelly for all the menu and their children.
*
* @param mixed[] $menu Given menu
* @return mixed[] $menus
*/
public function setFullBaseUrl(array $menu = []): array
{
$menu = array_map(
function ($v) {
$url = Hash::get($v, 'url');
$children = Hash::get($v, 'children');
if ($url) {
$v['url'] = Router::url($url, true);
}
if (is_array($children)) {
$v['children'] = $this->setFullBaseUrl($children);
}
return $v;
},
$menu
);
return $menu;
}
}
| <?php
/**
* Copyright (c) Qobo Ltd. (https://www.qobo.biz)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Qobo Ltd. (https://www.qobo.biz)
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Menu\View\Helper;
use Cake\Core\Configure;
use Cake\Utility\Hash;
use Cake\View\Helper;
use Cake\View\Helper\UrlHelper;
use Cake\View\View;
class MenuHelper extends Helper
{
/**
* Set the full base URL recursivelly for all the menu and their children.
*
* @param mixed[] $menu Given menu
* @return mixed[] $menus
*/
public function setFullBaseUrl(array $menu = []): array
{
$menu = array_map(
function ($v) {
$url = Hash::get($v, 'url');
$children = Hash::get($v, 'children');
if ($url) {
$v['url'] = UrlHelper::build($url, [
'fullBase' => true
]);
}
if (is_array($children)) {
$v['children'] = $this->setFullBaseUrl($children);
}
return $v;
},
$menu
);
return $menu;
}
}
|
BAP-2898: Add widgets to render lists of calls and emails on shopping cart and order page
- small fix in email listener | <?php
namespace Oro\Bundle\EmailBundle\EventListener\Datagrid;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Event\BuildAfter;
use Oro\Bundle\EmailBundle\Datagrid\EmailQueryFactory;
class EmailListener
{
/**
* @var EmailQueryFactory
*/
protected $factory;
/**
* @param EmailQueryFactory $factory
*/
public function __construct(EmailQueryFactory $factory)
{
$this->factory = $factory;
}
/**
* Add required filters
*
* @param BuildAfter $event
*/
public function onBuildAfter(BuildAfter $event)
{
/** @var OrmDatasource $ormDataSource */
$ormDataSource = $event->getDatagrid()->getDatasource();
$queryBuilder = $ormDataSource->getQueryBuilder();
$parameters = $event->getParameters();
$this->factory->prepareQuery($queryBuilder);
if (array_key_exists('emailIds', $parameters)) {
$emailIds = $parameters['emailIds'];
if (!is_array($emailIds)) {
$emailIds = explode(',', $emailIds);
}
$queryBuilder->andWhere($queryBuilder->expr()->in('e.id', $emailIds));
}
}
}
| <?php
namespace Oro\Bundle\EmailBundle\EventListener\Datagrid;
use Oro\Bundle\DataGridBundle\Datasource\Orm\OrmDatasource;
use Oro\Bundle\DataGridBundle\Event\BuildAfter;
use Oro\Bundle\EmailBundle\Datagrid\EmailQueryFactory;
class EmailListener
{
/**
* @var EmailQueryFactory
*/
protected $factory;
/**
* @param EmailQueryFactory $factory
*/
public function __construct(EmailQueryFactory $factory)
{
$this->factory = $factory;
}
/**
* Add required filters
*
* @param BuildAfter $event
*/
public function onBuildAfter(BuildAfter $event)
{
/** @var OrmDatasource $ormDataSource */
$ormDataSource = $event->getDatagrid()->getDatasource();
$queryBuilder = $ormDataSource->getQueryBuilder();
$parameters = $event->getParameters();
$this->factory->prepareQuery($queryBuilder);
if (array_key_exists('emailIds', $parameters)) {
$emailIds = $parameters['emailIds'];
if (!is_array($emailIds)) {
$emailIds = explode(',', $emailIds);
}
if (empty($emailIds)) {
$emailIds = array(0);
}
$queryBuilder->andWhere($queryBuilder->expr()->in('e.id', $emailIds));
}
}
}
|
Add key param to geojson scraper
Sometimes we encounter a geojson file with no 'id' attribute
This allows us to specify a property to use as a key instead | import json
import os
import urllib.request
from retry import retry
from urllib.error import HTTPError
from common import store_history, truncate, summarise
# hack to override sqlite database filename
# see: https://help.morph.io/t/using-python-3-with-morph-scraperwiki-fork/148
os.environ['SCRAPERWIKI_DATABASE_NAME'] = 'sqlite:///data.sqlite'
import scraperwiki
@retry(HTTPError, tries=2, delay=30)
def scrape(url, council_id, encoding, table, key=None):
with urllib.request.urlopen(url) as response:
# clear any existing data
truncate(table)
# load json
data_str = response.read()
data = json.loads(data_str.decode(encoding))
print("found %i %s" % (len(data['features']), table))
for feature in data['features']:
# assemble record
record = {
'council_id': council_id,
'geometry': json.dumps(feature),
}
if key is None:
record['pk'] = feature['id']
else:
record['pk'] = feature['properties'][key]
for field in feature['properties']:
if field != 'bbox':
record[field] = feature['properties'][field]
# save to db
scraperwiki.sqlite.save(
unique_keys=['pk'],
data=record,
table_name=table)
scraperwiki.sqlite.commit_transactions()
# print summary
summarise(table)
store_history(data_str, table)
| import json
import os
import urllib.request
from retry import retry
from urllib.error import HTTPError
from common import store_history, truncate, summarise
# hack to override sqlite database filename
# see: https://help.morph.io/t/using-python-3-with-morph-scraperwiki-fork/148
os.environ['SCRAPERWIKI_DATABASE_NAME'] = 'sqlite:///data.sqlite'
import scraperwiki
@retry(HTTPError, tries=2, delay=30)
def scrape(url, council_id, encoding, table):
with urllib.request.urlopen(url) as response:
# clear any existing data
truncate(table)
# load json
data_str = response.read()
data = json.loads(data_str.decode(encoding))
print("found %i %s" % (len(data['features']), table))
for feature in data['features']:
# assemble record
record = {
'pk': feature['id'],
'council_id': council_id,
'geometry': json.dumps(feature),
}
for field in feature['properties']:
if field != 'bbox':
record[field] = feature['properties'][field]
# save to db
scraperwiki.sqlite.save(
unique_keys=['pk'],
data=record,
table_name=table)
scraperwiki.sqlite.commit_transactions()
# print summary
summarise(table)
store_history(data_str, table)
|
Fix if statements checking if header/footer exist | from IPython.nbconvert.preprocessors import Preprocessor
from IPython.nbformat.current import read as read_nb
from IPython.utils.traitlets import Unicode
class IncludeHeaderFooter(Preprocessor):
"""A preprocessor for adding header and/or footer cells to a notebook."""
header = Unicode("", config=True, help="Path to header notebook")
footer = Unicode("", config=True, help="Path to footer notebook")
def preprocess(self, nb, resources):
"""Concatenates the cells from the header and footer notebooks to the
given cells.
"""
new_cells = []
# header
if self.header:
with open(self.header, 'r') as fh:
header_nb = read_nb(fh, 'ipynb')
new_cells.extend(header_nb.worksheets[0].cells)
# body
new_cells.extend(nb.worksheets[0].cells)
# footer
if self.footer:
with open(self.footer, 'r') as fh:
footer_nb = read_nb(fh, 'ipynb')
new_cells.extend(footer_nb.worksheets[0].cells)
nb.worksheets[0].cells = new_cells
super(IncludeHeaderFooter, self).preprocess(nb, resources)
return nb, resources
def preprocess_cell(self, cell, resources, cell_index):
return cell, resources
| from IPython.nbconvert.preprocessors import Preprocessor
from IPython.nbformat.current import read as read_nb
from IPython.utils.traitlets import Unicode
class IncludeHeaderFooter(Preprocessor):
"""A preprocessor for adding header and/or footer cells to a notebook."""
header = Unicode("", config=True, help="Path to header notebook")
footer = Unicode("", config=True, help="Path to footer notebook")
def preprocess(self, nb, resources):
"""Concatenates the cells from the header and footer notebooks to the
given cells.
"""
new_cells = []
# header
if self.header != "":
with open(self.header, 'r') as fh:
header_nb = read_nb(fh, 'ipynb')
new_cells.extend(header_nb.worksheets[0].cells)
# body
new_cells.extend(nb.worksheets[0].cells)
# footer
if self.footer != "":
with open(self.footer, 'r') as fh:
footer_nb = read_nb(fh, 'ipynb')
new_cells.extend(footer_nb.worksheets[0].cells)
nb.worksheets[0].cells = new_cells
super(IncludeHeaderFooter, self).preprocess(nb, resources)
return nb, resources
def preprocess_cell(self, cell, resources, cell_index):
return cell, resources
|
Fix project on home page if there's only 1 |
App.HomeController = Ember.ObjectController.extend({
needs: ['currentUser'],
project: null,
isCampaignHomePage: false,
projectIndex: 0,
actions: {
nextProject: function() { // TODO: similar thing for fundraisers?
var projects = this.get('projects');
this.incrementProperty('projectIndex');
if (this.get('projectIndex') >= projects.get('length')) {
this.set('projectIndex', 0);
}
this.loadProject();
},
previousProject: function() {
var projects = this.get('projects');
this.decrementProperty('projectIndex');
if (this.get('projectIndex') < 0) {
this.set('projectIndex', projects.get('length') - 1);
}
this.loadProject();
}
},
loadProject: function() {
var controller = this;
var projectId = this.get('projects').objectAt(this.get('projectIndex')).get('id');
App.Project.find(projectId).then(function(project) {
controller.set('project', project);
});
},
loadQuote: function() {
this.set('quote', this.get('quotes').objectAt(this.get('quoteIndex')));
},
});
|
App.HomeController = Ember.ObjectController.extend({
needs: ['currentUser'],
project: null,
isCampaignHomePage: false,
projectIndex: 1,
actions: {
nextProject: function() { // TODO: similar thing for fundraisers?
var projects = this.get('projects');
this.incrementProperty('projectIndex');
if (this.get('projectIndex') >= projects.get('length')) {
this.set('projectIndex', 0);
}
this.loadProject();
},
previousProject: function() {
var projects = this.get('projects');
this.decrementProperty('projectIndex');
if (this.get('projectIndex') < 0) {
this.set('projectIndex', projects.get('length') - 1);
}
this.loadProject();
}
},
loadProject: function() {
var controller = this;
var projectId = this.get('projects').objectAt(this.get('projectIndex')).get('id');
App.Project.find(projectId).then(function(project) {
controller.set('project', project);
});
},
loadQuote: function() {
this.set('quote', this.get('quotes').objectAt(this.get('quoteIndex')));
},
});
|
Fix error with file not found when clearing templates cache
Signed-off-by: Sam Poyigi <ccc2dd82f84c4106203d3b58d5938b70cab9f94a@users.noreply.github.com> | <?php
namespace System\Helpers;
use Igniter\Flame\Support\Facades\File;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
class CacheHelper
{
use \Igniter\Flame\Traits\Singleton;
/**
* Execute the console command.
*/
public static function clear()
{
Cache::flush();
self::clearInternal();
}
public static function clearInternal()
{
$instance = self::instance();
$instance->clearCache();
$instance->clearView();
$instance->clearTemplates();
$instance->clearCombiner();
$instance->clearMeta();
}
public function clearView()
{
$path = config()->get('view.compiled');
foreach (File::glob("{$path}/*") as $view) {
File::delete($view);
}
}
public function clearCombiner()
{
$this->clearDirectory('/system/combiner');
}
public function clearCache()
{
$this->clearDirectory('/system/cache');
}
public function clearTemplates()
{
$this->clearDirectory('/system/templates');
}
public function clearMeta()
{
File::delete(App::getCachedClassesPath());
File::delete(App::getCachedServicesPath());
}
public function clearDirectory($path)
{
if (!File::isDirectory(storage_path().$path))
return;
foreach (File::directories(storage_path().$path) as $directory) {
File::deleteDirectory($directory);
}
}
}
| <?php
namespace System\Helpers;
use Igniter\Flame\Support\Facades\File;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
class CacheHelper
{
use \Igniter\Flame\Traits\Singleton;
/**
* Execute the console command.
*/
public static function clear()
{
Cache::flush();
self::clearInternal();
}
public static function clearInternal()
{
$instance = self::instance();
$instance->clearCache();
$instance->clearView();
$instance->clearTemplates();
$instance->clearCombiner();
$instance->clearMeta();
}
public function clearView()
{
$path = config()->get('view.compiled');
foreach (File::glob("{$path}/*") as $view) {
File::delete($view);
}
}
public function clearCombiner()
{
$this->clearDirectory('/system/combiner');
}
public function clearCache()
{
$this->clearDirectory('/system/cache');
}
public function clearTemplates()
{
$this->clearDirectory('/system/templates');
}
public function clearMeta()
{
File::delete(App::getCachedClassesPath());
File::delete(App::getCachedServicesPath());
}
public function clearDirectory($path)
{
foreach (File::directories(storage_path().$path) as $directory) {
File::deleteDirectory($directory);
}
}
}
|
Make the first group a non-capturing one and remove the last group | /* 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/. */
// @flow
/**
* Takes a string and returns the string with public URLs removed.
* It doesn't remove the URLs like `chrome://..` because they are internal URLs
* and they shouldn't be removed.
*/
export function removeURLs(
string: string,
removeExtensions: boolean = true
): string {
const regExpExtension = removeExtensions ? '|moz-extension' : '';
const regExp = new RegExp(
'((?:https?|ftp' + regExpExtension + ')://)[^\\s/$.?#].[^\\s)]*',
// ^ ^ ^
// | | matches any characters except
// | | whitespaces and ) character.
// | | Other characters are allowed now
// | matches any characters except whitespaces
// | and / $ . ? # characters because this is
// | start of the URL
// Matches http, https, ftp and optionally moz-extension protocols
'gi'
);
return string.replace(regExp, '$1<URL>');
}
| /* 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/. */
// @flow
/**
* Takes a string and returns the string with public URLs removed.
* It doesn't remove the URLs like `chrome://..` because they are internal URLs
* and they shouldn't be removed.
*/
export function removeURLs(
string: string,
removeExtensions: boolean = true
): string {
const regExpExtension = removeExtensions ? '|moz-extension' : '';
const regExp = new RegExp(
'((https?|ftp' + regExpExtension + ')://)([^\\s/$.?#].[^\\s)]*)',
// ^ ^ ^
// | | matches any characters except
// | | whitespaces and ) character.
// | | Other characters are allowed now
// | matches any characters except whitespaces
// | and / $ . ? # characters because this is
// | start of the URL
// Matches http, https, ftp and optionally moz-extension protocols
'gi'
);
return string.replace(regExp, '$1<URL>');
}
|
Update 'search_term' functon. Add 'match_phrase' function. | from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http import HttpResponse
def search(request):
if request.method == 'GET':
term = request.GET.get('term_search')
if term == None:
term = ""
response = search_term(term)
pages = []
for hit in response['hits']['hits']:
x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]}
pages.append(x)
return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term})
def search_term(term):
es = Elasticsearch()
res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match_phrase": { "title": "\"" + str(term) + "\"" }},
{ "match_phrase": { "text": "\"" + str(term) + "\"" }},
{ "match_phrase": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}})
return res
| from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http import HttpResponse
def search(request):
if request.method == 'GET':
term = request.GET.get('term_search')
if term == None:
term = ""
response = search_term(term)
pages = []
for hit in response['hits']['hits']:
x = {'source': hit["_source"], 'highlight': hit["highlight"]["text"][0]}
pages.append(x)
return render(request, 'view_athena/index.html', {'pages':pages,'term_search':term})
def search_term(term):
es = Elasticsearch()
res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }},
{ "match": { "text": "\"" + str(term) + "\"" }},
{ "match": { "description": "\"" + str(term) + "\"" }}]}},"highlight": {"fields" : {"text" : {}}}})
return res
|
Add missing form type mapping in the form utils | <?php
namespace LAG\AdminBundle\Utils;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class FormUtils
{
/**
* Convert a shortcut type into its class type.
*
* @param string $type
*
* @return string
*/
public static function convertShortFormType(string $type)
{
$mapping = [
'choice' => ChoiceType::class,
'array' => ChoiceType::class,
'string' => TextType::class,
'entity' => EntityType::class,
'date' => DateType::class,
'datetime' => DateType::class,
'text' => TextType::class,
'number' => NumberType::class,
'integer' => NumberType::class,
'smallint' => NumberType::class,
'boolean' => CheckboxType::class,
];
if (key_exists($type, $mapping)) {
$type = $mapping[$type];
}
return $type;
}
}
| <?php
namespace LAG\AdminBundle\Utils;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class FormUtils
{
/**
* Convert a shortcut type into its class type.
*
* @param string $type
*
* @return string
*/
public static function convertShortFormType(string $type)
{
$mapping = [
'choice' => ChoiceType::class,
'string' => TextType::class,
'entity' => EntityType::class,
'date' => DateType::class,
'datetime' => DateType::class,
'text' => TextType::class,
'number' => NumberType::class,
'integer' => NumberType::class,
'smallint' => NumberType::class,
'boolean' => CheckboxType::class,
];
if (key_exists($type, $mapping)) {
$type = $mapping[$type];
}
return $type;
}
}
|
Fix password_reset_confirm URL for django change.
Django changed the uid parameter to the password_reset_confirm view to be
base64-encoded instead of base36. This means our URL had to change a bit.
Trivial change. | from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
| from __future__ import unicode_literals
from django.conf.urls import patterns, url
urlpatterns = patterns(
"reviewboard.accounts.views",
url(r'^register/$', 'account_register',
{'next_url': 'dashboard'}, name="register"),
url(r'^preferences/$', 'user_preferences', name="user-preferences"),
)
urlpatterns += patterns(
"django.contrib.auth.views",
url(r'^login/$', 'login',
{'template_name': 'accounts/login.html'},
name='login'),
url(r'^logout/$', 'logout_then_login', name='logout'),
url(r'^recover/$',
'password_reset',
{
'template_name': 'accounts/password_reset.html',
'email_template_name': 'accounts/password_reset_email.txt'
},
name='recover'),
url(r'^recover/done/$',
'password_reset_done',
{'template_name': 'accounts/password_reset_done.html'},
name='password_reset_done'),
url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
'password_reset_confirm',
{'template_name': 'accounts/password_reset_confirm.html'},
name='password-reset-confirm'),
url(r'^reset/done/$',
'password_reset_complete',
{'template_name': 'accounts/password_reset_complete.html'}),
)
|
Remove upper bound on jaraco.util. Incompatibility will be handled as it's encountered. | import sys
import setuptools
def read_long_description():
with open('README.rst') as f:
data = f.read()
with open('CHANGES.rst') as f:
data += '\n\n' + f.read()
return data
importlib_req = ['importlib'] if sys.version_info < (2,7) else []
argparse_req = ['argparse'] if sys.version_info < (2,7) else []
setup_params = dict(
name="irc",
description="IRC (Internet Relay Chat) protocol client library for Python",
long_description=read_long_description(),
use_hg_version=True,
packages=setuptools.find_packages(),
author="Joel Rosdahl",
author_email="[email protected]",
maintainer="Jason R. Coombs",
maintainer_email="[email protected]",
url="http://python-irclib.sourceforge.net",
license="MIT",
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
],
install_requires=[
'six',
'jaraco.util',
] + importlib_req + argparse_req,
setup_requires=[
'hgtools',
'pytest-runner',
],
tests_require=[
'pytest',
'mock',
],
)
if __name__ == '__main__':
setuptools.setup(**setup_params)
| import sys
import setuptools
def read_long_description():
with open('README.rst') as f:
data = f.read()
with open('CHANGES.rst') as f:
data += '\n\n' + f.read()
return data
importlib_req = ['importlib'] if sys.version_info < (2,7) else []
argparse_req = ['argparse'] if sys.version_info < (2,7) else []
setup_params = dict(
name="irc",
description="IRC (Internet Relay Chat) protocol client library for Python",
long_description=read_long_description(),
use_hg_version=True,
packages=setuptools.find_packages(),
author="Joel Rosdahl",
author_email="[email protected]",
maintainer="Jason R. Coombs",
maintainer_email="[email protected]",
url="http://python-irclib.sourceforge.net",
license="MIT",
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
],
install_requires=[
'six',
'jaraco.util<10dev',
] + importlib_req + argparse_req,
setup_requires=[
'hgtools',
'pytest-runner',
],
tests_require=[
'pytest',
'mock',
],
)
if __name__ == '__main__':
setuptools.setup(**setup_params)
|
Opcodes: Add tests for final two functions in ArrayAccess (only throw exceptions) | <?php
namespace BitWasp\Bitcoin\Tests\Script;
use BitWasp\Bitcoin\Script\Opcodes;
class OpcodesTest extends \PHPUnit_Framework_TestCase
{
public function testGetOpByName()
{
$op = new OpCodes;
$expected = 0;
$lookupOpName = 'OP_0';
$val = $op->getOpByName('OP_0');
$this->assertSame($expected, $val);
$this->assertTrue(isset($op[Opcodes::OP_0]));
$this->assertSame($lookupOpName, $op[Opcodes::OP_0]);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Opcode by that name not found
*/
public function testGetOpByNameFail()
{
$op = new Opcodes();
$op->getOpByName('OP_DEADBEEF');
}
public function testGetOp()
{
$op = new OpCodes;
// Check getRegisteredOpCode returns the right operation
$expected = 'OP_0';
$val = $op->getOp(0);
$this->assertSame($expected, $val);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Opcode not found
*/
public function testGetOpCodeException()
{
$op = new OpCodes;
$op->getOp(3);
}
/**
* @expectedException \RuntimeException
*/
public function testNoWriteSet()
{
$op = new Opcodes();
$op[1] = 2;
}
/**
* @expectedException \RuntimeException
*/
public function testNoWriteUnSet()
{
$op = new Opcodes();
unset($op[Opcodes::OP_1]);
}
}
| <?php
namespace BitWasp\Bitcoin\Tests\Script;
use BitWasp\Bitcoin\Script\Opcodes;
class OpcodesTest extends \PHPUnit_Framework_TestCase
{
public function testGetOpByName()
{
$op = new OpCodes;
$expected = 0;
$lookupOpName = 'OP_0';
$val = $op->getOpByName('OP_0');
$this->assertSame($expected, $val);
$this->assertTrue(isset($op[Opcodes::OP_0]));
$this->assertSame($lookupOpName, $op[Opcodes::OP_0]);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Opcode by that name not found
*/
public function testGetOpByNameFail()
{
$op = new Opcodes();
$op->getOpByName('OP_DEADBEEF');
}
public function testGetOp()
{
$op = new OpCodes;
// Check getRegisteredOpCode returns the right operation
$expected = 'OP_0';
$val = $op->getOp(0);
$this->assertSame($expected, $val);
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Opcode not found
*/
public function testGetOpCodeException()
{
$op = new OpCodes;
$op->getOp(3);
}
}
|
Move 'open all' link to same line as bug lings.
Rework JS a bit more. | "use strict";
var bugRe = /\bbug (\d+)\b/i;
var bugURL = 'https://bugzilla.mozilla.org/show_bug.cgi?id=';
function getBugIds() {
let bugIds = [];
$('a.message, div.commit-desc pre').each(function(){
let match = bugRe.exec(this.textContent);
if (match) {
let bugId = match[1];
if (bugIds.indexOf(bugId) === -1) {
bugIds.push(bugId);
}
}
});
return bugIds;
}
function getBugLinks(){
let bugIds = getBugIds();
return bugIds.map(function(k){
return '<a href="' + bugURL + k + '" target="_blank" class="bugzilla_link">' + k + '</a>';
});
}
var $bugsList = $([
'<p class="explain">Bugs in commits ',
'(<a href="#" id="open_all_bugzilla_links">open all</a>): ',
getBugLinks().join(', '),
'</p>'
].join('')).insertBefore('#commits_bucket .boxed-group:first');
$('#open_all_bugzilla_links').on('click', function(e){
e.preventDefault();
$bugsList.find('a.bugzilla_link').each(function(){
window.open(this.href);
});
});
| "use strict";
var bugRe = /\bbug (\d+)\b/i;
var bugURL = 'https://bugzilla.mozilla.org/show_bug.cgi?id=';
function getBugIds() {
let bugIds = [];
$('a.message, div.commit-desc pre').each(function(){
let match = bugRe.exec(this.textContent);
if (match) {
let bugId = match[1];
if (bugIds.indexOf(bugId) === -1) {
bugIds.push(bugId);
}
}
});
return bugIds;
}
function getBugLinks(){
let bugIds = getBugIds();
return bugIds.map(function(k){
return '<a href="' + bugURL + k + '" target="_blank" class="bugzilla-link">' + k + '</a>';
});
}
var $bugsList = $([
'<p class="explain" id="bugzilla-links">Bugs in commits: ',
getBugLinks().join(', '),
'</p>'
].join('')).insertBefore('#commits_bucket .boxed-group:first');
$('<p class="explain"><a href="#">Open all in tabs</a></p>')
.insertAfter($bugsList)
.find('a').on('click', function(e){
e.preventDefault();
$bugsList.find('a').each(function(){
window.open(this.href);
});
});
|
Remove support for Python 2. | import copy
import json
from urllib.parse import urlencode
import html5lib
import requests
from application import APPLICATION as APP
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
| import copy
import json
import requests
import html5lib
from application import APPLICATION as APP
# Be compatible with python 2 and 3
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
class BaseProvider(object):
# ==== HELPER METHODS ====
def parse_html(self, url, css_selector, timeout=60, cache=True):
html = self._http_get(url, timeout=timeout, cache=cache)
document = html5lib.parse(html)
results = document.cssselect(css_selector)
data = [result.text_content() for result in results]
return data
def traverse_json(self, data, path):
if not path:
return data
new_data = copy.copy(data)
for item in path.split("."):
if item.isdigit():
item = int(item)
try:
new_data = new_data[item]
except (IndexError, KeyError):
return {}
return new_data
def parse_json(self, url, path=None, timeout=60, cache=True):
data = self._http_get(url, timeout=timeout, cache=cache)
data = json.loads(data)
data = self.traverse_json(data, path)
return data
def urlencode(self, data):
return urlencode(data)
# ==== PRIVATE METHODS ====
def _http_get(self, url, timeout=60, cache=True):
base = requests if not cache else APP.setting("WEBCACHE")
response = base.get(url, timeout=timeout)
return response.text
|
Update URL since repository has moved to pytest-dev | from setuptools import setup
with open("README.rst") as readme_file:
readme = readme_file.read()
setup(
name='pytest-describe',
version='1.0.0',
description='Describe-style plugin for pytest',
long_description=readme,
long_description_content_type='text/x-rst',
url='https://github.com/pytest-dev/pytest-describe',
author='Robin Pedersen',
author_email='[email protected]',
license='MIT license',
install_requires=[
'pytest>=2.6.0',
],
entry_points={
'pytest11': [
'pytest-describe = pytest_describe.plugin'
],
},
packages=['pytest_describe'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
)
| from setuptools import setup
with open("README.rst") as readme_file:
readme = readme_file.read()
setup(
name='pytest-describe',
version='1.0.0',
description='Describe-style plugin for pytest',
long_description=readme,
long_description_content_type='text/x-rst',
url='https://github.com/ropez/pytest-describe',
author='Robin Pedersen',
author_email='[email protected]',
license='MIT license',
install_requires=[
'pytest>=2.6.0',
],
entry_points={
'pytest11': [
'pytest-describe = pytest_describe.plugin'
],
},
packages=['pytest_describe'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries',
'Topic :: Utilities',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
)
|
Fix author email for pypi packaging | from setuptools import setup
from setuptools import find_packages
import versioneer
# README #
def readme():
with open('README.rst') as f:
return f.read()
setup(name='fair',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Python package to perform calculations with the FaIR simple climate model',
long_description=readme(),
keywords='simple climate model temperature response carbon cycle emissions forcing',
url='https://github.com/OMS-NetZero/FAIR',
author='OMS-NetZero, Chris Smith, Richard Millar, Zebedee Nicholls, Myles Allen',
author_email='[email protected]',
license='Apache 2.0',
packages=find_packages(exclude=['tests*','docs*']),
package_data={'': ['*.csv']},
include_package_data=True,
install_requires=[
'matplotlib',
'numpy>=1.11.3',
'scipy>=0.19.0',
'pandas'
],
zip_safe=False,
extras_require={'docs': ['sphinx>=1.4', 'nbsphinx'],
'dev' : ['notebook', 'wheel', 'twine'],
'test': ['pytest>=4.0', 'nbval', 'pytest-cov', 'codecov']}
)
| from setuptools import setup
from setuptools import find_packages
import versioneer
# README #
def readme():
with open('README.rst') as f:
return f.read()
setup(name='fair',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Python package to perform calculations with the FaIR simple climate model',
long_description=readme(),
keywords='simple climate model temperature response carbon cycle emissions forcing',
url='https://github.com/OMS-NetZero/FAIR',
author='OMS-NetZero, Chris Smith, Richard Millar, Zebedee Nicholls, Myles Allen',
author_email='[email protected], [email protected]',
license='Apache 2.0',
packages=find_packages(exclude=['tests*','docs*']),
package_data={'': ['*.csv']},
include_package_data=True,
install_requires=[
'matplotlib',
'numpy>=1.11.3',
'scipy>=0.19.0',
'pandas'
],
zip_safe=False,
extras_require={'docs': ['sphinx>=1.4', 'nbsphinx'],
'dev' : ['notebook', 'wheel', 'twine'],
'test': ['pytest>=4.0', 'nbval', 'pytest-cov', 'codecov']}
)
|
Allow to modify the size of batchOperation | <?php
/**
* AppShell file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Shell', 'Console');
/**
* Application Shell
*
* Add your application-wide methods in the class below, your shells
* will inherit them.
*
* @package app.Console.Command
*/
class AppShell extends Shell {
public $batchOperationSize = 1000;
protected function batchOperation($model, $operation, $options) {
$proceeded = 0;
$options = array_merge(
array(
'contain' => array(),
'limit' => $this->batchOperationSize,
'offset' => 0,
),
$options
);
do {
$data = $this->{$model}->find('all', $options);
$proceeded += $this->{$operation}($data, $model);
echo ".";
$options['offset'] += $this->batchOperationSize;
} while ($data);
return $proceeded;
}
}
| <?php
/**
* AppShell file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Shell', 'Console');
/**
* Application Shell
*
* Add your application-wide methods in the class below, your shells
* will inherit them.
*
* @package app.Console.Command
*/
class AppShell extends Shell {
protected function batchOperation($model, $operation, $options) {
$batchSize = 1000;
$proceeded = 0;
$options = array_merge(
array(
'contain' => array(),
'limit' => $batchSize,
'offset' => 0,
),
$options
);
do {
$data = $this->{$model}->find('all', $options);
$proceeded += $this->{$operation}($data, $model);
echo ".";
$options['offset'] += $batchSize;
} while ($data);
return $proceeded;
}
}
|
Add method for limiting clients by grant. | <?php
namespace Northstar\Auth\Repositories;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use Northstar\Auth\Entities\ClientEntity;
use Northstar\Models\Client;
class ClientRepository implements ClientRepositoryInterface
{
/**
* Get a client.
*
* @param string $clientIdentifier The client's identifier
* @param string $grantType The grant type used
* @param null|string $clientSecret The client's secret (if sent)
* @param bool $mustValidateSecret If true the client must attempt to validate the secret unless the client
* is confidential
*
* @return \League\OAuth2\Server\Entities\ClientEntityInterface
*/
public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
{
// Fetch client from the database.
$model = Client::where('client_id', $clientIdentifier)->first();
if (! $model) {
return null;
}
// Is this client allowed to use this grant type?
if (! $this->clientCanUseGrant($model, $grantType)) {
return null;
}
// If the grant requires us to check the client secret, do that.
if ($mustValidateSecret && $model->client_secret !== $clientSecret) {
return null;
}
return new ClientEntity($model->client_id, $model->scope);
}
/**
* Is the given client allowed to use the given grant type?
*
* @param $client
* @param $grantType
* @return bool
*/
public function clientCanUseGrant($client, $grantType)
{
// @TODO: Limit this based on the 'allowed_grants' field on the Client.
return true;
}
}
| <?php
namespace Northstar\Auth\Repositories;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use Northstar\Auth\Entities\ClientEntity;
use Northstar\Models\Client;
class ClientRepository implements ClientRepositoryInterface
{
/**
* Get a client.
*
* @param string $clientIdentifier The client's identifier
* @param string $grantType The grant type used
* @param null|string $clientSecret The client's secret (if sent)
* @param bool $mustValidateSecret If true the client must attempt to validate the secret unless the client
* is confidential
*
* @return \League\OAuth2\Server\Entities\ClientEntityInterface
*/
public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null, $mustValidateSecret = true)
{
// Fetch client from the database.
$model = Client::where('client_id', $clientIdentifier)->first();
if (! $model) {
return null;
}
// If the grant requires us to check the client secret, do that.
if ($mustValidateSecret && $model->client_secret !== $clientSecret) {
return null;
}
return new ClientEntity($model->client_id, $model->scope);
}
}
|
Fix test after notification classes change | 'use strict';
/*global $*/
describe('ACP edit user group', function () {
it('should save changes', function (done) {
let user;
let adminGroupId;
TEST.browser
.do.auth('admin_users_usergroups_edit', usr => {
user = usr;
})
.fn(cb => TEST.N.models.users.UserGroup.findIdByName('administrators')
.then(res => {
adminGroupId = res;
user.usergroups.push(adminGroupId);
return user.save();
})
.asCallback(cb)
)
.do.open(() => TEST.N.router.linkTo('admin.users.usergroups.edit', { _id: adminGroupId }))
.do.click('#setting_can_see_deleted_users')
.do.click('button.btn-primary[type="submit"]')
.do.wait('.notification-info')
.do.reload()
.test.evaluate(function () {
return $('#setting_can_see_deleted_users').is(':checked') === false;
})
// Set setting back
.do.click('#setting_can_see_deleted_users')
.do.click('button.btn-primary[type="submit"]')
.do.wait('.notification-info')
.close()
.run(true, done);
});
});
| 'use strict';
/*global $*/
describe('ACP edit user group', function () {
it('should save changes', function (done) {
let user;
let adminGroupId;
TEST.browser
.do.auth('admin_users_usergroups_edit', usr => {
user = usr;
})
.fn(cb => TEST.N.models.users.UserGroup.findIdByName('administrators')
.then(res => {
adminGroupId = res;
user.usergroups.push(adminGroupId);
return user.save();
})
.asCallback(cb)
)
.do.open(() => TEST.N.router.linkTo('admin.users.usergroups.edit', { _id: adminGroupId }))
.do.click('#setting_can_see_deleted_users')
.do.click('button.btn-primary[type="submit"]')
.do.wait('.alert-info')
.do.reload()
.test.evaluate(function () {
return $('#setting_can_see_deleted_users').is(':checked') === false;
})
// Set setting back
.do.click('#setting_can_see_deleted_users')
.do.click('button.btn-primary[type="submit"]')
.do.wait('.alert-info')
.close()
.run(true, done);
});
});
|
Check autoAnchor before child iteration | package com.bottomsheetbehavior;
import android.support.design.widget.CoordinatorLayout;
import android.view.View;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ThemedReactContext;
public class CoordinatorLayoutManager extends ViewGroupManager<CoordinatorLayoutView> {
private final static String REACT_CLASS = "RCTCoordinatorLayoutAndroid";
@Override
public String getName() {
return REACT_CLASS;
}
@Override
public CoordinatorLayoutView createViewInstance(ThemedReactContext context) {
return new CoordinatorLayoutView(context);
}
@Override
public void addView(CoordinatorLayoutView parent, View child, int index) {
super.addView(parent, child, index);
// Sets FloatingActionButton anchor automatically
if (child instanceof FloatingActionButtonView) {
if (((FloatingActionButtonView) child).getAutoAnchor()) {
for (int i = 0; i < parent.getChildCount(); i++) {
View childView = parent.getChildAt(i);
if (childView instanceof BottomSheetBehaviorView) {
int bottomSheetId = childView.getId();
((CoordinatorLayout.LayoutParams) child.getLayoutParams()).setAnchorId(bottomSheetId);
}
}
}
}
}
@Override
public boolean needsCustomLayoutForChildren() {
return true;
}
}
| package com.bottomsheetbehavior;
import android.support.design.widget.CoordinatorLayout;
import android.view.View;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ThemedReactContext;
public class CoordinatorLayoutManager extends ViewGroupManager<CoordinatorLayoutView> {
private final static String REACT_CLASS = "RCTCoordinatorLayoutAndroid";
@Override
public String getName() {
return REACT_CLASS;
}
@Override
public CoordinatorLayoutView createViewInstance(ThemedReactContext context) {
return new CoordinatorLayoutView(context);
}
@Override
public void addView(CoordinatorLayoutView parent, View child, int index) {
super.addView(parent, child, index);
// Sets FloatingActionButton anchor automatically
if (child instanceof FloatingActionButtonView) {
boolean autoAnchor = ((FloatingActionButtonView) child).getAutoAnchor();
for (int i = 0; i < parent.getChildCount(); i++) {
View childView = parent.getChildAt(i);
if (childView instanceof BottomSheetBehaviorView && autoAnchor) {
int bottomSheetId = childView.getId();
((CoordinatorLayout.LayoutParams) child.getLayoutParams()).setAnchorId(bottomSheetId);
}
}
}
}
@Override
public boolean needsCustomLayoutForChildren() {
return true;
}
}
|
Disable toasts for network broadcast events. | package com.github.tuxdude.yani.network;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.widget.Toast;
import com.github.tuxdude.yani.utils.Logger;
public class NetworkBroadcastListener extends BroadcastReceiver {
private static NetworkBroadcastListener instance = null;
@Override
public void onReceive(Context context, Intent intent) {
Logger.trace();
if (intent.getAction().equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
//Toast.makeText(context, "Airplane Mode Changed!", Toast.LENGTH_LONG).show();
Logger.d("Airplane Mode Changed");
}
else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
//Toast.makeText(context, "Wifi State Changed!", Toast.LENGTH_LONG).show();
Logger.d("Wifi State Changed");
}
else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
//Toast.makeText(context, "Network State Changed!", Toast.LENGTH_LONG).show();
Logger.d("Network State Changed");
}
else {
Logger.d("Unhandled intent: " + intent.getAction().toString());
}
}
private NetworkBroadcastListener() {
// Empty constructor
}
public static NetworkBroadcastListener getInstance() {
if (instance == null) {
instance = new NetworkBroadcastListener();
}
return instance;
}
}
| package com.github.tuxdude.yani.network;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.widget.Toast;
import com.github.tuxdude.yani.utils.Logger;
public class NetworkBroadcastListener extends BroadcastReceiver {
private static NetworkBroadcastListener instance = null;
@Override
public void onReceive(Context context, Intent intent) {
Logger.trace();
if (intent.getAction().equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
Toast.makeText(context, "Airplane Mode Changed!", Toast.LENGTH_LONG).show();
Logger.d("Airplane Mode Changed");
}
else if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
Toast.makeText(context, "Wifi State Changed!", Toast.LENGTH_LONG).show();
Logger.d("Wifi State Changed");
}
else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
Toast.makeText(context, "Network State Changed!", Toast.LENGTH_LONG).show();
Logger.d("Network State Changed");
}
else {
Logger.d("Unhandled intent: " + intent.getAction().toString());
}
}
private NetworkBroadcastListener() {
// Empty constructor
}
public static NetworkBroadcastListener getInstance() {
if (instance == null) {
instance = new NetworkBroadcastListener();
}
return instance;
}
}
|
Update repeated to password type. | <?php namespace Kris\LaravelFormBuilder\Fields;
class RepeatedType extends ParentType
{
/**
* Get the template, can be config variable or view path
*
* @return string
*/
protected function getTemplate()
{
return 'repeated';
}
protected function getDefaults()
{
return [
'type' => 'password',
'second_name' => null,
'first_options' => ['label' => 'Password', 'is_child' => true],
'second_options' => ['label' => 'Password confirmation', 'is_child' => true]
];
}
protected function createChildren()
{
$firstName = $this->getOption('real_name', $this->name);
$secondName = $this->getOption('second_name');
if (is_null($secondName)) {
$secondName = $this->getOption('real_name', $this->name).'_confirmation';
}
$form = $this->parent->getFormBuilder()->plain([
'name' => $this->parent->getName()
])
->add($firstName, $this->getOption('type'), $this->getOption('first_options'))
->add($secondName, $this->getOption('type'), $this->getOption('second_options'));
$this->children['first'] = $form->getField($firstName);
$this->children['second'] = $form->getField($secondName);
}
}
| <?php namespace Kris\LaravelFormBuilder\Fields;
class RepeatedType extends ParentType
{
/**
* Get the template, can be config variable or view path
*
* @return string
*/
protected function getTemplate()
{
return 'repeated';
}
protected function getDefaults()
{
return [
'type' => 'text',
'second_name' => null,
'first_options' => ['label' => 'Password', 'is_child' => true],
'second_options' => ['label' => 'Password confirmation', 'is_child' => true]
];
}
protected function createChildren()
{
$firstName = $this->getOption('real_name', $this->name);
$secondName = $this->getOption('second_name');
if (is_null($secondName)) {
$secondName = $this->getOption('real_name', $this->name).'_confirmation';
}
$form = $this->parent->getFormBuilder()->plain([
'name' => $this->parent->getName()
])
->add($firstName, $this->getOption('type'), $this->getOption('first_options'))
->add($secondName, $this->getOption('type'), $this->getOption('second_options'));
$this->children['first'] = $form->getField($firstName);
$this->children['second'] = $form->getField($secondName);
}
}
|
Use or operator in python to tidy up completion building. | import vim, syncrequest, types
class Completion:
def get_completions(self, column, partialWord):
parameters = {}
parameters['column'] = vim.eval(column)
parameters['wordToComplete'] = vim.eval(partialWord)
parameters['WantDocumentationForEveryCompletionResult'] = \
bool(int(vim.eval('g:omnicomplete_fetch_full_documentation')))
want_snippet = \
bool(int(vim.eval('g:OmniSharp_want_snippet')))
parameters['WantSnippet'] = want_snippet
parameters['WantMethodHeader'] = want_snippet
parameters['WantReturnType'] = want_snippet
parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:])
response = syncrequest.get_response('/autocomplete', parameters)
enc = vim.eval('&encoding')
vim_completions = []
if response is not None:
for completion in response:
complete = {
'snip': completion['Snippet'] or '',
'word': completion['MethodHeader'] or completion['CompletionText'],
'menu': completion['ReturnType'] or completion['DisplayText'],
'info': completion['Description'].replace('\r\n', '\n') or '',
'icase': 1,
'dup':1
}
vim_completions.append(complete)
return vim_completions
| import vim, syncrequest, types
class Completion:
def get_completions(self, column, partialWord):
parameters = {}
parameters['column'] = vim.eval(column)
parameters['wordToComplete'] = vim.eval(partialWord)
parameters['WantDocumentationForEveryCompletionResult'] = \
bool(int(vim.eval('g:omnicomplete_fetch_full_documentation')))
want_snippet = \
bool(int(vim.eval('g:OmniSharp_want_snippet')))
parameters['WantSnippet'] = want_snippet
parameters['WantMethodHeader'] = want_snippet
parameters['WantReturnType'] = want_snippet
parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:])
response = syncrequest.get_response('/autocomplete', parameters)
enc = vim.eval('&encoding')
vim_completions = []
if response is not None:
for completion in response:
complete = {
'snip': completion['Snippet'] if completion['Snippet'] is not None else '',
'word': completion['MethodHeader'] if completion['MethodHeader'] is not None else completion['CompletionText'],
'menu': completion['ReturnType'] if completion['ReturnType'] is not None else completion['DisplayText'],
'info': completion['Description'].replace('\r\n', '\n') if completion['Description'] is not None else '',
'icase': 1,
'dup':1
}
vim_completions.append(complete)
return vim_completions
|
Add some more visionary words | 'use strict';
module.exports = defineRules;
var visionaryWords = [
/blue\s*sk(?:y|ies)/,
/enlighten(?:ed|ing)?/,
/green\s*fields?/,
/incentivi[sz]e/,
'paradigm',
/producti[sz]e/,
/reach(?:ed|ing) out/,
/synerg(?:y|ize|ise)/,
/visionar(?:y|ies)/
];
function defineRules (linter) {
// Visionary terminology
linter.addRule({
name: 'Visionary Terminology',
desc: 'Terms like "blue sky" and "enlightened" often indicate that a non technical ' +
'person (perhaps a CEO or stakeholder) has been involved in writing the spec. Be ' +
'down-to-earth, and explain things in plain English.',
test: function (spec, result) {
var visionaryMentions = spec.containsAnyOf(visionaryWords);
var amount = (visionaryMentions.length > 2 ? 'Lots of' : 'Some');
if (visionaryMentions.length > 0) {
result.addWarning(
amount + ' "visionary" terminology is used',
visionaryMentions
);
result.addCultureFailPoints(visionaryMentions.length / 2);
result.addRealismFailPoints(visionaryMentions.length / 2);
}
}
});
}
| 'use strict';
module.exports = defineRules;
var visionaryWords = [
/blue\s*sk(?:y|ies)/,
/enlighten(?:ed|ing)?/,
/green\s*fields?/,
/reach(?:ed|ing) out/,
/visionar(?:y|ies)/
];
function defineRules (linter) {
// Visionary terminology
linter.addRule({
name: 'Visionary Terminology',
desc: 'Terms like "blue sky" and "enlightened" often indicate that a non technical ' +
'person (perhaps a CEO or stakeholder) has been involved in writing the spec. Be ' +
'down-to-earth, and explain things in plain English.',
test: function (spec, result) {
var visionaryMentions = spec.containsAnyOf(visionaryWords);
var amount = (visionaryMentions.length > 2 ? 'Lots of' : 'Some');
if (visionaryMentions.length > 0) {
result.addWarning(
amount + ' "visionary" terminology is used',
visionaryMentions
);
result.addCultureFailPoints(visionaryMentions.length / 2);
result.addRealismFailPoints(visionaryMentions.length / 2);
}
}
});
}
|
Add parenthesis to print statement | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
##
# Test out the cor() functionality
# If NAs in the frame, they are skipped in calculation unless na.rm = F
# If any categorical columns, throw an error
##
import numpy as np
def cor_test():
iris_h2o = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv"))
iris_np = np.genfromtxt(pyunit_utils.locate("smalldata/iris/iris.csv"),
delimiter=',',
skip_header=1,
usecols=(0, 1, 2, 3))
cor_np = h2o.H2OFrame(np.corrcoef(iris_np,rowvar=0))
cor_h2o = iris_h2o[0:4].cor()
cor_diff = abs(cor_h2o - cor_np)
print("Correlation matrix with H2O: ")
print cor_h2o
print("Correlation matrix with Numpy: ")
print cor_np
print("Correlation differences between H2O and Numpy: ")
print cor_diff
print("Max difference in correlation calculation between H2O and Numpy: ")
print cor_diff.max()
max = cor_diff.max()
assert max < .006, "expected equal correlations"
if __name__ == "__main__":
pyunit_utils.standalone_test(cor_test)
else:
cor_test() | from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
##
# Test out the cor() functionality
# If NAs in the frame, they are skipped in calculation unless na.rm = F
# If any categorical columns, throw an error
##
import numpy as np
def cor_test():
iris_h2o = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv"))
iris_np = np.genfromtxt(pyunit_utils.locate("smalldata/iris/iris.csv"),
delimiter=',',
skip_header=1,
usecols=(0, 1, 2, 3))
cor_np = h2o.H2OFrame(np.corrcoef(iris_np,rowvar=0))
cor_h2o = iris_h2o[0:4].cor()
cor_diff = abs(cor_h2o - cor_np)
print "Correlation matrix with H2O: "
print cor_h2o
print "Correlation matrix with Numpy: "
print cor_np
print "Correlation differences between H2O and Numpy: "
print cor_diff
print "Max difference in correlation calculation between H2O and Numpy: "
print cor_diff.max()
max = cor_diff.max()
assert max < .006, "expected equal correlations"
if __name__ == "__main__":
pyunit_utils.standalone_test(cor_test)
else:
cor_test() |
Add missing semi-colons and if/else that statement | var gaTracker = (function(dLayer) {
// Push the object to the dataLayer
// Parameters:
// eventName, category, action, label, Type String
// value Type Number (int)
var pushEventToDataLayer = function(eventName, category, action, label, value) {
dLayer.push({
"event": eventName, // on GTM this would be the event that triggers the tag.
"category": category,
"action": action,
"label": label,
"value": value
});
};
var isUniversalAnalytics = function(ga) {
return typeof ga !== "undefined" && typeof ga.getAll === 'function' ? true : false;
};
var isClassicAnalytics = function(_gat) {
return typeof _gat !== "undefined" && typeof _gat._getTrackers === 'function' ? true : false;
};
// decorate target URL for cross domain tracker.
var decorateLink = function(url) {
var trackers, linker;
if (isUniversalAnalytics(ga)) {
trackers = ga.getAll();
if (trackers.length) {
linker = new window.gaplugins.Linker(trackers[0]);
url = linker.decorate(url);
}
} else if (isClassicAnalytics(_gat)) {
trackers = _gat._getTrackers();
if (trackers.length) {
url = trackers[0]._getLinkerUrl(url);
}
}
return url;
};
return {
"event": pushEventToDataLayer,
"decorateLink": decorateLink
};
})(dataLayer);
| var gaTracker = (function(dLayer) {
// Push the object to the dataLayer
// Parameters:
// eventName, category, action, label, Type String
// value Type Number (int)
var pushEventToDataLayer = function(eventName, category, action, label, value) {
dLayer.push({
"event": eventName, // on GTM this would be the event that triggers the tag.
"category": category,
"action": action,
"label": label,
"value": value
});
};
var isUniversalAnalytics = function(ga) {
return typeof ga !== "undefined" && typeof ga.getAll === 'function' ? true : false;
}
var isClassicAnalytics = function(_gat) {
return typeof _gat !== "undefined" && typeof _gat._getTrackers === 'function' ? true : false;
}
// decorate target URL for cross domain tracker.
var decorateLink = function(url) {
var trackers, linker;
if (isUniversalAnalytics(ga)) {
trackers = ga.getAll();
if (trackers.length) {
linker = new window.gaplugins.Linker(trackers[0]);
url = linker.decorate(url);
}
}
if (isClassicAnalytics(_gat)) {
trackers = _gat._getTrackers();
if (trackers.length) {
url = trackers[0]._getLinkerUrl(url);
}
}
return url;
};
return {
"event": pushEventToDataLayer,
"decorateLink": decorateLink
};
})(dataLayer);
|
Fix so migrations get included with pypi package. Update version | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-tenant-users',
version='0.2.17',
packages=[
'tenant_users',
'tenant_users.tenants',
'tenant_users.tenants.migrations',
'tenant_users.permissions',
'tenant_users.permissions.migrations',
],
include_package_data=True,
license='MIT License',
description='A Django app to extend django-tenant-schemas to incorporate global multi-tenant users',
long_description=README,
url='https://www.github.com/Corvia/django-tenant-users',
author='Corvia Technologies, LLC',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-tenant-users',
version='0.2.16',
packages=[
'tenant_users',
'tenant_users.tenants',
'tenant_users.permissions',
],
include_package_data=True,
license='MIT License',
description='A Django app to extend django-tenant-schemas to incorporate global multi-tenant users',
long_description=README,
url='https://www.github.com/Corvia/django-tenant-users',
author='Corvia Technologies, LLC',
author_email='[email protected]',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Disable test that calls System.exit | package com.netflix.governator;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Singleton;
import org.testng.annotations.Test;
public class ShutdownHookModuleTest {
@Singleton
private static class MySingleton {
@Override
public String toString() {
return "MySingleton [initCounter=" + initCounter.get()
+ ", shutdownCounter=" + shutdownCounter.get() + "]";
}
private AtomicInteger initCounter = new AtomicInteger(0);
private AtomicInteger shutdownCounter = new AtomicInteger(0);
@PostConstruct
void init() {
initCounter.incrementAndGet();
}
@PreDestroy
void shutdown() {
shutdownCounter.incrementAndGet();
}
}
@Test(enabled=false)
public void test() throws InterruptedException {
System.out.println("Starting");
LifecycleInjector injector = Governator.createInjector(new LifecycleModule(), new ShutdownHookModule());
Executors.newScheduledThreadPool(1).schedule(new Runnable(){
@Override
public void run() {
System.out.println("Terminating");
System.exit(-1);
}
}, 100, TimeUnit.MILLISECONDS);
MySingleton singleton = injector.getInstance(MySingleton.class);
System.out.println("Waiting");
injector.awaitTermination();
System.out.println("Terminated : " + singleton);
}
}
| package com.netflix.governator;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Singleton;
import org.testng.annotations.Test;
public class ShutdownHookModuleTest {
@Singleton
private static class MySingleton {
@Override
public String toString() {
return "MySingleton [initCounter=" + initCounter.get()
+ ", shutdownCounter=" + shutdownCounter.get() + "]";
}
private AtomicInteger initCounter = new AtomicInteger(0);
private AtomicInteger shutdownCounter = new AtomicInteger(0);
@PostConstruct
void init() {
initCounter.incrementAndGet();
}
@PreDestroy
void shutdown() {
shutdownCounter.incrementAndGet();
}
}
@Test
public void test() throws InterruptedException {
System.out.println("Starting");
LifecycleInjector injector = Governator.createInjector(new LifecycleModule(), new ShutdownHookModule());
Executors.newScheduledThreadPool(1).schedule(new Runnable(){
@Override
public void run() {
System.out.println("Terminating");
System.exit(-1);
}
}, 100, TimeUnit.MILLISECONDS);
MySingleton singleton = injector.getInstance(MySingleton.class);
System.out.println("Waiting");
injector.awaitTermination();
System.out.println("Terminated : " + singleton);
}
}
|
Fix in the apply() method in list context (did not returned the correct list when slice and sliceProperties) | <?php
/*
* Data Object
* https://github.com/ivopetkov/data-object
* Copyright (c) Ivo Petkov
* Free to use under the MIT license.
*/
namespace IvoPetkov;
/**
*
*/
trait DataListContextTrait
{
/**
* An array containing all the actions.
*
* @var array
*/
public $actions = [];
/**
* Apply the actions to the data list specified.
*
* @return void
*/
public function apply(&$list)
{
foreach ($this->actions as $action) {
switch ($action->name) {
case 'filter':
$list->filter($action->callback);
break;
case 'filterBy':
$list->filterBy($action->property, $action->value, $action->operator);
break;
case 'sort':
$list->sort($action->callback);
break;
case 'sortBy':
$list->sortBy($action->property, $action->order);
break;
case 'sliceProperties':
$list = $list->sliceProperties($action->properties);
break;
case 'reverse':
$list->reverse();
break;
case 'shuffle':
$list->shuffle();
break;
case 'slice':
$list = $list->slice($action->offset, $action->limit);
break;
case 'map':
$list->map($action->callback);
break;
default:
throw new \Exception('Should not get here for "' . $action->name . '"!');
break;
}
}
}
}
| <?php
/*
* Data Object
* https://github.com/ivopetkov/data-object
* Copyright (c) Ivo Petkov
* Free to use under the MIT license.
*/
namespace IvoPetkov;
/**
*
*/
trait DataListContextTrait
{
/**
* An array containing all the actions.
*
* @var array
*/
public $actions = [];
/**
* Apply the actions to the data list specified.
*
* @return void
*/
public function apply($list)
{
foreach ($this->actions as $action) {
switch ($action->name) {
case 'filter':
$list->filter($action->callback);
break;
case 'filterBy':
$list->filterBy($action->property, $action->value, $action->operator);
break;
case 'sort':
$list->sort($action->callback);
break;
case 'sortBy':
$list->sortBy($action->property, $action->order);
break;
case 'sliceProperties':
$list->sliceProperties($action->properties);
break;
case 'reverse':
$list->reverse();
break;
case 'shuffle':
$list->shuffle();
break;
case 'slice':
$list->slice($action->offset, $action->limit);
break;
case 'map':
$list->map($action->callback);
break;
default:
throw new \Exception('Should not get here for "' . $action->name . '"!');
break;
}
}
}
}
|
Disable downloader for non-existing tile test | var test = require('tape'),
almostEqual = function(t, actual, expected, delta, msg) {
var d = Math.abs(actual - expected);
delta = delta || 1e-9;
msg = msg || 'Should be almost equal';
if (d > delta) {
t.equal(actual, expected, msg);
} else {
t.ok(true, msg);
}
},
TileSet = require('../').TileSet;
test('can create tileset', function(t) {
var tileset = new TileSet(__dirname + '/data/');
tileset.destroy();
t.end();
});
test('can query tileset', function(t) {
var tileset = new TileSet(__dirname + '/data/');
tileset.getElevation([57.7, 11.9], function(err, elevation) {
if (err) {
t.fail('getElevation failed: ' + err.message);
} else {
almostEqual(t, elevation, 16);
}
tileset.destroy();
t.end();
});
});
test('can\'t query non-existing tiles', function(t) {
var tileset = new TileSet(__dirname + '/data/', {downloader:null});
tileset.getElevation([52.7, 11.9], function(err, elevation) {
if (!err) {
t.fail('getElevation for non-existing tile returned: ' + elevation);
} else {
t.ok(true, 'getElevation gave an error for non-existing tile.');
}
tileset.destroy();
t.end();
});
});
| var test = require('tape'),
almostEqual = function(t, actual, expected, delta, msg) {
var d = Math.abs(actual - expected);
delta = delta || 1e-9;
msg = msg || 'Should be almost equal';
if (d > delta) {
t.equal(actual, expected, msg);
} else {
t.ok(true, msg);
}
},
TileSet = require('../').TileSet;
test('can create tileset', function(t) {
var tileset = new TileSet(__dirname + '/data/');
tileset.destroy();
t.end();
});
test('can query tileset', function(t) {
var tileset = new TileSet(__dirname + '/data/');
tileset.getElevation([57.7, 11.9], function(err, elevation) {
if (err) {
t.fail('getElevation failed: ' + err.message);
} else {
almostEqual(t, elevation, 16);
}
tileset.destroy();
t.end();
});
});
test('can\'t query non-existing tiles', function(t) {
var tileset = new TileSet(__dirname + '/data/');
tileset.getElevation([52.7, 11.9], function(err, elevation) {
if (!err) {
t.fail('getElevation for non-existing tile returned: ' + elevation);
} else {
t.ok(true, 'getElevation gave an error for non-existing tile.');
}
tileset.destroy();
t.end();
});
});
|
Make sure that .py file is used, even if .pyc got executed
If python already byte-compiled the source code to .pyc file,
the __file__ points to .pyc, rather than to .py, which breaks the
copying mechanism.
Use regex substitution to make sure we're always copying the original
source file. | '''
Monkey patch setuptools to write faster console_scripts with this format:
from mymodule import entry_function
entry_function()
This is better.
'''
from setuptools.command import easy_install
@classmethod
def get_args(cls, dist, header=None):
"""
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
"""
template = 'import sys\nfrom {0} import {1}\nsys.exit({1}())'
if header is None:
header = cls.get_header()
spec = str(dist.as_requirement())
for type_ in 'console', 'gui':
group = type_ + '_scripts'
for name, ep in dist.get_entry_map(group).items():
cls._ensure_safe_name(name)
script_text = template.format(
ep.module_name, ep.attrs[0])
args = cls._get_script_args(type_, name, header, script_text)
for res in args:
yield res
easy_install.ScriptWriter.get_args = get_args
def main():
import re
import shutil
import sys
dests = sys.argv[1:] or ['.']
filename = re.sub('\.pyc$', '.py', __file__)
for dst in dests:
shutil.copy(filename, dst)
with open(dst + '/MANIFEST.in', 'a') as manifest:
manifest.write('\ninclude fastentrypoints.py')
| '''
Monkey patch setuptools to write faster console_scripts with this format:
from mymodule import entry_function
entry_function()
This is better.
'''
from setuptools.command import easy_install
@classmethod
def get_args(cls, dist, header=None):
"""
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
"""
template = 'import sys\nfrom {0} import {1}\nsys.exit({1}())'
if header is None:
header = cls.get_header()
spec = str(dist.as_requirement())
for type_ in 'console', 'gui':
group = type_ + '_scripts'
for name, ep in dist.get_entry_map(group).items():
cls._ensure_safe_name(name)
script_text = template.format(
ep.module_name, ep.attrs[0])
args = cls._get_script_args(type_, name, header, script_text)
for res in args:
yield res
easy_install.ScriptWriter.get_args = get_args
def main():
import shutil
import sys
dests = sys.argv[1:] or ['.']
print(__name__)
for dst in dests:
shutil.copy(__file__, dst)
with open(dst + '/MANIFEST.in', 'a') as manifest:
manifest.write('\ninclude fastentrypoints.py')
|
docs: Fix simple typo, convertable -> convertible
There is a small typo in django_enumfield/tests/test_validators.py.
Should read `convertible` rather than `convertable`. | import unittest
from django.db import models
from django_enumfield.exceptions import InvalidStatusOperationError
from django_enumfield.tests.models import BeerStyle, Person, PersonStatus
from django_enumfield.validators import validate_available_choice
class ValidatorTest(unittest.TestCase):
def test_validate_available_choice_1(self):
"""Test passing a value non convertible to an int raises an
InvalidStatusOperationError
"""
self.assertRaises(
InvalidStatusOperationError,
validate_available_choice,
*(BeerStyle, "Not an int")
)
def test_validate_available_choice_2(self):
"""Test passing an int as a string validation
"""
self.assertRaises(
InvalidStatusOperationError,
validate_available_choice,
BeerStyle,
str(BeerStyle.LAGER.value),
)
def test_validate_available_choice_3(self):
"""Test passing an int validation
"""
self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER))
def test_validate_by_setting(self):
person = Person()
with self.assertRaises(InvalidStatusOperationError):
person.status = PersonStatus.UNBORN
with self.assertRaises(InvalidStatusOperationError):
person.status = models.NOT_PROVIDED
| import unittest
from django.db import models
from django_enumfield.exceptions import InvalidStatusOperationError
from django_enumfield.tests.models import BeerStyle, Person, PersonStatus
from django_enumfield.validators import validate_available_choice
class ValidatorTest(unittest.TestCase):
def test_validate_available_choice_1(self):
"""Test passing a value non convertable to an int raises an
InvalidStatusOperationError
"""
self.assertRaises(
InvalidStatusOperationError,
validate_available_choice,
*(BeerStyle, "Not an int")
)
def test_validate_available_choice_2(self):
"""Test passing an int as a string validation
"""
self.assertRaises(
InvalidStatusOperationError,
validate_available_choice,
BeerStyle,
str(BeerStyle.LAGER.value),
)
def test_validate_available_choice_3(self):
"""Test passing an int validation
"""
self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER))
def test_validate_by_setting(self):
person = Person()
with self.assertRaises(InvalidStatusOperationError):
person.status = PersonStatus.UNBORN
with self.assertRaises(InvalidStatusOperationError):
person.status = models.NOT_PROVIDED
|
Add static highlighting on serviceDescription field | from flask import Markup
class SearchResults(object):
"""Provides access to the search results information"""
def __init__(self, response, lots_by_slug):
self.search_results = response['services']
self._lots = lots_by_slug
self._annotate()
self.total = response['meta']['total']
if 'page' in response['meta']['query']:
self.page = response['meta']['query']['page']
def _annotate(self):
for service in self.search_results:
self._replace_lot(service)
self._add_highlighting(service)
def _replace_lot(self, service):
# replace lot slug with reference to dict containing all the relevant lot data
service['lot'] = self._lots.get(service['lot'])
def _add_highlighting(self, service):
if 'highlight' in service:
for highlighted_field in ['serviceSummary', 'serviceDescription']:
if highlighted_field in service['highlight']:
service[highlighted_field] = Markup(
''.join(service['highlight'][highlighted_field])
)
class AggregationResults(object):
"""Provides access to the aggregation results information"""
def __init__(self, response):
self.results = response['aggregations']
self.total = response['meta']['total']
if 'page' in response['meta']['query']:
self.page = response['meta']['query']['page']
| from flask import Markup
class SearchResults(object):
"""Provides access to the search results information"""
def __init__(self, response, lots_by_slug):
self.search_results = response['services']
self._lots = lots_by_slug
self._annotate()
self.total = response['meta']['total']
if 'page' in response['meta']['query']:
self.page = response['meta']['query']['page']
def _annotate(self):
for service in self.search_results:
self._replace_lot(service)
self._add_highlighting(service)
def _replace_lot(self, service):
# replace lot slug with reference to dict containing all the relevant lot data
service['lot'] = self._lots.get(service['lot'])
def _add_highlighting(self, service):
if 'highlight' in service:
if 'serviceSummary' in service['highlight']:
service['serviceSummary'] = Markup(
''.join(service['highlight']['serviceSummary'])
)
class AggregationResults(object):
"""Provides access to the aggregation results information"""
def __init__(self, response):
self.results = response['aggregations']
self.total = response['meta']['total']
if 'page' in response['meta']['query']:
self.page = response['meta']['query']['page']
|
FIX keep-fnames for minify now works | const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const commonConfig = require('./webpack.config.common.js');
const AppCachePlugin = require('appcache-webpack-plugin');
module.exports = function(options) {
const ENV = options.ENV || 'production';
return webpackMerge(commonConfig, {
plugins: [
// new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'ENV': JSON.stringify(ENV)
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {
screw_ie8: true,
keep_fnames: false
},
compress: {
screw_ie8: true,
warnings: false
},
comments: false
}),
new AppCachePlugin({
exclude: ['app.js', 'styles.css'],
output: 'app.appcache'
})
]
});
};
| const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const commonConfig = require('./webpack.config.common.js');
const AppCachePlugin = require('appcache-webpack-plugin');
module.exports = function(options) {
const ENV = options.ENV || 'production';
return webpackMerge(commonConfig, {
plugins: [
// new webpack.optimize.DedupePlugin(),
new webpack.DefinePlugin({
'ENV': JSON.stringify(ENV)
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
beautify: false, //prod
mangle: {
screw_ie8: true,
keep_fnames: true // required for ng2 rc.5
}, //prod
compress: { //prod
screw_ie8: true,
warnings: false
},
comments: false //prod
}),
new AppCachePlugin({
exclude: ['app.js', 'styles.css'],
output: 'app.appcache'
})
]
});
};
|
Update help line and print system number | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Export talkgroup info'
def add_arguments(self, parser):
parser.add_argument('file')
parser.add_argument(
'--system',
type=int,
default=-1,
help='Export talkgroups from only this system',
)
def handle(self, *args, **options):
export_tg_file(self, options)
def export_tg_file(self, options):
''' Using the talkgroup file from trunk-recorder'''
file_name = options['file']
system = options['system']
talkgroups = TalkGroup.objects.all()
if system >= 0:
talkgroups = talkgroups.filter(system=system)
self.stdout.write("Exporting talkgroups for system #{}".format(system))
else:
self.stdout.write("Exporting talkgroups for all systems")
with open(file_name, "w") as tg_file:
for t in talkgroups:
alpha = t.alpha_tag
description = t.description
hex_val = str(hex(t.dec_id))[2:-1].zfill(3)
try:
alpha = alpha.rstrip()
except AttributeError:
pass
try:
description = description.rstrip()
except AttributeError:
pass
common = ''
if(t.common_name):
common = t.common_name
tg_file.write("{},{},{},{},{},{}\n".format(t.dec_id,hex_val,t.mode,alpha,description,t.priority))
| import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Import talkgroup info'
def add_arguments(self, parser):
parser.add_argument('file')
parser.add_argument(
'--system',
type=int,
default=-1,
help='Export talkgroups from only this system',
)
def handle(self, *args, **options):
export_tg_file(options)
def export_tg_file(options):
''' Using the talkgroup file from trunk-recorder'''
file_name = options['file']
system = options['system']
talkgroups = TalkGroup.objects.all()
if system >= 0:
talkgroups = talkgroups.filter(system=system)
with open(file_name, "w") as tg_file:
for t in talkgroups:
alpha = t.alpha_tag
description = t.description
hex_val = str(hex(t.dec_id))[2:-1].zfill(3)
try:
alpha = alpha.rstrip()
except AttributeError:
pass
try:
description = description.rstrip()
except AttributeError:
pass
common = ''
if(t.common_name):
common = t.common_name
tg_file.write("{},{},{},{},{},{}\n".format(t.dec_id,hex_val,t.mode,alpha,description,t.priority))
|
Remove "v" shortcut (allready use for verbosity) | <?php
/*
* This file is part of Octower.
*
* (c) William Pottier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Octower\Command;
use Octower\Metadata\Project;
use Octower\Packager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class PackageCommand extends Command
{
protected function configure()
{
$this
->setName('package:generate')
->setDescription('Create package to deploy')
->addOption('version', null, InputOption::VALUE_OPTIONAL)
->setHelp(<<<EOT
<info>php octower.phar package:generate</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$octower = $this->getOctower();
$io = $this->getIO();
if ($input->hasOption('version')) {
$context = $octower->getContext();
if ($context instanceof Project) {
$context->setVersion($input->getOption('version'));
}
}
$packager = Packager::create($io, $octower);
$packager->run();
}
}
| <?php
/*
* This file is part of Octower.
*
* (c) William Pottier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Octower\Command;
use Octower\Metadata\Project;
use Octower\Packager;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class PackageCommand extends Command
{
protected function configure()
{
$this
->setName('package:generate')
->setDescription('Create package to deploy')
->addOption('version', 'v', InputOption::VALUE_OPTIONAL)
->setHelp(<<<EOT
<info>php octower.phar package:generate</info>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$octower = $this->getOctower();
$io = $this->getIO();
if ($input->hasOption('version')) {
$context = $octower->getContext();
if ($context instanceof Project) {
$context->setVersion($input->getOption('version'));
}
}
$packager = Packager::create($io, $octower);
$packager->run();
}
} |
Correct culture code for Español | /*!
* numbro.js language configuration
* language : spanish Spain
* author : Hernan Garcia : https://github.com/hgarcia
*/
(function () {
var language = {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'mm',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
var b = number % 10;
return (b === 1 || b === 3) ? 'er' :
(b === 2) ? 'do' :
(b === 7 || b === 0) ? 'mo' :
(b === 8) ? 'vo' :
(b === 9) ? 'no' : 'to';
},
currency: {
symbol: '€',
position: 'postfix'
},
defaults: {
currencyFormat: ',0000 a'
},
formats: {
fourDigits: '0000 a',
fullWithTwoDecimals: ',0.00 $',
fullWithTwoDecimalsNoCurrency: ',0.00',
fullWithNoDecimals: ',0 $'
}
};
// Node
if (typeof module !== 'undefined' && module.exports) {
module.exports = language;
}
// Browser
if (typeof window !== 'undefined' && this.numbro && this.numbro.language) {
this.numbro.language('es-ES', language);
}
}());
| /*!
* numbro.js language configuration
* language : spanish Spain
* author : Hernan Garcia : https://github.com/hgarcia
*/
(function () {
var language = {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'mm',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
var b = number % 10;
return (b === 1 || b === 3) ? 'er' :
(b === 2) ? 'do' :
(b === 7 || b === 0) ? 'mo' :
(b === 8) ? 'vo' :
(b === 9) ? 'no' : 'to';
},
currency: {
symbol: '€',
position: 'postfix'
},
defaults: {
currencyFormat: ',0000 a'
},
formats: {
fourDigits: '0000 a',
fullWithTwoDecimals: ',0.00 $',
fullWithTwoDecimalsNoCurrency: ',0.00',
fullWithNoDecimals: ',0 $'
}
};
// Node
if (typeof module !== 'undefined' && module.exports) {
module.exports = language;
}
// Browser
if (typeof window !== 'undefined' && this.numbro && this.numbro.language) {
this.numbro.language('es', language);
}
}());
|
Create a ImmediateWorker that executes the posted jobs on the same thread synchronously | import queue
from bot.multithreading.work import Work
class Worker:
def run(self):
raise NotImplementedError()
def post(self, work: Work):
raise NotImplementedError()
def shutdown(self):
raise NotImplementedError()
class AbstractWorker(Worker):
def __init__(self, name: str, error_handler: callable):
self.name = name
self.error_handler = error_handler
def _work(self, work: Work):
try:
work.do_work()
except BaseException as e:
self._error(e, work)
def _error(self, e: BaseException, work: Work):
try:
self.error_handler(e, work, self)
except:
pass
def run(self):
raise NotImplementedError()
def post(self, work: Work):
raise NotImplementedError()
def shutdown(self):
raise NotImplementedError()
class QueueWorker(AbstractWorker):
def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable):
super().__init__(name, error_handler)
self.queue = work_queue
def run(self):
while True:
work = self.queue.get()
self._work(work)
self.queue.task_done()
def post(self, work: Work):
self.queue.put(work)
def shutdown(self):
self.queue.join()
class ImmediateWorker(AbstractWorker):
def __init__(self, error_handler: callable):
super().__init__("immediate", error_handler)
def run(self):
pass
def post(self, work: Work):
self._work(work)
def shutdown(self):
pass
| import queue
from bot.multithreading.work import Work
class Worker:
def run(self):
raise NotImplementedError()
def post(self, work: Work):
raise NotImplementedError()
def shutdown(self):
raise NotImplementedError()
class AbstractWorker(Worker):
def __init__(self, name: str, error_handler: callable):
self.name = name
self.error_handler = error_handler
def _work(self, work: Work):
try:
work.do_work()
except BaseException as e:
self._error(e, work)
def _error(self, e: BaseException, work: Work):
try:
self.error_handler(e, work, self)
except:
pass
def run(self):
raise NotImplementedError()
def post(self, work: Work):
raise NotImplementedError()
def shutdown(self):
raise NotImplementedError()
class QueueWorker(AbstractWorker):
def __init__(self, name: str, work_queue: queue.Queue, error_handler: callable):
super().__init__(name, error_handler)
self.queue = work_queue
def run(self):
while True:
work = self.queue.get()
self._work(work)
self.queue.task_done()
def post(self, work: Work):
self.queue.put(work)
def shutdown(self):
self.queue.join()
|
Revert "Moved API URL out of dev settings."
This reverts commit 134f113e3a2461ae9f7509c3998950726b640b8f. | /* eslint-env node */
'use strict';
module.exports = function (environment) {
let ENV = {
modulePrefix: 'frontend',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.APP.API_HOST = '/backend/api';
ENV.APP.API_NAMESPACE = '';
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* eslint-env node */
'use strict';
module.exports = function (environment) {
let ENV = {
modulePrefix: 'frontend',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
ENV.APP.API_HOST = '/backend/api';
ENV.APP.API_NAMESPACE = '';
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
Correct comment on parsing route parameters instead of query | 'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
function leagueTable_id(id) { // Auto parses id from route parameters
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable/" + item.id
return item
})
}
})() | 'use strict'
module.exports = (function(){
/**
* Import modules
*/
const footballDb = require('./../db/footballDb')
/**
* football module API
*/
return {
'leagues': leagues,
'leagueTable_id': leagueTable_id
}
/**
* football module API -- leagueTable
*/
function leagueTable_id(id) { // Auto parses id from query-string
return footballDb
.leagueTable(id)
.then(league => {
league.title = 'League Table'
return league
})
}
/**
* football module API -- leagues
*/
function leagues() {
return footballDb
.leagues()
.then(leagues => {
leagues = leaguesWithLinks(leagues)
return {
'title':'Leagues',
'leagues': leagues
}
})
}
/**
* Utility auxiliary function
*/
function leaguesWithLinks(leagues) {
return leagues.map(item => {
item.leagueHref = "/football/leagueTable/" + item.id
return item
})
}
})() |
Add notes for debugging Vega | 'use strict';
// In order to debug your Vega spec, run the following command in your browser's console:
// view = angular.element(document.getElementsByName('<name attribute>')).scope().$$childHead.vegaView
// You can then use the variable view as described in https://vega.github.io/vega/docs/api/debugging/
angular.module('arachne.visualizations.directives')
.directive('con10tVega', function () { // con10t-vega
return {
restrict: 'E',
scope: {
spec: '@',
name: '@'
},
link: function(scope, element, attrs) {
scope.renderVega = function (spec) {
scope.vegaView = new vega.View(vega.parse(spec))
.renderer('canvas')
.initialize('[name="' + scope.name + '"]')
//.logLevel(vega.Debug)
.hover()
.run();
};
vega.loader()
.load(scope.spec)
.then(function(data){
scope.renderVega(JSON.parse(data));
});
}
}
}); | 'use strict';
angular.module('arachne.visualizations.directives')
.directive('con10tVega', function () { // con10t-vega
return {
restrict: 'E',
scope: {
spec: '@',
name: '@'
},
link: function(scope, element, attrs) {
scope.renderVega = function (spec) {
scope.vegaView = new vega.View(vega.parse(spec))
.renderer('canvas')
.initialize('[name="' + scope.name + '"]')
.hover()
.run();
};
vega.loader()
.load(scope.spec)
.then(function(data){
scope.renderVega(JSON.parse(data));
});
}
}
}); |
Fix spelling mistake in invite command description | package com.avairebot.orion.commands.utility;
import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.AbstractCommand;
import com.avairebot.orion.factories.MessageFactory;
import net.dv8tion.jda.core.entities.Message;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class InviteCommand extends AbstractCommand {
public InviteCommand(Orion orion) {
super(orion);
}
@Override
public String getName() {
return "Invite Command";
}
@Override
public String getDescription() {
return "Returns a link that can be used to invite the bot to other servers.";
}
@Override
public List<String> getUsageInstructions() {
return Collections.singletonList("`!invite` - Gives you an invite link that can be used to invite Orion to servers.");
}
@Override
public List<String> getTriggers() {
return Arrays.asList("invite", "join");
}
@Override
public boolean onCommand(Message message, String[] args) {
MessageFactory.makeInfo(message,
"You can invite me to your server by [clicking here](%s) or use the link below:\n\n%s",
orion.config.botAuth().getOAuth(), orion.config.botAuth().getOAuth())
.queue();
return true;
}
}
| package com.avairebot.orion.commands.utility;
import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.AbstractCommand;
import com.avairebot.orion.factories.MessageFactory;
import net.dv8tion.jda.core.entities.Message;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class InviteCommand extends AbstractCommand {
public InviteCommand(Orion orion) {
super(orion);
}
@Override
public String getName() {
return "Invite Command";
}
@Override
public String getDescription() {
return "Returns a link that can be used to invite to bot to other servers.";
}
@Override
public List<String> getUsageInstructions() {
return Collections.singletonList("`!invite` - Gives you an invite link that can be used to invite Orion to servers.");
}
@Override
public List<String> getTriggers() {
return Arrays.asList("invite", "join");
}
@Override
public boolean onCommand(Message message, String[] args) {
MessageFactory.makeInfo(message,
"You can invite me to your server by [clicking here](%s) or use the link below:\n\n%s",
orion.config.botAuth().getOAuth(), orion.config.botAuth().getOAuth())
.queue();
return true;
}
}
|
Fix authorization when permission was used multiple times. | <?php
namespace Yajra\Acl\Traits;
use Illuminate\Support\Collection;
use Illuminate\Support\Fluent;
trait AuthorizesPermissionResources
{
/**
* Permission resource ability mapping.
*
* @var array
*/
protected $resourcePermissionMap = [
'index' => 'lists',
'create' => 'create',
'store' => 'create',
'show' => 'view',
'edit' => 'update',
'update' => 'update',
'destroy' => 'delete',
];
/**
* Controller specific permission ability map.
*
* @var array
*/
protected $customPermissionMap = [];
/**
* Authorize a permission resource action based on the incoming request.
*
* @param string $resource
* @param array $options
* @return void
*/
public function authorizePermissionResource($resource, array $options = [])
{
$permissions = $this->resourcePermissionMap();
$collection = new Collection;
foreach ($permissions as $method => $ability) {
$collection->push(new Fluent([
'ability' => $ability,
'method' => $method,
]));
}
$collection->groupBy('ability')->each(function ($permission, $ability) use ($resource, $options) {
$this->middleware("can:{$resource}.{$ability}", $options)
->only($permission->pluck('method')->toArray());
});
}
/**
* Get the map of permission resource methods to ability names.
*
* @return array
*/
protected function resourcePermissionMap()
{
return array_merge($this->resourcePermissionMap, $this->customPermissionMap);
}
} | <?php
namespace Yajra\Acl\Traits;
trait AuthorizesPermissionResources
{
/**
* Permission resource ability mapping.
*
* @var array
*/
protected $resourcePermissionMap = [
'index' => 'lists',
'create' => 'create',
'store' => 'create',
'show' => 'view',
'edit' => 'update',
'update' => 'update',
'destroy' => 'delete',
];
/**
* Controller specific permission ability map.
*
* @var array
*/
protected $customPermissionMap = [];
/**
* Authorize a permission resource action based on the incoming request.
*
* @param string $model
* @param string|null $parameter
* @param array $options
* @return void
*/
public function authorizePermissionResource($model, $parameter = null, array $options = [])
{
$parameter = $parameter ?: strtolower(class_basename($model));
foreach ($this->resourcePermissionMap() as $method => $ability) {
$modelName = in_array($method, ['index', 'create', 'store']) ? $model : $parameter;
$this->middleware("can:{$modelName}.{$ability}", $options)->only($method);
}
}
/**
* Get the map of permission resource methods to ability names.
*
* @return array
*/
protected function resourcePermissionMap()
{
return array_merge($this->resourcePermissionMap, $this->customPermissionMap);
}
} |
Add .dmg and .sig to copied file extensions | 'use strict';
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
return {
target: {
files: [
{
expand: true,
cwd: 'src/',
src: [
'**/*.html',
'**/*.css',
'**/*.png',
'**/*.jpg',
'**/*.jpeg',
'**/*.svg',
'**/*.json',
'**/*.pdf',
'**/*.exe',
'**/*.zip',
'**/*.gz',
'**/*.dmg',
'**/*.sig'
],
dest: '.dist/'
}
]
}
};
};
| 'use strict';
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-copy');
return {
target: {
files: [
{
expand: true,
cwd: 'src/',
src: [
'**/*.html',
'**/*.css',
'**/*.png',
'**/*.jpg',
'**/*.jpeg',
'**/*.svg',
'**/*.json',
'**/*.pdf',
'**/*.exe',
'**/*.zip',
'**/*.gz'
],
dest: '.dist/'
}
]
}
};
};
|
Add a link to the 'add library' instructions in the footer | import React from 'react';
import Link from '../components/Link';
export default () => {
return (
<footer className="footer">
<style jsx>{`
.footer {
border-top: 1px solid #ececec;
width: 100%;
}
.footer-container {
width: 100%;
max-width: 1319px;
padding: 0 24px 0 24px;
box-sizing: border-box;
margin: 0 auto 0 auto;
display: 'flex';
align-items: 'flex-start';
justify-content: 'space-between';
}
.footer-container-text {
margin: 24px 0 24px 0;
}
`}</style>
<div className="footer-container">
<p className="footer-container-text">
Missing a library?{' '}
<Link
isStyled
href="https://github.com/react-community/native-directory#how-to-add-a-library">
Add it to the directory
</Link>. Want to learn more about React Native? Check out the{' '}
<Link
isStyled
href="https://facebook.github.io/react-native/docs/getting-started.html">
offical docs
</Link>, and{' '}
<Link isStyled href="https://expo.io">
Expo
</Link>.
</p>
</div>
</footer>
);
};
| import React from 'react';
import Link from '../components/Link';
export default () => {
return (
<footer className="footer">
<style jsx>{`
.footer {
border-top: 1px solid #ececec;
width: 100%;
}
.footer-container {
width: 100%;
max-width: 1319px;
padding: 0 24px 0 24px;
box-sizing: border-box;
margin: 0 auto 0 auto;
display: 'flex';
align-items: 'flex-start';
justify-content: 'space-between';
}
.footer-container-text {
margin: 24px 0 24px 0;
}
`}</style>
<div className="footer-container">
<p className="footer-container-text">
Want to learn more about React Native? Check out the{' '}
<Link
isStyled
href="https://facebook.github.io/react-native/docs/getting-started.html">
offical docs
</Link>, and{' '}
<Link isStyled href="https://expo.io">
Expo
</Link>.
</p>
</div>
</footer>
);
};
|
Fix delete project in admin list | angular
.module('app')
.controller('projectListController', [
'$scope',
'projectService',
'flash',
'MetaMachine',
'$location',
function($scope, projectAPI, notification, MetaMachine, $location) {
$scope.projects = projectAPI.getAll();
MetaMachine.title("Projects", "Admin");
$scope.remove = function(item) {
if(confirm('Are you sure you want to delete this Project?')) {
item.$remove(function() {
$scope.projects = projectAPI.getAll();
notification.set({
body: 'Your Project has been successfully removed',
type: 'success'
});
});
}
};
$scope.publish = function(id, status) {
projectAPI.getById(id).then(function(response) {
var project = response;
project.publish = status;
projectAPI.updateById(id, project).then(function(response) {
$scope.projects = projectAPI.getAll();
notification.pop({
body: 'Your Project has been successfully ' + (status) ? 'published' : 'unpublished',
type: 'success'
});
});
});
};
}
]);
| angular
.module('app')
.controller('projectListController', [
'$scope',
'projectService',
'flash',
'MetaMachine',
'$location',
function($scope, projectAPI, notification, MetaMachine, $location) {
$scope.projects = projectAPI.getAll();
MetaMachine.title("Projects", "Admin");
$scope.remove = function(item) {
var confirm = confirm('Are you sure you want to delete this Project?');
if(confirm) {
item.$remove(function() {
notification.set({
body: 'Your Project has been successfully removed',
type: 'success'
});
$location.path('admin').replace();
});
}
};
$scope.publish = function(id, status) {
projectAPI.getById(id).then(function(response) {
var project = response;
project.publish = status;
projectAPI.updateById(id, project).then(function(response) {
$scope.projects = projectAPI.getAll();
notification.pop({
body: 'Your Project has been successfully ' + (status) ? 'published' : 'unpublished',
type: 'success'
});
});
});
};
}
]);
|
Fix email and password validation. | <?php
namespace Application\Module {
class User extends \Application\Module {
public function Index() {
return $this->Login();
}
public function Login() {
$Request = $this->getRequest();
$User = $this->getModel("User");
if (!empty($Request['Arguments']['Email'])) {
$User->setEmail($Request['Arguments']['Email']);
}
if (!empty($Request['Arguments']['Password'])) {
$User->setPassword($Request['Arguments']['Password']);
}
$Error = null;
$Email = $User->getEmail();
$Password = $User->getPassword();
if (isset($Email)) ;
else {
$Error = "No email given.";
};
if (isset($Password)) ;
else {
$Error = "No password given.";
}
$User->Error = $Error;
$View = $this->getView("Login.phtml", array("User" => $User));
return $View;
}
protected function Info() {
$User = $this->getModel("User");
$View = $this->getView("User.phtml", array("User" => $User));
return $View;
}
}
}
?> | <?php
namespace Application\Module {
class User extends \Application\Module {
public function Index() {
return $this->Login();
}
public function Login() {
$Request = $this->getRequest();
$User = $this->getModel("User");
if (isset($Request['Arguments']['Email']) && $Request['Arguments']['Email'] !== "") {
$User->setEmail($Request['Arguments']['Email']);
}
if (isset($Request['Arguments']['Password']) && $Request['Arguments']['Password'] !== "") {
$User->setPassword($Request['Arguments']['Password']);
}
$Error = null;
$Email = $User->getEmail();
$Password = $User->getPassword();
if (isset($Email)) ;
else {
$Error = "No email given.";
};
if (isset($Password)) ;
else {
$Error = "No password given.";
}
$User->Error = $Error;
$View = $this->getView("Login.phtml", array("User" => $User));
return $View;
}
protected function Info() {
$User = $this->getModel("User");
$View = $this->getView("User.phtml", array("User" => $User));
return $View;
}
}
}
?> |
Move up/down votes from the far right to just before the title
Now that it's only two icons (and will be only 1 soon), it makes more sense to put it here. | <?php
use yii\helpers\Html;
/* @var $model ShortCirquit\LinkoScopeApi\models\Link */
?>
<div>
<div>
<?= ($index + 1) ?>:
<?= Html::a('<span class="glyphicon glyphicon-arrow-up"></span>', ['up', 'id' => $model->id,], ['title' => 'Up']) ?>
<?= Html::a('<span class="glyphicon glyphicon-arrow-down"></span>', ['down', 'id' => $model->id,], ['title' => 'Down']) ?>
[<?= Html::a($model->title, $model->url, ['target' => '_blank',]); ?>]
(<?= parse_url($model->url, PHP_URL_HOST) ?>)
</div>
<?php if (!Yii::$app->user->isGuest) : ?>
<div style="top: 0px; float: right;">
<?= '' /* Html::a('<span class="glyphicon glyphicon-trash"></span>', ['delete', 'id' => $model->id,], ['title' => 'Delete']) */ ?>
</div>
<?php endif; ?>
</div>
<div>
<?=
"$model->authorName | " .
date(DATE_RFC2822, strtotime($model->date)) .
" | $model->votes votes | " .
Html::a($model->comments == 0 ? "discuss" : "$model->comments comments", ['link/view', 'id' => $model->id])
?>
</div>
| <?php
use yii\helpers\Html;
/* @var $model ShortCirquit\LinkoScopeApi\models\Link */
?>
<div>
<div>
<?= ($index + 1) ?>:
[<?= Html::a($model->title, $model->url, ['target' => '_blank',]); ?>]
(<?= parse_url($model->url, PHP_URL_HOST) ?>)
</div>
<?php if (!Yii::$app->user->isGuest) : ?>
<div style="top: 0px; float: right;">
<?= Html::a('<span class="glyphicon glyphicon-arrow-up"></span>', ['up', 'id' => $model->id,], ['title' => 'Up']) ?>
<?= Html::a('<span class="glyphicon glyphicon-arrow-down"></span>', ['down', 'id' => $model->id,], ['title' => 'Down']) ?>
<?= '' /* Html::a('<span class="glyphicon glyphicon-trash"></span>', ['delete', 'id' => $model->id,], ['title' => 'Delete']) */ ?>
</div>
<?php endif; ?>
</div>
<div>
<?=
"$model->authorName | " .
date(DATE_RFC2822, strtotime($model->date)) .
" | $model->votes votes | " .
Html::a($model->comments == 0 ? "discuss" : "$model->comments comments", ['link/view', 'id' => $model->id])
?>
</div>
|
Add source links to all comments | "use strict";
module.exports = React.createClass({displayName: 'CommentView',
render: function() {
var comment = this.props.comment;
if (!comment) {
return (
<div>
No comment.
</div>
);
}
var htmlBody = comment.getHtmlBody();
if (/<\/blockquote>$/.test(htmlBody)) {
// TODO ends in a block quote, hide it behind a toggle button.
}
return (
<div className="CommentView">
<img className="CommentView_avatar" src={
comment.getUser().getAvatarUrl()
} />
<div className="CommentView_header">
{comment.getUser().getUserLinkJsx()} commented {
comment.getTimeAgo()
} ago <a href={comment.getLink()} target="_blank">(Source)</a>
</div>
<div className="CommentView_body"
dangerouslySetInnerHTML={{__html: htmlBody}}>
</div>
</div>
);
}
});
| "use strict";
module.exports = React.createClass({displayName: 'CommentView',
render: function() {
var comment = this.props.comment;
if (!comment) {
return (
<div>
No comment.
</div>
);
}
var htmlBody = comment.getHtmlBody();
if (/<\/blockquote>$/.test(htmlBody)) {
// TODO ends in a block quote, hide it behind a toggle button.
}
return (
<div className="CommentView">
<img className="CommentView_avatar" src={
comment.getUser().getAvatarUrl()
} />
<div className="CommentView_header">
{comment.getUser().getUserLinkJsx()} commented {
comment.getTimeAgo()
} ago
</div>
<div className="CommentView_body"
dangerouslySetInnerHTML={{__html: htmlBody}}>
</div>
</div>
);
}
});
|
Revert "Print "Geschaeftsprozessmodelle" when 'l' has been pressed"
This reverts commit d8b19a1f8486ea6259783d2be898e11cc9ed48c4. | package rogue.creature;
import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;
public class Player extends Creature implements Camera
{
private Terminal term;
private ViewField fov;
public Player(Terminal term)
{
super(ColoredChar.create('@'));
this.term = term;
fov = new RayCaster();
}
@Override
public void act()
{
try
{
char key;
key = term.getKey();
switch(key)
{
case 'q':
expire();
break;
default:
Direction dir = Direction.keyToDir(key);
if(dir != null)
move(dir);
break;
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
@Override
public Collection<Coordinate> getViewField()
{
return fov.getViewField(world(), pos(), 5);
}
}
| package rogue.creature;
import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;
public class Player extends Creature implements Camera
{
private Terminal term;
private ViewField fov;
public Player(Terminal term)
{
super(ColoredChar.create('@'));
this.term = term;
fov = new RayCaster();
}
@Override
public void act()
{
try
{
char key;
key = term.getKey();
switch(key)
{
case 'q':
expire();
break;
case 'l':
System.out.println("Geschaeftsprozessmodelle");
// Do not break; here, otherwise we can't move left!
default:
Direction dir = Direction.keyToDir(key);
if(dir != null)
move(dir);
break;
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
@Override
public Collection<Coordinate> getViewField()
{
return fov.getViewField(world(), pos(), 5);
}
}
|
Downgrade to guzzle 2.8 for react compatibility | <?php
namespace RabbitMQ\Management;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
use RabbitMQ\Management\Exception\RuntimeException;
class HttpClient extends Client
{
private $hydrator;
public function getHydrator()
{
if (!$this->hydrator) {
$this->hydrator = new Hydrator();
}
return $this->hydrator;
}
/**
* Factory method to create the HttpClient
*
* The following array keys and values are available options:
* - url : Base URL of web service
* - port : Port of web service
* - scheme : URI scheme: http or https
* - username: API username
* - password: API password
*
* @param array|Collection $options Configuration data
*
* @return self
*/
public static function factory($options = array())
{
$default = array(
'base_url' => '{scheme}://{username}:{password}@{url}:{port}',
'scheme' => 'http',
'username' => 'guest',
'password' => 'guest',
'port' => '55672',
);
$options = array_merge($default, $options);
$required = array('port', 'url', 'username', 'password');
foreach ($required as $key) {
if (!array_key_exists($key, $options)) {
throw new RuntimeException(sprintf('Missing option `%s`', $key));
}
}
$config = new Collection($options);
$client = new self($config->get('base_url'), $config);
return $client;
}
} | <?php
namespace RabbitMQ\Management;
use Guzzle\Common\Collection;
use Guzzle\Service\Client;
class HttpClient extends Client
{
private $hydrator;
public function getHydrator()
{
if (!$this->hydrator) {
$this->hydrator = new Hydrator();
}
return $this->hydrator;
}
/**
* Factory method to create the HttpClient
*
* The following array keys and values are available options:
* - url : Base URL of web service
* - port : Port of web service
* - scheme : URI scheme: http or https
* - username: API username
* - password: API password
*
* @param array|Collection $config Configuration data
*
* @return self
*/
public static function factory($config = array())
{
$default = array(
'base_url' => '{scheme}://{username}:{password}@{url}:{port}',
'scheme' => 'http',
'username' => 'guest',
'password' => 'guest',
'port' => '55672',
);
$required = array('port', 'url', 'username', 'password');
$config = Collection::fromConfig($config, $default, $required);
$client = new self($config->get('base_url'), $config);
return $client;
}
} |
Fix the vote buttons which weren't appearing when signed in
This fixes a bug whereby the vote buttons were not appearing on proposal pages even if you were signed in. | import Ember from "ember";
import ENV from '../../config/environment';
// global _gaq //
export default Ember.ArrayController.extend({
needs: [ "proposal", "application" ],
proposal: Ember.computed.alias("controllers.proposal.model"),
isOpen: Ember.computed.alias("controllers.proposal.isOpen"),
currentUser: Ember.computed.alias("controllers.application.currentUser"),
myVote: function() {
return this.get("model").filterBy("usurped", false).filterBy("withdrawn", false).findBy("user", this.get("currentUser"));
}.property("[email protected]", "currentUser"),
canVote: function() {
return (!this.get("myVote"));
}.property("myVote"),
actions: {
registerVote: function(type) {
if(this.get("canVote")) {
var _this = this;
var p = _this.get("proposal");
this.set("justVoted", true);
Ember.$.post(ENV.api + "/votes", {
vote: {
type: type,
proposal_id: p.get('id'),
},
}).then(function() {
_this.send("log", "votes", type);
});
_this.send("randomProposal", p.get("id"));
}
},
withdrawVote: function() {
var _this = this;
Ember.$.post(ENV.api + "/votes/" + this.get("myVote.id") + "/withdraw",
{}, function(data) {
_this.store.pushPayload('proposal', data);
});
},
},
});
| import Ember from "ember";
import ENV from '../../config/environment';
// global _gaq //
export default Ember.ArrayController.extend({
needs: [ "proposal", "application" ],
proposal: Ember.computed.alias("controllers.proposal.model"),
isOpen: Ember.computed.alias("controllers.proposal.isOpen"),
currentUser: Ember.computed.alias("controllers.application.session.currentUser"),
myVote: function() {
return this.get("model").filterBy("usurped", false).filterBy("withdrawn", false).findBy("user", this.get("currentUser"));
}.property("[email protected]", "currentUser"),
canVote: function() {
return (!this.get("myVote"));
}.property("myVote"),
actions: {
registerVote: function(type) {
if(this.get("canVote")) {
var _this = this;
var p = _this.get("proposal");
this.set("justVoted", true);
Ember.$.post(ENV.api + "/votes", {
vote: {
type: type,
proposal_id: p.get('id'),
},
}).then(function() {
_this.send("log", "votes", type);
});
_this.send("randomProposal", p.get("id"));
}
},
withdrawVote: function() {
var _this = this;
Ember.$.post(ENV.api + "/votes/" + this.get("myVote.id") + "/withdraw",
{}, function(data) {
_this.store.pushPayload('proposal', data);
});
},
},
});
|
Move ProxyStore creation to tabris._init method
Creating the ProxyStore inside _init ensures a fresh ProxyStore
when _init is called again to reset a tabris mock in tests.
Change-Id: I443047400cb6168afe92b9718b3d7ac581afb69e | import {extend} from './util';
import Events from './Events';
import NativeBridge from './NativeBridge';
import ProxyStore from './ProxyStore';
export default function Tabris() {
this._loadFunctions = [];
this._ready = false;
this._init = this._init.bind(this);
this._notify = this._notify.bind(this);
}
extend(Tabris.prototype, Events, {
load(fn) {
if (this._ready) {
fn.call();
} else {
this._loadFunctions.push(fn);
}
},
version: '${VERSION}',
_init(client) {
this._client = client;
this._proxies = new ProxyStore();
this._nativeBridge = new NativeBridge(client);
let i = 0;
while (i < this._loadFunctions.length) {
this._loadFunctions[i++].call();
}
this._ready = true;
},
_setEntryPoint(entryPoint) {
this._entryPoint = entryPoint;
},
_notify(cid, event, param) {
let returnValue;
try {
let proxy = this._proxies.find(cid);
if (proxy) {
try {
returnValue = proxy._trigger(event, param);
} catch (error) {
console.error(error);
console.log(error.stack);
}
}
this.trigger('flush');
} catch (ex) {
console.error(ex);
console.log(ex.stack);
}
return returnValue;
}
});
| import {extend} from './util';
import Events from './Events';
import NativeBridge from './NativeBridge';
import ProxyStore from './ProxyStore';
export default function Tabris() {
this._loadFunctions = [];
this._proxies = new ProxyStore();
this._ready = false;
this._init = this._init.bind(this);
this._notify = this._notify.bind(this);
}
extend(Tabris.prototype, Events, {
load(fn) {
if (this._ready) {
fn.call();
} else {
this._loadFunctions.push(fn);
}
},
version: '${VERSION}',
_init(client) {
this._client = client;
this._nativeBridge = new NativeBridge(client);
let i = 0;
while (i < this._loadFunctions.length) {
this._loadFunctions[i++].call();
}
this._ready = true;
},
_setEntryPoint(entryPoint) {
this._entryPoint = entryPoint;
},
_notify(cid, event, param) {
let returnValue;
try {
let proxy = this._proxies.find(cid);
if (proxy) {
try {
returnValue = proxy._trigger(event, param);
} catch (error) {
console.error(error);
console.log(error.stack);
}
}
this.trigger('flush');
} catch (ex) {
console.error(ex);
console.log(ex.stack);
}
return returnValue;
}
});
|
Use env name MYSQL_DATABASE instead of MYSQL_DB
MYSQL_DATABASE matches the environment variable name expected by the
Docker MySQL image (https://hub.docker.com/_/mysql/) which will make it
easier to set up deployments, as I can just set up a secret with
MYSQL_DATABASE, MYSQL_USER, MYSQL_PASSWORD and so on, and allow that
secret to populate environment variables for both the mysql container
and the ldapi container. | import Knex from 'knex';
import dotenv from 'dotenv';
dotenv.config()
const dbs = {
get public() {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters
delete this.public;
return this.public = Knex({
client: 'mysql2',
useNullAsDefault: true,
connection: {
host : process.env.MYSQL_HOST || '127.0.0.1',
user : process.env.MYSQL_USER || '',
password : process.env.MYSQL_PASSWORD || '',
database : process.env.MYSQL_DATABASE || 'testldapi'
},
});
},
get private() {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters
delete this.private;
return this.private = Knex({
client: 'mysql2',
useNullAsDefault: true,
connection: {
host : process.env.MYSQL_HOST || '127.0.0.1',
user : process.env.MYSQL_USER || '',
password : process.env.MYSQL_PASSWORD || '',
database : process.env.MYSQL_DATABASE || 'testldapi' // `${process.env.MYSQL_DATABASE || 'testldapi'}pvt`
},
});
}
}
export { dbs };
| import Knex from 'knex';
import dotenv from 'dotenv';
dotenv.config()
const dbs = {
get public() {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters
delete this.public;
return this.public = Knex({
client: 'mysql2',
useNullAsDefault: true,
connection: {
host : process.env.MYSQL_HOST || '127.0.0.1',
user : process.env.MYSQL_USER || '',
password : process.env.MYSQL_PASSWORD || '',
database : process.env.MYSQL_DB || 'testldapi'
},
});
},
get private() {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters
delete this.private;
return this.private = Knex({
client: 'mysql2',
useNullAsDefault: true,
connection: {
host : process.env.MYSQL_HOST || '127.0.0.1',
user : process.env.MYSQL_USER || '',
password : process.env.MYSQL_PASSWORD || '',
database : process.env.MYSQL_DB || 'testldapi' // `${process.env.MYSQL_DB || 'testldapi'}pvt`
},
});
}
}
export { dbs };
|
Edit the parameters. Not fix yet | from random import choice
from pygraphc.evaluation.InternalEvaluation import InternalEvaluation
class SimulatedAnnealing(object):
def __init__(self, tmin, tmax, alpha, parameters, energy_type, max_iteration):
"""The constructor of Simulated Annealing method.
Parameters
----------
tmin : float
Minimum temperature.
tmax : float
Maximum temperature.
alpha : float
Cooling factor. Tnew = alpha * Tcurrent
parameters : dict
Dictionary of parameters. Key: parameters, value: list.
energy_type : str
Objective function of simulated annealing. We use internal evaluation for graph clustering.
max_iteration : int
Maximum iteration for simulated annealing.
"""
self.Tmin = tmin
self.Tmax = tmax
self.alpha = alpha
self.parameters = parameters
self.energy_type = energy_type
self.max_iteration = max_iteration
def get_parameter(self):
"""Get random parameter based on given range.
Returns
-------
random_parameter : dict[str, float]
Dictionary of random parameters.
"""
random_parameter = {}
for param, value in self.parameters.iteritems():
random_parameter[param] = choice(value)
return random_parameter
def get_temperature(self, current_temperature):
new_temperature = self.alpha * current_temperature
return new_temperature
def get_energy(self, graph, clusters):
energy = 0.
if self.energy_type == 'silhoutte':
energy = InternalEvaluation.get_silhoutte_index(graph, clusters)
return energy
| from random import choice
from pygraphc.evaluation.InternalEvaluation import InternalEvaluation
class SimulatedAnnealing(object):
def __init__(self, method, tmin, tmax, parameter, energy_type):
"""The constructor of Simulated Annealing method.
Parameters
----------
method : str
The method to run with simulated annealing.
tmin : float
Minimum temperature.
tmax : float
Maximum temperature.
parameter : dict
Dictionary of parameter. Key: parameter, value: list.
energy_type : str
Objective function of simulated annealing. We use internal evaluation for graph clustering.
"""
self.method = method
self.Tmin = tmin
self.Tmax = tmax
self.parameter = parameter
self.energy_type = energy_type
def __get_parameter(self):
chosen_parameter = {}
for param, value in self.parameter.iteritems():
chosen_parameter[param] = choice(value)
return chosen_parameter
def __run_method(self):
if self.method == 'max_clique':
pass
def __get_energy(self, graph, clusters):
energy = 0.
if self.energy_type == 'silhoutte':
energy = InternalEvaluation.get_silhoutte_index(graph, clusters)
return energy
|
Fix to Product block product lookup | <?php
namespace Concrete\Package\VividStore\Src\VividStore\Utilities;
use Controller;
use Core;
use User;
use Database;
defined('C5_EXECUTE') or die(_("Access Denied."));
class ProductFinder extends Controller
{
public function getProductMatch()
{
$u = new User();
if (!$u->isLoggedIn()) {
echo "Access Denied";
exit;
}
if(!$_POST['query']){
echo "Access Denied";
exit;
} else {
$query = $_POST['query'];
$db = Database::get();
$results = $db->query('SELECT * FROM VividStoreProducts WHERE pName LIKE "%'.$query.'%"');
if($results){
foreach($results as $result){ ?>
<li data-product-id="<?=$result['pID']?>"><?=$result['pName']?></li>
<?php } //for each
} else { //if no results ?>
<li><?=t("I can't find a product by that name")?></li>
<?php }
}
}
} | <?php
namespace Concrete\Package\VividStore\Src\VividStore\Utilities;
use Controller;
use Core;
use User;
use Database;
defined('C5_EXECUTE') or die(_("Access Denied."));
class ProductFinder extends Controller
{
public function getProductMatch()
{
$u = new User();
if (!$u->isLoggedIn()) {
echo "Access Denied";
exit;
}
if(!$_POST['query']){
echo "Access Denied";
exit;
} else {
$query = $_POST['query'];
$db = Database::get();
$results = $db->query('SELECT * FROM VividStoreProduct WHERE pName LIKE "%'.$query.'%"');
if($results){
foreach($results as $result){ ?>
<li data-product-id="<?=$result['pID']?>"><?=$result['pName']?></li>
<?php } //for each
} else { //if no results ?>
<li><?=t("I can't find a product by that name")?></li>
<?php }
}
}
} |
Fix old bug - close stream after reading | package com.crowdin.cli.utils.file;
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.util.Map;
import java.util.ResourceBundle;
public class FileReader {
private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;
private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";
private static final String YAML_EXTENSION = ".yaml";
private static final String YML_EXTENSION = ".yml";
public Map<String, Object> readCliConfig(File fileCfg) {
if (fileCfg == null) {
throw new NullPointerException("FileReader.readCliConfig has null args");
}
if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
}
Yaml yaml = new Yaml();
try (InputStream inputStream = new FileInputStream(fileCfg)){
return (Map<String, Object>) yaml.load(inputStream);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
}
} | package com.crowdin.cli.utils.file;
import com.crowdin.cli.utils.MessageSource;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
import java.util.ResourceBundle;
public class FileReader {
private static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;
private static final String DEFAULT_CONFIG_FILE_NAME = "crowdin.yml";
private static final String YAML_EXTENSION = ".yaml";
private static final String YML_EXTENSION = ".yml";
public Map<String, Object> readCliConfig(File fileCfg) {
if (fileCfg == null) {
throw new NullPointerException("FileReader.readCliConfig has null args");
}
if (!(fileCfg.getName().endsWith(YAML_EXTENSION) || fileCfg.getName().endsWith(YML_EXTENSION))) {
System.out.println("WARN: file with name '" + fileCfg.getAbsolutePath() + "' has different type from YAML");
}
Yaml yaml = new Yaml();
InputStream inputStream = null;
try {
inputStream = new FileInputStream(fileCfg);
} catch (FileNotFoundException e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.configuration_file_not_exist"));
}
Map<String, Object> result = null;
try {
result = (Map<String, Object>) yaml.load(inputStream);
} catch (Exception e) {
throw new RuntimeException(RESOURCE_BUNDLE.getString("error.reading_configuration_file"), e);
}
return result;
}
} |
Add Acme\DemoBundle to main bundles, for testing | <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\AopBundle\JMSAopBundle(),
new JMS\DiExtraBundle\JMSDiExtraBundle($this),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new Acme\DemoBundle\AcmeDemoBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| <?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\AopBundle\JMSAopBundle(),
new JMS\DiExtraBundle\JMSDiExtraBundle($this),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
|
Fix - Configuration is not displayed | 'use strict';
angular.module('<%=angularAppName%>')
.config(function ($stateProvider) {
$stateProvider
.state('configuration', {
parent: 'admin',
url: '/configuration',
data: {
roles: ['ROLE_ADMIN']
},
views: {
'content@': {
templateUrl: 'scripts/app/admin/configuration/configuration.html',
controller: 'ConfigurationController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('configuration');
return $translate.refresh();
}]
}
});
})
.controller('ConfigurationController', function ($scope, ConfigurationService) {
ConfigurationService.get().then(function(configuration) {
$scope.configuration = configuration;
});
});
| 'use strict';
angular.module('<%=angularAppName%>')
.config(function ($stateProvider) {
$stateProvider
.state('configuration', {
parent: 'admin',
url: '/configuration',
data: {
roles: ['ROLE_ADMIN']
},
views: {
'content@': {
templateUrl: 'scripts/app/admin/configuration/configuration.html',
controller: 'ConfigurationController'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('configuration');
return $translate.refresh();
}]
}
});
})
.controller('ConfigurationController', function ($scope, ConfigurationService) {
$scope.configuration = ConfigurationService.get();
});
|
Allow to specify arguments for new function | /* See license.txt for terms of usage */
define([
"firebug/lib/trace"
],
function(FBTrace) {
// ********************************************************************************************* //
// Constants
const Cc = Components.classes;
const Ci = Components.interfaces;
var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci["nsIConsoleService"]);
// ********************************************************************************************* //
// Module implementation
var Deprecated = {};
Deprecated.deprecated = function(msg, fnc, args)
{
return function deprecationWrapper()
{
if (!this.nagged)
{
// drop frame with deprecated()
var caller = Components.stack.caller;
var explain = "Deprecated function, " + msg;
if (typeof(FBTrace) !== undefined)
{
FBTrace.sysout(explain, getStackDump());
//if (exc.stack)
// exc.stack = exc.stack.split("\n");
FBTrace.sysout(explain + " " + caller.toString());
}
if (consoleService)
consoleService.logStringMessage(explain + " " + caller.toString());
this.nagged = true;
}
return fnc.apply(this, args || arguments);
}
};
// ********************************************************************************************* //
// Local helpers
function getStackDump()
{
var lines = [];
for (var frame = Components.stack; frame; frame = frame.caller)
lines.push(frame.filename + " (" + frame.lineNumber + ")");
return lines.join("\n");
};
// ********************************************************************************************* //
// Registration
return Deprecated;
// ********************************************************************************************* //
});
| /* See license.txt for terms of usage */
define([
"firebug/lib/trace"
],
function(FBTrace) {
// ********************************************************************************************* //
// Constants
const Cc = Components.classes;
const Ci = Components.interfaces;
var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci["nsIConsoleService"]);
// ********************************************************************************************* //
// Module implementation
var Deprecated = {};
Deprecated.deprecated = function(msg, fnc)
{
return function deprecationWrapper()
{
if (!this.nagged)
{
// drop frame with deprecated()
var caller = Components.stack.caller;
var explain = "Deprecated function, " + msg;
if (typeof(FBTrace) !== undefined)
{
FBTrace.sysout(explain, getStackDump());
//if (exc.stack)
// exc.stack = exc.stack.split("\n");
FBTrace.sysout(explain + " " + caller.toString());
}
if (consoleService)
consoleService.logStringMessage(explain + " " + caller.toString());
this.nagged = true;
}
return fnc.apply(this, arguments);
}
}
// ********************************************************************************************* //
// Local helpers
function getStackDump()
{
var lines = [];
for (var frame = Components.stack; frame; frame = frame.caller)
lines.push(frame.filename + " (" + frame.lineNumber + ")");
return lines.join("\n");
};
// ********************************************************************************************* //
// Registration
return Deprecated;
// ********************************************************************************************* //
});
|
Add the missing logical not in the scan model validation | define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
idAttribute: 'SCANPARAMETERSMODELID',
urlRoot: '/exp/parameters/models',
defaults: {
SEQUENCENUMBER: null,
START: null,
STOP: null,
STEP: null,
ARRAY: null,
},
validation: {
DATACOLLECTIONPLANID: {
required: true,
pattern: 'digits',
},
SCANPARAMETERSSERVICEID: {
required: true,
pattern: 'digits',
},
SEQUENCENUMBER: {
required: true,
pattern: 'number'
},
START: {
required: function() {
return !this.get('ARRAY')
},
pattern: 'number'
},
STOP: {
required: function() {
return !this.get('ARRAY')
},
pattern: 'number'
},
STEP: {
required: function() {
return !this.get('ARRAY')
},
pattern: 'number'
},
ARRAY: {
required: function() {
return !(this.get('START') || this.get('STOP') || this.get('STEP'))
},
pattern: 'array'
},
},
})
})
| define(['backbone'], function(Backbone) {
return Backbone.Model.extend({
idAttribute: 'SCANPARAMETERSMODELID',
urlRoot: '/exp/parameters/models',
defaults: {
SEQUENCENUMBER: null,
START: null,
STOP: null,
STEP: null,
ARRAY: null,
},
validation: {
DATACOLLECTIONPLANID: {
required: true,
pattern: 'digits',
},
SCANPARAMETERSSERVICEID: {
required: true,
pattern: 'digits',
},
SEQUENCENUMBER: {
required: true,
pattern: 'number'
},
START: {
required: function() {
return !this.get('ARRAY')
},
pattern: 'number'
},
STOP: {
required: function() {
return !this.get('ARRAY')
},
pattern: 'number'
},
STEP: {
required: function() {
return !this.get('ARRAY')
},
pattern: 'number'
},
ARRAY: {
required: function() {
return (this.get('START') || this.get('STOP') || this.get('STEP'))
},
pattern: 'array'
},
},
})
})
|
Check whether read file is actually a file, and if it's not too big. | var fs = require('fs'),
expandHomeDir = require('expand-home-dir'),
async = require('async')
;
function readFile(fileLocation, cb) {
fs.stat(fileLocation, function (stats) {
if (stats.size > Math.pow(1024, 2) || !stats.isFile()) {
cb(new Error('File ' + fileLocation + ' too large or not an ordinary file!'));
} else {
fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) {
if (err) {
cb(err);
return;
}
cb(null, fileContents);
});
}
});
}
function loadConfigs(configLocations, cb) {
async.map(configLocations, function (configLocation, cb) {
var absoluteConfigLocation = expandHomeDir(configLocation);
fs.exists(absoluteConfigLocation, function (exists) {
if (exists) {
readFile(absoluteConfigLocation, function (err, rawConfig) {
if (err) {
console.log("Unable to read config from: ", absoluteConfigLocation);
cb(null, {});
return;
}
try {
cb(null, JSON.parse(rawConfig));
} catch (err) {
console.log("Unable to parse config from: ", absoluteConfigLocation);
}
});
} else {
cb(null, {});
}
});
}, function (err, results) {
cb(results);
});
}
module.exports.readFile = readFile;
module.exports.loadConfigs = loadConfigs; | var fs = require('fs'),
expandHomeDir = require('expand-home-dir'),
async = require('async')
;
function readFile(fileLocation, cb) {
fs.readFile(fileLocation, {encoding: 'utf8'}, function (err, fileContents) {
if (err) {
cb(err);
return;
}
cb(null, fileContents);
});
}
function loadConfigs(configLocations, cb) {
async.map(configLocations, function (configLocation, cb) {
var absoluteConfigLocation = expandHomeDir(configLocation);
fs.exists(absoluteConfigLocation, function (exists) {
if (exists) {
readFile(absoluteConfigLocation, function (err, rawConfig) {
if (err) {
console.log("Unable to read config from: ", absoluteConfigLocation);
cb(null, {});
return;
}
try {
cb(null, JSON.parse(rawConfig));
} catch (err) {
console.log("Unable to parse config from: ", absoluteConfigLocation);
}
});
} else {
cb(null, {});
}
});
}, function (err, results) {
cb(results);
});
}
module.exports.readFile = readFile;
module.exports.loadConfigs = loadConfigs; |
Add todo for hp stuff | # -*- coding: utf-8 -*-
import hackarena.constants
from hackarena.constants import Classes
from hackarena.constants import Spell
from hackarena.game_objects import BaseGameObject
AVAILABLE_SPELLS = {
Classes.TANK: [Spell.TANK_ATTACK, Spell.TANK_AOE],
Classes.MAGE: [Spell.MAGE_DIRECT_DAMAGE, Spell.MAGE_AOE],
Classes.HEALER: [Spell.HEALER_DIRECT_DAMAGE, Spell.HEALER_HEAL],
Classes.HQ: [],
}
MAX_HP = 130
class Player(BaseGameObject):
def __init__(
self,
username,
character_class,
team,
hp=MAX_HP,
last_death=0,
):
# TODO: set different MAX_HP based on class
self.MAX_HP = MAX_HP
self.username = username
self.character_class = character_class
self.available_spells = AVAILABLE_SPELLS[character_class]
self.spell_cast_times = dict((spell, 0) for spell in self.available_spells)
self.team = team
self.reset()
self.last_death = last_death
def reset(self):
# TODO: set different HP based on class
self.hp = MAX_HP
self.position = {
'x': 2 if self.team == 'blue' else hackarena.constants.MAP_TILES_WIDTH - 2,
'y': 2 if self.team == 'blue' else hackarena.constants.MAP_TILES_HEIGHT - 2,
}
| # -*- coding: utf-8 -*-
import hackarena.constants
from hackarena.constants import Classes
from hackarena.constants import Spell
from hackarena.game_objects import BaseGameObject
AVAILABLE_SPELLS = {
Classes.TANK: [Spell.TANK_ATTACK, Spell.TANK_AOE],
Classes.MAGE: [Spell.MAGE_DIRECT_DAMAGE, Spell.MAGE_AOE],
Classes.HEALER: [Spell.HEALER_DIRECT_DAMAGE, Spell.HEALER_HEAL],
Classes.HQ: [],
}
MAX_HP = 130
class Player(BaseGameObject):
def __init__(
self,
username,
character_class,
team,
hp=MAX_HP,
last_death=0,
):
self.MAX_HP = MAX_HP
self.username = username
self.character_class = character_class
self.available_spells = AVAILABLE_SPELLS[character_class]
self.spell_cast_times = dict((spell, 0) for spell in self.available_spells)
self.team = team
self.reset()
self.last_death = last_death
def reset(self):
self.hp = MAX_HP
self.position = {
'x': 2 if self.team == 'blue' else hackarena.constants.MAP_TILES_WIDTH - 2,
'y': 2 if self.team == 'blue' else hackarena.constants.MAP_TILES_HEIGHT - 2,
}
|
Use MEDIUMINT for steps per day (no effect, not used, and ignored by sqlite) | package nodomain.freeyourgadget.gadgetbridge.database.schema;
import android.database.sqlite.SQLiteDatabase;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.database.DBUpdateScript;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_PROVIDER;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_STEPS;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_TIMESTAMP;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.TABLE_STEPS_PER_DAY;
/**
* Adds a table "STEPS_PER_DAY".
*/
public class ActivityDBUpdate_6 implements DBUpdateScript {
@Override
public void upgradeSchema(SQLiteDatabase db) {
String CREATE_STEPS_PER_DAY_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_STEPS_PER_DAY + " ("
+ KEY_TIMESTAMP + " INT,"
+ KEY_PROVIDER + " TINYINT,"
+ KEY_STEPS + " MEDIUMINT,"
+ " PRIMARY KEY (" + KEY_TIMESTAMP + "," + KEY_PROVIDER + ") ON CONFLICT REPLACE)" + DBHelper.getWithoutRowId();
db.execSQL(CREATE_STEPS_PER_DAY_TABLE);
}
@Override
public void downgradeSchema(SQLiteDatabase db) {
DBHelper.dropTable(TABLE_STEPS_PER_DAY, db);
}
}
| package nodomain.freeyourgadget.gadgetbridge.database.schema;
import android.database.sqlite.SQLiteDatabase;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.database.DBUpdateScript;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_PROVIDER;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_STEPS;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.KEY_TIMESTAMP;
import static nodomain.freeyourgadget.gadgetbridge.database.DBConstants.TABLE_STEPS_PER_DAY;
/**
* Adds a table "STEPS_PER_DAY".
*/
public class ActivityDBUpdate_6 implements DBUpdateScript {
@Override
public void upgradeSchema(SQLiteDatabase db) {
String CREATE_STEPS_PER_DAY_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_STEPS_PER_DAY + " ("
+ KEY_TIMESTAMP + " INT,"
+ KEY_PROVIDER + " TINYINT,"
+ KEY_STEPS + " TINYINT,"
+ " PRIMARY KEY (" + KEY_TIMESTAMP + "," + KEY_PROVIDER + ") ON CONFLICT REPLACE)" + DBHelper.getWithoutRowId();
db.execSQL(CREATE_STEPS_PER_DAY_TABLE);
}
@Override
public void downgradeSchema(SQLiteDatabase db) {
DBHelper.dropTable(TABLE_STEPS_PER_DAY, db);
}
}
|
Fix routing deprecation for Ember 2.13 | import Ember from 'ember';
import Config from 'ember-routable-modal/configuration';
export default Ember.Service.extend({
routing: Ember.inject.service('-routing'),
routeName: null,
activeListener: function() {
if (typeof Ember.$ !== 'undefined') {
Ember.$('body')[this.get('routeName') ? 'addClass' : 'removeClass'](Config.modalOpenBodyClassName);
}
}.observes('routeName'),
init() {
this._super(...arguments);
if (typeof Ember.$ !== 'undefined' && typeof window !== 'undefined') {
Ember.$(window).on('popstate.ember-routable-modal', () => {
if (this.get('routeName')) {
this.set('routeName', null);
}
});
}
},
clear() {
if (this.get('routeName')) {
this.set('routeName', null);
}
},
close() {
const routerMain = this.get('routing.router');
const routerLib = routerMain._routerMicrolib || routerMain.router;
const handlerInfos = routerLib.state.handlerInfos;
const currentController = handlerInfos[handlerInfos.length - 1]._handler.controller;
this.set('routeName', null);
if (currentController._isModalRoute) {
const parentRoute = handlerInfos[handlerInfos.length - 2].name;
routerLib.transitionTo(parentRoute);
} else {
const url = this.get('routing').generateURL(this.get('routing.currentPath'));
routerLib.updateURL(url);
}
}
});
| import Ember from 'ember';
import Config from 'ember-routable-modal/configuration';
export default Ember.Service.extend({
routing: Ember.inject.service('-routing'),
routeName: null,
activeListener: function() {
if (typeof Ember.$ !== 'undefined') {
Ember.$('body')[this.get('routeName') ? 'addClass' : 'removeClass'](Config.modalOpenBodyClassName);
}
}.observes('routeName'),
init() {
this._super(...arguments);
if (typeof Ember.$ !== 'undefined' && typeof window !== 'undefined') {
Ember.$(window).on('popstate.ember-routable-modal', () => {
if (this.get('routeName')) {
this.set('routeName', null);
}
});
}
},
clear() {
if (this.get('routeName')) {
this.set('routeName', null);
}
},
close() {
const rout = this.get('routing.router.router');
const handlerInfos = this.get('routing.router.router.state.handlerInfos');
const currentController = handlerInfos[handlerInfos.length - 1]._handler.controller;
this.set('routeName', null);
if (currentController._isModalRoute) {
const parentRoute = handlerInfos[handlerInfos.length - 2].name;
rout.transitionTo(parentRoute);
} else {
const url = this.get('routing').generateURL(this.get('routing.currentPath'));
rout.updateURL(url);
}
}
});
|
Make comment of 'add_a_getter' method | import copy
def add_a_field(cls, field):
setattr(cls, field.string, field)
pass
def add_a_getter(cls, field):
fieldname = field.string
getter_template = copy.deepcopy(field.get_getterTemplate())
getter_template.__doc__ = "get%s - method to get value of field: %s" % (fieldname,fieldname)
getter_template.__name__ = "get%s" % fieldname
setattr(cls, getter_template.__name__, classmethod(getter_template))
pass
class BaseOLiMSModel(object):
'''
This is the base class of all OLiMS model. In addition to models.Model, every OLiMS model will
be derived from this class and get all its code from a Bika Content class i.e. a Bika
content class will be converted to OLiMS model class by removing irrelevant code,
and adding derivation from this class, with the calling of following in the end
DerivedModel_Of_BaseOLiMSModel.initialze(bika_schema)
'''
@classmethod
def initialze(cls, schema):
# take out each filed from the passed schema and:
# 1. make a model variable for it, and assign this field to this variable
# 2. make getter methods for each model variable defined in step 1
for field in schema:
add_a_field(cls, field)
# add_a_getter(cls, field)
pass
pass
pass
| import copy
def add_a_field(cls, field):
setattr(cls, field.string, field)
pass
def add_a_getter(cls, field):
fieldname = field.string
getter_template = copy.deepcopy(field.get_getterTemplate())
getter_template.__doc__ = "get%s - method to get value of field: %s" % (fieldname,fieldname)
getter_template.__name__ = "get%s" % fieldname
setattr(cls, getter_template.__name__, classmethod(getter_template))
pass
class BaseOLiMSModel(object):
'''
This is the base class of all OLiMS model. In addition to models.Model, every OLiMS model will
be derived from this class and get all its code from a Bika Content class i.e. a Bika
content class will be converted to OLiMS model class by removing irrelevant code,
and adding derivation from this class, with the calling of following in the end
DerivedModel_Of_BaseOLiMSModel.initialze(bika_schema)
'''
@classmethod
def initialze(cls, schema):
# take out each filed from the passed schema and:
# 1. make a model variable for it, and assign this field to this variable
# 2. make getter methods for each model variable defined in step 1
for field in schema:
add_a_field(cls, field)
add_a_getter(cls, field)
pass
pass
pass
|
Fix testcase for Cache dispense | <?php
/**
* CacheTest.php.
*/
namespace Pagon;
class CacheTest extends \PHPUnit_Framework_TestCase
{
/**
* @var App
*/
protected $app;
public function setUp()
{
$this->app = new App(array(
'cache' => array(
'user' => array(
'type' => 'file',
)
)
));
}
public function testFactory()
{
$file = Cache::factory('file');
$this->assertInstanceOf('Pagon\Cache\File', $file);
}
public function testFactoryNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$none = Cache::factory('none');
}
public function testDispense()
{
$user_cache = Cache::dispense('cache.user');
$this->assertInstanceOf('Pagon\Cache\File', $user_cache);
$try_new_cache = Cache::dispense('cache.user');
$this->assertEquals($try_new_cache, $user_cache);
}
public function testDispenseNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$user_cache = Cache::dispense('cache.user1');
}
}
| <?php
/**
* CacheTest.php.
*/
namespace Pagon;
class CacheTest extends \PHPUnit_Framework_TestCase
{
/**
* @var App
*/
protected $app;
public function setUp()
{
$this->app = new App(array(
'cache' => array(
'user' => array(
'type' => 'file',
)
)
));
}
public function testFactory()
{
$file = Cache::factory('file');
$this->assertInstanceOf('Pagon\Cache\File', $file);
}
public function testFactoryNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$none = Cache::factory('none');
}
public function testDispense()
{
$user_cache = Cache::dispense('cache.user');
$this->assertInstanceOf('Pagon\Cache\File', $user_cache);
$try_new_cache = Cache::dispense('user');
$this->assertEquals($try_new_cache, $user_cache);
}
public function testDispenseNonExists()
{
$this->setExpectedException('InvalidArgumentException');
$user_cache = Cache::dispense('cache.user1');
}
}
|
Set default currency to USD if none | import { fromJS } from 'immutable';
import {
SERVER_DATA_AUTHORIZE,
SERVER_DATA_BALANCE,
SERVER_DATA_PAYOUT_CURRENCIES,
SERVER_DATA_BUY,
UPDATE_TOKEN,
} from '../_constants/ActionTypes';
const initialState = fromJS({
loginid: '',
fullname: '',
currency: 'USD',
balance: 0,
token: '',
currencies: ['USD'],
});
export default (state = initialState, action) => {
switch (action.type) {
case SERVER_DATA_AUTHORIZE: {
const authorize = fromJS(action.serverResponse.authorize);
if (!authorize.currency) {
return state.merge(authorize).set('currency', 'USD');
}
return state.merge(authorize);
}
case SERVER_DATA_BALANCE: {
return state.set('balance', action.serverResponse.balance.balance);
}
case SERVER_DATA_BUY: {
return state.setIn(['account', 'balance'], action.serverResponse.balance_after);
}
case SERVER_DATA_PAYOUT_CURRENCIES: {
return state.set('currencies', action.serverResponse.payout_currencies);
}
case UPDATE_TOKEN: {
return state.set('token', action.token);
}
default:
return state;
}
};
| import { fromJS } from 'immutable';
import {
SERVER_DATA_AUTHORIZE,
SERVER_DATA_BALANCE,
SERVER_DATA_PAYOUT_CURRENCIES,
SERVER_DATA_BUY,
UPDATE_TOKEN,
} from '../_constants/ActionTypes';
const initialState = fromJS({
loginid: '',
fullname: '',
currency: 'USD',
balance: 0,
token: '',
currencies: ['USD'],
});
export default (state = initialState, action) => {
switch (action.type) {
case SERVER_DATA_AUTHORIZE: {
const authorize = fromJS(action.serverResponse.authorize);
return state.merge(authorize);
}
case SERVER_DATA_BALANCE: {
return state.set('balance', action.serverResponse.balance.balance);
}
case SERVER_DATA_BUY: {
return state.setIn(['account', 'balance'], action.serverResponse.balance_after);
}
case SERVER_DATA_PAYOUT_CURRENCIES: {
return state.set('currencies', action.serverResponse.payout_currencies);
}
case UPDATE_TOKEN: {
return state.set('token', action.token);
}
default:
return state;
}
};
|
Add lenient to abstract BaseSource signature | #
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
class BaseSource(object):
def __init__(self, id):
self.id = id
if not getattr(self, 'log', False):
raise NotImplementedError('Abstract base class, log property '
'missing')
if not hasattr(self, 'SUPPORTS_GEO'):
raise NotImplementedError('Abstract base class, SUPPORTS_GEO '
'property missing')
if not hasattr(self, 'SUPPORTS'):
raise NotImplementedError('Abstract base class, SUPPORTS '
'property missing')
def populate(self, zone, target=False, lenient=False):
'''
Loads all zones the provider knows about
When `target` is True the populate call is being made to load the
current state of the provider.
When `lenient` is True the populate call may skip record validation and
do a "best effort" load of data. That will allow through some common,
but not best practices stuff that we otherwise would reject. E.g. no
trailing . or mising escapes for ;.
'''
raise NotImplementedError('Abstract base class, populate method '
'missing')
def supports(self, record):
return record._type in self.SUPPORTS
def __repr__(self):
return self.__class__.__name__
| #
#
#
from __future__ import absolute_import, division, print_function, \
unicode_literals
class BaseSource(object):
def __init__(self, id):
self.id = id
if not getattr(self, 'log', False):
raise NotImplementedError('Abstract base class, log property '
'missing')
if not hasattr(self, 'SUPPORTS_GEO'):
raise NotImplementedError('Abstract base class, SUPPORTS_GEO '
'property missing')
if not hasattr(self, 'SUPPORTS'):
raise NotImplementedError('Abstract base class, SUPPORTS '
'property missing')
def populate(self, zone, target=False):
'''
Loads all zones the provider knows about
When `target` is True the populate call is being made to load the
current state of the provider.
When `lenient` is True the populate call may skip record validation and
do a "best effort" load of data. That will allow through some common,
but not best practices stuff that we otherwise would reject. E.g. no
trailing . or mising escapes for ;.
'''
raise NotImplementedError('Abstract base class, populate method '
'missing')
def supports(self, record):
return record._type in self.SUPPORTS
def __repr__(self):
return self.__class__.__name__
|
Change maker self URL name | from django.conf.urls import patterns, url
from maker.views import (RegsitrationView,
AuthenticationView,
MakerSelfView,
MakerProfileView,
ResetPasswordRequestView,
ResetPasswordProcessView,
ChangePasswordView,
EmailChangeRequestView,
EmailChangeProcessView)
urlpatterns = patterns(
'',
url(
r'^self/?$',
MakerSelfView.as_view(),
name='maker-self'
),
url(
r'^register/?$',
RegsitrationView.as_view(),
name='registration'
),
url(
r'^authenticate/?$',
AuthenticationView.as_view(),
name='authentication'
),
url(
r'^password/?$',
ChangePasswordView.as_view(),
name='change-password'
),
url(
r'^password/reset/?$',
ResetPasswordRequestView.as_view(),
name='password-reset'
),
url(
r'^password/reset/update?$',
ResetPasswordProcessView.as_view(),
name='password-reset-process'
),
url(
r'^email/?$',
EmailChangeRequestView.as_view(),
name='email-change-request'
),
url(
r'^email/update?$',
EmailChangeProcessView.as_view(),
name='email-change-process'
),
url(
r'^(?P<pk>[0-9]+)/?$',
MakerProfileView.as_view(),
name='maker-profile-view'
)
)
| from django.conf.urls import patterns, url
from maker.views import (RegsitrationView,
AuthenticationView,
MakerSelfView,
MakerProfileView,
ResetPasswordRequestView,
ResetPasswordProcessView,
ChangePasswordView,
EmailChangeRequestView,
EmailChangeProcessView)
urlpatterns = patterns(
'',
url(
r'^/?$',
MakerSelfView.as_view(),
name='maker-self'
),
url(
r'^register/?$',
RegsitrationView.as_view(),
name='registration'
),
url(
r'^authenticate/?$',
AuthenticationView.as_view(),
name='authentication'
),
url(
r'^password/?$',
ChangePasswordView.as_view(),
name='change-password'
),
url(
r'^password/reset/?$',
ResetPasswordRequestView.as_view(),
name='password-reset'
),
url(
r'^password/reset/update?$',
ResetPasswordProcessView.as_view(),
name='password-reset-process'
),
url(
r'^email/?$',
EmailChangeRequestView.as_view(),
name='email-change-request'
),
url(
r'^email/update?$',
EmailChangeProcessView.as_view(),
name='email-change-process'
),
url(
r'^(?P<pk>[0-9]+)/?$',
MakerProfileView.as_view(),
name='maker-profile-view'
)
)
|
BB-3603: Add new flag to the role entity
- removed unneseccary empty line | <?php
namespace Oro\Bundle\UserBundle\Tests\Unit\Entity;
use Oro\Bundle\UserBundle\Entity\Role;
class RoleTest extends \PHPUnit_Framework_TestCase
{
public function testCreate()
{
$strRole = 'foo';
$role = new Role($strRole);
$this->assertEquals($strRole, $role->getLabel());
$this->assertEquals($strRole, $role->getRole());
}
public function testRole()
{
$role = new Role();
$this->assertEmpty($role->getId());
$this->assertEmpty($role->getRole());
$role->setRole('foo');
$this->assertStringStartsWith('ROLE_FOO', $role->getRole());
$this->assertEquals(Role::PREFIX_ROLE, $role->getPrefix());
}
public function testLabel()
{
$role = new Role();
$label = 'Test role';
$this->assertEmpty($role->getLabel());
$role->setLabel($label);
$this->assertEquals($label, $role->getLabel());
$this->assertEquals($label, (string)$role);
}
public function testClone()
{
$role = new Role();
$class = new \ReflectionClass($role);
$prop = $class->getProperty('id');
$prop->setAccessible(true);
$prop->setValue($role, 1);
$copy = clone $role;
$this->assertEmpty($copy->getId());
}
}
| <?php
namespace Oro\Bundle\UserBundle\Tests\Unit\Entity;
use Oro\Bundle\UserBundle\Entity\Role;
class RoleTest extends \PHPUnit_Framework_TestCase
{
public function testCreate()
{
$strRole = 'foo';
$role = new Role($strRole);
$this->assertEquals($strRole, $role->getLabel());
$this->assertEquals($strRole, $role->getRole());
}
public function testRole()
{
$role = new Role();
$this->assertEmpty($role->getId());
$this->assertEmpty($role->getRole());
$role->setRole('foo');
$this->assertStringStartsWith('ROLE_FOO', $role->getRole());
$this->assertEquals(Role::PREFIX_ROLE, $role->getPrefix());
}
public function testLabel()
{
$role = new Role();
$label = 'Test role';
$this->assertEmpty($role->getLabel());
$role->setLabel($label);
$this->assertEquals($label, $role->getLabel());
$this->assertEquals($label, (string)$role);
}
public function testClone()
{
$role = new Role();
$class = new \ReflectionClass($role);
$prop = $class->getProperty('id');
$prop->setAccessible(true);
$prop->setValue($role, 1);
$copy = clone $role;
$this->assertEmpty($copy->getId());
}
}
|
Include course semester and year in results | /** Course search utility for admin **/
!function(app, $) {
$(document).ready(function() {
if($('.courses-search-query').length) {
var target = $('.courses-search-query');
$.ajax({
url: target.data('autocompleteurl'),
dataType: "json",
success: function(courses) {
target.omniselect({
source: courses,
resultsClass: 'typeahead dropdown-menu course-result',
activeClass: 'active',
itemLabel: function(course) {
return course.courseno + " " + course.name +
" (" + course.semester + " " + course.year + ")";
},
itemId: function(course) {
return course.id;
},
renderItem: function(label) {
return '<li><a href="#">' + label + '</a></li>';
},
filter: function(item, query) {
var regex = new RegExp(query, 'i');
return item.name.match(regex) || item.courseno.match(regex);
}
}).on('omniselect:select', function(event, id) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "/current_course/change");
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", "course_id");
field.setAttribute("value", id);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
return false;
});
}
});
}
});
}(Gradecraft, jQuery);
| /** Course search utility for admin **/
!function(app, $) {
$(document).ready(function() {
if($('.courses-search-query').length) {
var target = $('.courses-search-query');
$.ajax({
url: target.data('autocompleteurl'),
dataType: "json",
success: function(courses) {
target.omniselect({
source: courses,
resultsClass: 'typeahead dropdown-menu course-result',
activeClass: 'active',
itemLabel: function(course) {
return course.courseno + " " + course.name;
},
itemId: function(course) {
return course.id;
},
renderItem: function(label) {
return '<li><a href="#">' + label + '</a></li>';
},
filter: function(item, query) {
var regex = new RegExp(query, 'i');
return item.name.match(regex) || item.courseno.match(regex);
}
}).on('omniselect:select', function(event, id) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "/current_course/change");
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", "course_id");
field.setAttribute("value", id);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
return false;
});
}
});
}
});
}(Gradecraft, jQuery);
|
Upd: Normalize behaviour of getVersionNumber on windows.
The windows version returns `2.2.9.0`, whereas the iOS and android version limit it to `2.2.9`. | AppVersionProxy = {
getVersionNumber: function (successCallback, failCallback, args) {
var version = Windows.ApplicationModel.Package.current.id.version;
successCallback([version.major, version.minor, version.build].join('.'));
},
getAppName: function (successCallback, failCallback, args) {
if(Windows.ApplicationModel.Package.current && Windows.ApplicationModel.Package.current.displayName){
var name = Windows.ApplicationModel.Package.current.displayName;
successCallback(name);
} else {
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync("AppxManifest.xml").then(function (file) {
Windows.Data.Xml.Dom.XmlDocument.loadFromFileAsync(file).then(function (xdoc) {
var displayName = xdoc.getElementsByTagName("DisplayName");
if (displayName && displayName.length === 1) {
var name = displayName[0].innerText;
successCallback(name);
} else {
(failCallback || function(){})({ code: -1, message: "ERR_DISPLAY_NAME_NOT_FOUND" });
}
}, (failCallback || function(){}));
}, (failCallback || function(){}));
}
},
getPackageName: function (successCallback, failCallback, args) {
var name = Windows.ApplicationModel.Package.current.id.name;
successCallback(name);
},
getVersionCode: function (successCallback, failCallback, args) {
var build = Windows.ApplicationModel.Package.current.id.version.build;
successCallback(build);
}
};
cordova.commandProxy.add("AppVersion", AppVersionProxy);
| AppVersionProxy = {
getVersionNumber: function (successCallback, failCallback, args) {
var version = Windows.ApplicationModel.Package.current.id.version;
successCallback([version.major, version.minor, version.build, version.revision].join('.'));
},
getAppName: function (successCallback, failCallback, args) {
if(Windows.ApplicationModel.Package.current && Windows.ApplicationModel.Package.current.displayName){
var name = Windows.ApplicationModel.Package.current.displayName;
successCallback(name);
} else {
Windows.ApplicationModel.Package.current.installedLocation.getFileAsync("AppxManifest.xml").then(function (file) {
Windows.Data.Xml.Dom.XmlDocument.loadFromFileAsync(file).then(function (xdoc) {
var displayName = xdoc.getElementsByTagName("DisplayName");
if (displayName && displayName.length === 1) {
var name = displayName[0].innerText;
successCallback(name);
} else {
(failCallback || function(){})({ code: -1, message: "ERR_DISPLAY_NAME_NOT_FOUND" });
}
}, (failCallback || function(){}));
}, (failCallback || function(){}));
}
},
getPackageName: function (successCallback, failCallback, args) {
var name = Windows.ApplicationModel.Package.current.id.name;
successCallback(name);
},
getVersionCode: function (successCallback, failCallback, args) {
var build = Windows.ApplicationModel.Package.current.id.version.build;
successCallback(build);
}
};
cordova.commandProxy.add("AppVersion", AppVersionProxy);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.