text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add encoding and unicode literals import | # encoding: utf-8
from __future__ import unicode_literals
import pytest
import turbasen
@pytest.fixture
def configure_dev():
turbasen.configure(ENDPOINT_URL='http://dev.nasjonalturbase.no/')
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_get(configure_dev):
sted = turbasen.Sted.get('52407fb375049e561500004e')
assert sted.navn == u'Tjørnbrotbu'
assert sted.ssr_id == 382116
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_lookup(configure_dev):
results = turbasen.Sted.lookup(pages=2)
result_list = list(results)
assert len(result_list) == turbasen.settings.Settings.LIMIT * 2
assert result_list[0].object_id != ''
| import pytest
import turbasen
@pytest.fixture
def configure_dev():
turbasen.configure(ENDPOINT_URL='http://dev.nasjonalturbase.no/')
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_get(configure_dev):
sted = turbasen.Sted.get('52407fb375049e561500004e')
assert sted.navn == u'Tjørnbrotbu'
assert sted.ssr_id == 382116
@pytest.mark.skipif(turbasen.settings.Settings.API_KEY is None, reason="API key not set")
def test_lookup(configure_dev):
results = turbasen.Sted.lookup(pages=2)
result_list = list(results)
assert len(result_list) == turbasen.settings.Settings.LIMIT * 2
assert result_list[0].object_id != ''
|
Revert to using jmbo gis flag | from django.utils.translation import ugettext as _
from jmbo import USE_GIS
from jmbo.views import ObjectList
from jmbo_calendar.models import Event
class ObjectList(ObjectList):
def get_context_data(self, **kwargs):
context = super(ObjectList, self).get_context_data(**kwargs)
show_distance = False
if USE_GIS:
from django.contrib.gis.geos import Point
show_distance = isinstance(
self.request.session['location']['position'], Point
)
context["title"] = _("Events")
context["show_distance"] = show_distance
return context
def get_queryset(self):
qs = Event.coordinator.upcoming()
qs = qs.filter(
location__country=self.request.session['location']['city'].country_id
)
position = self.request.session['location']['position']
if not isinstance(position, Point):
position = self.request.session['location']['city'].coordinates
qs = qs.distance(position).order_by('distance', 'start')
return qs
def get_paginate_by(self, *args, **kwargs):
# todo: needs work in Jmbo to work
return 10
| from django.utils.translation import ugettext as _
from jmbo.views import ObjectList
from jmbo_calendar.models import Event
class ObjectList(ObjectList):
def get_context_data(self, **kwargs):
context = super(ObjectList, self).get_context_data(**kwargs)
try:
from django.contrib.gis.geos import Point
show_distance = isinstance(
self.request.session['location']['position'], Point
)
except ImportError:
show_distance = False
context["title"] = _("Events")
context["show_distance"] = show_distance
return context
def get_queryset(self):
qs = Event.coordinator.upcoming()
qs = qs.filter(
location__country=self.request.session['location']['city'].country_id
)
position = self.request.session['location']['position']
if not isinstance(position, Point):
position = self.request.session['location']['city'].coordinates
qs = qs.distance(position).order_by('distance', 'start')
return qs
def get_paginate_by(self, *args, **kwargs):
# todo: needs work in Jmbo to work
return 10
|
Add condition to check for latest commit activity | '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
from datetime import datetime, date
def send_sms():
'''
Send SMS reminder
'''
config = {'account_sid' : '', 'auth_token' : ''}
client = TwilioRestClient(config['account_sid'], config['auth_token'])
message = client.messages.create(to="", from_="",
body="Hello there!")
def check_commit_activity():
'''
Check if there was any change in the commit history of the user. If date of
latest event is the same as current date, commit was made, hence return True
else return False. Returning False triggers sending of an SMS reminder
'''
get_recent_event = requests.get("https://api.github.com/users/%s/events/public" % '')
event_date = datetime.strptime(get_recent_event.json()[0]['created_at'].split('T')[0], '%Y-%m-%d').date()
return event_date == date.today()
def main():
if not check_commit_activity():
send_sms()
if __name__ == "__main__":
main()
| '''
This module will send SMS reminders periodically, using Twilio.
The aim is to encourage user to code, commit and push to GitHub everyday
'''
import requests
from twilio.rest import TwilioRestClient
from datetime import datetime, date
def send_sms():
'''
Send SMS reminder
'''
config = {'account_sid' : '', 'auth_token' : ''}
client = TwilioRestClient(config['account_sid'], config['auth_token'])
message = client.messages.create(to="", from_="",
body="Hello there!")
def check_commit_activity():
'''
Check if there was any change in the commit history of the user
'''
get_recent_event = requests.get("https://api.github.com/users/ueg1990/events/public")
print datetime.strptime(get_recent_event.json()[0]['created_at'].split('T')[0], '%Y-%m-%d').date()
print date.today()
print datetime.strptime(get_recent_event.json()[0]['created_at'].split('T')[0], '%Y-%m-%d').date() == date.today()
print type(datetime.strptime(get_recent_event.json()[0]['created_at'].split('T')[0], '%Y-%m-%d').date()), type(date.today())
return False
def main():
check_commit_activity()
# send_sms()
if __name__ == "__main__":
main()
|
Insert new files, Alura, Projeto de Algoritmos 1, Aula 20 | public class TestaOrdenacao {
public static void main(String[] args) {
Produto produtos[] = {
new Produto("Lamborghini", 1000000),
new Produto("Jipe", 46000),
new Produto("Brasília", 16000),
new Produto("Smart", 46000),
new Produto("Fusca", 17000)
};
for(int atual = 0; atual < produtos.length - 1; atual++) {
int menor = buscaMenor(produtos, atual, produtos.length - 1);
Produto produtoAtual = produtos[atual];
Produto produtoMenor = produtos[menor];
produtos[atual] = produtoMenor;
produtos[menor] = produtoAtual;
}
for(Produto produto : produtos) {
System.out.println(produto.getNome() + " custa " + produto.getPreco());
}
}
private static int buscaMenor(Produto[] produtos, int inicio, int termino) {
int maisBarato = inicio;
for(int atual = inicio; atual <= termino; atual++) {
if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
maisBarato = atual;
}
}
return maisBarato;
}
}
| public class TestaOrdenacao {
public static void main(String[] args) {
Produto produtos[] = {
new Produto("Lamborghini", 1000000),
new Produto("Jipe", 46000),
new Produto("Brasília", 16000),
new Produto("Smart", 46000),
new Produto("Fusca", 17000)
};
for(int atual = 0; atual < produtos.length; atual++) {
int menor = buscaMenor(produtos, atual, produtos.length - 1);
Produto produtoAtual = produtos[atual];
Produto produtoMenor = produtos[menor];
produtos[atual] = produtoMenor;
produtos[menor] = produtoAtual;
}
for(Produto produto : produtos) {
System.out.println(produto.getNome() + " custa " + produto.getPreco());
}
}
private static int buscaMenor(Produto[] produtos, int inicio, int termino) {
int maisBarato = inicio;
for(int atual = inicio; atual <= termino; atual++) {
if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
maisBarato = atual;
}
}
return maisBarato;
}
}
|
Remove console log from NotificationsRoot | import React, { Component, PropTypes } from 'react';
import NotificationSystem from 'react-notification-system';
export class NotificationsRoot extends Component {
static propTypes = {
notifications: PropTypes.array.isRequired,
actions: PropTypes.shape({
shift: PropTypes.func.isRequired,
}),
};
componentDidMount() {
const { addNotification, removeNotification } = this.refs.notificationSystem;
this.addNotification = addNotification;
this.removeNotification = removeNotification;
const { notifications } = this.props;
if (notifications.length) this.shiftNotifications(notifications);
}
componentWillReceiveProps(nextProps) {
const { notifications } = nextProps;
if (notifications.length) this.shiftNotifications(notifications);
}
shiftNotifications = notifications => notifications.forEach(notification => {
this.addNotification(notification);
this.props.actions.shift(notification.uid);
});
render() {
return (
<div>
<NotificationSystem ref="notificationSystem" />
</div>
);
}
}
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { createStructuredActions } from 'helpers/actions';
import { getSubstate } from 'modules/notifications/selectors';
import { shift } from 'modules/notifications/actions';
export default connect(
createStructuredSelector({ notifications: getSubstate }),
createStructuredActions({ shift })
)(NotificationsRoot);
| import React, { Component, PropTypes } from 'react';
import NotificationSystem from 'react-notification-system';
export class NotificationsRoot extends Component {
static propTypes = {
notifications: PropTypes.array.isRequired,
actions: PropTypes.shape({
shift: PropTypes.func.isRequired,
}),
};
componentDidMount() {
const { addNotification, removeNotification } = this.refs.notificationSystem;
this.addNotification = addNotification;
this.removeNotification = removeNotification;
const { notifications } = this.props;
if (notifications.length) this.shiftNotifications(notifications);
}
componentWillReceiveProps(nextProps) {
console.log(nextProps);
const { notifications } = nextProps;
if (notifications.length) this.shiftNotifications(notifications);
}
shiftNotifications = notifications => notifications.forEach(notification => {
this.addNotification(notification);
this.props.actions.shift(notification.uid);
});
render() {
return (
<div>
<NotificationSystem ref="notificationSystem" />
</div>
);
}
}
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { createStructuredActions } from 'helpers/actions';
import { getSubstate } from 'modules/notifications/selectors';
import { shift } from 'modules/notifications/actions';
export default connect(
createStructuredSelector({ notifications: getSubstate }),
createStructuredActions({ shift })
)(NotificationsRoot);
|
Add Link in PDF-Export in Download-Component | <?php
class Kwc_Basic_Download_Pdf extends Kwc_Abstract_Pdf
{
public function writeContent()
{
$fileSizeHelper = new Kwf_View_Helper_FileSize();
$encodeTextHelper = new Kwf_View_Helper_Link();
$vars = $this->_component->getTemplateVars();
if ($vars['icon']) {
$this->_pdf->Image($vars['icon']->getFilename(), $this->_pdf->getX(), $this->_pdf->getY(), 3, 3, 'PNG');
}
$this->_pdf->setX($this->_pdf->getX() + 4);
if ($vars['filesize']) {
$filesize = ' (' . $fileSizeHelper->fileSize($vars['filesize']) . ')';
} else {
$filesize = '';
}
$downloadTagVars = $this->_component->getData()
->getChildComponent('-downloadTag')->getComponent()->getTemplateVars();
$protocol = Kwf_Config::getValue('server.https') ? 'https' : 'http';
$link = $protocol . '://' . $this->_component->getData()->getDomain() . $downloadTagVars['url'];
$this->_pdf->Cell(0, 0, $vars['infotext'].$filesize, '', 1, '', 0, $link);
$this->Ln(1);
}
}
| <?php
class Kwc_Basic_Download_Pdf extends Kwc_Abstract_Pdf
{
public function writeContent()
{
$fileSizeHelper = new Kwf_View_Helper_FileSize();
$encodeTextHelper = new Kwf_View_Helper_MailEncodeText();
$vars = $this->_component->getTemplateVars();
if ($vars['icon']) {
$this->_pdf->Image($vars['icon']->getFilename(), $this->_pdf->getX(), $this->_pdf->getY(), 3, 3, 'PNG');
}
$this->_pdf->setX($this->_pdf->getX() + 4);
if ($vars['filesize']) {
$filesize = ' (' . $fileSizeHelper->fileSize($vars['filesize']) . ')';
} else {
$filesize = '';
}
//Hier keine normale Textbox, da diese einen Link nicht unterstützt
$this->_pdf->Cell(0, 0, $encodeTextHelper->mailEncodeText($vars['infotext'].$filesize), '', 1, '', 0);
$this->Ln(1);
}
}
|
Update ad_append_domain setting for backwards-compatibility with v4 and earlier | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\Models\Setting;
class AddAdAppendDomainSettings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('settings', function (Blueprint $table) {
$table->boolean('ad_append_domain')->nullable(false)->default('0');
});
$s = Setting::first(); // we are deliberately *not* using the ::getSettings() method, as it caches things, and our Settings table is being migrated right now
\Log::info("is ad? ".($s->is_ad)." is enabled? ".($s->ldap_enabled)." ad_domain? ".($s->ad_domain));
if($s->is_ad && $s->ldap_enabled && $s->ad_domain) { //backwards-compatibility setting; < v5 always appended AD Domains
$s->ad_append_domain = 1;
$s->save();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('settings', function (Blueprint $table) {
$table->dropColumn('ad_append_domain');
});
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddAdAppendDomainSettings extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('settings', function (Blueprint $table) {
$table->boolean('ad_append_domain')->nullable(false)->default('0');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('settings', function (Blueprint $table) {
$table->dropColumn('ad_append_domain');
});
}
}
|
Fix crash if form-specific rules were not specified | import random
def generateWord(meaning, form, categories, settings, formrules=None):
'''Takes an English string, desired form, generation
categories, settings, and optional form-specific rules.
Returns a generated word.
'''
word = ""
print(categories)
minS = settings["minS"]
maxS = settings["maxS"]
defaultrule = settings["rule"]
if formrules is not None:
if form in formrules:
rule = formrules[form]
else:
rule = defaultrule
else:
rule = defaultrule
for syllable in range(random.randint(minS, maxS)):
word += generateSyllable(categories, rule)
return {'english': meaning, 'word': word, 'form': form}
def generateSyllable(categories, rule):
'''Takes a category dictionary and a rule. Returns a
generated syllable.
'''
syllable = ""
for place in rule:
if isinstance(place, str):
syllable += random.choice(categories[place])
else:
x = random.choice(place)
if x is not None:
syllable += random.choice(categories[x])
return syllable
| import random
def generateWord(meaning, form, categories, settings, formrules=None):
'''Takes an English string, desired form, generation
categories, settings, and optional form-specific rules.
Returns a generated word.
'''
word = ""
print(categories)
minS = settings["minS"]
maxS = settings["maxS"]
defaultrule = settings["rule"]
if form in formrules:
rule = formrules[form]
else:
rule = defaultrule
print(rule)
for syllable in range(random.randint(minS, maxS)):
word += generateSyllable(categories, rule)
return {'english': meaning, 'word': word, 'form': form}
def generateSyllable(categories, rule):
'''Takes a category dictionary and a rule. Returns a
generated syllable.
'''
syllable = ""
for place in rule:
if isinstance(place, str):
syllable += random.choice(categories[place])
else:
x = random.choice(place)
if x is not None:
syllable += random.choice(categories[x])
return syllable
|
Update logic for reading boolean environment variables | import os
try:
from local_config import *
except ImportError:
twilio_sid = os.environ.get('TWILIO_SID', '')
twilio_token = os.environ.get('TWILIO_TOKEN', '')
twilio_number = os.environ.get('TWILIO_NUMBER', '')
google_client_id = os.environ.get('GOOGLE_CLIENT_ID', '')
google_client_secret = os.environ.get('GOOGLE_CLIENT_SECRET', '')
google_sheet_key = os.environ.get('GOOGLE_SHEET_KEY', '')
website_user = os.environ.get('WEBSITE_USER', '')
website_pass = os.environ.get('WEBSITE_PASS', '')
# We need the following variables to be boolean so we just check for a value against the environment variable
# to mean True and then take absence of either a value or the variable to mean False
demo_mode = bool(os.environ.get('DEMO_MODE', False))
debug_mode = bool(os.environ.get('DEBUG_MODE', False)) | import os
try:
from local_config import *
except ImportError:
twilio_sid = os.environ.get('TWILIO_SID', '')
twilio_token = os.environ.get('TWILIO_TOKEN', '')
twilio_number = os.environ.get('TWILIO_NUMBER', '')
google_client_id = os.environ.get('GOOGLE_CLIENT_ID', '')
google_client_secret = os.environ.get('GOOGLE_CLIENT_SECRET', '')
google_sheet_key = os.environ.get('GOOGLE_SHEET_KEY', '')
website_user = os.environ.get('WEBSITE_USER', '')
website_pass = os.environ.get('WEBSITE_PASS', '')
demo_mode = os.environ.get('DEMO_MODE', '')
debug_mode = os.environ.get('DEBUG_MODE', '') |
Remove trailing commas for IE | var RestoreViewMixin = {
restoreView: function () {
var storage = window.localStorage || {};
if (!this.__initRestore) {
this.on('moveend', function (e) {
if (!this._loaded)
return; // Never access map bounds if view is not set.
var view = {
lat: this.getCenter().lat,
lng: this.getCenter().lng,
zoom: this.getZoom()
};
storage['mapView'] = JSON.stringify(view);
}, this);
this.__initRestore = true;
}
var view = storage['mapView'];
try {
view = JSON.parse(view || '');
this.setView(L.latLng(view.lat, view.lng), view.zoom, true);
return true;
}
catch (err) {
return false;
}
}
};
L.Map.include(RestoreViewMixin);
| var RestoreViewMixin = {
restoreView: function () {
var storage = window.localStorage || {};
if (!this.__initRestore) {
this.on('moveend', function (e) {
if (!this._loaded)
return; // Never access map bounds if view is not set.
var view = {
lat: this.getCenter().lat,
lng: this.getCenter().lng,
zoom: this.getZoom()
};
storage['mapView'] = JSON.stringify(view);
}, this);
this.__initRestore = true;
}
var view = storage['mapView'];
try {
view = JSON.parse(view || '');
this.setView(L.latLng(view.lat, view.lng), view.zoom, true);
return true;
}
catch (err) {
return false;
}
},
};
L.Map.include(RestoreViewMixin);
|
Fix masonry bulk loader in the about page | (function(App) {
'use strict';
App.Controller = App.Controller || {};
App.Controller.About = App.Controller.Page.extend({
index: function() {
new App.View.Anchors({});
new App.View.StaffCategories();
if(this.isScreen_s) {
this.initSliders();
} else {
_.each($('.masonry-layout'), function(element) {
if($(element).find('.masonry-column').length === 0) {
new App.View.Masonry({
el: element
});
}
});
}
},
initSliders: function() {
_.each($('.js_slider'), function(element) {
if($(element).find(".js_slide").length > 0) {
lory(element, {
enableMouseEvents: true
});
}
});
}
});
})(this.App);
| (function(App) {
'use strict';
App.Controller = App.Controller || {};
App.Controller.About = App.Controller.Page.extend({
index: function() {
new App.View.Anchors({});
new App.View.StaffCategories();
if(this.isScreen_s) {
this.initSliders();
} else {
_.each($('.masonry-layout'), function(element) {
if($('.masonry-layout').find('.masonry-column').length === 0) {
new App.View.Masonry({
el: element
});
}
});
}
},
initSliders: function() {
_.each($('.js_slider'), function(element) {
if($(element).find(".js_slide").length > 0) {
lory(element, {
enableMouseEvents: true
});
}
});
}
});
})(this.App);
|
Fix issue in ajax call on page refresh
This closes #25 | /*
---
name: Request
description: Provides a request that allow loading files locally.
license: MIT-style license.
authors:
- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
requires:
- Core/Class
- Core/Class.Extras
- Core/Request
- Class-Extras/Class.Binds
provides:
- Request
...
*/
if (!window.Moobile) window.Moobile = {};
/**
* @see http://moobilejs.com/doc/latest/Request/Request
* @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
* @since 0.1.0
*/
Moobile.Request = new Class({
Extends: Request,
/**
* @see http://moobilejs.com/doc/latest/Request/Request#options
* @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
* @since 0.1.0
*/
options: {
isSuccess: function() {
var status = this.status;
return (status === 0 || (status >= 200 && status <= 304));
}
}
});
| /*
---
name: Request
description: Provides a request that allow loading files locally.
license: MIT-style license.
authors:
- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
requires:
- Core/Class
- Core/Class.Extras
- Core/Request
- Class-Extras/Class.Binds
provides:
- Request
...
*/
if (!window.Moobile) window.Moobile = {};
/**
* @see http://moobilejs.com/doc/latest/Request/Request
* @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
* @since 0.1.0
*/
Moobile.Request = new Class({
Extends: Request,
/**
* @see http://moobilejs.com/doc/latest/Request/Request#options
* @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
* @since 0.1.0
*/
options: {
isSuccess: function() {
var status = this.status;
return (status === 0 || (status >= 200 && status < 300));
}
}
});
|
[Client] Disable reset for the moment | import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
const ActionsButtons = ({ t, saving }) => (
<p>
{/* Bug for the moment */}
{/* <Button bsStyle="danger" onClick={resetForm}>
{t('Annuler')}
</Button>{" "} */}
<Button bsStyle="success" type="submit" disabled={saving}>
{saving &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Enregistrer')}
</Button>
</p>
);
ActionsButtons.propTypes = {
t: PropTypes.func.isRequired,
resetForm: PropTypes.func.isRequired,
saving: PropTypes.bool.isRequired,
};
ActionsButtons.defaultProps = {
saving: false,
};
export default translate()(ActionsButtons);
| import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
const ActionsButtons = ({ t, resetForm, saving }) => (
<p>
<Button bsStyle="danger" onClick={resetForm}>
{t('Annuler')}
</Button>{" "}
<Button bsStyle="success" type="submit" disabled={saving}>
{saving &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Enregistrer')}
</Button>
</p>
);
ActionsButtons.propTypes = {
t: PropTypes.func.isRequired,
resetForm: PropTypes.func.isRequired,
saving: PropTypes.bool.isRequired,
};
ActionsButtons.defaultProps = {
saving: false,
};
export default translate()(ActionsButtons);
|
Move n_days back to 60 so social distancing can be seen in the plots | #!/usr/bin/env python
from datetime import date
from .parameters import Parameters, Regions, RateLos
DEFAULTS = Parameters(
region=Regions(
delaware=564696,
chester=519293,
montgomery=826075,
bucks=628341,
philly=1581000,
),
current_hospitalized=32,
date_first_hospitalized=date(2020,3,7),
doubling_time=4.0,
hospitalized=RateLos(0.025, 7),
icu=RateLos(0.0075, 9),
infectious_days=14,
known_infected=510,
market_share=0.15,
n_days=60,
relative_contact_rate=0.3,
ventilated=RateLos(0.005, 10),
)
| #!/usr/bin/env python
from datetime import date
from .parameters import Parameters, Regions, RateLos
DEFAULTS = Parameters(
region=Regions(
delaware=564696,
chester=519293,
montgomery=826075,
bucks=628341,
philly=1581000,
),
current_hospitalized=32,
date_first_hospitalized=date(2020,3,7),
doubling_time=4.0,
hospitalized=RateLos(0.025, 7),
icu=RateLos(0.0075, 9),
infectious_days=14,
known_infected=510,
market_share=0.15,
n_days=75,
relative_contact_rate=0.3,
ventilated=RateLos(0.005, 10),
)
|
Change commit_begin channel to commit_requested | package com.vsct.dt.haas.admin.nsq.producer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.brainlag.nsq.NSQProducer;
import com.github.brainlag.nsq.exceptions.NSQException;
import java.util.Base64;
import java.util.concurrent.TimeoutException;
public class Producer {
private final NSQProducer producer;
private final ObjectMapper mapper = new ObjectMapper();
public Producer(String host, int port) {
this.producer = new NSQProducer();
this.producer.addAddress(host, port);
}
public void sendCommitBegin(String correlationId, String haproxy, String application, String platform, String conf) throws JsonProcessingException, NSQException, TimeoutException {
String confBase64 = new String(Base64.getEncoder().encode(conf.getBytes()));
CommitBeginPayload payload = new CommitBeginPayload(correlationId, application, platform, confBase64);
producer.produce("commit_requested_" + haproxy, mapper.writeValueAsBytes(payload));
}
public void start(){
this.producer.start();
}
public void stop(){
this.producer.shutdown();
}
}
| package com.vsct.dt.haas.admin.nsq.producer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.brainlag.nsq.NSQProducer;
import com.github.brainlag.nsq.exceptions.NSQException;
import java.util.Base64;
import java.util.concurrent.TimeoutException;
public class Producer {
private final NSQProducer producer;
private final ObjectMapper mapper = new ObjectMapper();
public Producer(String host, int port) {
this.producer = new NSQProducer();
this.producer.addAddress(host, port);
}
public void sendCommitBegin(String correlationId, String haproxy, String application, String platform, String conf) throws JsonProcessingException, NSQException, TimeoutException {
String confBase64 = new String(Base64.getEncoder().encode(conf.getBytes()));
CommitBeginPayload payload = new CommitBeginPayload(correlationId, application, platform, confBase64);
producer.produce("commit_begin_" + haproxy, mapper.writeValueAsBytes(payload));
}
public void start(){
this.producer.start();
}
public void stop(){
this.producer.shutdown();
}
}
|
Rename package "si_prefix" to "si-prefix" | from paver.easy import task, needs, path, sh, cmdopts
from paver.setuputils import setup, install_distutils_tasks, find_package_data
from distutils.extension import Extension
from optparse import make_option
from Cython.Build import cythonize
import version
pyx_files = ['si_prefix/si_prefix.pyx']
ext_modules = [Extension(f[:-4].replace('/', '.'), [f],
extra_compile_args=['-O3'],
include_dirs=['cythrust'])
for f in pyx_files]
ext_modules = cythonize(ext_modules)
setup(name='si-prefix',
version=version.getVersion(),
description='Functions for formatting numbers according to SI standards.',
keywords='si prefix format number precision',
author='Christian Fobel',
url='https://github.com/cfobel/si_prefix',
license='GPL',
packages=['si_prefix'],
package_data=find_package_data('si_prefix', package='si_prefix',
only_in_packages=False),
ext_modules=ext_modules)
@task
@needs('build_ext', 'generate_setup', 'minilib', 'setuptools.command.sdist')
def sdist():
"""Overrides sdist to make sure that our setup.py is generated."""
pass
| from paver.easy import task, needs, path, sh, cmdopts
from paver.setuputils import setup, install_distutils_tasks, find_package_data
from distutils.extension import Extension
from optparse import make_option
from Cython.Build import cythonize
import version
pyx_files = ['si_prefix/si_prefix.pyx']
ext_modules = [Extension(f[:-4].replace('/', '.'), [f],
extra_compile_args=['-O3'],
include_dirs=['cythrust'])
for f in pyx_files]
ext_modules = cythonize(ext_modules)
setup(name='si_prefix',
version=version.getVersion(),
description='Functions for formatting numbers according to SI standards.',
keywords='si prefix format number precision',
author='Christian Fobel',
url='https://github.com/cfobel/si_prefix',
license='GPL',
packages=['si_prefix'],
package_data=find_package_data('si_prefix', package='si_prefix',
only_in_packages=False),
ext_modules=ext_modules)
@task
@needs('build_ext', 'generate_setup', 'minilib', 'setuptools.command.sdist')
def sdist():
"""Overrides sdist to make sure that our setup.py is generated."""
pass
|
Use ε when detecting equirectangular case. | // @import parallel2
function conicEquidistant(φ0, φ1) {
var cosφ0 = Math.cos(φ0),
n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0),
G = cosφ0 / n + φ0;
if (Math.abs(n) < ε) return d3.geo.equirectangular.raw;
function forward(λ, φ) {
var ρ = G - φ;
return [
ρ * Math.sin(n * λ),
G - ρ * Math.cos(n * λ)
];
}
forward.invert = function(x, y) {
var ρ0_y = G - y;
return [
Math.atan2(x, ρ0_y) / n,
G - sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y)
];
};
return forward;
}
(d3.geo.conicEquidistant = function() { return parallel2Projection(conicEquidistant); }).raw = conicEquidistant;
| // @import parallel2
function conicEquidistant(φ0, φ1) {
var cosφ0 = Math.cos(φ0),
n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0),
G = cosφ0 / n + φ0;
if (!n) return d3.geo.equirectangular.raw;
function forward(λ, φ) {
var ρ = G - φ;
return [
ρ * Math.sin(n * λ),
G - ρ * Math.cos(n * λ)
];
}
forward.invert = function(x, y) {
var ρ0_y = G - y;
return [
Math.atan2(x, ρ0_y) / n,
G - sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y)
];
};
return forward;
}
(d3.geo.conicEquidistant = function() { return parallel2Projection(conicEquidistant); }).raw = conicEquidistant;
|
Add logger kafkajs to log lines | const LEVELS = {
NOTHING: 0,
ERROR: 1,
WARN: 2,
INFO: 4,
DEBUG: 5,
}
const createLevel = (label, level, currentLevel, namespace, loggerFunction) => (
message,
extra = {}
) => {
if (level > currentLevel) return
loggerFunction(
namespace,
Object.assign(
{
level: label,
timestamp: new Date().toISOString(),
logger: 'kafkajs',
message,
},
extra
)
)
}
const createLogger = ({ level = LEVELS.INFO, logFunction = null } = {}) => {
const logLevel = parseInt(process.env.LOG_LEVEL, 10) || level
const createLogFunctions = namespace => ({
info: createLevel('INFO', LEVELS.INFO, logLevel, namespace, logFunction),
error: createLevel('ERROR', LEVELS.ERROR, logLevel, namespace, logFunction),
warn: createLevel('WARN', LEVELS.WARN, logLevel, namespace, logFunction),
debug: createLevel('DEBUG', LEVELS.DEBUG, logLevel, namespace, logFunction),
})
return Object.assign(createLogFunctions(), {
namespace: namespace => createLogFunctions(namespace),
})
}
module.exports = {
LEVELS,
createLogger,
}
| const LEVELS = {
NOTHING: 0,
ERROR: 1,
WARN: 2,
INFO: 4,
DEBUG: 5,
}
const createLevel = (label, level, currentLevel, namespace, loggerFunction) => (
message,
extra = {}
) => {
if (level > currentLevel) return
loggerFunction(
namespace,
Object.assign(
{
level: label,
timestamp: new Date().toISOString(),
message,
},
extra
)
)
}
const createLogger = ({ level = LEVELS.INFO, logFunction = null } = {}) => {
const logLevel = parseInt(process.env.LOG_LEVEL, 10) || level
const createLogFunctions = namespace => ({
info: createLevel('INFO', LEVELS.INFO, logLevel, namespace, logFunction),
error: createLevel('ERROR', LEVELS.ERROR, logLevel, namespace, logFunction),
warn: createLevel('WARN', LEVELS.WARN, logLevel, namespace, logFunction),
debug: createLevel('DEBUG', LEVELS.DEBUG, logLevel, namespace, logFunction),
})
return Object.assign(createLogFunctions(), {
namespace: namespace => createLogFunctions(namespace),
})
}
module.exports = {
LEVELS,
createLogger,
}
|
Store error message in $message
Fixes #6 | <?php
namespace Omnipay\Sisow\Message;
use Omnipay\Common\Message\AbstractResponse as BaseAbstractResponse;
use Omnipay\Common\Message\RequestInterface;
abstract class AbstractResponse extends BaseAbstractResponse
{
/**
* @var string
*/
protected $code;
/**
* @var string
*/
protected $message;
/**
* {@inheritdoc}
*/
public function __construct(RequestInterface $request, $data)
{
parent::__construct($request, $data);
if (isset($this->data->error)) {
$this->code = (string) $this->data->error->errorcode;
$this->message = (string) $this->data->error->errormessage;
}
}
/**
* {@inheritdoc}
*/
public function getMessage()
{
if (!$this->isSuccessful()) {
return $this->message;
}
return null;
}
/**
* {@inheritdoc}
*/
public function getCode()
{
if (!$this->isSuccessful()) {
return $this->code;
}
return null;
}
}
| <?php
namespace Omnipay\Sisow\Message;
use Omnipay\Common\Message\AbstractResponse as BaseAbstractResponse;
use Omnipay\Common\Message\RequestInterface;
abstract class AbstractResponse extends BaseAbstractResponse
{
/**
* @var string
*/
protected $code;
/**
* {@inheritdoc}
*/
public function __construct(RequestInterface $request, $data)
{
parent::__construct($request, $data);
if (isset($this->data->error)) {
$this->code = (string) $this->data->error->errorcode;
$this->data = (string) $this->data->error->errormessage;
}
}
/**
* {@inheritdoc}
*/
public function getMessage()
{
if (!$this->isSuccessful()) {
return $this->data;
}
return null;
}
/**
* {@inheritdoc}
*/
public function getCode()
{
if (!$this->isSuccessful()) {
return $this->code;
}
return null;
}
}
|
Revert "Populate services allows to specify the fixture file as an argument"
This reverts commit 0a113d198b883abfbcdd82581036eccce9a6235d. | var storageFactory = require('../../lib/storage/storage-factory');
var populator = require('../../test/lib/util/populator');
var dummyServiceGenerator = require('../../test/fixtures/dummy-services');
var services;
function run(program){
var env = program.env || 'development';
var storage = storageFactory.getStorageInstance(env);
if (!storage) {
console.error('Not available storage for the provided environment ' + env);
return;
}
if (program.real) {
console.log('Populating real services...');
services = require('../../test/fixtures/real-services');
} else {
console.log('Populating real services...');
services = dummyServiceGenerator.generate(program.numberServices || 20);
}
populator.populate(services, storage, function(err){
if (err) {
console.error(err);
} else {
console.log('done! ' + services.length + ' services populated');
}
storage.quit();
});
}
var program = require('commander');
program
.option('-r, --real', 'User real data')
.option('-e, --env [env]', 'Storage environment key')
.option('-s, --number-services [numberServices]', 'Number of services')
.parse(process.argv);
run(program);
| var storageFactory = require('../../lib/storage/storage-factory');
var populator = require('../../test/lib/util/populator');
var dummyServiceGenerator = require('../../test/fixtures/dummy-services');
var services;
function run(program){
var env = program.env || 'development';
var storage = storageFactory.getStorageInstance(env);
if (!storage) {
console.error('Not available storage for the provided environment ' + env);
return;
}
if (program.file) {
console.log('Populating from ' + program.file);
services = require(program.file);
} else if (program.real) {
console.log('Populating real services...');
services = require('../../test/fixtures/real-services');
} else {
console.log('Populating real services...');
services = dummyServiceGenerator.generate(program.numberServices || 20);
}
populator.populate(services, storage, function(err){
if (err) {
console.error(err);
} else {
console.log('done! ' + services.length + ' services populated');
}
storage.quit();
});
}
var program = require('commander');
program
.option('-r, --real', 'User real data')
.option('-f, --file [file]', 'Fixture file')
.option('-e, --env [env]', 'Storage environment key')
.option('-s, --number-services [numberServices]', 'Number of services')
.parse(process.argv);
run(program);
|
Delete sub folders in log directory | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import logging
import os
import shutil
logger = logging.getLogger(__name__)
def create_directory(path):
"""
Creates a directory if it doesn't already exist.
"""
# Check if path is a file_path or a dir_path. Dir path is a string that
# ends with os.sep
if path[-1] != os.sep:
path, file_name = os.path.split(path)
if not os.path.exists(path):
logger.info("Creating directory: %s", path)
os.makedirs(path)
def get_unique_postfix(file_path, extension):
"""Add numeric postfix for file."""
postfix = 0
new_path = file_path + str(postfix) + extension
while os.path.isfile(new_path):
postfix += 1
new_path = file_path + str(postfix) + extension
return new_path
def delete_directory_contents(path):
"""Remove all files and sub-dir in provided path."""
shutil.rmtree(path)
| # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import os
import logging
logger = logging.getLogger(__name__)
def create_directory(path):
"""
Creates a directory if it doesn't already exist.
"""
# Check if path is a file_path or a dir_path. Dir path is a string that
# ends with os.sep
if path[-1] != os.sep:
path, file_name = os.path.split(path)
if not os.path.exists(path):
logger.info("Creating directory: %s", path)
os.makedirs(path)
def get_unique_postfix(file_path, extension):
postfix = 0
new_path = file_path + str(postfix) + extension
while os.path.isfile(new_path):
postfix += 1
new_path = file_path + str(postfix) + extension
return new_path
def delete_directory_contents(path):
for file_name in os.listdir(path):
os.remove(path + os.sep + file_name)
|
Fix doc comment for CommandGroup and add one for the Subcommand constructor | /*
* Optics / subcommand.js
* copyright (c) 2016 Susisu
*/
/**
* @module subcommand
*/
"use strict";
function endModule() {
module.exports = Object.freeze({
Subcommand,
CommandGroup
});
}
const command = require("./command.js");
/**
* The `Subcommand` associates a name with a command.
* @static
*/
class Subcommand {
/**
* Creates a new `Subcommand` instance.
* @param {string} name The name of the subcommand.
* @param {module:command.CommandBase} cmd The command associated to the name.
*/
constructor(name, cmd) {
this.name = name;
this.cmd = cmd;
}
}
/**
* A `CommandGroup` instance represents a group of subcommands.
* @static
* @extends {module:command.CommandBase}
*/
class CommandGroup extends command.CommandBase {
/**
* Creates a new `CommandGroup` instance.
* @param {string} desc The description of the command group.
* @param {module:subcommand.Subcommand[]} subcmds Subcommands the group contains.
* @param {(module:command.CommandBase | null)} defaultCmd Default command, invoked when no subcommand is specified.
*/
constructor(desc, subcmds, defaultCmd) {
super();
this.desc = desc;
this.subcmds = subcmds;
this.defaultCmd = defaultCmd;
}
}
endModule();
| /*
* Optics / subcommand.js
* copyright (c) 2016 Susisu
*/
/**
* @module subcommand
*/
"use strict";
function endModule() {
module.exports = Object.freeze({
Subcommand,
CommandGroup
});
}
const command = require("./command.js");
/**
* The `Subcommand` associates a name with a command.
* @static
*/
class Subcommand {
constructor(name, cmd) {
this.name = name;
this.cmd = cmd;
}
}
/**
* A `CommandGroup` instance represents a group of subcommands.
* @static
* @extends {module:command.CommandBase}
*/
class CommandGroup extends command.CommandBase {
/**
* Creates a new `CommandGroup` instance.
* @param {string} desc The description of the command group.
* @param {module:subcommand.Subcommand[]]} subcmds Subcommands the group contains.
* @param {(module:command.CommandBase | null)} defaultCmd Default command, invoked when no subcommand is specified.
*/
constructor(desc, subcmds, defaultCmd) {
super();
this.desc = desc;
this.subcmds = subcmds;
this.defaultCmd = defaultCmd;
}
}
endModule();
|
Update copyright notice to reference Curator | /**
* Copyright 2013-2014 The Apache Software Foundation (Curator Project)
*
* The Apache Software Foundation licenses this file to you under the Apache
* License, version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.dropwizard.jetty;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
/**
* @see https://github.com/apache/curator/blob/master/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java
*/
public interface LocalIpFilter {
public boolean use(NetworkInterface networkInterface,
InetAddress address) throws SocketException;
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.dropwizard.jetty;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
/**
* @see https://github.com/apache/curator/blob/master/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java
*/
public interface LocalIpFilter {
public boolean use(NetworkInterface networkInterface,
InetAddress address) throws SocketException;
} |
Fix provider_location column add for PSQL
Migration 006 (commit 690cae58e6bbac5758ea2f7b60774c797d28fba5)
didn't work properly for postgres,
this patch corrects the upgrade by ensuring the execute
is performed and the value is initialized to None.
Since we haven't released a milestone etc with this migration in the
code it should be safe to just fix it here and submit.
Change-Id: I10a09aed3470c35c8ebbe22f29aa511592167c35 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import Column
from sqlalchemy import MetaData, String, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
snapshots = Table('snapshots', meta, autoload=True)
provider_location = Column('provider_location', String(255))
snapshots.create_column(provider_location)
snapshots.update().values(provider_location=None).execute()
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
snapshots = Table('snapshots', meta, autoload=True)
provider_location = snapshots.columns.provider_location
snapshots.drop_column(provider_location)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from sqlalchemy import Column
from sqlalchemy import MetaData, String, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
snapshots = Table('snapshots', meta, autoload=True)
provider_location = Column('provider_location', String(255))
snapshots.create_column(provider_location)
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
snapshots = Table('snapshots', meta, autoload=True)
provider_location = snapshots.columns.provider_location
provider_location.drop()
|
Simplify isStatic and isDynamic logic, and make sure they return boolean values | var AudioletParameter = new Class({
initialize: function(node, inputIndex, value) {
this.node = node;
if (typeof inputIndex != 'undefined' && inputIndex != null) {
this.input = node.inputs[inputIndex];
}
else {
this.input = null;
}
this.value = value || 0;
},
isStatic: function() {
var input = this.input;
return (input == null ||
input.connectedFrom.length == 0 ||
input.buffer.isEmpty);
},
isDynamic: function() {
var input = this.input;
return (input != null &&
input.connectedFrom.length > 0 &&
!input.buffer.isEmpty);
},
setValue: function(value) {
this.value = value;
},
getValue: function() {
return this.value;
},
getChannel: function() {
return this.input.buffer.channels[0];
}
});
| var AudioletParameter = new Class({
initialize: function(node, inputIndex, value) {
this.node = node;
if (typeof inputIndex != 'undefined' && inputIndex != null) {
this.input = node.inputs[inputIndex];
}
else {
this.input = null;
}
this.value = value || 0;
},
isStatic: function() {
var input = this.input;
return (!(input &&
input.connectedFrom.length &&
!(input.buffer.isEmpty)));
},
isDynamic: function() {
var input = this.input;
return (input && input.connectedFrom.length && !(input.buffer.isEmpty));
},
setValue: function(value) {
this.value = value;
},
getValue: function() {
return this.value;
},
getChannel: function() {
return this.input.buffer.channels[0];
}
});
|
Fix vertical alignment of edit avatar screen | /* @flow */
import React from 'react'
import {Avatar, Box, Text, Button} from '../common-adapters'
import {globalStyles, globalMargins} from '../styles'
import {noAvatarMessage, hasAvatarMessage} from './edit-avatar.shared'
import type {Props} from './edit-avatar'
const Render = ({keybaseUsername, hasAvatar, onAck}: Props) => {
const text = !hasAvatar ? noAvatarMessage : hasAvatarMessage
return (
<Box style={{...globalStyles.flexBoxColumn, flex: 1, alignItems: 'center', justifyContent: 'center', padding: globalMargins.large}}>
<Avatar size={176} username={keybaseUsername} />
<Text type='Body' style={{marginTop: globalMargins.medium, textAlign: 'center'}}>{text}</Text>
<Button type='Primary' onClick={onAck} label='Got it!' style={{marginTop: globalMargins.medium}} />
</Box>
)
}
export default Render
| /* @flow */
import React from 'react'
import {Avatar, Box, Text, Button} from '../common-adapters'
import {globalStyles, globalMargins} from '../styles'
import {noAvatarMessage, hasAvatarMessage} from './edit-avatar.shared'
import type {Props} from './edit-avatar'
const Render = ({keybaseUsername, hasAvatar, onAck}: Props) => {
const text = !hasAvatar ? noAvatarMessage : hasAvatarMessage
return (
<Box style={{...globalStyles.flexBoxColumn, flex: 1}}>
<Box style={{...globalStyles.flexBoxColumn, alignItems: 'center', padding: globalMargins.large}}>
<Avatar size={176} username={keybaseUsername} />
<Text type='Body' style={{marginTop: globalMargins.medium, textAlign: 'center'}}>{text}</Text>
<Button type='Primary' onClick={onAck} label='Got it!' style={{marginTop: globalMargins.medium}} />
</Box>
</Box>
)
}
export default Render
|
Add test for unknown command
Signed-off-by: David Gageot <aa743a0aaec8f7d7a1f01442503957f4d7a2d634@gageot.net> | /*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"bytes"
"io/ioutil"
"os"
"testing"
"github.com/GoogleContainerTools/skaffold/testutil"
)
func TestMainHelp(t *testing.T) {
var (
output bytes.Buffer
errOutput bytes.Buffer
)
defer func(args []string) { os.Args = args }(os.Args)
os.Args = []string{"skaffold", "help"}
err := Run(&output, &errOutput)
testutil.CheckError(t, false, err)
testutil.CheckContains(t, "Available Commands", output.String())
testutil.CheckDeepEqual(t, "", errOutput.String())
}
func TestMainUnknownCommand(t *testing.T) {
defer func(args []string) { os.Args = args }(os.Args)
os.Args = []string{"skaffold", "unknown"}
err := Run(ioutil.Discard, ioutil.Discard)
testutil.CheckError(t, true, err)
}
| /*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package app
import (
"bytes"
"os"
"testing"
"github.com/GoogleContainerTools/skaffold/testutil"
)
func TestMain(t *testing.T) {
var (
output bytes.Buffer
errOutput bytes.Buffer
)
defer func(args []string) { os.Args = args }(os.Args)
os.Args = []string{"skaffold", "help"}
err := Run(&output, &errOutput)
testutil.CheckError(t, false, err)
testutil.CheckContains(t, "Available Commands", output.String())
testutil.CheckDeepEqual(t, "", errOutput.String())
}
|
Change delivery of communication to manual digital by default | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import api, models, fields
import logging
logger = logging.getLogger(__name__)
class ResPartner(models.Model):
""" Add a field for communication preference. """
_inherit = 'res.partner'
##########################################################################
# FIELDS #
##########################################################################
global_communication_delivery_preference = fields.Selection(
selection='_get_delivery_preference',
default='digital',
required=True,
help='Delivery preference for Global Communication')
@api.model
def _get_delivery_preference(self):
return self.env[
'partner.communication.config'].get_delivery_preferences()
| # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import api, models, fields
import logging
logger = logging.getLogger(__name__)
class ResPartner(models.Model):
""" Add a field for communication preference. """
_inherit = 'res.partner'
##########################################################################
# FIELDS #
##########################################################################
global_communication_delivery_preference = fields.Selection(
selection='_get_delivery_preference',
default='auto_digital',
required=True,
help='Delivery preference for Global Communication')
@api.model
def _get_delivery_preference(self):
return self.env[
'partner.communication.config'].get_delivery_preferences()
|
[marv] Support webapi extension via entry points | # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from __future__ import absolute_import, division, print_function
from pkg_resources import iter_entry_points
from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delete
from .tag import tag
from .collection import collection, meta
from .tooling import api_group as marv_api_group
@marv_api_group()
def webapi(app):
pass
# Groups and endpoints are all the same for now
webapi.add_endpoint(auth)
webapi.add_endpoint(comment)
webapi.add_endpoint(dataset)
webapi.add_endpoint(delete)
webapi.add_endpoint(collection)
webapi.add_endpoint(meta)
webapi.add_endpoint(tag)
from marv_robotics.webapi import robotics
webapi.add_endpoint(robotics)
for ep in iter_entry_points(group='marv_webapi'):
endpoint = ep.load()
webapi.add_endpoint(endpoint)
| # -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018 Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only
from __future__ import absolute_import, division, print_function
from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delete
from .tag import tag
from .collection import collection, meta
from .tooling import api_group as marv_api_group
@marv_api_group()
def webapi(app):
pass
# Groups and endpoints are all the same for now
webapi.add_endpoint(auth)
webapi.add_endpoint(comment)
webapi.add_endpoint(dataset)
webapi.add_endpoint(delete)
webapi.add_endpoint(collection)
webapi.add_endpoint(meta)
webapi.add_endpoint(tag)
from marv_robotics.webapi import robotics
webapi.add_endpoint(robotics)
|
Add "nodeResource" to base Provisioning plugin | package org.ligoj.app.plugin.prov;
import java.util.Map;
import org.ligoj.app.api.SubscriptionStatusWithData;
import org.ligoj.app.resource.node.NodeResource;
import org.ligoj.app.resource.plugin.AbstractToolPluginResource;
import org.springframework.beans.factory.annotation.Autowired;
/**
* The base class for provisioning tool. There is complete quote configuration along the subscription.
*/
public abstract class AbstractProvResource extends AbstractToolPluginResource implements ProvisioningService {
@Autowired
protected ProvResource provResource;
@Autowired
protected NodeResource nodeResource;
@Override
public SubscriptionStatusWithData checkSubscriptionStatus(final int subscription, final String node,
final Map<String, String> parameters) {
final SubscriptionStatusWithData status = new SubscriptionStatusWithData();
// Complete the tool status with the generic quote data
status.put("quote", provResource.getSusbcriptionStatus(subscription));
return status;
}
}
| package org.ligoj.app.plugin.prov;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.ligoj.app.api.SubscriptionStatusWithData;
import org.ligoj.app.model.Node;
import org.ligoj.app.plugin.prov.model.ProvInstancePrice;
import org.ligoj.app.plugin.prov.model.ProvInstancePriceTerm;
import org.ligoj.app.plugin.prov.model.ProvInstanceType;
import org.ligoj.app.plugin.prov.model.ProvStorageType;
import org.ligoj.app.resource.plugin.AbstractToolPluginResource;
import org.springframework.beans.factory.annotation.Autowired;
/**
* The base class for provisioning tool. There is complete quote configuration
* along the subscription.
*/
public abstract class AbstractProvResource extends AbstractToolPluginResource implements ProvisioningService {
@Autowired
protected ProvResource provResource;
@Override
public SubscriptionStatusWithData checkSubscriptionStatus(final int subscription, final String node,
final Map<String, String> parameters) throws Exception {
final SubscriptionStatusWithData status = super.checkSubscriptionStatus(subscription, node, parameters);
// Complete the tool status with the generic quote data
status.put("quote", provResource.getSusbcriptionStatus(subscription));
return status;
}
@Override
public List<Class<?>> getInstalledEntities() {
return Arrays.asList(Node.class, ProvInstancePriceTerm.class, ProvInstanceType.class, ProvInstancePrice.class,
ProvStorageType.class);
}
}
|
Send response on proxy timeout | 'use strict'; // jshint node: true, browser: false, esnext: true
var proxy = require('http-proxy').createProxyServer({});
var express = require('express');
var app = express();
// Configure options
app.use(require('morgan')('dev'));
// Configure routes
app.use('/printsmart/app', express.static(__dirname + '/app'));
app.all('/api/*', function(req, res) { proxy.web(req, res, { target: 'https://api.cbd.int:443', secure: false } ); } );
app.get('/printsmart*', function(req, res) { res.sendFile(__dirname + '/app/template.html', {maxAge:300000}); });
app.all('/*', function(req, res) { res.status(404).send(); });
// START HTTP SERVER
app.listen(process.env.PORT || 2000, '0.0.0.0', function () {
console.log('Server listening on %j', this.address());
});
// Handle proxy errors ignore
proxy.on('error', function (e,req, res) {
console.error('proxy error:', e);
res.status(502).send();
});
process.on('SIGTERM', ()=>process.exit());
| 'use strict'; // jshint node: true, browser: false, esnext: true
var proxy = require('http-proxy').createProxyServer({});
var express = require('express');
var app = express();
// Configure options
app.use(require('morgan')('dev'));
// Configure routes
app.use('/printsmart/app', express.static(__dirname + '/app'));
app.all('/api/*', function(req, res) { proxy.web(req, res, { target: 'https://api.cbd.int:443', secure: false } ); } );
app.get('/printsmart*', function(req, res) { res.sendFile(__dirname + '/app/template.html', {maxAge:300000}); });
app.all('/*', function(req, res) { res.status(404).send(); });
// LOG PROXY ERROR & RETURN http:500
proxy.on('error', function (e) {
console.error('proxy error:', e);
});
// START HTTP SERVER
app.listen(process.env.PORT || 2000, '0.0.0.0', function () {
console.log('Server listening on %j', this.address());
});
process.on('SIGTERM', ()=>process.exit());
|
Make Organization Number a unique field | from datetime import datetime
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10, unique=True)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
registration_date = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.registration_date = bisnode_date_to_date(
company_data['dateReg'])
self.save()
| from datetime import datetime
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date()
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
null=True, blank=True)
date_of_rating = models.DateField(blank=True, null=True)
registration_date = models.DateField(blank=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
def get(self):
rating_report = get_bisnode_company_report(
report_type=COMPANY_RATING_REPORT,
organization_number=self.organization_number)
company_data = rating_report.generalCompanyData[0]
self.rating = company_data['ratingCode']
self.date_of_rating = bisnode_date_to_date(
company_data['dateOfRating'])
self.registration_date = bisnode_date_to_date(
company_data['dateReg'])
self.save()
|
Change the name of the method for getting lower case values. | package uk.ac.ebi.quickgo.webservice.definitions;
import java.util.HashMap;
import java.util.Map;
/**
* @Author Tony Wardell
* Date: 22/06/2015
* Time: 09:01
* Created with IntelliJ IDEA.
*/
public enum FilterParameter {
Exact("exact"),
Ancestor("ancestor"),
Slim("slim"),
I("i"),
IPO("ipo"),
IPOR("ipor");
private String lc;
private static Map<String,FilterParameter> map = new HashMap<>();
static {
for(FilterParameter aParm:FilterParameter.values()){
map.put(aParm.toLowerCase(),aParm);
}
}
FilterParameter(String lowerCase) {
this.lc = lowerCase;
}
public String toLowerCase() {
return lc;
}
public static FilterParameter lookup(String value){
return map.get(value);
}
}
| package uk.ac.ebi.quickgo.webservice.definitions;
import java.util.HashMap;
import java.util.Map;
/**
* @Author Tony Wardell
* Date: 22/06/2015
* Time: 09:01
* Created with IntelliJ IDEA.
*/
public enum FilterParameter {
Exact("exact"),
Ancestor("ancestor"),
Slim("slim"),
I("i"),
IPO("ipo"),
IPOR("ipor");
private String lc;
private static Map<String,FilterParameter> map = new HashMap<>();
static {
for(FilterParameter aParm:FilterParameter.values()){
map.put(aParm.getLowerCase(),aParm);
}
}
FilterParameter(String lowerCase) {
this.lc = lowerCase;
}
public String getLowerCase() {
return lc;
}
public static FilterParameter lookup(String value){
return map.get(value);
}
}
|
Add quotes to order by | from braces.views import CsrfExemptMixin
from django.core.mail import send_mail
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from clowder_server.models import Ping
class APIView(CsrfExemptMixin, View):
def post(self, request):
name = request.POST.get('name')
value = request.POST.get('value')
status = int(request.POST.get('status', 1))
if status == -1:
send_mail('Subject here', 'Here is the message.', 'admin@clowder.io',
['keith@parkme.com'], fail_silently=False)
Ping.objects.create(
name=name,
value=value,
)
return HttpResponse('ok')
class DashboardView(TemplateView):
template_name = "dashboard.html"
def get_context_data(self, **context):
context['pings'] = Ping.objects.all().order_by('name')
return context
| from braces.views import CsrfExemptMixin
from django.core.mail import send_mail
from django.http import HttpResponse
from django.views.generic import TemplateView, View
from clowder_server.models import Ping
class APIView(CsrfExemptMixin, View):
def post(self, request):
name = request.POST.get('name')
value = request.POST.get('value')
status = int(request.POST.get('status', 1))
if status == -1:
send_mail('Subject here', 'Here is the message.', 'admin@clowder.io',
['keith@parkme.com'], fail_silently=False)
Ping.objects.create(
name=name,
value=value,
)
return HttpResponse('ok')
class DashboardView(TemplateView):
template_name = "dashboard.html"
def get_context_data(self, **context):
context['pings'] = Ping.objects.all().order_by(name)
return context
|
Move toString conversions to only happen once. | let input = require("fs").readFileSync("./data").toString();
let santaPosition = [0, 0];
let roboSantaPosition = [0, 0];
let uniqueSantaPositions = [];
function updateUniquePositions() {
let santaPositionStr = santaPosition.toString();
let roboSantaPositionStr = roboSantaPosition.toString();
if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) {
uniqueSantaPositions.push(santaPositionStr);
}
if (uniqueSantaPositions.indexOf(roboSantaPositionStr) === -1) {
uniqueSantaPositions.push(roboSantaPositionStr);
}
}
updateUniquePositions();
input.split("").forEach((char, index) => {
let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2
if (char === "^") {
currentSantaPos[1]++;
} else if (char === "v") {
currentSantaPos[1]--;
} else if (char === ">") {
currentSantaPos[0]++;
} else if (char === "<") {
currentSantaPos[0]--;
}
updateUniquePositions();
});
console.log("Houses with at least one present:", uniqueSantaPositions.length);
| let input = require("fs").readFileSync("./data").toString();
let santaPosition = [0, 0];
let roboSantaPosition = [0, 0];
let uniqueSantaPositions = [];
function updateUniquePositions() {
if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) {
uniqueSantaPositions.push(santaPosition.toString());
}
if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) {
uniqueSantaPositions.push(roboSantaPosition.toString());
}
}
updateUniquePositions();
input.split("").forEach((char, index) => {
let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2
if (char === "^") {
currentSantaPos[1]++;
} else if (char === "v") {
currentSantaPos[1]--;
} else if (char === ">") {
currentSantaPos[0]++;
} else if (char === "<") {
currentSantaPos[0]--;
}
updateUniquePositions();
});
console.log("Houses with at least one present:", uniqueSantaPositions.length);
|
Fix issue mixing %s and format for ValueError in AES | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
class AES(object):
name = "AES"
block_size = 128
key_sizes = set([128, 192, 256])
def __init__(self, key):
super(AES, self).__init__()
self.key = key
# Verify that the key size matches the expected key size
if self.key_size not in self.key_sizes:
raise ValueError("Invalid key size ({0}) for {1}".format(
self.key_size, self.name
))
@property
def key_size(self):
return len(self.key) * 8
| # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
class AES(object):
name = "AES"
block_size = 128
key_sizes = set([128, 192, 256])
def __init__(self, key):
super(AES, self).__init__()
self.key = key
# Verify that the key size matches the expected key size
if self.key_size not in self.key_sizes:
raise ValueError("Invalid key size (%s) for %s".format(
self.key_size, self.name
))
@property
def key_size(self):
return len(self.key) * 8
|
Disable jscs check for camel case property name | import Ember from 'ember';
import layout from '../templates/components/md-btn-dropdown';
import MaterializeButton from './md-btn';
const { run: { scheduleOnce }, computed } = Ember;
export default MaterializeButton.extend({
layout,
tagName: 'a',
classNames: ['dropdown-button'],
icon: 'mdi-navigation-expand-more',
iconPosition: 'right',
attributeBindings: [
'inDuration', 'outDuration', 'constrainWidth', 'hover', 'gutter', 'belowOrigin'
],
didInsertElement() {
this._super(...arguments);
scheduleOnce('afterRender', this, this._setupDropdown);
},
_setupDropdown() {
// needed until the Materialize.dropdown plugin is replaced
this.$().attr('data-activates', this.get('_dropdownContentId'));
this.$().dropdown({
hover: !!this.getWithDefault('hover', false),
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
constrain_width: !!this.getWithDefault('constrainWidth', true),
inDuration: this.getWithDefault('inDuration', this.get('_mdSettings.dropdownInDuration')),
outDuration: this.getWithDefault('outDuration', this.get('_mdSettings.dropdownOutDuration')),
gutter: this.getWithDefault('gutter', 0),
belowOrigin: !!this.getWithDefault('belowOrigin', false)
});
},
_dropdownContentId: computed(function() {
return `${this.get('elementId')}-dropdown-content`;
})
});
| import Ember from 'ember';
import layout from '../templates/components/md-btn-dropdown';
import MaterializeButton from './md-btn';
const { run: { scheduleOnce }, computed } = Ember;
export default MaterializeButton.extend({
layout,
tagName: 'a',
classNames: ['dropdown-button'],
icon: 'mdi-navigation-expand-more',
iconPosition: 'right',
attributeBindings: [
'inDuration', 'outDuration', 'constrainWidth', 'hover', 'gutter', 'belowOrigin'
],
didInsertElement() {
this._super(...arguments);
scheduleOnce('afterRender', this, this._setupDropdown);
},
_setupDropdown() {
// needed until the Materialize.dropdown plugin is replaced
this.$().attr('data-activates', this.get('_dropdownContentId'));
this.$().dropdown({
hover: !!this.getWithDefault('hover', false),
constrain_width: !!this.getWithDefault('constrainWidth', true),
inDuration: this.getWithDefault('inDuration', this.get('_mdSettings.dropdownInDuration')),
outDuration: this.getWithDefault('outDuration', this.get('_mdSettings.dropdownOutDuration')),
gutter: this.getWithDefault('gutter', 0),
belowOrigin: !!this.getWithDefault('belowOrigin', false)
});
},
_dropdownContentId: computed(function() {
return `${this.get('elementId')}-dropdown-content`;
})
});
|
Use argparse for main python entrypoint args.
Will make it easier to add proto_langdir as a flag argument in a future commit. | import metasentence
import language_model
import standard_kaldi
import diff_align
import json
import os
import sys
vocab = metasentence.load_vocabulary('PROTO_LANGDIR/graphdir/words.txt')
def lm_transcribe(audio_f, text_f):
ms = metasentence.MetaSentence(open(text_f).read(), vocab)
model_dir = language_model.getLanguageModel(ms.get_kaldi_sequence())
print 'generated model', model_dir
k = standard_kaldi.Kaldi(os.path.join(model_dir, 'graphdir', 'HCLG.fst'))
trans = standard_kaldi.transcribe(k, audio_f)
ret = diff_align.align(trans["words"], ms)
return ret
if __name__=='__main__':
import argparse
parser = argparse.ArgumentParser(
description='Align a transcript to audio by generating a new language model.')
parser.add_argument('audio_file', help='input audio file in any format supported by FFMPEG')
parser.add_argument('text_file', help='input transcript as plain text')
parser.add_argument('output_file', type=argparse.FileType('w'),
help='output json file for aligned transcript')
parser.add_argument('--proto_langdir', default="PROTO_LANGDIR",
help='path to the prototype language directory')
args = parser.parse_args()
ret = lm_transcribe(args.audio_file, args.text_file)
json.dump(ret, args.output_file, indent=2)
| import metasentence
import language_model
import standard_kaldi
import diff_align
import json
import os
import sys
vocab = metasentence.load_vocabulary('PROTO_LANGDIR/graphdir/words.txt')
def lm_transcribe(audio_f, text_f):
ms = metasentence.MetaSentence(open(text_f).read(), vocab)
model_dir = language_model.getLanguageModel(ms.get_kaldi_sequence())
print 'generated model', model_dir
k = standard_kaldi.Kaldi(os.path.join(model_dir, 'graphdir', 'HCLG.fst'))
trans = standard_kaldi.transcribe(k, audio_f)
ret = diff_align.align(trans["words"], ms)
return ret
if __name__=='__main__':
AUDIO_FILE = sys.argv[1]
TEXT_FILE = sys.argv[2]
OUTPUT_FILE = sys.argv[3]
ret = lm_transcribe(AUDIO_FILE, TEXT_FILE)
json.dump(ret, open(OUTPUT_FILE, 'w'), indent=2)
|
Fix database errors not displaying | module.exports = function (req, res) {
var keystone = req.keystone;
if (!keystone.security.csrf.validate(req)) {
return res.apiError(403, 'invalid csrf');
}
req.list.model.findById(req.params.id, function (err, item) {
if (err) return res.status(500).json({ err: 'database error', detail: err });
if (!item) return res.status(404).json({ err: 'not found', id: req.params.id });
req.list.validateInput(item, req.body, function (err) {
if (err) return res.status(400).json(err);
req.list.updateItem(item, req.body, { files: req.files }, function (err) {
if (err) return res.apiError(500, err.detail);
res.json(req.list.getData(item));
});
});
});
};
| module.exports = function (req, res) {
var keystone = req.keystone;
if (!keystone.security.csrf.validate(req)) {
return res.apiError(403, 'invalid csrf');
}
req.list.model.findById(req.params.id, function (err, item) {
if (err) return res.status(500).json({ err: 'database error', detail: err });
if (!item) return res.status(404).json({ err: 'not found', id: req.params.id });
req.list.validateInput(item, req.body, function (err) {
if (err) return res.status(400).json(err);
req.list.updateItem(item, req.body, { files: req.files }, function (err) {
if (err) return res.status(500).json(err);
res.json(req.list.getData(item));
});
});
});
};
|
Fix use statement for SequentialCommandBus | <?php
namespace LiteCQRS\Plugin\SymfonyBundle;
use LiteCQRS\Bus\SequentialCommandBus;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContainerCommandBus extends SequentialCommandBus
{
private $container;
private $commandServices;
public function __construct(ContainerInterface $container, array $proxyFactories = array())
{
parent::__construct($proxyFactories);
$this->container = $container;
}
public function registerServices($commandServices)
{
$this->commandServices = $commandServices;
}
protected function getService($commandType)
{
if (!isset($this->commandServices[$commandType])) {
throw new \RuntimeException("No command handler exists for command '" . $commandType . "'");
}
$serviceId = $this->commandServices[$commandType];
if (!$this->container->has($serviceId)) {
throw new \RuntimeException("Symfony Service Container has no service '".$serviceId."' that is registered for command '". $commandType . "'");
}
return $this->container->get($serviceId);
}
}
| <?php
namespace LiteCQRS\Plugin\SymfonyBundle;
use LiteCQRS\Bus\CommandBus;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContainerCommandBus extends SequentialCommandBus
{
private $container;
private $commandServices;
public function __construct(ContainerInterface $container, array $proxyFactories = array())
{
parent::__construct($proxyFactories);
$this->container = $container;
}
public function registerServices($commandServices)
{
$this->commandServices = $commandServices;
}
protected function getService($commandType)
{
if (!isset($this->commandServices[$commandType])) {
throw new \RuntimeException("No command handler exists for command '" . $commandType . "'");
}
$serviceId = $this->commandServices[$commandType];
if (!$this->container->has($serviceId)) {
throw new \RuntimeException("Symfony Service Container has no service '".$serviceId."' that is registered for command '". $commandType . "'");
}
return $this->container->get($serviceId);
}
}
|
Use generic types in Filemanager | package com.max.soundboard;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
class FileManager {
private FileManager() {
}
public static List<String> getSubdirectories(String path) {
List<String> subdirectories = new ArrayList<>();
for (File file : new File(path).listFiles()) {
if (file.isDirectory()) {
subdirectories.add(file.getName());
}
}
return subdirectories;
}
public static List<String> getSoundFileNames(String path) {
List<String> soundFiles = new ArrayList<>();
for (File file : new File(path).listFiles()) {
if (file.isFile() && isSoundFileName(file.getName())) {
soundFiles.add(file.getName());
}
}
return soundFiles;
}
private static boolean isSoundFileName(String filename) {
return filename.endsWith(".mp3") || filename.endsWith(".wav");
}
}
| package com.max.soundboard;
import java.io.File;
import java.util.ArrayList;
class FileManager {
private FileManager() {}
public static ArrayList<String> getSubdirectories(String path) {
ArrayList<String> subdirectories = new ArrayList<>();
File[] files = new File(path).listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
subdirectories.add(file.getName());
}
}
}
return subdirectories;
}
public static ArrayList<String> getSoundFileNames(String path) {
ArrayList<String> soundFiles = new ArrayList<>();
for (File file : new File(path).listFiles()) {
if (file.isFile() && isSoundFileName(file.getName())) {
soundFiles.add(file.getName());
}
}
return soundFiles;
}
private static boolean isSoundFileName(String filename) {
return filename.endsWith(".mp3") || filename.endsWith(".wav");
}
}
|
Fix plural name for Categories model. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Event(models.Model):
name = models.CharField(max_length=200)
location = models.CharField(max_length=300)
event_date = models.DateTimeField('event date')
description = models.TextField()
def __str__(self):
return self.name
def is_future(self):
return self.event_date > timezone.now()
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
posted = models.DateField(db_index=True, auto_now_add=True)
category = models.ForeignKey('Category')
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
class Meta:
verbose_name_plural = 'Categories'
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
# Create your models here.
class Event(models.Model):
name = models.CharField(max_length=200)
location = models.CharField(max_length=300)
event_date = models.DateTimeField('event date')
description = models.TextField()
def __str__(self):
return self.name
def is_future(self):
return self.event_date > timezone.now()
class Post(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
posted = models.DateField(db_index=True, auto_now_add=True)
category = models.ForeignKey('Category')
class Category(models.Model):
title = models.CharField(max_length=100, db_index=True)
slug = models.SlugField(max_length=100, db_index=True)
|
FE: Add ARIA role and state on field-help | (function () {
'use strict';
moj.Modules.FieldHelp = {
moreInfos: [],
init: function() {
this.cacheEls();
this.bindEvents();
this.addMoreInfoLink();
},
bindEvents: function() {
this.moreInfos.parent()
.on('click', 'a', this.handleToggle);
},
handleToggle: function(evt) {
var $fieldHelp = $(evt.target).parent();
$fieldHelp
.toggleClass('s-expanded')
.find('.field-more-info')
.attr('aria-expanded', function() {
return $(this).attr('aria-expanded') === 'false';
});
},
addMoreInfoLink: function() {
$.each(this.moreInfos, function(i, el) {
$(this).attr('aria-expanded', 'false');
$('<a class="field-more-info-toggle" role="button">more info</a>')
.insertBefore($(el));
});
},
cacheEls: function() {
this.moreInfos = $('.field-more-info');
}
};
}());
| (function () {
'use strict';
moj.Modules.FieldHelp = {
moreInfos: [],
init: function() {
this.cacheEls();
this.bindEvents();
this.addMoreInfoLink();
},
bindEvents: function() {
this.moreInfos.parent()
.on('click', 'a', this.handleToggle);
},
handleToggle: function(evt) {
$(evt.target).parent().toggleClass('s-expanded');
},
addMoreInfoLink: function() {
$.each(this.moreInfos, function(i, el) {
$('<a class="field-more-info-toggle">more info</a>').insertBefore($(el));
});
},
cacheEls: function() {
this.moreInfos = $('.field-more-info');
}
};
}());
|
Handle errors in queue processing | #!/usr/bin/env python
import pika
import subprocess
import json
import os
from pymongo import MongoClient
dbcon = MongoClient()
NETSNIFF_UTIL = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tools', 'netsniff.js')
queuecon = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = queuecon.channel()
channel.exchange_declare(exchange='perfmonitor', type='direct')
result = channel.queue_declare('perf')
queue_name = result.method.queue
channel.queue_bind(exchange='perfmonitor', queue=queue_name, routing_key='perftest')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
content = json.loads(body)
print ' [x] Executing command phantomjs', content['url']
harcontent = subprocess.check_output(['phantomjs', NETSNIFF_UTIL, content['url']])
try:
jscontent = json.loads(harcontent)
jscontent['site'] = content['site']
dbcon.perfmonitor.har.insert(jscontent)
except:
print ' [x] Unable to parse JSON, ignoring request'
ch.basic_ack(delivery_tag = method.delivery_tag)
print " [x] Done"
channel.basic_consume(callback,
queue=queue_name)
channel.start_consuming()
| #!/usr/bin/env python
import pika
import subprocess
import json
import os
from pymongo import MongoClient
dbcon = MongoClient()
NETSNIFF_UTIL = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tools', 'netsniff.js')
queuecon = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = queuecon.channel()
channel.exchange_declare(exchange='perfmonitor', type='direct')
result = channel.queue_declare('perf')
queue_name = result.method.queue
channel.queue_bind(exchange='perfmonitor', queue=queue_name, routing_key='perftest')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
content = json.loads(body)
print ' [x] Executing command phantomjs', content['url']
harcontent = subprocess.check_output(['phantomjs', NETSNIFF_UTIL, content['url']])
jscontent = json.loads(harcontent)
jscontent['site'] = content['site']
dbcon.perfmonitor.har.insert(jscontent)
ch.basic_ack(delivery_tag = method.delivery_tag)
print " [x] Done"
channel.basic_consume(callback,
queue=queue_name)
channel.start_consuming()
|
Use new error handling middleware for API | <?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Server;
use Zend\Stratigility\MiddlewarePipe;
// Instantiate the application, register providers etc.
$app = require __DIR__.'/system/bootstrap.php';
// Set up everything we need for the API
$app->instance('type', 'api');
$app->register('Flarum\Api\ApiServiceProvider');
$app->register('Flarum\Support\Extensions\ExtensionsServiceProvider');
// Build a middleware pipeline for the API
$api = new MiddlewarePipe();
$api->pipe($app->make('Flarum\Api\Middleware\ReadJsonParameters'));
$api->pipe($app->make('Flarum\Api\Middleware\LoginWithHeader'));
$api->pipe('/api', $app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.api.routes')]));
$api->pipe(new \Flarum\Api\Middleware\JsonApiErrors());
$server = Server::createServer(
$api,
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$server->listen();
| <?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Server;
use Zend\Stratigility\MiddlewarePipe;
// Instantiate the application, register providers etc.
$app = require __DIR__.'/system/bootstrap.php';
// Set up everything we need for the API
$app->instance('type', 'api');
$app->register('Flarum\Api\ApiServiceProvider');
$app->register('Flarum\Support\Extensions\ExtensionsServiceProvider');
// Build a middleware pipeline for the API
$api = new MiddlewarePipe();
$api->pipe($app->make('Flarum\Api\Middleware\ReadJsonParameters'));
$api->pipe($app->make('Flarum\Api\Middleware\LoginWithHeader'));
$api->pipe('/api', $app->make('Flarum\Http\RouterMiddleware', ['routes' => $app->make('flarum.api.routes')]));
$api->pipe(new \Franzl\Middleware\Whoops\Middleware());
$server = Server::createServer(
$api,
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$server->listen();
|
Remove py2 Ska.DBI assert in report test | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
assert db.conn._is_connected == 1
HAS_SYBASE_ACCESS = True
except:
HAS_SYBASE_ACCESS = False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not HAS_SYBASE_ACCESS', reason='Report test requires Sybase/OCAT access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archive')
def test_write_reports():
"""
Make a report and database
"""
tempdir = tempfile.mkdtemp()
# Get a temporary file, but then delete it, because report.py will only
# make a new table if the supplied file doesn't exist
fh, fn = tempfile.mkstemp(dir=tempdir, suffix='.db3')
os.unlink(fn)
report.REPORT_ROOT = tempdir
report.REPORT_SERVER = fn
for obsid in [20001, 15175, 54778]:
report.main(obsid)
os.unlink(fn)
shutil.rmtree(tempdir)
|
Switch to hash-based routing so that it works with firebase. Fine for dev and home screened app won't see | import { applyMiddleware, compose, createStore } from 'redux';
import rootReducer from '../reducers';
import { devTools } from 'redux-devtools';
import thunk from 'redux-thunk';
import routes from '../routes';
import { reduxReactRouter } from 'redux-router';
import createHistory from 'history/lib/createHashHistory';
export default function configureStore (initialState, debug = false) {
let createStoreWithMiddleware;
const middleware = applyMiddleware(thunk);
if (debug) {
createStoreWithMiddleware = compose(middleware, reduxReactRouter({ routes, createHistory }), devTools());
} else {
createStoreWithMiddleware = compose(middleware, reduxReactRouter({ routes, createHistory }));
}
const store = createStoreWithMiddleware(createStore)(
rootReducer, initialState
);
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
| import { applyMiddleware, compose, createStore } from 'redux';
import rootReducer from '../reducers';
import { devTools } from 'redux-devtools';
import thunk from 'redux-thunk';
import routes from '../routes';
import { reduxReactRouter } from 'redux-router';
import createHistory from 'history/lib/createBrowserHistory';
export default function configureStore (initialState, debug = false) {
let createStoreWithMiddleware;
const middleware = applyMiddleware(thunk);
if (debug) {
createStoreWithMiddleware = compose(middleware, reduxReactRouter({ routes, createHistory }), devTools());
} else {
createStoreWithMiddleware = compose(middleware, reduxReactRouter({ routes, createHistory }));
}
const store = createStoreWithMiddleware(createStore)(
rootReducer, initialState
);
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers/index');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
|
Use dots instead of index notation | GAME.setConsts({
SHIT : 1
});
GAME.Generator = (function() {
var wow = false;
function generate(level) {
width = level.size.width;
height = level.size.height;
// generate tilemap full of floor
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
tilemap[i][j] = FLOOR_TILE;
}
}
// shitty generation
// every 10th tile is a wall
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
if (Math.random > 0.9) {
tilemap[i][j] = WALL_TILE;
}
}
}
return level;
}
return {
generate : generate
}
})(); | GAME.setConsts({
SHIT : 1
});
GAME.Generator = (function() {
var wow = false;
function generate(level) {
width = level.size[width];
height = level.size[height];
// generate tilemap full of floor
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
tilemap[i][j] = FLOOR_TILE;
}
}
// shitty generation
// every 10th tile is a wall
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
if (Math.random > 0.9) {
tilemap[i][j] = WALL_TILE;
}
}
}
return level;
}
return {
generate : generate
}
})(); |
Remove workaround for fixed bug in SettingToggle
SettingToggle was toggling itself in response to keydown of space, and then the keyup was doing it again | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
meta: PropTypes.node,
onChange: PropTypes.func.isRequired,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingKey, target.checked);
}
render () {
const { prefix, settings, settingKey, label, meta } = this.props;
const id = ['setting-toggle', prefix, ...settingKey].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle id={id} checked={settings.getIn(settingKey)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
{meta && <span className='setting-meta__label'>{meta}</span>}
</div>
);
}
}
| import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
meta: PropTypes.node,
onChange: PropTypes.func.isRequired,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingKey, target.checked);
}
onKeyDown = e => {
if (e.key === ' ') {
this.props.onChange(this.props.settingKey, !e.target.checked);
}
}
render () {
const { prefix, settings, settingKey, label, meta } = this.props;
const id = ['setting-toggle', prefix, ...settingKey].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle id={id} checked={settings.getIn(settingKey)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
{meta && <span className='setting-meta__label'>{meta}</span>}
</div>
);
}
}
|
Install from git: try to install babel + presets automatically | const stat = require("fs").stat
const spawn = require("child_process").spawn
const join = require("path").join
const pkg = require("../package.json")
console.log(pkg.name, "post-install", process.cwd())
stat("lib", function(error, stats1) {
if (!error && stats1.isDirectory()) {
return true
}
console.warn(
"\n" +
"Builded sources not found. It looks like you might be attempting " +
`to install ${ pkg.name } from git. \n` +
"Sources need to be transpiled before use. This may take a moment." +
"\n"
)
const spawnOpts = {
stdio: "inherit",
cwd: join(__dirname, "../"),
}
const fail = (err) => {
console.error(`Failed to build ${ pkg.name } automatically. `)
if (err) {
throw err
}
}
const installTranspiler = spawn(
"npm",
[ "i" , "babel-core", "babel-cli", ...pkg.babel.presets ],
spawnOpts
)
installTranspiler.on("error", fail)
installTranspiler.on("close", (code) => {
if (code === 0) {
const installer = spawn(
"npm",
[ "run", "transpile" ],
spawnOpts
)
installer.on("error", fail)
}
})
})
| /* eslint-disable no-var */
var stat = require("fs").stat
var spawn = require("child_process").spawn
var join = require("path").join
var pkg = require("../package.json")
console.log(pkg.name, "post-install", process.cwd())
stat("lib", function(error, stats1) {
if (!error && stats1.isDirectory()) {
return true
}
console.warn(
"-".repeat(40) + "\n" +
"Builded sources not found. It looks like you might be attempting " +
`to install ${ pkg.name } from git. ` +
"Sources need to be transpiled before use and this will require you to " +
`have babel-cli installed as well as ${ pkg.babel.presets }.\n` +
"-".repeat(40) + "\n" +
"TL;DR;\n" +
"Type this command\n" +
"npm install babel-core babel-cli " + pkg.babel.presets.join(" ") +
" && npm rebuild statinamic"
)
var installer = spawn("npm", [ "run", "transpile" ], {
stdio: "inherit",
cwd: join(__dirname, "../"),
})
installer.on("error", function(err) {
console.error(`Failed to build ${ pkg.name } automatically. `)
console.error(err)
})
})
|
Check for existence of $_GET keys
`$dir` may for example very well not get passed at well. | <?php
/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Check if we are a user
OCP\User::checkLoggedIn();
\OC::$server->getSession()->close();
$files = isset($_GET['files']) ? $_GET['files'] : '';
$dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$files_list = json_decode($files);
// in case we get only a single file
if (!is_array($files_list)) {
$files_list = array($files);
}
OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD');
| <?php
/**
* ownCloud - ajax frontend
*
* @author Robin Appelman
* @copyright 2010 Robin Appelman icewind1991@gmail.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Check if we are a user
OCP\User::checkLoggedIn();
\OC::$server->getSession()->close();
$files = $_GET["files"];
$dir = $_GET["dir"];
$files_list = json_decode($files);
// in case we get only a single file
if (!is_array($files_list)) {
$files_list = array($files);
}
OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD');
|
Fix GetById should return 404
Should return 404 when the organization resource doesn't exists | 'use strict';
const Boom = require('boom');
const Organization = require('../model/Organization');
const internals = {};
internals.validateObjectId = require('../helpers/validateObjectId');
internals.fieldsToReturn = require('../helpers/fieldsToReturn');
internals.getOrganizationById = function (id) {
return Organization.findById(id, internals.fieldsToReturn)
.then((org) => {
if (org === null) {
return Boom.notFound();
}
return org;
})
.catch((err) => {
return Boom.badImplementation(err);
});
};
internals.requestHandler = function (request, reply) {
const id = request.params.id;
if (!internals.validateObjectId(id)){
return reply(Boom.badRequest('Must provide a valid organization id'));
}
return reply(internals.getOrganizationById(request.params.id));
};
module.exports = {
path: '/api/organizations/{id}',
method: 'GET',
handler: internals.requestHandler
};
| 'use strict';
const Boom = require('boom');
const Organization = require('../model/Organization');
const internals = {};
internals.validateObjectId = require('../helpers/validateObjectId');
internals.fieldsToReturn = require('../helpers/fieldsToReturn');
internals.getOrganizationById = function (id) {
return Organization.findById(id, internals.fieldsToReturn)
.then((org) => {
return org;
})
.catch((err) => {
return Boom.badImplementation(err);
});
};
internals.requestHandler = function (request, reply) {
const id = request.params.id;
if (!internals.validateObjectId(id)){
return reply(Boom.badRequest('Must provide a valid organization id'));
}
return reply(internals.getOrganizationById(request.params.id));
};
module.exports = {
path: '/api/organizations/{id}',
method: 'GET',
handler: internals.requestHandler
};
|
Handle absolute import for py27 | # -*- coding: utf-8 -*-
"""
Crossfolium
-----------
"""
from __future__ import absolute_import
from crossfolium import marker_function
from crossfolium.crossfolium import (
Crossfilter,
PieFilter,
RowBarFilter,
BarFilter,
TableFilter,
CountFilter,
ResetFilter,
GeoChoroplethFilter,
)
from crossfolium.map import (
FeatureGroupFilter,
HeatmapFilter,
)
__version__ = "0.0.0"
__all__ = [
'__version__',
'marker_function',
'Crossfilter',
'PieFilter',
'RowBarFilter',
'BarFilter',
'FeatureGroupFilter',
'TableFilter',
'CountFilter',
'ResetFilter',
'HeatmapFilter',
'GeoChoroplethFilter',
]
| # -*- coding: utf-8 -*-
"""
Crossfolium
-----------
"""
import crossfolium.marker_function as marker_function
from crossfolium.crossfolium import (
Crossfilter,
PieFilter,
RowBarFilter,
BarFilter,
TableFilter,
CountFilter,
ResetFilter,
GeoChoroplethFilter,
)
from .map import (
FeatureGroupFilter,
HeatmapFilter,
)
__version__ = "0.0.0"
__all__ = [
'__version__',
'marker_function',
'Crossfilter',
'PieFilter',
'RowBarFilter',
'BarFilter',
'FeatureGroupFilter',
'TableFilter',
'CountFilter',
'ResetFilter',
'HeatmapFilter',
'GeoChoroplethFilter',
]
|
Rename package name to lightmatchingengine | from setuptools import setup, find_packages
setup(
name="lightmatchingengine",
url="https://github.com/gavincyi/LightMatchingEngine",
license='MIT',
author="Gavin Chan",
author_email="gavincyi@gmail.com",
description="A light matching engine",
packages=find_packages(exclude=('tests',)),
use_scm_version=True,
install_requires=[],
setup_requires=['setuptools_scm'],
tests_require=[
'pytest'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
| from setuptools import setup, find_packages
setup(
name="LightMatchingEngine",
url="https://github.com/gavincyi/LightMatchingEngine",
license='MIT',
author="Gavin Chan",
author_email="gavincyi@gmail.com",
description="A light matching engine",
packages=find_packages(exclude=('tests',)),
use_scm_version=True,
install_requires=[],
setup_requires=['setuptools_scm'],
tests_require=[
'pytest'
],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
|
Add function to reset pickers from stored data
This will be required for the import functionality. | function WinClassicTheme() {
Theme.call(this);
this.pickers = document.getElementsByClassName("color-item");
var exportDestination = document.getElementById("export");
for (var i = 0; i < this.pickers.length; i++) {
var picker = this.pickers[i];
var itemName = picker.dataset.item;
this.updateFromStylesheet(itemName);
picker.value = this.getItemColor(itemName);
picker.oninput = this.onColorChange.bind(this);
picker.onchange = function() {
exportDestination.value = this.exportToIni();
}.bind(this);
}
exportDestination.value = this.exportToIni();
return this;
}
Object.setPrototypeOf(WinClassicTheme.prototype, Theme.prototype);
WinClassicTheme.prototype.onColorChange = function(e) {
var name = e.target.dataset.item;
var color = e.target.value;
this.setItemColor(name, color);
this.updateStylesheet(name);
}
WinClassicTheme.prototype.exportToIni = function() {
var ini = "";
for (var item in this.items) {
var rgb = window.normalizeColor.rgba(window.normalizeColor(this.items[item].color));
ini += item + "=" + rgb.r + " " + rgb.g + " " + rgb.b + "\n";
}
return ini.trim();
}
WinClassicTheme.prototype.resetPickers = function() {
for (var i = 0; i < this.pickers.length; i++) {
var picker = this.pickers[i];
picker.value = this.getItemColor(picker.dataset.item);
}
}
| function WinClassicTheme() {
Theme.call(this);
var pickers = document.getElementsByClassName("color-item");
var exportDestination = document.getElementById("export");
for (var i = 0; i < pickers.length; i++) {
var picker = pickers[i];
var itemName = picker.dataset.item;
this.updateFromStylesheet(itemName);
picker.value = this.getItemColor(itemName);
picker.oninput = this.onColorChange.bind(this);
picker.onchange = function() {
exportDestination.value = this.exportToIni();
}.bind(this);
}
exportDestination.value = this.exportToIni();
return this;
}
Object.setPrototypeOf(WinClassicTheme.prototype, Theme.prototype);
WinClassicTheme.prototype.onColorChange = function(e) {
var name = e.target.dataset.item;
var color = e.target.value;
this.setItemColor(name, color);
this.updateStylesheet(name);
}
WinClassicTheme.prototype.exportToIni = function() {
var ini = "";
for (var item in this.items) {
var rgb = window.normalizeColor.rgba(window.normalizeColor(this.items[item].color));
ini += item + "=" + rgb.r + " " + rgb.g + " " + rgb.b + "\n";
}
return ini.trim();
}
|
Enforce the limit to be reset in get query :
```
$query = \Admingenerator\PropelDemoBundle\Model\MovieQuery::create('q')
$paginator = new Pagerfanta(new PagerAdapter($query));
$paginator->setMaxPerPage(3);
$paginator->setCurrentPage($this->getPage(), false, true);
```
```
SELECT propel_movies.ID, propel_movies.TITLE, propel_movies.IS_PUBLISHED, propel_movies.RELEASE_DATE, propel_movies.PRODUCER_ID
FROM `propel_movies` LIMIT 3
Time: 0.041 sec - Memory: 22.1 MB
SELECT COUNT(*)
FROM (SELECT propel_movies.ID, propel_movies.TITLE, propel_movies.IS_PUBLISHED, propel_movies.RELEASE_DATE, propel_movies.PRODUCER_ID
FROM `propel_movies` LIMIT 3) propelmatch4cnt
Time: 0.002 sec - Memory: 24.6 MB
```
So was always make one page !! | <?php
/*
* This file is part of the Pagerfanta package.
*
* (c) Pablo Díez <pablodip@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pagerfanta\Adapter;
/**
* PropelAdapter.
*
* @author William DURAND <william.durand1@gmail.com>
*/
class PropelAdapter implements AdapterInterface
{
private $query;
/**
* Constructor.
*/
public function __construct($query)
{
$this->query = $query;
}
/**
* Returns the query.
*/
public function getQuery()
{
return $this->query;
}
/**
* {@inheritdoc}
*/
public function getNbResults()
{
return $this->query->limit(0)->count();
}
/**
* {@inheritdoc}
*/
public function getSlice($offset, $length)
{
return $this->query->limit($length)->offset($offset)->find();
}
}
| <?php
/*
* This file is part of the Pagerfanta package.
*
* (c) Pablo Díez <pablodip@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pagerfanta\Adapter;
/**
* PropelAdapter.
*
* @author William DURAND <william.durand1@gmail.com>
*/
class PropelAdapter implements AdapterInterface
{
private $query;
/**
* Constructor.
*/
public function __construct($query)
{
$this->query = $query;
}
/**
* Returns the query.
*/
public function getQuery()
{
return $this->query;
}
/**
* {@inheritdoc}
*/
public function getNbResults()
{
return $this->query->count();
}
/**
* {@inheritdoc}
*/
public function getSlice($offset, $length)
{
return $this->query->limit($length)->offset($offset)->find();
}
}
|
Remove `LIKE` and raw from viewUserList rename | <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', '%viewDiscussions')
->update(['permission' => $db->raw("REPLACE(permission, 'viewDiscussions', 'viewForum')")]);
$db->table('group_permission')
->where('permission', 'viewUserList')
->update(['permission' => 'searchUsers']);
},
'down' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', '%viewForum')
->update(['permission' => $db->raw("REPLACE(permission, 'viewForum', 'viewDiscussions')")]);
$db->table('group_permission')
->where('permission', 'searchUsers')
->update(['permission' => 'viewUserList']);
}
];
| <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', '%viewDiscussions')
->update(['permission' => $db->raw("REPLACE(permission, 'viewDiscussions', 'viewForum')")]);
$db->table('group_permission')
->where('permission', 'LIKE', 'viewUserList')
->update(['permission' => $db->raw("REPLACE(permission, 'viewUserList', 'searchUsers')")]);
},
'down' => function (Builder $schema) {
$db = $schema->getConnection();
$db->table('group_permission')
->where('permission', 'LIKE', '%viewForum')
->update(['permission' => $db->raw("REPLACE(permission, 'viewForum', 'viewDiscussions')")]);
$db->table('group_permission')
->where('permission', 'LIKE', 'searchUsers')
->update(['permission' => $db->raw("REPLACE(permission, 'searchUsers', 'viewUserList')")]);
}
];
|
Correct adapter type to allow nullable | <?php
namespace Bolt;
use Bolt\Interfaces\Connection;
abstract class Repository extends Base
{
protected ?Adapter $adapter = null;
public function __construct(Connection $connection = null, $data = null)
{
$this->adapter($connection);
if ($data !== null)
{
parent::__construct($data);
}
}
public function adapter(Connection $connection = null)
{
if ($connection !== null)
{
$className = $this->className(false);
$className = "App\\Adapters\\Repositories\\" . $className . "\\" . $connection->className(false);
$this->adapter = new $className($connection, $this);
return $this;
}
return $this->adapter;
}
public function __call($name, $args)
{
return $this->adapter->{$name}($args);
}
}
?>
| <?php
namespace Bolt;
use Bolt\Interfaces\Adapter;
use Bolt\Interfaces\Connection;
abstract class Repository extends Base
{
protected Adapter $adapter;
public function __construct(Connection $connection = null, $data = null)
{
$this->adapter($connection);
if ($data !== null)
{
parent::__construct($data);
}
}
public function adapter(Connection $connection = null)
{
if ($connection !== null)
{
$className = $this->className(false);
$className = "App\\Adapters\\Repositories\\" . $className . "\\" . $connection->className(false);
$this->adapter = new $className($connection, $this);
return $this;
}
return $this->adapter;
}
public function __call($name, $args)
{
return $this->adapter->{$name}($args);
}
}
?>
|
Add final modifier to field | package de.idrinth.waraddonclient.model;
import java.util.ArrayList;
import java.util.HashMap;
public class CaseInsensitiveHashMap<T> extends HashMap<String, T> {
private final ArrayList<String> keys = new ArrayList<>();
@Override
public T put(String key, T value) {
for (String k : keys) {
if (k.equalsIgnoreCase(key)) {
return super.put(k, value);
}
}
keys.add(key);
return super.put(key, value);
}
public T get(String key) {
for (String k : keys) {
if (k.equalsIgnoreCase(key)) {
return super.get(k);
}
}
return super.get(key);
}
public boolean containsKey(String key) {
for (String k : keys) {
if (k.equalsIgnoreCase(key)) {
return true;
}
}
return false;
}
}
| package de.idrinth.waraddonclient.model;
import java.util.ArrayList;
import java.util.HashMap;
public class CaseInsensitiveHashMap<T> extends HashMap<String, T> {
private ArrayList<String> keys = new ArrayList<>();
@Override
public T put(String key, T value) {
for (String k : keys) {
if (k.equalsIgnoreCase(key)) {
return super.put(k, value);
}
}
keys.add(key);
return super.put(key, value);
}
public T get(String key) {
for (String k : keys) {
if (k.equalsIgnoreCase(key)) {
return super.get(k);
}
}
return super.get(key);
}
public boolean containsKey(String key) {
for (String k : keys) {
if (k.equalsIgnoreCase(key)) {
return true;
}
}
return false;
}
}
|
Fix for touch scrolling on mobile | (function () {
'use strict';
var precincts,
map = L.map('map', {
dragging: false,
touchZoom: false,
scrollWheelZoom: false,
doubleClickZoom: false,
boxZoom: false,
tap: false,
keyboard: false,
zoomControl: false,
attributionControl: false
});
function initMap(data) {
precincts = L.geoJson(topojson.feature(data, data.objects.precincts), {
style: {
color: '#E8E6E5',
opacity: 1,
weight: 2,
fillColor: '#D4D1D0',
fillOpacity: 1
}
});
map.fitBounds(precincts).addLayer(precincts);
}
$(function () {
$.ajax({
dataType: 'json',
url: 'data/precinct-boundaries.json',
data: {},
async: false,
success: function (data) { initMap(data); }
});
$(window).resize(function() {
map.fitBounds(precincts);
});
});
}()); | (function () {
'use strict';
var precincts,
map = L.map('map', {
dragging: false,
touchZoom: false,
scrollWheelZoom: false,
doubleClickZoom: false,
boxZoom: false,
keyboard: false,
zoomControl: false,
attributionControl: false
});
function initMap(data) {
precincts = L.geoJson(topojson.feature(data, data.objects.precincts), {
style: {
color: '#E8E6E5',
opacity: 1,
weight: 2,
fillColor: '#D4D1D0',
fillOpacity: 1
}
});
map.fitBounds(precincts).addLayer(precincts);
}
$(function () {
$.ajax({
dataType: 'json',
url: 'data/precinct-boundaries.json',
data: {},
async: false,
success: function (data) { initMap(data); }
});
$(window).resize(function() {
map.fitBounds(precincts);
});
});
}()); |
Fix Google Analytics plugin to actually work | <?php
// Support Do Not Track header.
// http://donottrack.us/
function isDntEnabled() {
return (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] == 1);
}
if(isDntEnabled() && Settings::pluginGet("dnt"))
echo "<!-- Disabling Google Analytics because you have Do Not Track set! We're awesome like that. -->";
else
{
$loginstatus = json_encode($loguserid?"Yes":"No");
$tracking_id = json_encode(trim(Settings::pluginGet("trackingid")));
echo <<<EOS
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', $tracking_id]);
_gaq.push(['_setCustomVar', 1, 'Logged in', $loginstatus, 2]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
EOS;
}
| <?php
// Support Do Not Track header.
// http://donottrack.us/
function isDntEnabled() {
return (isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] == 1);
}
if(isDntEnabled() && Settings::pluginGet("dnt"))
echo "<!-- Disabling Google Analytics because you have Do Not Track set! We're awesome like that. -->";
else
{
$loginstatus = $loguserid?"Yes":"No";
echo <<<EOS
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<?php print trim(Settings::pluginGet("trackingid"));?>']);
_gaq.push(['_setCustomVar', 1, 'Logged in', '$loginstatus', 2]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
EOS;
}
|
Fix failing build: added getsentry/responses as installation requirement | from setuptools import setup
setup(
name="teamscale-client",
version="4.1.0",
author="Thomas Kinnen - CQSE GmbH",
author_email="kinnen@cqse.eu",
description=("A simple service client to interact with Teamscale's REST API."),
license="Apache",
keywords="rest api teamscale",
url="https://github.com/cqse/teamscale-client-python",
packages=['teamscale_client'],
long_description="A simple service client to interact with Teamscale's REST API.",
classifiers=[
"Topic :: Utilities",
],
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle',
'responses'
],
tests_require=[
'pytest',
'responses'
],
setup_requires=["pytest-runner"]
)
| from setuptools import setup
setup(
name="teamscale-client",
version="4.1.0",
author="Thomas Kinnen - CQSE GmbH",
author_email="kinnen@cqse.eu",
description=("A simple service client to interact with Teamscale's REST API."),
license="Apache",
keywords="rest api teamscale",
url="https://github.com/cqse/teamscale-client-python",
packages=['teamscale_client'],
long_description="A simple service client to interact with Teamscale's REST API.",
classifiers=[
"Topic :: Utilities",
],
install_requires=[
'simplejson',
'requests>=2.0',
'jsonpickle'
],
tests_require=[
'pytest',
'responses'
],
setup_requires=["pytest-runner"]
)
|
fix: Use 404 instead of 500 when a file is not found | #!/usr/bin/env node
const express = require('express');
const fileExists = require('file-exists');
const bodyParser = require('body-parser');
const fs = require('fs');
const { port = 8123 } = require('minimist')(process.argv.slice(2));
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) {
return res.status(500).send('Server did not provide file path');
}
if (!fileExists(filePath)) {
return res.status(404).send('Cannot find such file on the server');
}
try {
require(filePath)(req, res); // eslint-disable-line global-require
} catch (e) {
return res.status(500).send(`<pre>${e.stack}</pre>`);
}
const watcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change') {
delete require.cache[require.resolve(filePath)];
watcher.close();
}
});
return undefined;
});
app.listen(port, () => {
console.log(`node-direct listening on port ${port}!`);
});
| #!/usr/bin/env node
const express = require('express');
const fileExists = require('file-exists');
const bodyParser = require('body-parser');
const fs = require('fs');
const { port = 8123 } = require('minimist')(process.argv.slice(2));
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('*', (req, res) => {
const filePath = req.get('X-Requested-File-Path');
if (!filePath) {
return res.status(500).send('Server did not provide file path');
}
if (!fileExists(filePath)) {
return res.status(500).send('Cannot find such file on the server');
}
try {
require(filePath)(req, res); // eslint-disable-line global-require
} catch (e) {
return res.status(500).send(`<pre>${e.stack}</pre>`);
}
const watcher = fs.watch(filePath, (eventType) => {
if (eventType === 'change') {
delete require.cache[require.resolve(filePath)];
watcher.close();
}
});
return undefined;
});
app.listen(port, () => {
console.log(`node-direct listening on port ${port}!`);
});
|
Refactor some redundancy in the views tests | from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
def make_POST_request(titleValue, descriptionValue):
request = HttpRequest()
request.method = 'POST'
request.POST['title'] = titleValue
request.POST['description'] = descriptionValue
return request
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
def test_does_create_campaign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
create_campaign(make_POST_request('C1', 'C1Descr'))
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
def test_create_campaign_dont_saves_empty_objects(self):
self.assertEqual(Campaign.objects.count(), 0)
create_campaign(make_POST_request('', ''))
self.assertEqual(Campaign.objects.count(), 0)
| from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
def test_does_create_camapign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
request = HttpRequest()
request.method = 'POST'
request.POST['title'] = 'C1'
request.POST['description'] = 'C1Descr'
create_campaign(request)
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
|
Remove PositionLayer as it's an expensive operation | import PIXI from 'pixi.js';
import Hexagon from './hexagon.js';
import GroundLayer from './layer/groundLayer.js';
let hexagon = new Hexagon(80);
/**
* Represents a tile in the game.
*/
export default class Tile {
constructor(x, y, entities) {
this.x = x;
this.y = y;
this.entities = entities;
this.selected = false;
this.hover = false;
this.sprite = new PIXI.Container();
this.layers = [];
this.addLayer(new GroundLayer(this));
}
addLayer(layer) {
this.layers.push(layer);
this.sprite.addChild(layer.getSprite());
}
shouldComponentUpdate() {
return !this.layers.every((e) => !e.shouldComponentUpdate());
}
update(renderer) {
this.layers.forEach((e) => {
if (e.shouldComponentUpdate()) e.update(renderer);
});
}
static get hexagon() {
return hexagon;
}
}
| import PIXI from 'pixi.js';
import Hexagon from './hexagon.js';
import GroundLayer from './layer/groundLayer.js';
import PositionLayer from './layer/positionLayer.js';
let hexagon = new Hexagon(80);
/**
* Represents a tile in the game.
*/
export default class Tile {
constructor(x, y, entities) {
this.x = x;
this.y = y;
this.entities = entities;
this.selected = false;
this.hover = false;
this.sprite = new PIXI.Container();
this.layers = [];
this.addLayer(new GroundLayer(this));
this.addLayer(new PositionLayer(this));
}
addLayer(layer) {
this.layers.push(layer);
this.sprite.addChild(layer.getSprite());
}
shouldComponentUpdate() {
return !this.layers.every((e) => !e.shouldComponentUpdate());
}
update(renderer) {
this.layers.forEach((e) => {
if (e.shouldComponentUpdate()) e.update(renderer);
});
}
static get hexagon() {
return hexagon;
}
}
|
Use random_bytes for call ID | <?php
namespace WyriHaximus\React\ChildProcess\Messenger;
class OutstandingCalls
{
/**
* @var OutstandingCall[]
*/
protected $calls = [];
/**
* @param callable $canceller
* @return OutstandingCall
*/
public function newCall(callable $canceller = null)
{
$uniqid = $this->getNewUniqid();
$this->calls[$uniqid] = new OutstandingCall($uniqid, $canceller, function (OutstandingCall $call) {
unset($this->calls[$call->getUniqid()]);
});
return $this->calls[$uniqid];
}
/**
* @param string $uniqid
*
* @return OutstandingCall
*/
public function getCall($uniqid)
{
return $this->calls[$uniqid];
}
/**
* @return string
*/
protected function getNewUniqid()
{
do {
$uniqid = bin2hex(random_bytes(32));
} while (isset($this->calls[$uniqid]));
return $uniqid;
}
}
| <?php
namespace WyriHaximus\React\ChildProcess\Messenger;
class OutstandingCalls
{
/**
* @var OutstandingCall[]
*/
protected $calls = [];
/**
* @param callable $canceller
* @return OutstandingCall
*/
public function newCall(callable $canceller = null)
{
$uniqid = $this->getNewUniqid();
$this->calls[$uniqid] = new OutstandingCall($uniqid, $canceller, function (OutstandingCall $call) {
unset($this->calls[$call->getUniqid()]);
});
return $this->calls[$uniqid];
}
/**
* @param string $uniqid
*
* @return OutstandingCall
*/
public function getCall($uniqid)
{
return $this->calls[$uniqid];
}
/**
* @return string
*/
protected function getNewUniqid()
{
do {
$uniqid = uniqid('', true);
} while (isset($this->calls[$uniqid]));
return $uniqid;
}
}
|
Add animate() and deanimate() methods | //= require ../chef
(function($, window) {
'use strict';
$.fn.animate = function() {
this.addClass('animate');
};
$.fn.deanimate = function() {
this.find('.mark g').one('webkitAnimationIteration MSAnimationIteration animationiteration', $.proxy(function() {
this.removeClass('animate');
}, this));
};
Chef.Web.Core.components.logo = {
init: function() {
$('.logo').each(function() {
var $el = $(this);
if ($el.find('> svg').length === 0) {
$el.load(Chef.Web.Core.imageUrl('chef-logo.svg'), function() {
var tag = $el.data('tag-line');
if (tag) {
this.querySelector('svg .tag-line text').textContent = tag;
}
});
}
});
},
refresh: function() {
$('.logo svg').remove();
this.init();
}
};
})(jQuery, window); | //= require ../chef
(function($, window) {
'use strict';
Chef.Web.Core.components.logo = {
init: function() {
$('.logo').each(function() {
var $el = $(this);
if ($el.find('> svg').length === 0) {
$el.load(Chef.Web.Core.imageUrl('chef-logo.svg'), function() {
var tag = $el.data('tag-line');
if (tag) {
this.querySelector('svg .tag-line text').textContent = tag;
}
});
}
});
},
refresh: function() {
$('.logo svg').remove();
this.init();
}
};
})(jQuery, window); |
Order by last seen, descending. | from django.contrib import admin
from .models import TaskStore, TaskStoreActivityLog, UserMetadata
class TaskStoreAdmin(admin.ModelAdmin):
search_fields = ('user__username', 'local_path', 'taskrc_extras', )
list_display = ('user', 'local_path', 'configured', )
list_filter = ('configured', )
admin.site.register(TaskStore, TaskStoreAdmin)
class TaskStoreActivityLogAdmin(admin.ModelAdmin):
search_fields = ('store__user__username', 'message', )
list_display = (
'username', 'last_seen', 'created', 'error', 'message', 'count'
)
date_hierarchy = 'last_seen'
list_filter = ('created', 'last_seen', )
list_select_related = True
ordering = ('-last_seen', )
def username(self, obj):
return obj.store.user.username
username.short_description = 'Username'
admin.site.register(TaskStoreActivityLog, TaskStoreActivityLogAdmin)
class UserMetadataAdmin(admin.ModelAdmin):
search_fields = ('user__username', )
list_display = ('user', 'tos_version', 'tos_accepted', )
list_filter = ('tos_version', )
admin.site.register(UserMetadata, UserMetadataAdmin)
| from django.contrib import admin
from .models import TaskStore, TaskStoreActivityLog, UserMetadata
class TaskStoreAdmin(admin.ModelAdmin):
search_fields = ('user__username', 'local_path', 'taskrc_extras', )
list_display = ('user', 'local_path', 'configured', )
list_filter = ('configured', )
admin.site.register(TaskStore, TaskStoreAdmin)
class TaskStoreActivityLogAdmin(admin.ModelAdmin):
search_fields = ('store__user__username', 'message', )
list_display = (
'username', 'last_seen', 'created', 'error', 'message', 'count'
)
date_hierarchy = 'last_seen'
list_filter = ('created', 'last_seen', )
list_select_related = True
def username(self, obj):
return obj.store.user.username
username.short_description = 'Username'
admin.site.register(TaskStoreActivityLog, TaskStoreActivityLogAdmin)
class UserMetadataAdmin(admin.ModelAdmin):
search_fields = ('user__username', )
list_display = ('user', 'tos_version', 'tos_accepted', )
list_filter = ('tos_version', )
admin.site.register(UserMetadata, UserMetadataAdmin)
|
Set test for start cmd to test env | import unittest
from unittest import mock
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
cls.cli_run = cli_run
def test_initdb(self):
result = self.cli_run('initdb')
self.assertEqual(0, result.exit_code, msg=str(result))
@mock.patch('flask.Flask.run', create=True, return_value=True)
def test_start(self, new_app_run_func):
result = self.cli_run('start', '--env', 'test')
self.assertEqual(0, result.exit_code, msg=str(result))
| import unittest
from unittest import mock
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
cls.cli_run = cli_run
def test_initdb(self):
result = self.cli_run('initdb')
self.assertEqual(0, result.exit_code, msg=str(result))
@mock.patch('flask.Flask.run', create=True, return_value=True)
def test_start(self, new_app_run_func):
result = self.cli_run('start')
self.assertEqual(0, result.exit_code, msg=str(result))
|
Fix for Google Analytics event tracking | var _ = require('underscore');
/**
* Track an event to analytics providers (e.g. Google Analytics, Mixpanel).
*
* @param {string} event_category Typically the object interacted with, e.g. 'Clipboard'
* @param {string} event_action The type of interaction, e.g. 'Add item'
* @param {object} event_data (Optional) Properties to include about the
* event, e.g. {title: 'Sparks Fly'}
*/
function track(event_category, event_action, event_data) {
var event_data_string = "";
if (_.isObject(event_data)) {
event_data_string = JSON.stringify(event_data);
}
console.log(`Tracking analytics event "${event_category}: ${event_action}"`,
` ${event_data_string}`);
window.gtag && gtag('event', event_action, _.extend(event_data, {
event_category: event_category,
event_label: event_data_string,
}));
// TODO(davidhu): Uncomment this in the next PR that adds Mixpanel tracking
//window.mixpanel && mixpanel.track(`${event_category}: ${event_action}`, event_data);
}
module.exports = {
track: track
};
| var _ = require('underscore');
/**
* Track an event to analytics providers (e.g. Google Analytics, Mixpanel).
*
* @param {string} event_category Typically the object interacted with, e.g. 'Clipboard'
* @param {string} event_action The type of interaction, e.g. 'Add item'
* @param {object} event_data (Optional) Properties to include about the
* event, e.g. {title: 'Sparks Fly'}
*/
function track(event_category, event_action, event_data) {
var event_data_string = "";
if (_.isObject(event_data)) {
event_data_string = JSON.stringify(event_data);
}
console.log(`Tracking analytics event "${event_category}: ${event_action}"`,
` ${event_data_string}`);
window.ga && ga(event_category, event_action, event_data_string);
// TODO(davidhu): Uncomment this in the next PR that adds Mixpanel tracking
//window.mixpanel && mixpanel.track(`${event_category}: ${event_action}`, event_data);
}
module.exports = {
track: track
};
|
Access data of object instead | function populateMarkers(mapData) {
console.log(mapData[0]);
}
function initMap() {
var element = document.createElement('div');
var mapDiv = document.getElementById('map-hider').appendChild(element);
mapDiv.id = 'map';
mapDiv.style.cssText = 'width:100%; height:750px; margin: auto';
var map = new google.maps.Map(mapDiv, {
center: {lat: 54.2774, lng: -1.7126},
zoom: 7
});
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: {lat: 54.2774, lng: -1.7126}
});
var mapdata = Papa.parse("https://rawcdn.githack.com/WearyWanderer/wearywanderer.github.io/master/assets/csv/wanderlustvids.csv", {
download: true,
complete: function(results) {
console.log(results);
populateMarkers(results.data);
}
});
}
window.onload = initMap;
| function populateMarkers(mapData) {
console.log(mapData[0]);
}
function initMap() {
var element = document.createElement('div');
var mapDiv = document.getElementById('map-hider').appendChild(element);
mapDiv.id = 'map';
mapDiv.style.cssText = 'width:100%; height:750px; margin: auto';
var map = new google.maps.Map(mapDiv, {
center: {lat: 54.2774, lng: -1.7126},
zoom: 7
});
marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: {lat: 54.2774, lng: -1.7126}
});
var mapdata = Papa.parse("https://rawcdn.githack.com/WearyWanderer/wearywanderer.github.io/master/assets/csv/wanderlustvids.csv", {
download: true,
complete: function(results) {
console.log(results);
populateMarkers(results);
}
});
}
window.onload = initMap;
|
Update ptvsd version number for 2.2 release. | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.2.0',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://aka.ms/ptvs',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
| #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
from distutils.core import setup
setup(name='ptvsd',
version='2.2.0rc2',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@microsoft.com',
url='https://aka.ms/ptvs',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License'],
packages=['ptvsd']
)
|
Update comment about piping hook. | var nconf = require('nconf');
// Specifying an env delimiter allows you to override below config when shipping to production server
// by e.g. defining piping__ignore or version variables.
nconf.env('__');
var config = {
appLocales: ['en', 'fr'],
defaultLocale: 'en',
googleAnalyticsId: 'UA-XXXXXXX-X',
isProduction: process.env.NODE_ENV === 'production',
piping: {
// Ignore webpack custom loaders on server. TODO: Reuse index.js config.
ignore: /(\/\.|~$|\.(css|less|sass|scss|styl))/,
// Hook ensures always fresh server response even for client file change.
hook: true
},
port: process.env.PORT || 8000,
version: require('../../package').version,
webpackStylesExtensions: ['css', 'less', 'sass', 'scss', 'styl']
};
// Use above config as a default one
// Multiple other providers are available like loading config from json and more
// Check out nconf docs for fancier examples
nconf.defaults(config);
module.exports = nconf.get();
| var nconf = require('nconf');
// Specifying an env delimiter allows you to override below config when shipping to production server
// by e.g. defining piping__ignore or version variables.
nconf.env('__');
var config = {
appLocales: ['en', 'fr'],
defaultLocale: 'en',
googleAnalyticsId: 'UA-XXXXXXX-X',
isProduction: process.env.NODE_ENV === 'production',
piping: {
// Ignore webpack custom loaders on server. TODO: Reuse index.js config.
ignore: /(\/\.|~$|\.(css|less|sass|scss|styl))/,
// Hook ensures server restart on all required deps, even client side.
// Server restarting invalidates require cache, no more stale html.
hook: true
},
port: process.env.PORT || 8000,
version: require('../../package').version,
webpackStylesExtensions: ['css', 'less', 'sass', 'scss', 'styl']
};
// Use above config as a default one
// Multiple other providers are available like loading config from json and more
// Check out nconf docs for fancier examples
nconf.defaults(config);
module.exports = nconf.get();
|
Fix template and static paths | import os
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'../frontend/templates'
)
static_directory = '../frontend/static'
app = Flask(__name__, template_folder=template_directory, static_folder=static_directory)
app.config.from_object('config.flask_config')
def init_db():
"""
Initialize the SQLAlchemy database object.
:return: A SQLAlchemy instance used universally for database operations.
"""
return SQLAlchemy(app, session_options={
'expire_on_commit': False,
})
def init_login_manager():
"""
Initialize the login manager.
:return: A LoginManager instance used universally for flask-login loaders.
"""
login_manager = LoginManager()
login_manager.init_app(app)
return login_manager
| import os
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'frontend/templates'
)
static_directory = 'frontend/static'
app = Flask(__name__, template_folder=template_directory, static_folder=static_directory)
app.config.from_object('config.flask_config')
def init_db():
"""
Initialize the SQLAlchemy database object.
:return: A SQLAlchemy instance used universally for database operations.
"""
return SQLAlchemy(app, session_options={
'expire_on_commit': False,
})
def init_login_manager():
"""
Initialize the login manager.
:return: A LoginManager instance used universally for flask-login loaders.
"""
login_manager = LoginManager()
login_manager.init_app(app)
return login_manager
|
Use same defines as c++ interface in java code | package com.mapzen.tangram;
import java.util.ArrayList;
import java.util.List;
/**
* {@code TouchLabel} represents labels that can be selected on the screen
*/
public class TouchLabel {
/**
* Options for the type of TouchLabel
*/
public enum LabelType {
ICON,
TEXT,
}
private List<LngLat> coordinates;
private LabelType type;
public TouchLabel(double[] coordinates, int type) {
this.coordinates = new ArrayList<>();
for (int i = 0; i < coordinates.length - 1; i += 2) {
this.coordinates.add(new LngLat(coordinates[i], coordinates[i + 1]));
}
this.type = LabelType.values()[type];
}
public LabelType getType() {
return this.type;
}
public List<LngLat> getCoordinates() {
return this.coordinates;
}
}
| package com.mapzen.tangram;
import java.util.ArrayList;
import java.util.List;
/**
* {@code TouchLabel} represents labels that can be selected on the scree
*/
public class TouchLabel {
/**
* Options for the type of TouchLabel
*/
public enum LabelType {
POINT,
TEXT,
}
private List<LngLat> coordinates;
private LabelType type;
public TouchLabel(double[] coordinates, int type) {
this.coordinates = new ArrayList<>();
for (int i = 0; i < coordinates.length - 1; i += 2) {
this.coordinates.add(new LngLat(coordinates[i], coordinates[i + 1]));
}
this.type = LabelType.values()[type];
}
public LabelType getType() {
return this.type;
}
public List<LngLat> getCoordinates() {
return this.coordinates;
}
}
|
Fix dot escaping for jQuery and use $()[0] | /* Can't use $.toggle() as we are using a custom `display` that is `none`
when the page first loads */
function toggle (name, mode) {
var id = name.replace(/\./g, '\\.') + '-' + mode
, e = $('#' + id)
if (e.css('display') === 'none') var activating = 1
else var activating = 0
e.css('display', activating ? 'table-row' : 'none')
$('#' + id + '-btn').toggleClass('active')
if (activating) {
if (e.hasClass('loaded')) return
$.getJSON('/api/' + slot + '/' + date + '/' + name, null,
function success (data) {
var codeElement = e.find('code.language-git')
codeElement.html(decodeURIComponent(escape(atob(data[mode]))))
e.addClass('loaded')
Prism.highlightElement(codeElement[0])
})
}
}
function hide (id) {
var e = document.getElementById(id)
e.style.display = 'none'
$('#' + id.replace(/\./g, '\\.') + '-btn').removeClass('active')
}
function show_diff (name) {
hide(name + '-stderr')
toggle(name, 'diff')
}
function show_err (name) {
hide(name + '-diff')
toggle(name, 'stderr')
}
| /* Can't use $.toggle() as we are using a custom `display` that is `none`
when the page first loads */
function toggle (name, mode) {
var id = name + '-' + mode
var e = document.getElementById(id)
var ej = $(e)
e.style.display = e.style.display == 'table-row' ? 'none' : 'table-row'
$('#' + id + '-btn').toggleClass('active')
if (e.style.display === 'table-row') {
if (ej.hasClass('loaded')) return
$.getJSON('/api/' + slot + '/' + date + '/' + name, null,
function success (data) {
ej.find('code.language-git').html(
decodeURIComponent(escape(atob(data[mode]))))
ej.addClass('loaded')
Prism.highlightAll() // FIXME
})
}
}
function hide (id) {
var e = document.getElementById(id)
e.style.display = 'none'
$('#' + id + '-btn').removeClass('active')
}
function show_diff (name) {
hide(name + '-stderr')
toggle(name, 'diff')
}
function show_err (name) {
hide(name + '-diff')
toggle(name, 'stderr')
}
|
Fixed: Make regression test return verbose output for debugging. | <?php
namespace Qafoo\ChangeTrack;
/**
* @group regression
*/
class AnalyzerRegressionTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
`rm -rf src/var/tmp`;
`mkdir src/var/tmp`;
}
public function tearDown()
{
unlink('test/temp_result.xml');
}
public function testAnalyzerRegressionDaemonRepository()
{
`src/bin/track analyze -o test/temp_result.xml -v https://github.com/QafooLabs/Daemon.git`;
$this->assertXmlFileEqualsXmlFile(
__DIR__ . '/../../_fixtures/regression_analysis_daemon.xml',
'test/temp_result.xml'
);
}
}
| <?php
namespace Qafoo\ChangeTrack;
/**
* @group regression
*/
class AnalyzerRegressionTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
`rm -rf src/var/tmp`;
`mkdir src/var/tmp`;
}
public function tearDown()
{
unlink('test/temp_result.xml');
}
public function testAnalyzerRegressionDaemonRepository()
{
`src/bin/track analyze -o test/temp_result.xml https://github.com/QafooLabs/Daemon.git`;
$this->assertXmlFileEqualsXmlFile(
__DIR__ . '/../../_fixtures/regression_analysis_daemon.xml',
'test/temp_result.xml'
);
}
}
|
Move from python anywhere to webfaction | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_command.sh') as f:
raw_command = f.read()
if lines:
subject = 'Tube delays for commute'
body = ', '.join(': '.join([line.capitalize(), s]) for line, s in status.items())
else:
subject = 'Good service for commute'
body = 'Good service on all lines'
os.system(raw_command.format(subject=subject, body=body))
def main():
commute_lines = ['metropolitan', 'jubilee', 'central']
status = update()
delays = {c: status[c] for c in commute_lines if status[c] != 'Good Service'}
email(delays)
if __name__ == '__main__':
main()
| import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_command.sh') as f:
raw_command = f.read()
if lines:
subject = 'Tube delays for commute'
body = ', '.join(': '.join([line.capitalize(), s]) for line, s in status.items())
else:
subject = 'Good service for commute'
body = 'Good service on all lines'
# We must have this running on PythonAnywhere - Monday to Sunday.
# Ignore Saturday and Sunday
if datetime.date.today().isoweekday() in range(1, 6):
os.system(raw_command.format(subject=subject, body=body))
def main():
commute_lines = ['metropolitan', 'jubilee', 'central']
status = update()
delays = {c: status[c] for c in commute_lines if status[c] != 'Good Service'}
email(delays)
if __name__ == '__main__':
main()
|
Use generator instead of list.
Co-authored-by: Teemu Erkkola <ee6c9b9748887a4d25e9c1c5e0aff697ac55fd56@gofore.com> | from ckan.plugins import toolkit
from ckanext.apply_permissions_for_service import model
def service_permission_application_list(context, data_dict):
return {'success': True}
def service_permission_application_show(context, data_dict):
permission_application_id = toolkit.get_or_bust(data_dict, 'id')
application = model.ApplyPermission.get(permission_application_id).as_dict()
organization = application.get('organization')
target_organization = application.get('target_organization')
membership_organizations = toolkit.get_action('organization_list_for_user')(context, {'permission': 'read'})
if any(True for x in (org.get('id') for org in membership_organizations)
if x in (organization['id'], target_organization['id'])):
return {'success': True}
return {'success': False,
"msg": toolkit._("User not authorized to view permission application.")}
def service_permission_settings(context, data_dict):
return {'success': toolkit.check_access('package_update', context, {'id': data_dict['subsystem_id']})}
def service_permission_application_create(context, data_dict):
editor_or_admin_orgs = toolkit.get_action('organization_list_for_user')(context, {'permission': 'create_dataset'})
return {'success': len(editor_or_admin_orgs) > 0}
| from ckan.plugins import toolkit
from ckanext.apply_permissions_for_service import model
def service_permission_application_list(context, data_dict):
return {'success': True}
def service_permission_application_show(context, data_dict):
permission_application_id = toolkit.get_or_bust(data_dict, 'id')
application = model.ApplyPermission.get(permission_application_id).as_dict()
organization = application.get('organization')
target_organization = application.get('target_organization')
membership_organizations = toolkit.get_action('organization_list_for_user')(context, {'permission': 'read'})
if any(True for x in [org.get('id') for org in membership_organizations]
if x in (organization['id'], target_organization['id'])):
return {'success': True}
return {'success': False,
"msg": toolkit._("User not authorized to view permission application.")}
def service_permission_settings(context, data_dict):
return {'success': toolkit.check_access('package_update', context, {'id': data_dict['subsystem_id']})}
def service_permission_application_create(context, data_dict):
editor_or_admin_orgs = toolkit.get_action('organization_list_for_user')(context, {'permission': 'create_dataset'})
return {'success': len(editor_or_admin_orgs) > 0}
|
Remove import of delta module. | """
Provides access and a location for storage class logic like 'trend',
'attribute', etc..
"""
__docformat__ = "restructuredtext en"
__copyright__ = """
Copyright (C) 2008-2013 Hendrikx-ITC B.V.
Distributed under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option) any later
version. The full license is in the file COPYING, distributed as part of
this software.
"""
def load_plugins():
from minerva.storage import trend, attribute, geospatial, notification
"""
Load and return a dictionary with plugins by their names.
"""
return {
'attribute': attribute.create,
'trend': trend.create,
'notification': notification.NotificationPlugin,
'geospatial': geospatial.create
}
def get_plugin(name):
"""
Return storage plugin with name `name`.
"""
return load_plugins().get(name)
| """
Provides access and a location for storage class logic like 'trend',
'attribute', etc..
"""
__docformat__ = "restructuredtext en"
__copyright__ = """
Copyright (C) 2008-2013 Hendrikx-ITC B.V.
Distributed under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option) any later
version. The full license is in the file COPYING, distributed as part of
this software.
"""
def load_plugins():
from minerva.storage import trend, attribute, geospatial, notification, delta
"""
Load and return a dictionary with plugins by their names.
"""
return {
'attribute': attribute.create,
'trend': trend.create,
'notification': notification.NotificationPlugin,
'geospatial': geospatial.create
}
def get_plugin(name):
"""
Return storage plugin with name `name`.
"""
return load_plugins().get(name)
|
Add missing import of sys. | import sys
import unittest
if sys.platform.startswith('darwin'):
from nativeconfig.config import NSUserDefaultsConfig
from test.config import TestConfigMixin
class MyNSUserDefaultsConfig(NSUserDefaultsConfig):
pass
class TestMemoryConfig(unittest.TestCase, TestConfigMixin):
CONFIG_TYPE = MyNSUserDefaultsConfig
def tearDown(self):
try:
c = self.CONFIG_TYPE.get_instance()
c.del_value_for_option_name('FirstName')
c.del_value_for_option_name('LastName')
c.del_value_for_option_name('LuckyNumber')
except OSError:
pass
TestConfigMixin.tearDown(self)
def test_config_is_created_if_not_found(self):
pass
| import unittest
if sys.platform.startswith('darwin'):
from nativeconfig.config import NSUserDefaultsConfig
from test.config import TestConfigMixin
class MyNSUserDefaultsConfig(NSUserDefaultsConfig):
pass
class TestMemoryConfig(unittest.TestCase, TestConfigMixin):
CONFIG_TYPE = MyNSUserDefaultsConfig
def tearDown(self):
try:
c = self.CONFIG_TYPE.get_instance()
c.del_value_for_option_name('FirstName')
c.del_value_for_option_name('LastName')
c.del_value_for_option_name('LuckyNumber')
except OSError:
pass
TestConfigMixin.tearDown(self)
def test_config_is_created_if_not_found(self):
pass
|
Add TODO with plan for getting rid of findDOMNode in dragHandle | /* @flow */
import React from 'react';
import type {Element as ReactElement} from 'react';
import {findDOMNode} from 'react-dom';
type Props = {
onMouseDown: Function;
onTouchStart: Function;
children: ReactElement<any>;
};
export default class DragHandle extends React.Component<Props> {
componentDidMount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.addEventListener('mousedown', this._onMouseDown);
node.addEventListener('touchstart', this._onTouchStart);
}
componentWillUnmount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.removeEventListener('mousedown', this._onMouseDown);
node.removeEventListener('touchstart', this._onTouchStart);
}
_onMouseDown: Function = (e) => {
this.props.onMouseDown.call(null, e);
};
_onTouchStart: Function = (e) => {
this.props.onTouchStart.call(null, e);
};
render() {
// TODO In next major version remove the need for findDOMNode by using React.cloneElement here.
// Update documentation to require that the element given to dragHandle is either
// a native DOM element or forwards its props to one.
return React.Children.only(this.props.children);
}
}
| /* @flow */
import React from 'react';
import type {Element as ReactElement} from 'react';
import {findDOMNode} from 'react-dom';
type Props = {
onMouseDown: Function;
onTouchStart: Function;
children: ReactElement<any>;
};
export default class DragHandle extends React.Component<Props> {
componentDidMount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.addEventListener('mousedown', this._onMouseDown);
node.addEventListener('touchstart', this._onTouchStart);
}
componentWillUnmount() {
const node = findDOMNode(this);
if (!node) throw new Error('DragHandle missing element');
node.removeEventListener('mousedown', this._onMouseDown);
node.removeEventListener('touchstart', this._onTouchStart);
}
_onMouseDown: Function = (e) => {
this.props.onMouseDown.call(null, e);
};
_onTouchStart: Function = (e) => {
this.props.onTouchStart.call(null, e);
};
render() {
return React.Children.only(this.props.children);
}
}
|
Check that GA is defined | $(document).ready(function () {
$("table.sortable").stupidtable();
$(document).on("click", "table tr", function (evt) {
var url = $(this).attr("data-url"),
type = $(this).attr("data-type"),
links = $(this).find("a");
if (typeof url === "undefined" || typeof type === "undefined")
return;
evt.preventDefault();
if (type === "folder" || type === "parent-folder") {
window.location.href = url;
}
else if (type === "image") {
links.first().ekkoLightbox({
always_show_close: false,
loadingMessage: '<div class="text-center"><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw margin-bottom"></i><span class="sr-only">Loading...</span></div>'
});
} else if (typeof(ga) != "undefined"){
ga('send', 'event', 'Download', type, url);
window.location.href = url;
}
});
}); | $(document).ready(function () {
$("table.sortable").stupidtable();
$(document).on("click", "table tr", function (evt) {
var url = $(this).attr("data-url"),
type = $(this).attr("data-type"),
links = $(this).find("a");
if (typeof url === "undefined" || typeof type === "undefined")
return;
evt.preventDefault();
if (type === "folder" || type === "parent-folder") {
window.location.href = url;
}
else if (type === "image") {
links.first().ekkoLightbox({
always_show_close: false,
loadingMessage: '<div class="text-center"><i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw margin-bottom"></i><span class="sr-only">Loading...</span></div>'
});
} else {
ga('send', 'event', 'Download', type, url);
window.location.href = url;
}
});
}); |
Use keyCode '4' instead of '27' to prevent conflicts in platforms where '27' key code works | if (navigator.userAgent.indexOf('Android') >= 0) {
log = console.log.bind(console)
log("Android detected")
exports.core.vendor = "google"
exports.core.device = 2
exports.core.os = "android"
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
37: 'Left',
32: 'Space',
38: 'Up',
39: 'Right',
40: 'Down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
179: 'Pause',
112: 'Red',
113: 'Green',
114: 'Yellow',
115: 'Blue'
}
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
Object.defineProperty(event, 'keyCode', { get : function() { return 4; } })
document.dispatchEvent(event);
}, false);
} else {
log("'cordova' not defined. 'Back' button will be unhandable. It looks like you forget to include 'cordova.js'")
}
log("Android initialized")
}
| if (navigator.userAgent.indexOf('Android') >= 0) {
log = console.log.bind(console)
log("Android detected")
exports.core.vendor = "google"
exports.core.device = 2
exports.core.os = "android"
exports.core.keyCodes = {
4: 'Back',
13: 'Select',
27: 'Back',
37: 'Left',
32: 'Space',
38: 'Up',
39: 'Right',
40: 'Down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
179: 'Pause',
112: 'Red',
113: 'Green',
114: 'Yellow',
115: 'Blue'
}
if (window.cordova) {
document.addEventListener("backbutton", function(e) {
var event = new KeyboardEvent("keydown", { bubbles : true });
Object.defineProperty(event, 'keyCode', { get : function() { return 27; } })
document.dispatchEvent(event);
}, false);
} else {
log("'cordova' not defined. 'Back' button will be unhandable. It looks like you forget to include 'cordova.js'")
}
log("Android initialized")
}
|
Remove is_null() calls and use require_once
* Change is_null() in "=== null" to be consistant with "!== null" in
codebase (as a bonus, it's faster (no function call))
* Use require_once instead of require (also marginally faster)
* Remove parenthesis from require_once calls, as it's a language
construct
* Use null coalescing operator to improve readability | <?php
use Lit\Voltage\AbstractAction;
use Lit\Voltage\App;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\ResponseFactory;
use Zend\Diactoros\ServerRequestFactory;
use Zend\HttpHandlerRunner\Emitter\SapiEmitter;
// @codeCoverageIgnoreStart
/** @noinspection PhpIncludeInspection */
require_once __DIR__ . '/../vendor/autoload.php';
class HelloAction extends AbstractAction
{
public function __construct()
{
$this->responseFactory = new ResponseFactory();
}
protected function main(): ResponseInterface
{
return $this->json()->render([
'hello' => 'world',
'method' => $this->request->getMethod(),
'uri' => $this->request->getUri()->__toString(),
]);
}
}
$app = new App(new HelloAction());
$request = ServerRequestFactory::fromGlobals();
$response = $app->handle($request);
$emitter = new SapiEmitter();
$emitter->emit($response);
// @codeCoverageIgnoreEnd
| <?php
use Lit\Voltage\AbstractAction;
use Lit\Voltage\App;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\ResponseFactory;
use Zend\Diactoros\ServerRequestFactory;
use Zend\HttpHandlerRunner\Emitter\SapiEmitter;
// @codeCoverageIgnoreStart
/** @noinspection PhpIncludeInspection */
require(__DIR__ . '/../vendor/autoload.php');
class HelloAction extends AbstractAction
{
public function __construct()
{
$this->responseFactory = new ResponseFactory();
}
protected function main(): ResponseInterface
{
return $this->json()->render([
'hello' => 'world',
'method' => $this->request->getMethod(),
'uri' => $this->request->getUri()->__toString(),
]);
}
}
$app = new App(new HelloAction());
$request = ServerRequestFactory::fromGlobals();
$response = $app->handle($request);
$emitter = new SapiEmitter();
$emitter->emit($response);
// @codeCoverageIgnoreEnd
|
Fix instructions in 'react-native init'
Summary: This was buggy and didn't print the folder we need to cd into.
Reviewed By: mkonicek
Differential Revision:
D4313396
Ninja: OSS only
fbshipit-source-id: 0e15baf818065b63e939def60a1366e2251aac7d | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var chalk = require('chalk');
var path = require('path');
function printRunInstructions(projectDir, projectName) {
const absoluteProjectDir = path.resolve(projectDir);
// iOS
const xcodeProjectPath = path.resolve(projectDir, 'ios', projectName) + '.xcodeproj';
const relativeXcodeProjectPath = path.relative(process.cwd(), xcodeProjectPath);
console.log(chalk.white.bold('To run your app on iOS:'));
console.log(' cd ' + absoluteProjectDir);
console.log(' react-native run-ios');
console.log(' - or -');
console.log(' Open ' + relativeXcodeProjectPath + ' in Xcode');
console.log(' Hit the Run button');
// Android
console.log(chalk.white.bold('To run your app on Android:'));
console.log(' cd ' + absoluteProjectDir);
console.log(' Have an Android emulator running (quickest way to get started), or a device connected');
console.log(' react-native run-android');
}
module.exports = printRunInstructions;
| /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var chalk = require('chalk');
var path = require('path');
function printRunInstructions(projectDir, projectName) {
const absoluteProjectDir = path.resolve(projectDir);
const relativeProjectDir = path.relative(process.cwd(), absoluteProjectDir);
// If we're in the project directory already, no need to 'cd' into it
const needToCd = !!relativeProjectDir;
// iOS
const xcodeProjectPath = path.resolve(projectDir, 'ios', projectName) + '.xcodeproj';
const relativeXcodeProjectPath = path.relative(process.cwd(), xcodeProjectPath);
console.log(chalk.white.bold('To run your app on iOS:'));
if (needToCd) { console.log(' cd ' + relativeProjectDir); }
console.log(' react-native run-ios');
console.log(' - or -');
console.log(' Open ' + relativeXcodeProjectPath + ' in Xcode');
console.log(' Hit the Run button');
// Android
console.log(chalk.white.bold('To run your app on Android:'));
console.log(' Have an Android emulator running (quickest way to get started), or a device connected');
if (needToCd) { console.log(' cd ' + relativeProjectDir); }
console.log(' react-native run-android');
}
module.exports = printRunInstructions;
|
Remove unused code for monkeyed methods | from zope.interface import implements
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
| from zope.interface import implements
#from Products.Archetypes.CatalogMultiplex import CatalogMultiplex
#from Products.CMFCore.CMFCatalogAware import CMFCatalogAware
from zerodb.collective.indexing.interfaces import IIndexQueueProcessor
# container to hold references to the original and "monkeyed" indexing methods
# these are populated by `collective.indexing.monkey`
catalogMultiplexMethods = {}
catalogAwareMethods = {}
monkeyMethods = {}
def getOwnIndexMethod(obj, name):
""" return private indexing method if the given object has one """
attr = getattr(obj.__class__, name, None)
if attr is not None:
method = attr.im_func
monkey = monkeyMethods.get(name.rstrip('Object'), None)
if monkey is not None and method is not monkey:
return method
class IPortalCatalogQueueProcessor(IIndexQueueProcessor):
""" an index queue processor for the standard portal catalog via
the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """
class PortalCatalogProcessor(object):
implements(IPortalCatalogQueueProcessor)
def index(self, obj, attributes=None):
#index(obj, attributes)
pass
def reindex(self, obj, attributes=None):
#reindex(obj, attributes)
pass
def unindex(self, obj):
#unindex(obj)
pass
def begin(self):
pass
def commit(self):
pass
def abort(self):
pass
|
timing: Remove fractional ms in diagnostics screen.
endMs and startMs are created by Date.now(), which has a precision
of ±1 ms. Don't suggest a precision that we don't have. Remove all
fractional digits. | /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, View } from 'react-native';
import format from 'date-fns/format';
import type { TimingItemType } from '../types';
import { RawLabel } from '../common';
import { numberWithSeparators } from '../utils/misc';
const styles = StyleSheet.create({
item: {
padding: 16,
borderBottomWidth: 1,
borderColor: 'rgba(127, 127, 127, 0.25)',
},
label: {
fontWeight: 'bold',
},
value: {
opacity: 0.9,
},
});
export default class TimeItem extends PureComponent<TimingItemType> {
props: TimingItemType;
render() {
const { text, startMs, endMs } = this.props;
const startStr = format(startMs, 'HH:mm:ss.S'); // eslint-disable-line
const durationStrMs = numberWithSeparators(endMs - startMs);
const timingStr = `Start: ${startStr} Duration: ${durationStrMs} ms`;
return (
<View style={styles.item}>
<RawLabel style={styles.label} text={text} />
<RawLabel style={styles.value} text={timingStr} />
</View>
);
}
}
| /* @flow */
import React, { PureComponent } from 'react';
import { StyleSheet, View } from 'react-native';
import format from 'date-fns/format';
import type { TimingItemType } from '../types';
import { RawLabel } from '../common';
import { numberWithSeparators } from '../utils/misc';
const styles = StyleSheet.create({
item: {
padding: 16,
borderBottomWidth: 1,
borderColor: 'rgba(127, 127, 127, 0.25)',
},
label: {
fontWeight: 'bold',
},
value: {
opacity: 0.9,
},
});
export default class TimeItem extends PureComponent<TimingItemType> {
props: TimingItemType;
render() {
const { text, startMs, endMs } = this.props;
const startStr = format(startMs, 'HH:mm:ss.S'); // eslint-disable-line
const durationStrMs = numberWithSeparators((endMs - startMs).toFixed(2));
const timingStr = `Start: ${startStr} Duration: ${durationStrMs} ms`;
return (
<View style={styles.item}>
<RawLabel style={styles.label} text={text} />
<RawLabel style={styles.value} text={timingStr} />
</View>
);
}
}
|
Simplify action type generation code | // This function generates the five statuses from a single CRUD action.
// For instance, you'd probably pass "CREATE", "READ", "UPDATE", or "DELETE"
// as `crudAction`.
const mapConstant = (crudAction) => ({
[`${crudAction}_RESOURCES`]: `${crudAction}_RESOURCES`,
[`${crudAction}_RESOURCES_SUCCEED`]: `${crudAction}_RESOURCES_SUCCEED`,
[`${crudAction}_RESOURCES_FAIL`]: `${crudAction}_RESOURCES_FAIL`,
[`${crudAction}_RESOURCES_NULL`]: `${crudAction}_RESOURCES_NULL`,
});
const createTypes = mapConstant('CREATE');
const readTypes = mapConstant('READ');
const updateTypes = mapConstant('UPDATE');
const deleteTypes = mapConstant('DELETE');
export default {
...createTypes,
...readTypes,
...updateTypes,
...deleteTypes
};
| // This function generates the five statuses from a single CRUD action.
// For instance, you'd probably pass "CREATE", "READ", "UPDATE", or "DELETE"
// as `crudAction`.
const mapConstant = (resourceName, crudAction) => ({
[`${crudAction}_${resourceName}`]: `${crudAction}_${resourceName}`,
[`${crudAction}_${resourceName}_SUCCEED`]: `${crudAction}_${resourceName}_SUCCEED`,
[`${crudAction}_${resourceName}_FAIL`]: `${crudAction}_${resourceName}_FAIL`,
[`${crudAction}_${resourceName}_NULL`]: `${crudAction}_${resourceName}_NULL`,
});
const createTypes = mapConstant('RESOURCES', 'CREATE');
const readTypes = mapConstant('RESOURCES', 'READ');
const updateTypes = mapConstant('RESOURCES', 'UPDATE');
const deleteTypes = mapConstant('RESOURCES', 'DELETE');
export default {
...createTypes,
...readTypes,
...updateTypes,
...deleteTypes
};
|
Handle writing exceptions that don't have log_exception attribute | import types
from cyclone import escape
from cyclone import web
class OONIBHandler(web.RequestHandler):
def write_error(self, status_code, exception=None, **kw):
self.set_status(status_code)
if hasattr(exception, 'log_message'):
self.write({'error': exception.log_message})
else:
self.write({'error': 'error'})
def write(self, chunk):
"""
This is a monkey patch to RequestHandler to allow us to serialize also
json list objects.
"""
if isinstance(chunk, types.ListType):
chunk = escape.json_encode(chunk)
web.RequestHandler.write(self, chunk)
self.set_header("Content-Type", "application/json")
else:
web.RequestHandler.write(self, chunk)
| import types
from cyclone import escape
from cyclone import web
class OONIBHandler(web.RequestHandler):
def write_error(self, status_code, exception=None, **kw):
self.set_status(status_code)
if exception:
self.write({'error': exception.log_message})
def write(self, chunk):
"""
This is a monkey patch to RequestHandler to allow us to serialize also
json list objects.
"""
if isinstance(chunk, types.ListType):
chunk = escape.json_encode(chunk)
web.RequestHandler.write(self, chunk)
self.set_header("Content-Type", "application/json")
else:
web.RequestHandler.write(self, chunk)
|
doc: Add basic doc to Neural entities | from Entity import *
class NeuralEntity(Entity):
"""Entity the represents timestamps of action potentials, i.e. spike times.
Cutouts of the waveforms corresponding to spike data in a neural entity
might be found in a separate :class:`SegmentEntity` (cf. :func:`source_entity_id`).
"""
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
"""[**Optional**] Id of the source entity of this spike, if any.
For example the spike waveform of the action potential corresponding
to this spike might have been recoreded in a segment entity."""
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
"""Retrieve the spike times associated with this entity. A subset
of the data can be requested via the ``inde`` and ``count``
parameters."""
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
| from Entity import *
class NeuralEntity(Entity):
def __init__(self, nsfile, eid, info):
super(NeuralEntity,self).__init__(eid, nsfile, info)
@property
def probe_info(self):
return self._info['ProbeInfo']
@property
def source_entity_id(self):
return self._info['SourceEntityID']
@property
def source_unit_id(self):
return self._info['SourceUnitID']
def get_data (self, index=0, count=-1):
lib = self.file.library
if count < 0:
count = self.item_count
data = lib._get_neural_data (self, index, count)
return data
|
fix(build): Fix template literal issue with underscore templates. | const rollupBabel = require('rollup-plugin-babel');
const rollupCommonjs = require('rollup-plugin-commonjs');
const rollupNodeResolve = require('rollup-plugin-node-resolve');
const rollupUglify = require('rollup-plugin-uglify');
const path = require('path');
const pkg = require(path.join(process.cwd(), 'package.json'));
const shouldMinify = process.argv.indexOf('--min') !== -1;
const presetEs2015 = require('babel-preset-es2015-rollup');
const babel = rollupBabel({
presets: presetEs2015,
});
const plugins = [
babel,
rollupCommonjs(),
rollupNodeResolve(),
];
if (shouldMinify) {
plugins.push(rollupUglify());
}
const entry = pkg['jsnext:main'] || pkg.main || 'src/index.js';
const moduleName = pkg['build:global'] || pkg.name;
module.exports = {
dest: 'dist/index' + (shouldMinify ? '.min' : '') + '.js',
entry,
exports: 'named',
format: 'umd',
moduleName,
plugins,
sourceMap: true,
useStrict: false,
};
| const rollupBabel = require('rollup-plugin-babel');
const rollupCommonjs = require('rollup-plugin-commonjs');
const rollupNodeResolve = require('rollup-plugin-node-resolve');
const rollupUglify = require('rollup-plugin-uglify');
const path = require('path');
const pkg = require(path.join(process.cwd(), 'package.json'));
const shouldMinify = process.argv.indexOf('--min') !== -1;
const presetEs2015 = require('babel-preset-es2015-rollup');
const babel = rollupBabel({
presets: presetEs2015,
});
const plugins = [
babel,
rollupCommonjs(),
rollupNodeResolve(),
];
if (shouldMinify) {
plugins.push(rollupUglify());
}
const entry = pkg['jsnext:main'] || pkg.main || 'src/index.js';
const moduleName = pkg['build:global'] || pkg.name;
module.exports = {
dest: `dist/index${shouldMinify ? '.min' : ''}.js`,
entry,
exports: 'named',
format: 'umd',
moduleName,
plugins,
sourceMap: true,
useStrict: false,
};
|
Copy role doesn't work, need to manually copy the link target | const remote = require('electron').remote;
const clipboard = require('electron').clipboard;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
module.exports = {
build: function(target) {
var template = [
{
label: 'Copy Link Address',
click: function (e, focusedWindow) {
clipboard.writeText(target.href);
}
}
];
if (process.platform == 'darwin') {
template = [...template,
{
type: 'separator'
},
{
label: 'Services',
role: 'services',
submenu: []
}
];
}
return Menu.buildFromTemplate(template);
}
};
| const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
module.exports = {
build: function(target) {
var template = [
{
label: 'Copy Link Address',
role: 'copy'
}
];
if (process.platform == 'darwin') {
template = [...template,
{
type: 'separator'
},
{
label: 'Services',
role: 'services',
submenu: []
}
];
}
return Menu.buildFromTemplate(template);
}
};
|
Change scrolling directive. It doesn't require separate element to scroll to. | angular.module('codebrag.commits')
.directive('scrollCommitsList', function(events) {
return {
restrict: 'A',
link: function(scope, el) {
scope.$on(events.nextCommitsLoaded, function() {
el.animate({scrollTop: el[0].scrollHeight});
});
scope.$on(events.previousCommitsLoaded, function() {
el.animate({scrollTop: 0});
})
}
}
}); | angular.module('codebrag.commits')
.directive('scrollCommitsList', function(events) {
var idToScrollTo = '#commits-list-end';
return {
restrict: 'A',
link: function(scope, el) {
scope.$on(events.moreCommitsLoaded, function() {
var options = {
duration: 1000,
easing:'easeOutCirc'
};
el.scrollTo(el.find(idToScrollTo), options);
})
}
}
}); |
Address flag validation for tank format | package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"github.com/coxx/es-slowlog/internal/parser"
)
func main() {
const defaultFormat = "{{.Source}}"
stderr := log.New(os.Stderr, "", 0)
flagUsage := flag.Bool("h", false, "Print usage")
flagFormat := flag.String("f", defaultFormat, "Format template")
flagAddress := flag.String("a", "", "Target address")
flag.Parse()
if *flagUsage {
flag.Usage()
os.Exit(1)
}
if (*flagFormat == "vegeta" || *flagFormat == "tank") && *flagAddress == "" {
stderr.Fatalln("Target address should be specified")
}
formater, err := newFormater(*flagFormat, *flagAddress)
if err != nil {
stderr.Fatalf("Bad format: %v\n", err)
}
parser := parser.New(os.Stdin)
for {
logRecord, err := parser.Parse()
if err == io.EOF {
break
}
if err != nil {
stderr.Fatalf("Can't parse input: %v\n", err)
}
s, err := formater(logRecord)
if err != nil {
stderr.Fatalln(err)
}
fmt.Println(s)
}
}
| package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"github.com/coxx/es-slowlog/internal/parser"
)
func main() {
const defaultFormat = "{{.Source}}"
stderr := log.New(os.Stderr, "", 0)
flagUsage := flag.Bool("h", false, "Print usage")
flagFormat := flag.String("f", defaultFormat, "Format template")
flagAddress := flag.String("a", "", "Target address")
flag.Parse()
if *flagUsage {
flag.Usage()
os.Exit(1)
}
if *flagFormat == "vegeta" && *flagAddress == "" {
stderr.Fatalln("Target address should be specified")
}
formater, err := newFormater(*flagFormat, *flagAddress)
if err != nil {
stderr.Fatalf("Bad format: %v\n", err)
}
parser := parser.New(os.Stdin)
for {
logRecord, err := parser.Parse()
if err == io.EOF {
break
}
if err != nil {
stderr.Fatalf("Can't parse input: %v\n", err)
}
s, err := formater(logRecord)
if err != nil {
stderr.Fatalln(err)
}
fmt.Println(s)
}
}
|
Decrease example timeout timers to 1000
Mocha tests will timeout if timers are set to 2000. | import * as types from '../constants/error';
/**
* @function rejectPromiseWithGlobalError ✨
* @description This function demonstrates how to handle a rejected
* promise "globally" in the middleware.
* @param message {string} the error message
* @returns {object}
*/
export const rejectPromiseWithGlobalError = message => dispatch => dispatch({
type: types.GLOBAL_ERROR,
payload: new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(message))
}, 1000);
})
}).catch(error => {
// There is nothing to catch at the action creator because an error middleware handles it
});
/**
* @function throwLocalError ✨
* @description This function demonstrates how to handle a rejected
* promise locally in the action creator.
* @param message {string} the error message
* @returns {object} the promise
*/
export const rejectPromiseWithLocalError = message => dispatch => dispatch({
type: types.LOCAL_ERROR,
payload: new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(message))
}, 1000);
})
}).catch(error => {
console.warn(`${types.LOCAL_ERROR} caught at action creator with reason: ${JSON.stringify(error.message)}.`);
});
| import * as types from '../constants/error';
/**
* @function rejectPromiseWithGlobalError ✨
* @description This function demonstrates how to handle a rejected
* promise "globally" in the middleware.
* @param message {string} the error message
* @returns {object}
*/
export const rejectPromiseWithGlobalError = message => dispatch => dispatch({
type: types.GLOBAL_ERROR,
payload: new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(message))
}, 2000);
})
}).catch(error => {
// There is nothing to catch at the action creator because an error middleware handles it
});
/**
* @function throwLocalError ✨
* @description This function demonstrates how to handle a rejected
* promise locally in the action creator.
* @param message {string} the error message
* @returns {object} the promise
*/
export const rejectPromiseWithLocalError = message => dispatch => dispatch({
type: types.LOCAL_ERROR,
payload: new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(message))
}, 2000);
})
}).catch(error => {
console.warn(`${types.LOCAL_ERROR} caught at action creator with reason: ${JSON.stringify(error.message)}.`);
});
|
Add update_reservation to dummy plugin
update_reservation is now an abstract method. It needs to be added to
all plugins.
Change-Id: I921878bd5233613b804b17813af1aac5bdfed9e7 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from blazar.plugins import base
class DummyVMPlugin(base.BasePlugin):
"""Plugin for VM resource that does nothing."""
resource_type = 'virtual:instance'
title = 'Dummy VM Plugin'
description = 'This plugin does nothing.'
def reserve_resource(self, reservation_id, values):
return None
def update_reservation(self, reservation_id, values):
return None
def on_start(self, resource_id):
"""Dummy VM plugin does nothing."""
return 'VM %s should be waked up this moment.' % resource_id
def on_end(self, resource_id):
"""Dummy VM plugin does nothing."""
return 'VM %s should be deleted this moment.' % resource_id
| # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from blazar.plugins import base
class DummyVMPlugin(base.BasePlugin):
"""Plugin for VM resource that does nothing."""
resource_type = 'virtual:instance'
title = 'Dummy VM Plugin'
description = 'This plugin does nothing.'
def reserve_resource(self, reservation_id, values):
return None
def on_start(self, resource_id):
"""Dummy VM plugin does nothing."""
return 'VM %s should be waked up this moment.' % resource_id
def on_end(self, resource_id):
"""Dummy VM plugin does nothing."""
return 'VM %s should be deleted this moment.' % resource_id
|
Add limit of 6(arbitrary) to each key in Active Errors | Meteor.methods({
'logKeyError': function (keyID, vCode, errorType, message) {
Errors.update(
{ keyID: keyID },
{
$set: {
keyID: keyID,
vCode: vCode
},
$addToSet: {
log: {
errorType: errorType,
message: message
}
}
},
{
upsert: true,
validate: false
}
);
Errors.update(
{keyID: keyID},
{
$push: {
log:{
$each: [],
$slice: -6
}
}
}
);
console.log("Key " + keyID + " with vCode " + vCode + " threw the following error:");
console.log("[" + errorType + "] " + message);
}
});
| Meteor.methods({
'logKeyError': function (keyID, vCode, errorType, message) {
Errors.update(
{ keyID: keyID },
{
$set: {
keyID: keyID,
vCode: vCode
},
$addToSet: {
log: {
errorType: errorType,
message: message
}
}
},
{
upsert: true,
validate: false
});
console.log("Key " + keyID + " with vCode " + vCode + " threw the following error:");
console.log("[" + errorType + "] " + message);
}
});
|
Add comment for event state | /*
* Copyright 2017 Axway Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.axway.ats.log.autodb.events;
import org.apache.log4j.Logger;
import com.axway.ats.log.autodb.LifeCycleState;
import com.axway.ats.log.autodb.model.AbstractLoggingEvent;
import com.axway.ats.log.autodb.model.LoggingEventType;
@SuppressWarnings( "serial")
public class EndAfterClassEvent extends AbstractLoggingEvent {
public EndAfterClassEvent( String loggerFQCN, Logger logger ) {
super(loggerFQCN, logger, "End after class execution", LoggingEventType.END_AFTER_CLASS);
}
@Override
protected LifeCycleState getExpectedLifeCycleState( LifeCycleState state ) {
/* This event is fired after a suite is already closed,
since ATS (AtsTestngListener) could not be certain that @AfterClass will be available
*/
return LifeCycleState.ATLEAST_RUN_STARTED;
}
}
| /*
* Copyright 2017 Axway Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.axway.ats.log.autodb.events;
import org.apache.log4j.Logger;
import com.axway.ats.log.autodb.LifeCycleState;
import com.axway.ats.log.autodb.model.AbstractLoggingEvent;
import com.axway.ats.log.autodb.model.LoggingEventType;
@SuppressWarnings( "serial")
public class EndAfterClassEvent extends AbstractLoggingEvent {
public EndAfterClassEvent( String loggerFQCN, Logger logger ) {
super(loggerFQCN, logger, "End after class execution", LoggingEventType.END_AFTER_CLASS);
}
@Override
protected LifeCycleState getExpectedLifeCycleState( LifeCycleState state ) {
return LifeCycleState.ATLEAST_RUN_STARTED;
}
}
|
Change engine fixture to use db obj | import os.path
import pytest
from alembic.command import upgrade
from alembic.config import Config
from app.database import db as _db
from app.database import create_engine, create_db_session
from app.models import Base
HERE = os.path.dirname(os.path.abspath(__file__))
ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini")
def apply_migrations(engine):
"""Applies all alembic migrations."""
from alembic.config import Config
from alembic import command
alembic_cfg = Config(ALEMBIC_CONFIG)
with engine.begin() as connection:
alembic_cfg.attributes['connection'] = connection
command.upgrade(alembic_cfg, "head")
@pytest.fixture(scope='session')
def db(request):
"""Session-wide test database."""
# create a SQLite DB in memory
_db.engine = create_engine("sqlite://")
# setup models in DB
Base.metadata.create_all(_db.engine)
return _db
@pytest.fixture(scope='function')
def session(db, request):
"""Creates a new database session for a test."""
_session = create_db_session(db.engine)
connection = db.engine.connect()
transaction = connection.begin()
def fin():
transaction.rollback()
connection.close()
request.addfinalizer(fin)
return _session
| import os.path
import pytest
from alembic.command import upgrade
from alembic.config import Config
from app.database import sa, create_engine, create_db_session
from app.models import Base
HERE = os.path.dirname(os.path.abspath(__file__))
ALEMBIC_CONFIG = os.path.join(HERE, "..", "..", "alembic.ini")
def apply_migrations(engine):
"""Applies all alembic migrations."""
from alembic.config import Config
from alembic import command
alembic_cfg = Config(ALEMBIC_CONFIG)
with engine.begin() as connection:
alembic_cfg.attributes['connection'] = connection
command.upgrade(alembic_cfg, "head")
@pytest.fixture(scope='session')
def engine(request):
"""Session-wide test database."""
# create a SQLite DB in memory
_engine = create_engine("sqlite://")
# setup models in DB
Base.metadata.create_all(_engine)
return _engine
@pytest.fixture(scope='function')
def session(engine, request):
"""Creates a new database session for a test."""
_session = create_db_session(engine)
connection = engine.connect()
transaction = connection.begin()
def fin():
transaction.rollback()
connection.close()
request.addfinalizer(fin)
return _session
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.