text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
:hammer: Rename nonceGenerator() method to getNonceGenerator(). | <?php
namespace Risan\OAuth1\Request;
interface RequestBuilderInterface
{
/**
* Get the ConfigInterface instance.
*
* @return \Risan\OAuth1\ConfigInterface
*/
public function getConfig();
/**
* Get the SignerInterface instance.
*
* @return \Risan\OAuth1\Signature\SignerInterface
*/
public function getSigner();
/**
* Get the NonceGeneratorInterface instance.
*
* @return \Risan\OAuth1\Request\NonceGeneratorInterface
*/
public function getNonceGenerator();
/**
* Get current timestamp in seconds since Unix Epoch.
*
* @return string
*/
public function getCurrentTimestamp();
/**
* Get url for obtaining temporary credentials.
*
* @return string
*/
public function getTemporaryCredentialsUrl();
/**
* Get authorization header for obtaining temporary credentials.
*
* @return string
*/
public function getTemporaryCredentialsAuthorizationHeader();
}
| <?php
namespace Risan\OAuth1\Request;
interface RequestBuilderInterface
{
/**
* Get the ConfigInterface instance.
*
* @return \Risan\OAuth1\ConfigInterface
*/
public function getConfig();
/**
* Get the SignerInterface instance.
*
* @return \Risan\OAuth1\Signature\SignerInterface
*/
public function getSigner();
/**
* Get the NonceGeneratorInterface instance.
*
* @return \Risan\OAuth1\Request\NonceGeneratorInterface
*/
public function nonceGenerator();
/**
* Get current timestamp in seconds since Unix Epoch.
*
* @return string
*/
public function getCurrentTimestamp();
/**
* Get url for obtaining temporary credentials.
*
* @return string
*/
public function getTemporaryCredentialsUrl();
/**
* Get authorization header for obtaining temporary credentials.
*
* @return string
*/
public function getTemporaryCredentialsAuthorizationHeader();
}
|
Fix: Test missing checking for InvalidOrderException raised | # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
from mmvdApp.utils import InvalidOrderException
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
with pytest.raises(InvalidOrderException):
valid_solution(states1[0:-1], order, drop_zone1)
| # coding: utf-8
import pytest
from mmvdApp.utils import objective_function
from mmvdApp.utils import valid_solution
@pytest.mark.utils
@pytest.mark.linprog
def test_objective_function(states1):
"""
Test if ``utils.linprog.objective_function`` correctly calculates expected
objective function value.
"""
assert objective_function(states1) == 17
@pytest.mark.utils
@pytest.mark.linprog
def test_solution_validity(states1, order1, drop_zone1):
"""
Test if ``utils.linprog.valid_solution`` correctly checks for valid
solution.
"""
# cut order in half because states1 is intended only for first 3 products
order = order1[0:3]
assert valid_solution(states1, order, drop_zone1)
# check for valid solution when one product isn't returned
assert not valid_solution(states1[0:-1], order, drop_zone1)
|
Fix 300ms delay for ClickAwayable
Fixes #766 | var React = require('react');
var Events = require('../utils/events');
var Dom = require('../utils/dom');
module.exports = {
//When the component mounts, listen to click events and check if we need to
//Call the componentClickAway function.
componentDidMount: function() {
if (!this.manuallyBindClickAway) this._bindClickAway();
},
componentWillUnmount: function() {
this._unbindClickAway();
},
_checkClickAway: function(e) {
var el = React.findDOMNode(this);
// Check if the target is inside the current component
if (e.target != el &&
!Dom.isDescendant(el, e.target) &&
document.documentElement.contains(e.target)) {
if (this.componentClickAway) this.componentClickAway();
}
},
_bindClickAway: function() {
// On touch-enabled devices, both events fire, and the handler is called twice,
// but it's fine since all operations for which the mixin is used
// are idempotent.
Events.on(document, 'mouseup', this._checkClickAway);
Events.on(document, 'touchend', this._checkClickAway);
},
_unbindClickAway: function() {
Events.off(document, 'mouseup', this._checkClickAway);
Events.off(document, 'touchend', this._checkClickAway);
}
};
| var React = require('react');
var Events = require('../utils/events');
var Dom = require('../utils/dom');
module.exports = {
//When the component mounts, listen to click events and check if we need to
//Call the componentClickAway function.
componentDidMount: function() {
if (!this.manuallyBindClickAway) this._bindClickAway();
},
componentWillUnmount: function() {
this._unbindClickAway();
},
_checkClickAway: function(e) {
var el = React.findDOMNode(this);
// Check if the target is inside the current component
if (e.target != el &&
!Dom.isDescendant(el, e.target) &&
document.documentElement.contains(e.target)) {
if (this.componentClickAway) this.componentClickAway();
}
},
_bindClickAway: function() {
Events.on(document, 'click', this._checkClickAway);
},
_unbindClickAway: function() {
Events.off(document, 'click', this._checkClickAway);
}
};
|
Revert "fix bug import six"
This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb. | from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU"""
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(six.u(txt))
breaks = list(bd)
return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)]
if __name__ == "__main__":
print(segment('ทดสอบระบบตัดคำด้วยไอซียู'))
print(segment('ผมชอบพูดไทยคำ English คำ'))
print(segment('ผมชอบพูดไทยคำEnglishคำ')) | from __future__ import absolute_import,print_function
from itertools import groupby
import PyICU
import six
# ตัดคำภาษาไทย
def segment(txt):
"""รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU"""
bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th"))
bd.setText(six.u(txt))
breaks = list(bd)
return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)]
if __name__ == "__main__":
print(segment('ทดสอบระบบตัดคำด้วยไอซียู'))
print(segment('ผมชอบพูดไทยคำ English คำ'))
print(segment('ผมชอบพูดไทยคำEnglishคำ')) |
Fix compound iterator for case where empty iterators appear in the list. | package org.metaborg.util.iterators;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.google.common.collect.Iterators;
public class CompoundIterator<T> implements Iterator<T> {
private final Iterator<? extends Iterator<T>> iterators;
private Iterator<T> iterator = Iterators.emptyIterator();
public CompoundIterator(Iterable<? extends Iterator<T>> iterators) {
this.iterators = iterators.iterator();
}
@Override public boolean hasNext() {
if(iterator.hasNext()) {
return true;
}
try {
iterator = iterators.next();
} catch(NoSuchElementException ex) {
return false;
}
return hasNext();
}
@Override public T next() {
try {
return iterator.next();
} catch(NoSuchElementException ex) {
iterator = iterators.next();
}
return next();
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
}
| package org.metaborg.util.iterators;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;
import com.google.common.collect.Queues;
public class CompoundIterator<T> implements Iterator<T> {
private final Queue<? extends Iterator<T>> iterators;
public CompoundIterator(Iterable<? extends Iterator<T>> iterators) {
this.iterators = Queues.newArrayDeque(iterators);
}
@Override public boolean hasNext() {
final Iterator<T> iterator = iterators.peek();
if(iterator == null) {
return false;
}
return iterator.hasNext();
}
@Override public T next() {
final Iterator<T> iterator = iterators.peek();
if(iterator == null) {
throw new NoSuchElementException();
}
if(iterator.hasNext()) {
return iterator.next();
} else {
iterators.poll();
return next();
}
}
@Override public void remove() {
throw new UnsupportedOperationException();
}
}
|
Remove unnecessary logs and comments (used for debugging) | function solvePassword() {
$(".js-mod-passwords .js-mod-passwords-word").each(function() {
wordOfInput = $(this).attr('js-data-word');
arrayOfWordInput = wordOfInput.split('');
compareArray = [];
for (var i = 0; i < arrayOfWordInput.length; i++) {
compareArray.push(compareWithInput(arrayOfWordInput[i], i));
};
if (compareArray.indexOf('found') > -1 &&
compareArray.indexOf('not-found') == -1) {
$(this).removeClass('js-word-inactive');
$(this).addClass('js-word-active');
} else {
$(this).removeClass('js-word-active');
$(this).addClass('js-word-inactive');
}
});
}
function compareWithInput(char, inputIndex) {
var currentInputValArray = $('.js-mod-passwords .js-mod-passwords-input:eq('+inputIndex+')').val().split('');
if (currentInputValArray.length == 0) {
var result = 'empty'
} else if (currentInputValArray.indexOf(char) > -1) {
var result = 'found'
} else {
var result = 'not-found'
}
return result;
}
$('.js-mod-passwords .js-mod-passwords-input').keyup(function(){
solvePassword();
});
| function solvePassword() {
$(".js-mod-passwords .js-mod-passwords-word").each(function() {
wordOfInput = $(this).attr('js-data-word');
arrayOfWordInput = wordOfInput.split('');
compareArray = [];
for (var i = 0; i < arrayOfWordInput.length; i++) {
compareArray.push(compareWithInput(arrayOfWordInput[i], i));
};
if (compareArray.indexOf('found') > -1 &&
compareArray.indexOf('not-found') == -1) {
$(this).removeClass('js-word-inactive');
$(this).addClass('js-word-active');
} else {
$(this).removeClass('js-word-active');
$(this).addClass('js-word-inactive');
}
console.log(compareArray);
});
}
function compareWithInput(char, inputIndex) {
var currentInputValArray = $('.js-mod-passwords .js-mod-passwords-input:eq('+inputIndex+')').val().split('');
if (currentInputValArray.length == 0) {
var result = 'empty'
// console.log('input '+inputIndex+' vazio');
} else if (currentInputValArray.indexOf(char) > -1) {
var result = 'found'
// console.log("char "+char+" encontrado no input "+inputIndex);
} else {
var result = 'not-found'
// console.log("char "+char+" não encontrado no input "+inputIndex);
}
return result;
}
$('.js-mod-passwords .js-mod-passwords-input').keyup(function(){
solvePassword();
});
|
Add email address to registration script output | from competition.models import (Competition, RegistrationQuestion,
RegistrationQuestionResponse)
import csv
import StringIO
def run():
shirt = RegistrationQuestion.objects.filter(question__contains="shirt")
for c in Competition.objects.all().order_by('start_time'):
print c.name
csv_content = StringIO.StringIO()
writer = csv.writer(csv_content)
for r in c.registration_set.filter(active=True).order_by('signup_date'):
try:
size = r.response_set.get(question=shirt).choices.get().choice
except RegistrationQuestionResponse.DoesNotExist:
size = None
writer.writerow([r.signup_date,
r.user.username,
r.user.get_full_name(),
r.user.email,
size])
print csv_content.getvalue()
| from competition.models import (Competition, RegistrationQuestion,
RegistrationQuestionResponse)
import csv
import StringIO
def run():
shirt = RegistrationQuestion.objects.filter(question__contains="shirt")
for c in Competition.objects.all().order_by('start_time'):
print c.name
csv_content = StringIO.StringIO()
writer = csv.writer(csv_content)
for r in c.registration_set.filter(active=True).order_by('signup_date'):
try:
size = r.response_set.get(question=shirt).choices.get().choice
except RegistrationQuestionResponse.DoesNotExist:
size = None
writer.writerow([r.signup_date,
r.user.username,
r.user.get_full_name(),
size])
print csv_content.getvalue()
|
BUG: Fix nose call so tests run in __main__. | """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
| """Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
Move event alias mappings to their components. | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
final class AuthenticationEvents
{
/**
* The AUTHENTICATION_SUCCESS event occurs after a user is authenticated
* by one provider.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent")
*/
const AUTHENTICATION_SUCCESS = 'security.authentication.success';
/**
* The AUTHENTICATION_FAILURE event occurs after a user cannot be
* authenticated by any of the providers.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationFailureEvent")
*/
const AUTHENTICATION_FAILURE = 'security.authentication.failure';
/**
* Event aliases.
*
* These aliases can be consumed by RegisterListenersPass.
*/
const ALIASES = [
AuthenticationSuccessEvent::class => self::AUTHENTICATION_SUCCESS,
AuthenticationFailureEvent::class => self::AUTHENTICATION_FAILURE,
];
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core;
final class AuthenticationEvents
{
/**
* The AUTHENTICATION_SUCCESS event occurs after a user is authenticated
* by one provider.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent")
*/
const AUTHENTICATION_SUCCESS = 'security.authentication.success';
/**
* The AUTHENTICATION_FAILURE event occurs after a user cannot be
* authenticated by any of the providers.
*
* @Event("Symfony\Component\Security\Core\Event\AuthenticationFailureEvent")
*/
const AUTHENTICATION_FAILURE = 'security.authentication.failure';
}
|
Make interface name optional and remove unicode prefixes | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField("Besitzer-ID")
name = TextField("Name", validators=[Optional()],
description="z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField("Name",
description="z.B. eth0, en0 oder enp0s29u1u1u5",
validators=[Optional()])
mac = MacField("MAC", [MacAddress(message="MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
| from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField(u"Besitzer-ID")
name = TextField(u"Name", validators=[Optional()],
description=u"z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField(u"Name",description=u"z.B. eth0, en0 oder enp0s29u1u1u5")
mac = MacField(u"MAC", [MacAddress(message=u"MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
|
Hide new / delete button on welcome page | /**
* garp.welcomepanel.js
*
* Convenience Class, creates a panel with a message from HTML markup in de view.
*
* @class Garp.WelcomePanel
* @extends Panel
* @author Peter
*/
Garp.WelcomePanel = function(cfg){
this.html = Ext.getDom('welcome-panel-content').innerHTML;
Garp.WelcomePanel.superclass.constructor.call(this, cfg);
};
Ext.extend(Garp.WelcomePanel, Ext.Container, {
border: true,
hideButtonArr: ['newButton', 'deleteButton', 'separator'],
listeners: {
'render': function () {
Ext.each(this.hideButtonArr, function(item){
Garp.toolbar[item].hide();
});
},
'destroy': function () {
Ext.each(this.hideButtonArr, function(item){
Garp.toolbar[item].show();
});
}
}
});
| /**
* garp.welcomepanel.js
*
* Convenience Class, creates a panel with a message from HTML markup in de view.
*
* @class Garp.WelcomePanel
* @extends Panel
* @author Peter
*/
Garp.WelcomePanel = function(cfg){
this.html = Ext.getDom('welcome-panel-content').innerHTML;
Garp.WelcomePanel.superclass.constructor.call(this, cfg);
};
Ext.extend(Garp.WelcomePanel, Ext.Container, {
border: true
/*,
hideButtonArr: ['fileMenu', 'editMenu', 'viewMenu'],
listeners: {
'render': function(){
Ext.each(this.hideButtonArr, function(item){
Garp.toolbar[item].hide();
});
this.getEl().fadeIn({duration:2.2});
if (Garp.viewport && Garp.viewport.formPanelCt) {
Garp.viewport.formPanelCt.hide();
}
},
'destroy': function(){
Ext.each(this.hideButtonArr, function(item){
Garp.toolbar[item].show();
});
if (Garp.viewport && Garp.viewport.formPanelCt) {
Garp.viewport.formPanelCt.show();
}
}
}*/
}); |
Replace regex with faster check | import { utils } from "stylelint"
export const ruleName = "extend-require-placeholder"
export const messages = utils.ruleMessages(ruleName, {
rejected: "Use a placeholder selector (e.g. %some-placeholder) with @extend",
})
export default function (actual) {
return function (root, result) {
const validOptions = utils.validateOptions(result, ruleName, { actual })
if (!validOptions) { return }
root.walkAtRules("extend", atrule => {
const isPlaceholder = atrule.params.trim()[0] === "%"
const isInterpolation = (/^#{.+}/).test(atrule.params.trim())
if (!isPlaceholder && !isInterpolation) {
utils.report({
ruleName,
result,
node: atrule,
message: messages.rejected,
})
}
})
}
}
| import { utils } from "stylelint"
export const ruleName = "extend-require-placeholder"
export const messages = utils.ruleMessages(ruleName, {
rejected: "Use a placeholder selector (e.g. %some-placeholder) with @extend",
})
export default function (actual) {
return function (root, result) {
const validOptions = utils.validateOptions(result, ruleName, { actual })
if (!validOptions) { return }
root.walkAtRules("extend", atrule => {
const isPlaceholder = (/^%/).test(atrule.params.trim())
const isInterpolation = (/^#{.+}/).test(atrule.params.trim())
if (!isPlaceholder && !isInterpolation) {
utils.report({
ruleName,
result,
node: atrule,
message: messages.rejected,
})
}
})
}
}
|
Include propositions in the description | package yokohama.unit.ast;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
@ToString
@EqualsAndHashCode(exclude={"span"})
@AllArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@Getter
public class InstanceSuchThatMatcher implements Matcher {
private String varName;
private ClassType clazz;
private List<Proposition> propositions;
private Span span;
@Override
public <T> T accept(MatcherVisitor<T> visitor) {
return visitor.visitInstanceSuchThat(this);
}
@Override
public String getDescription() {
return "an instance " + varName + " of " + clazz.getName() + " s.t. " +
propositions.stream().map(Proposition::getDescription).collect(Collectors.joining(" and "));
}
}
| package yokohama.unit.ast;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.FieldDefaults;
@ToString
@EqualsAndHashCode(exclude={"span"})
@AllArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@Getter
public class InstanceSuchThatMatcher implements Matcher {
private String varName;
private ClassType clazz;
private List<Proposition> propositions;
private Span span;
@Override
public <T> T accept(MatcherVisitor<T> visitor) {
return visitor.visitInstanceSuchThat(this);
}
@Override
public String getDescription() {
return "an instance of " + clazz.getName() + " s.t. ...";
}
}
|
Add import script for Portsmouth
Closes #1502 | from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E06000044"
addresses_name = (
"local.2019-05-02/Version 1/Democracy_Club__02May2019Portsmouth.tsv"
)
stations_name = "local.2019-05-02/Version 1/Democracy_Club__02May2019Portsmouth.tsv"
elections = ["local.2019-05-02"]
csv_delimiter = "\t"
def address_record_to_dict(self, record):
rec = super().address_record_to_dict(record)
if record.addressline6 == "PO4 099":
rec["postcode"] = "PO4 0PL"
if record.property_urn.strip().lstrip("0") in [
"1775122942",
"1775122943",
"1775122944",
]:
rec["postcode"] = "PO5 2BZ"
return rec
def station_record_to_dict(self, record):
rec = super().station_record_to_dict(record)
if rec["internal_council_id"] == "3596":
rec["location"] = Point(-1.059545, 50.7866578, srid=4326)
return rec
| from django.contrib.gis.geos import Point
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E06000044"
addresses_name = "local.2018-05-03/Version 1/Democracy_Club__03May2018.tsv"
stations_name = "local.2018-05-03/Version 1/Democracy_Club__03May2018.tsv"
elections = ["local.2018-05-03"]
csv_delimiter = "\t"
def address_record_to_dict(self, record):
if record.addressline6 == "PO1 5BZ":
return None
return super().address_record_to_dict(record)
def station_record_to_dict(self, record):
rec = super().station_record_to_dict(record)
if rec["internal_council_id"] == "3270":
rec["location"] = Point(-1.059545, 50.7866578, srid=4326)
return rec
|
Remove socket connection time out configuration | package name.webdizz.fault.tolerance.timeout;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
public class HttpOperationTimeoutTest {
public static final int MS = 50;
@Test(expected = ConnectTimeoutException.class)
public void shouldMakeSureTimeOutCaughtUsingApacheHttpClient() throws Exception {
int timeout = 1;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * MS)
.build();
CloseableHttpClient client =
HttpClientBuilder.create().setDefaultRequestConfig(config).build();
client.execute(new HttpGet("http://yahoo.com"));
}
}
| package name.webdizz.fault.tolerance.timeout;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
public class HttpOperationTimeoutTest {
public static final int MS = 50;
@Test(expected = ConnectTimeoutException.class)
public void shouldMakeSureTimeOutCaughtUsingApacheHttpClient() throws Exception {
int timeout = 1;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout * MS)
.setConnectionRequestTimeout(timeout * MS)
.setSocketTimeout(timeout * MS).build();
CloseableHttpClient client =
HttpClientBuilder.create().setDefaultRequestConfig(config).build();
client.execute(new HttpGet("http://yahoo.com"));
}
}
|
Update app module with bundle tag | package me.mattlogan.pancakes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import me.mattlogan.library.ViewStack;
import me.mattlogan.library.ViewStackDelegate;
public class MainActivity extends AppCompatActivity
implements ViewStackActivity, ViewStackDelegate {
private static final String STACK_TAG = "stack";
private ViewStack viewStack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewStack = ViewStack.create((ViewGroup) findViewById(R.id.container), this);
if (savedInstanceState != null) {
viewStack.rebuildFromBundle(savedInstanceState, STACK_TAG);
} else {
viewStack.push(new RedView.Factory());
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
viewStack.saveToBundle(outState, STACK_TAG);
super.onSaveInstanceState(outState);
}
@Override
public void onBackPressed() {
viewStack.pop();
}
@Override
public ViewStack viewStack() {
return viewStack;
}
@Override
public void onFinishStack() {
finish();
}
}
| package me.mattlogan.pancakes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import me.mattlogan.library.ViewStack;
import me.mattlogan.library.ViewStackDelegate;
public class MainActivity extends AppCompatActivity
implements ViewStackActivity, ViewStackDelegate {
private ViewStack viewStack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewStack = ViewStack.create((ViewGroup) findViewById(R.id.container), this);
if (savedInstanceState != null) {
viewStack.rebuildFromBundle(savedInstanceState);
} else {
viewStack.push(new RedView.Factory());
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
viewStack.saveToBundle(outState);
super.onSaveInstanceState(outState);
}
@Override
public void onBackPressed() {
viewStack.pop();
}
@Override
public ViewStack viewStack() {
return viewStack;
}
@Override
public void onFinishStack() {
finish();
}
}
|
Update eslint for switch/case statements | // http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'eslint:recommended',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
'indent': ["error", 4, {"SwitchCase": 1}],
'no-undef': 0,
'no-unused-vars': 0,
'no-console': 0,
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
| // http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'eslint:recommended',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
'indent': ["error", 4],
'no-undef': 0,
'no-unused-vars': 0,
'no-console': 0,
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
|
Make our LiveFlotWidget not pull in jQuery | # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
from tw.jquery.flot import flot_js, excanvas_js, flot_css
from moksha.api.widgets import LiveWidget
class LiveFlotWidget(LiveWidget):
""" A live graphing widget """
topic = 'flot_demo'
params = ['id', 'data', 'options', 'height', 'width', 'onmessage']
onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])'
template = '<div id="${id}" style="width:${width};height:${height};" />'
javascript = [flot_js, excanvas_js]
css = [flot_css]
height = '250px'
width = '390px'
options = {}
data = [{}]
| # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
from tw.jquery.flot import FlotWidget
from moksha.api.widgets import LiveWidget
class LiveFlotWidget(LiveWidget):
""" A live graphing widget """
topic = 'flot_demo'
params = ['id', 'data', 'options', 'height', 'width', 'onmessage']
children = [FlotWidget('flot')]
onmessage = '$.plot($("#${id}"),json[0]["data"],json[0]["options"])'
template = '<div id="${id}" style="width:${width};height:${height};" />'
height = '250px'
width = '390px'
options = {}
data = [{}]
|
Remove slash from sandbox path | import os
import inspect
# Flask
DEBUG = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = 'www.vpr.net'
AWS_DIRECTORY = 'sandbox/members'
NPR_API_KEY = ''
GOOGLE_SPREADSHEET = {'USER': '',
'PASSWORD': '',
'SOURCE': ''}
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
FREEZER_DESTINATION = 'build'
FREEZER_BASE_URL = 'http://%s/%s' % (AWS_BUCKET, AWS_DIRECTORY)
FREEZER_STATIC_IGNORE = ['Gruntfile*', 'node_modules', 'package.json',
'dev', '.sass-cache']
WEBFACTION_PATH = AWS_DIRECTORY
ABSOLUTE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/'
| import os
import inspect
# Flask
DEBUG = True
# Amazon S3 Settings
AWS_KEY = ''
AWS_SECRET_KEY = ''
AWS_BUCKET = 'www.vpr.net'
AWS_DIRECTORY = 'sandbox/members/'
NPR_API_KEY = ''
GOOGLE_SPREADSHEET = {'USER': '',
'PASSWORD': '',
'SOURCE': ''}
# Cache Settings (units in seconds)
STATIC_EXPIRES = 60 * 24 * 3600
HTML_EXPIRES = 3600
# Frozen Flask
FREEZER_DEFAULT_MIMETYPE = 'text/html'
FREEZER_IGNORE_MIMETYPE_WARNINGS = True
FREEZER_DESTINATION = 'build'
FREEZER_BASE_URL = 'http://%s/%s' % (AWS_BUCKET, AWS_DIRECTORY)
FREEZER_STATIC_IGNORE = ['Gruntfile*', 'node_modules', 'package.json',
'dev', '.sass-cache']
WEBFACTION_PATH = AWS_DIRECTORY
ABSOLUTE_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) + '/'
|
Add type conversion for mime | <?php
/**
* This file is part of the MessageX PHP SDK package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MessageX\Service\Email\ValueObject\Body;
use JMS\Serializer\Annotation as Serializer;
/**
* Class Body
* @package MessageX\Service\Email\ValueObject\Body
* @author Silvio Marijic <silvio.marijic@smsglobal.com>
*/
final class Body
{
/**
* @var string Content type of the email.
* @Serializer\Type("string")
*/
private $mime;
/**
* @var string Email content.
* @Serializer\Type("string")
*/
private $content;
/**
* Body constructor.
* @param string $mime Content type of the email.
* @param string $content Email content.
*/
public function __construct($mime, $content)
{
$this->mime = new MimeType($mime);
$this->content = $content;
}
/**
* @return string Content type of the email.
*/
public function getMime()
{
return (string) $this->mime;
}
/**
* @return string Email content.
*/
public function getContent()
{
return $this->content;
}
}
| <?php
/**
* This file is part of the MessageX PHP SDK package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MessageX\Service\Email\ValueObject\Body;
use JMS\Serializer\Annotation as Serializer;
/**
* Class Body
* @package MessageX\Service\Email\ValueObject\Body
* @author Silvio Marijic <silvio.marijic@smsglobal.com>
*/
final class Body
{
/**
* @var string Content type of the email.
* @Serializer\Type("string")
*/
private $mime;
/**
* @var string Email content.
* @Serializer\Type("string")
*/
private $content;
/**
* Body constructor.
* @param string $mime Content type of the email.
* @param string $content Email content.
*/
public function __construct($mime, $content)
{
$this->mime = new MimeType($mime);
$this->content = $content;
}
/**
* @return string Content type of the email.
*/
public function getMime()
{
return $this->mime;
}
/**
* @return string Email content.
*/
public function getContent()
{
return $this->content;
}
}
|
Use PropTypes prop verification for well component. | import React from 'react';
import PropTypes from 'prop-types';
const Well = props => {
return (
<div className={`well ${props.className}`}>
<span className="well-icon">
<i className={`fa fa-${props.icon}`} />
</span>
<span className="operation-amount">{props.content}</span>
<br />
<span className="well-title">{props.title}</span>
<br />
<span className="well-sub">{props.subtitle}</span>
</div>
);
};
Well.propTypes = {
// The CSS class to be applied to the well.
className: PropTypes.string.isRequired,
// The icon name to be added in the well.
icon: PropTypes.string.isRequired,
// The content to be displayed.
content: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
// The title of the well.
title: PropTypes.string.isRequired,
// The subtitle of the well.
subtitle: PropTypes.string.isRequired
};
export default Well;
| import React from 'react';
import { assertHas } from '../../helpers';
export default props => {
assertHas(props, 'className');
assertHas(props, 'icon');
assertHas(props, 'title');
assertHas(props, 'subtitle');
assertHas(props, 'content');
return (
<div className={`well ${props.className}`}>
<span className="well-icon">
<i className={`fa fa-${props.icon}`} />
</span>
<span className="operation-amount">{props.content}</span>
<br />
<span className="well-title">{props.title}</span>
<br />
<span className="well-sub">{props.subtitle}</span>
</div>
);
};
|
Update: Fix incorrect wording in addInfoToCSVReport.py | #!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to user account notes to the Shared account configuration report(account_configurations.csv)
host="https://localhost:9192/rpc/api/xmlrpc" # If not localhost then this address will need to be whitelisted in PaperCut
auth="token" # Value defined in advanced config property "auth.webservices.auth-token". Should be random
proxy = ServerProxy(host, verbose=False,
context = create_default_context(Purpose.CLIENT_AUTH))#Create new ServerProxy Instance
# #TODO open and manipulate CSV
csv_reader = reader(stdin, delimiter=',') #Read in standard input
line_count = 0
for row in csv_reader:
if line_count == 1: #Header row
row.insert(4,"Notes data")
elif line_count > 2:
row.insert(4,proxy.api.getSharedAccountProperty(auth, row[0] + "\\" + row[2], "notes")) #Add Note data for shared account(Parent or child)
print(", ".join(row))
line_count += 1 | #!/usr/bin/env python3
from csv import reader
from sys import stdin
from xmlrpc.client import ServerProxy
from ssl import create_default_context, Purpose
# Script to user account notes to the Shared account configuration report(account_configurations.csv)
host="https://localhost:9192/rpc/api/xmlrpc" # If not localhost then this address will need to be whitelisted in PaperCut
auth="token" # Value defined in advanced config property "auth.webservices.auth-token". Should be random
proxy = ServerProxy(host, verbose=False,
context = create_default_context(Purpose.CLIENT_AUTH))#Create new ServerProxy Instance
# #TODO open and manipulate CSV
csv_reader = reader(stdin, delimiter=',') #Read in standard data
line_count = 0
for row in csv_reader:
if line_count == 1: #Header row
row.insert(4,"Notes data")
elif line_count > 2:
row.insert(4,proxy.api.getSharedAccountProperty(auth, row[0] + "\\" + row[2], "notes")) #Add Note data for shared account(Parent or child)
print(", ".join(row))
line_count += 1 |
Stop using os.path.join, because Visual Studio can actually handle forward
slash style paths, and the os.path method was creating mixed \\ and /
style paths, b0rking everything. | #!/usr/bin/env python
import os
import sys
import glob
import getopt
def file_list(path):
files = []
if os.path.isfile(path):
return [path]
for f in os.listdir(path):
new_dir = path + '/' + f
if os.path.isdir(new_dir) and not os.path.islink(new_dir):
files.extend(file_list(new_dir))
else:
if f.endswith('.lua'):
files.append(path + '/' + f)
return files
def generate_bundle_map(module_name, path, is_base=False):
t = []
for os_filename in file_list(path):
bundle_filename = (os_filename.replace(path, '')[1:])
if is_base:
bundle_filename = 'modules/' + bundle_filename
else:
bundle_filename = module_name + '/' + bundle_filename
t.append({ 'os_filename': os_filename, 'bundle_filename': bundle_filename })
return t
try:
opts, args = getopt.getopt(sys.argv[1:], 'lb', [])
except:
sys.exit(2)
if __name__ == '__main__':
module_path = args[0]
module_name = os.path.basename(module_path)
for o, a in opts:
if o == '-l':
for path in args:
print('\n'.join(file_list(path)))
elif o == '-b':
for path in args:
print(generate_bundle_map(module_name, path))
| #!/usr/bin/env python
import os
import sys
import glob
import getopt
def file_list(path):
files = []
if os.path.isfile(path):
return [path]
for f in os.listdir(path):
new_dir = os.path.join(path, f)
if os.path.isdir(new_dir) and not os.path.islink(new_dir):
files.extend(file_list(new_dir))
else:
if f.endswith('.lua'):
files.append(path + '/' + f)
return files
def generate_bundle_map(module_name, path, is_base=False):
t = []
for os_filename in file_list(path):
bundle_filename = (os_filename.replace(path, '')[1:])
if is_base:
bundle_filename = 'modules/' + bundle_filename
else:
bundle_filename = module_name + '/' + bundle_filename
t.append({ 'os_filename': os_filename, 'bundle_filename': bundle_filename })
return t
try:
opts, args = getopt.getopt(sys.argv[1:], 'lb', [])
except:
sys.exit(2)
if __name__ == '__main__':
module_path = args[0]
module_name = os.path.basename(module_path)
for o, a in opts:
if o == '-l':
for path in args:
print('\n'.join(file_list(path)))
elif o == '-b':
for path in args:
print(generate_bundle_map(module_name, path))
|
Add gulp test help info via JSdoc comment
Next step: implement gulp app/build/compile. | const _ = require('lodash/fp');
const args = require('yargs').argv;
const gulp = require('gulp');
const gutil = require('gulp-util');
const path = require('path');
const proc = require('child_process');
const usage = require('gulp-help-doc');
gulp.task('help', () => usage(gulp));
/**
* Run Raven.Assure.Test xUnit tests.
* Same as `dotnet test src/Raven.Assure.Test/`
* @task {test}
*/
gulp.task('test', function testRavenAssure(done) {
var testProcess = proc
.spawn('dotnet', ['test'], {
cwd: path.join('src', 'Raven.Assure.Test')
});
// dotnet CLI adds line break, so when combined with log it adds an additional empty line.
// This replaces that line break with an empty string.
var removeLineBreaks = (msg) => msg.replace(/(\r\n|\r|\n)/g, '');
var toString = (msg) => msg.toString();
var logDatar = _.flow(toString, removeLineBreaks, gutil.log);
var logError = _.flow(gutil.colors.red, logDatar);
testProcess.stdout.on('data', logDatar);
testProcess.stderr.on('data', logError);
testProcess.on('close', done);
});
| const _ = require('lodash/fp');
const args = require('yargs').argv;
const gulp = require('gulp');
const gutil = require('gulp-util');
// const log = gutil.log;
const path = require('path');
const proc = require('child_process');
const usage = require('gulp-help-doc');
gulp.task('help', function() { return usage(gulp); });
/*
TODO: Document this.
*/
gulp.task('test', function testRavenAssure(done) {
debugger;
var testProcess = proc
.spawn('dotnet', ['test'], {
cwd: path.join('src', 'Raven.Assure.Test')
});
// dotnet CLI adds line break, so when combined with log it adds an additional empty line.
var removeLineBreaks = (msg) => msg.replace(/(\r\n|\r|\n)/g, '');
var toString = (msg) => msg.toString();
var logDatar = _.flow(toString, removeLineBreaks, gutil.log);
var logError = _.flow(gutil.colors.red, logDatar);
testProcess.stdout.on('data', logDatar);
testProcess.stderr.on('data', logError);
testProcess.on('close', done);
});
|
Use local etcd server for development | var _ = require('lodash');
var defaultConfig = {
database: {
backend: 'leveldown',
file: __dirname + '/data/baixs.db'
},
etcd: {
host: 'localhost',
port: '4001',
},
zabbix: {
url: '',
user: '',
password: '',
},
};
var config = {
development: function() {
return _.merge(defaultConfig, {
zabbix: {
url: 'http://192.168.8.225/zabbix/api_jsonrpc.php',
user: 'Admin',
password: 'zabbix',
},
});
},
test: function() {
return _.merge(defaultConfig,{
database:{
backend: 'memdown'
},
etcd: {
host: 'localhost',
port: 4001
},
});
},
production: function() {
return _.merge(defaultConfig, require('./config.production.js'));
}
};
var env = process.env.NODE_ENV || 'development';
module.exports = config[env]();
| var _ = require('lodash');
var defaultConfig = {
database: {
backend: 'leveldown',
file: __dirname + '/data/baixs.db'
},
etcd: {
host: 'racktables.hupu.com',
port: '4001',
},
zabbix: {
url: '',
user: '',
password: '',
},
};
var config = {
development: function() {
return _.merge(defaultConfig, {
database: {
},
etcd: {
},
zabbix: {
url: 'http://192.168.8.225/zabbix/api_jsonrpc.php',
user: 'Admin',
password: 'zabbix',
},
});
},
test: function() {
return _.merge(defaultConfig,{
database:{
backend: 'memdown'
},
etcd: {
host: 'localhost',
port: 4001
},
zabbix: {
},
});
},
production: function() {
return _.merge(defaultConfig, require('./config.production.js'));
}
};
var env = process.env.NODE_ENV || 'development';
module.exports = config[env]();
|
Update login task to get username from settings | import requests
from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
from .models import Account
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = "gopherairtime.recharges.tasks.hotsocket_login"
def run(self, **kwargs):
"""
Returns the token
"""
l = self.get_logger(**kwargs)
l.info("Logging into hotsocket")
auth = {'username': settings.HOTSOCKET_API_USERNAME,
'password': settings.HOTSOCKET_API_PASSWORD,
'as_json': True}
r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT,
data=auth)
result = r.json()
# Store the result for other tasks to use
token = result["response"]["token"]
account = Account()
account.token = token
account.save()
return True
hotsocket_login = Hotsocket_Login()
| import requests
from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
from .models import Account
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = "gopherairtime.recharges.tasks.hotsocket_login"
def run(self, **kwargs):
"""
Returns the token
"""
l = self.get_logger(**kwargs)
l.info("Logging into hotsocket")
auth = {'username': 'trial_acc_1212', 'password': 'tr14l_l1k3m00n',
'as_json': True}
r = requests.post("%s/login" % settings.HOTSOCKET_API_ENDPOINT,
data=auth)
result = r.json()
token = result["response"]["token"]
account = Account()
account.token = token
account.save()
return True
hotsocket_login = Hotsocket_Login()
|
Add method to set the widget name | <?php namespace Modules\Dashboard\Composers;
use Illuminate\Contracts\View\View;
class WidgetViewComposer
{
/**
* @var array
*/
private $subViews;
/**
* @param View $view
*/
public function compose(View $view)
{
$view->with(['widgets' => $this->subViews]);
}
/**
* Add the html of the widget view to the given widget name
* @param string $name
* @param string $view
* @return $this
*/
public function addSubview($name, $view)
{
$this->subViews[$name]['html'] = $view;
return $this;
}
/**
* Add widget options to the given widget name
* @param $name
* @param array $options
* @return $this
*/
public function addWidgetOptions($name, array $options)
{
$this->subViews[$name]['options'] = $options;
return $this;
}
/**
* Set the widget name
* @param string $name
* @return $this
*/
public function setWidgetName($name)
{
$this->subViews[$name]['name'] = $name;
return $this;
}
}
| <?php namespace Modules\Dashboard\Composers;
use Illuminate\Contracts\View\View;
class WidgetViewComposer
{
/**
* @var array
*/
private $subViews;
/**
* @param View $view
*/
public function compose(View $view)
{
$view->with(['widgets' => $this->subViews]);
}
/**
* Add the html of the widget view to the given widget name
* @param string $name
* @param string $view
* @return $this
*/
public function addSubview($name, $view)
{
$this->subViews[$name]['html'] = $view;
return $this;
}
/**
* Add widget options to the given widget name
* @param $name
* @param array $options
* @return $this
*/
public function addWidgetOptions($name, array $options)
{
$this->subViews[$name]['options'] = $options;
return $this;
}
}
|
Make sure we add any flickr metadata into the tag cloud too. | function queryFlickr(keywords) {
// Clear out any old data that's hanging about.
var flickr = document.getElementById('flickr');
flickr.innerHTML = "";
var req = new Ajax.Request("/flickr/" + sanitize( keywords ) + ".json", {
method: 'GET',
onFailure: function(request) {
alert('AJAX doesnt work.');
},
onComplete: function(request) {
receiveFlickrResponse( request.responseText );
}
});
return true;
}
function receiveFlickrResponse(results) {
if (results != "") {
showStatus("done.");
var jdoc = results.evalJSON();
var result = jdoc['items'];
var tmp = "";
var point = document.getElementById('flickr');
for (var i = 0; i < result.length; i++) {
tmp += "<img src='" + result[i]['media']['m'] + "'/>";
var tags = result[i]['tags'].split(" ");
for (var j = 0; j < tags.length; j++) {
addToTagCloud(tags[j], "", "flickr");
}
}
point.innerHTML = tmp;
}
else {
showStatus("Bad Flickr results.");
}
}
| function queryFlickr(keywords) {
// Clear out any old data that's hanging about.
var flickr = document.getElementById('flickr');
flickr.innerHTML = "";
var req = new Ajax.Request("/flickr/" + sanitize( keywords ) + ".json", {
method: 'GET',
onFailure: function(request) {
alert('AJAX doesnt work.');
},
onComplete: function(request) {
receiveFlickrResponse( request.responseText );
}
});
return true;
}
function receiveFlickrResponse(results) {
if (results != "") {
showStatus("done.");
var jdoc = results.evalJSON();
var result = jdoc['items'];
var tmp = "";
var point = document.getElementById('flickr');
for (var i = 0; i < result.length; i++) {
tmp += "<img src='" + result[i]['media']['m'] + "'/>";
}
point.innerHTML = tmp;
}
else {
showStatus("Bad Flickr results.");
}
}
|
Fix failing build because there was an extra space in JavaScript. Yep, that's right, a build failed because of a space in JavaScript. | // ------------------------------------------------------------------------------
//
// ImagePreloader
//
// ------------------------------------------------------------------------------
define([ "jquery" ], function($) {
"use strict";
var ImagePreloader = function() {};
ImagePreloader.prototype.loadImages = function($images, callback) {
var loadedImages = 0,
badTags = 0,
loadHandler;
$images.each(function() {
var image = new Image(),
$el = $(this),
src = $el.attr("src"),
backgroundImage = $el.css("backgroundImage");
// Search for css background style
if ( src === undefined && backgroundImage != "none" ) {
var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;
src = pattern.exec(backgroundImage)[1];
} else {
badTags++;
}
loadHandler = function() {
loadedImages++;
if ( loadedImages == ($images.length - badTags) ){
callback();
}
};
// Load images
$(image)
.load(loadHandler)
.error(loadHandler)
.attr("src", src);
});
};
return ImagePreloader;
});
| // ------------------------------------------------------------------------------
//
// ImagePreloader
//
// ------------------------------------------------------------------------------
define([ "jquery" ], function($) {
"use strict";
var ImagePreloader = function() {};
ImagePreloader.prototype.loadImages = function($images, callback) {
var loadedImages = 0,
badTags = 0,
loadHandler;
$images.each(function() {
var image = new Image(),
$el = $(this),
src = $el.attr("src"),
backgroundImage = $el.css("backgroundImage");
// Search for css background style
if ( src === undefined && backgroundImage != "none" ) {
var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;
src = pattern.exec(backgroundImage)[1];
} else {
badTags++;
}
loadHandler = function() {
loadedImages++;
if ( loadedImages == ($images.length - badTags) ){
callback();
}
};
// Load images
$(image)
.load(loadHandler)
.error(loadHandler)
.attr("src", src);
});
};
return ImagePreloader;
});
|
Use serverInit or globalInit where possible.
--
MOS_MIGRATED_REVID=126813515 | // Copyright 2014 The Bazel Authors. 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.
package com.google.devtools.build.lib.bazel;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.common.options.OptionsProvider;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* Shutdown log output when Bazel runs in batch mode
*/
public class BazelShutdownLoggerModule extends BlazeModule {
private Logger globalLogger;
@Override
public void globalInit(OptionsProvider startupOptions) {
LogManager.getLogManager().reset();
globalLogger = Logger.getGlobal();
globalLogger.setLevel(java.util.logging.Level.OFF);
}
}
| // Copyright 2014 The Bazel Authors. 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.
package com.google.devtools.build.lib.bazel;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.BlazeVersionInfo;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.util.Clock;
import com.google.devtools.common.options.OptionsProvider;
import java.util.UUID;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* Shutdown log output when Bazel runs in batch mode
*/
public class BazelShutdownLoggerModule extends BlazeModule {
private Logger globalLogger;
@Override
public void blazeStartup(OptionsProvider startupOptions, BlazeVersionInfo versionInfo,
UUID instanceId, BlazeDirectories directories, Clock clock) {
LogManager.getLogManager().reset();
globalLogger = Logger.getGlobal();
globalLogger.setLevel(java.util.logging.Level.OFF);
}
}
|
Stop encoding the jwtSigningKey as base64 | "use strict";
const isCi = require('is-ci');
const jwtSigningKey = process.env.jwtSigningKey ? process.env.jwtSigningKey : '' ;
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: process.env.DB_PORT || '5432',
database: process.env.DB_DATABASE || 'postgres',
username: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD,
dialect: process.env.DB_DIALECT || 'postgres',
logging: process.env.DB_LOGGING || false
};
module.exports = {
dbConfig,
host: process.env.HOST || '127.0.0.1',
port: process.env.PORT || 8080,
baseUrl: process.env.baseUrl || 'http://localhost:8080',
jwtSigningKey,
auth0ClientId: process.env.auth0ClientId,
auth0Domain: process.env.auth0Domain,
googleAnalyticsUA: (process.env.NODE_ENV === 'production') ? process.env.GOOGLE_ANALYTICS_UA : '',
ga: {
view_id: process.env.GOOGLE_ANALYTICS_VIEW_ID
}
};
| "use strict";
const isCi = require('is-ci');
const jwtSigningKey = process.env.jwtSigningKey ? new Buffer(process.env.jwtSigningKey, 'base64') : '' ;
const dbConfig = {
host: process.env.DB_HOST || '127.0.0.1',
port: process.env.DB_PORT || '5432',
database: process.env.DB_DATABASE || 'postgres',
username: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD,
dialect: process.env.DB_DIALECT || 'postgres',
logging: process.env.DB_LOGGING || false
};
module.exports = {
dbConfig,
host: process.env.HOST || '127.0.0.1',
port: process.env.PORT || 8080,
baseUrl: process.env.baseUrl || 'http://localhost:8080',
jwtSigningKey,
auth0ClientId: process.env.auth0ClientId,
auth0Domain: process.env.auth0Domain,
googleAnalyticsUA: (process.env.NODE_ENV === 'production') ? process.env.GOOGLE_ANALYTICS_UA : '',
ga: {
view_id: process.env.GOOGLE_ANALYTICS_VIEW_ID
}
};
|
Rename internal variables to start with a _ | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import urllib.parse
class BaseTransport(object):
@property
def scheme(self):
raise NotImplementedError("Transports must have a scheme")
class HTTPTransport(BaseTransport):
scheme = "http"
class Client(object):
def __init__(self, uri, transports=None):
if transports is None:
transports = [HTTPTransport]
# Initialize transports
self._transports = {}
for transport in transports:
t = transport()
self._transports[t.scheme] = t
parsed = urllib.parse.urlparse(uri)
if parsed.scheme not in self._transports:
raise ValueError("Invalid uri scheme {scheme}. Must be one of {available}.".format(scheme=parsed.scheme, available=",".join(self._transports)))
self._transport = self._transports[parsed.scheme]
# Default to /RPC2 for path as it is a common endpoint
if not parsed.path:
parsed = parsed[:2] + ("/RPC2",) + parsed[3:]
self._uri = urllib.parse.urlunparse(parsed)
| from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import urllib.parse
class BaseTransport(object):
@property
def scheme(self):
raise NotImplementedError("Transports must have a scheme")
class HTTPTransport(BaseTransport):
scheme = "http"
class Client(object):
def __init__(self, uri, transports=None):
if transports is None:
transports = [HTTPTransport]
# Initialize transports
self.transports = {}
for transport in transports:
t = transport()
self.transports[t.scheme] = t
parsed = urllib.parse.urlparse(uri)
if parsed.scheme not in self.transports:
raise ValueError("Invalid uri scheme {scheme}. Must be one of {available}.".format(scheme=parsed.scheme, available=",".join(self.transports)))
self.transport = self.transports[parsed.scheme]
# Default to /RPC2 for path as it is a common endpoint
if not parsed.path:
parsed = parsed[:2] + ("/RPC2",) + parsed[3:]
self.uri = urllib.parse.urlunparse(parsed)
|
Simplify the help message for the -k/--api-key parameter.
We can use the '%(default)s' placeholder instead of string formatting. | #
# Project: retdec-python
# Copyright: (c) 2015-2016 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tools that use the library to analyze and decompile files."""
from retdec import DEFAULT_API_URL
from retdec import __version__
def _add_arguments_shared_by_all_tools(parser):
"""Adds arguments that are used by all tools to the given parser."""
parser.add_argument(
'-k', '--api-key',
dest='api_key',
metavar='KEY',
help='API key to be used.'
)
parser.add_argument(
'-u', '--api-url',
dest='api_url',
metavar='URL',
default=DEFAULT_API_URL,
help='URL to the API. Default: %(default)s.'
)
parser.add_argument(
'-V', '--version',
action='version',
version='%(prog)s (via retdec-python) {}'.format(__version__)
)
| #
# Project: retdec-python
# Copyright: (c) 2015-2016 by Petr Zemek <s3rvac@gmail.com> and contributors
# License: MIT, see the LICENSE file for more details
#
"""Tools that use the library to analyze and decompile files."""
from retdec import DEFAULT_API_URL
from retdec import __version__
def _add_arguments_shared_by_all_tools(parser):
"""Adds arguments that are used by all tools to the given parser."""
parser.add_argument(
'-k', '--api-key',
dest='api_key',
metavar='KEY',
help='API key to be used.'
)
parser.add_argument(
'-u', '--api-url',
dest='api_url',
metavar='URL',
default=DEFAULT_API_URL,
help='URL to the API. Default: {}.'.format(DEFAULT_API_URL)
)
parser.add_argument(
'-V', '--version',
action='version',
version='%(prog)s (via retdec-python) {}'.format(__version__)
)
|
Fix stress test to avoid cdb bus error
bug ref 125505
Signed-off-by: Marja Hassinen <97dfd0cfe579e2c003b71e95ee20ee035e309879@nokia.com> | #!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
| #!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
Fix parsing of initState JSON as noticed by @aawc | 'use strict';
var Q = require('q');
var request = Q.denodeify(require('request'));
var chromecastHomeURL = 'https://clients3.google.com/cast/chromecast/home/v/c9541b08';
var initJSONStateRegex = /(JSON\.parse\(.+'\))/;
var parseChromecastHome = function(htmlString) {
var JSONParse = htmlString.match(initJSONStateRegex)[1];
var initState = eval(JSONParse); // I don't know why this is ok but JSON.parse fails.
var parsedBackgrounds = [];
for (var i in initState[0]) {
var backgroundEntry = {
url: initState[0][i][0],
author: initState[0][i][1]
};
parsedBackgrounds.push(backgroundEntry);
}
return parsedBackgrounds;
};
module.exports = function() {
return request(chromecastHomeURL).then(function(requestResult) {
return parseChromecastHome(requestResult[1]);
});
};
| 'use strict';
var Q = require('q');
var request = Q.denodeify(require('request'));
var chromecastHomeURL = 'https://clients3.google.com/cast/chromecast/home/v/c9541b08';
var initJSONStateRegex = /(JSON\.parse\(.+'\))/;
var parseChromecastHome = function(htmlString) {
var JSONParse = htmlString.match(initJSONStateRegex)[1];
var initState = eval(JSONParse); // I don't know why this is ok but JSON.parse fails.
var parsedBackgrounds = [];
for (var i in initState[1]) {
var backgroundEntry = {
url: initState[1][i][1],
author: initState[1][i][2]
};
parsedBackgrounds.push(backgroundEntry);
}
return parsedBackgrounds;
};
module.exports = function() {
return request(chromecastHomeURL).then(function(requestResult) {
return parseChromecastHome(requestResult[1]);
});
};
|
Add proper printing for py2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pikalang module.
A brainfuck derivative based off the vocabulary of Pikachu from Pokemon.
Copyright (c) 2019 Blake Grotewold
"""
from __future__ import print_function
import sys
import os
from pikalang.interpreter import PikalangProgram
def load_source(file):
if os.path.isfile(file):
if os.path.splitext(file)[1] == ".pokeball":
with open(file, "r") as pikalang_file:
pikalang_data = pikalang_file.read()
return pikalang_data
else:
print("pikalang: file is not a pokeball", file=sys.stderr)
return False
else:
print("pikalang: file does not exist", file=sys.stderr)
return False
def evaluate(source):
"""Run Pikalang system."""
program = PikalangProgram(source)
program.run()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pikalang module.
A brainfuck derivative based off the vocabulary of Pikachu from Pokemon.
Copyright (c) 2019 Blake Grotewold
"""
import sys
import os
from pikalang.interpreter import PikalangProgram
def load_source(file):
if os.path.isfile(file):
if os.path.splitext(file)[1] == ".pokeball":
with open(file, "r") as pikalang_file:
pikalang_data = pikalang_file.read()
return pikalang_data
else:
print("pikalang: file is not a pokeball", file=sys.stderr)
return False
else:
print("pikalang: file does not exist", file=sys.stderr)
return False
def evaluate(source):
"""Run Pikalang system."""
program = PikalangProgram(source)
program.run()
|
Use subject for test settings | # -*- coding: utf-8 -*-
from mamba import describe, context
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe(Settings) as _:
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.subject.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.subject).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
| # -*- coding: utf-8 -*-
from mamba import describe, context, before
from sure import expect
from mamba.settings import Settings
IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1'
with describe('Settings') as _:
@before.each
def create_settings():
_.settings = Settings()
with context('when loading defaults'):
def it_should_have_75_millis_as_slow_test_threshold():
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(0.075)
with context('when setting custom values'):
def it_should_set_slow_test_threshold():
_.settings.slow_test_threshold = IRRELEVANT_SLOW_TEST_THRESHOLD
expect(_.settings).to.have.property('slow_test_threshold').to.be.equal(IRRELEVANT_SLOW_TEST_THRESHOLD)
|
Define returns all entries for given query. | import json
import random
import pprint
class Noah(object):
def __init__(self, dictionary_file):
self.dictionary = json.load(dictionary_file)
def list(self):
return '\n'.join([entry['word'] for entry in self.dictionary])
def define(self, word):
return self.output(filter(lambda x: x['word'] == word, self.dictionary))
if not entry is None:
return self.output(entry)
def random(self):
return self.output(random.choice(self.dictionary))
def output(self, data):
return json.dumps(data, indent=4)
def main():
with open('../dictionaries/english.json') as dictionary:
n = Noah(dictionary)
print n.list()
print n.define('run')
print n.random()
if __name__ == '__main__':
main() | import json
import random
class Noah(object):
def __init__(self, dictionary_file):
self.dictionary = json.load(dictionary_file)
def list(self):
return '\n'.join([entry['word'] for entry in self.dictionary])
def define(self, word):
entry = next((x for x in self.dictionary if x['word'] == word), None)
if not entry is None:
return '%s (%s)' % (entry['word'], entry['part_of_speech'])
def random(self):
return(random.choice(self.dictionary))
def main():
with open('../dictionaries/english.json') as dictionary:
n = Noah(dictionary)
print n.list()
print n.define('aardvark')
print n.random()
if __name__ == '__main__':
main() |
Change to function declaration so this is bound by scope | import React from "react";
import {Router, Route, Link, browserHistory, IndexRoute} from 'react-router';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise';
import {createStore, applyMiddleware} from 'redux';
import * as ga from 'react-ga';
import mainReducer from "./reducers/mainReducer";
import App from "./components/App";
import Home from "./components/Home";
import Farm from "./components/Farm";
// google analytics
ga.initialize('UA-75597006-1');
function logPageView () { // eslint-disable-line
ga.pageview(this.state.location.pathname);
}
// Redux store stuff
const store = createStore(mainReducer, applyMiddleware(
thunk, promiseMiddleware
));
class Routes extends React.Component {
render () {
return (
<Provider store={store}>
<Router history={browserHistory} onUpdate={logPageView}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path=":id" component={Farm} />
</Route>
</Router>
</Provider>
);
}
}
export default Routes;
| import React from "react";
import {Router, Route, Link, browserHistory, IndexRoute} from 'react-router';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise';
import {createStore, applyMiddleware} from 'redux';
import * as ga from 'react-ga';
import mainReducer from "./reducers/mainReducer";
import App from "./components/App";
import Home from "./components/Home";
import Farm from "./components/Farm";
// google analytics
ga.initialize('UA-75597006-1');
const logPageView = () => {
ga.pageview(this.state.location.pathname);
};
// Redux store stuff
const store = createStore(mainReducer, applyMiddleware(
thunk, promiseMiddleware
));
class Routes extends React.Component {
render () {
return (
<Provider store={store}>
<Router history={browserHistory} onUpdate={logPageView}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path=":id" component={Farm} />
</Route>
</Router>
</Provider>
);
}
}
export default Routes;
|
Fix route to setting user | var express = require('express');
var router = express.Router();
var userModel = require('../models/user');
var mongoose = require('mongoose');
router.get('/:currentUser', function (req, res) {
userModel.findOne({'username': req.params.currentUser}, function (err, user) {
if (err) {
res.send(err);
} else {
res.json(user);
}
});
});
router.put('/:currentUser', function (req, res) {
userModel.findOneAndUpdate({'username': req.params.currentUser}, {
"username": req.body.username,
"email": req.body.email,
"password": req.body.password,
"confirmpassword": req.body.confirmpassword,
"date": req.body.date
}, function (err, user) {
if (err)
res.send(err);
res.status(200).send(user);
})
});
module.exports = router; | var express = require('express');
var router = express.Router();
var userModel = require('../models/user');
var mongoose = require('mongoose');
router.get('/:id', function (req, res) {
userModel.find({'_id': req.params.id}, function (err, user) {
if (err)
res.send(err);
res.json(user);
});
});
router.put('/:id', function (req, res) {
userModel.findOneAndUpdate({"_id": req.body._id}, {
"username": req.body.username, "email": req.body.email, "password": req.body.password,
"confirmpassword": req.body.confirmpassword, "date": req.body.date
}, function (err, user) {
if (err)
res.send(err);
res.status(200).send(user);
})
});
module.exports = router; |
Remove warning suppression that Eclipse doesn't like | /*
* SafeUriStringImpl.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.core.client;
import com.google.gwt.safehtml.shared.SafeUri;
public class SafeUriStringImpl implements SafeUri
{
public SafeUriStringImpl(String value)
{
value_ = value;
}
@Override
public String asString()
{
return value_;
}
@Override
public int hashCode()
{
return value_.hashCode();
}
@Override
public boolean equals(Object o)
{
if (o == null ^ value_ == null)
return false;
if (value_ == null)
return false;
return value_.equals(o.toString());
}
@Override
public String toString()
{
return value_;
}
private final String value_;
}
| /*
* SafeUriStringImpl.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.core.client;
import com.google.gwt.safehtml.shared.SafeUri;
public class SafeUriStringImpl implements SafeUri
{
public SafeUriStringImpl(String value)
{
value_ = value;
}
@Override
public String asString()
{
return value_;
}
@Override
public int hashCode()
{
return value_.hashCode();
}
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"})
@Override
public boolean equals(Object o)
{
if (o == null ^ value_ == null)
return false;
if (value_ == null)
return false;
return value_.equals(o.toString());
}
@Override
public String toString()
{
return value_;
}
private final String value_;
}
|
Disable ip_forward in the Pax Mininet node class | # coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __init__(self, name, **params):
super(PaxNode, self).__init__(name, **params)
def config(self, **params):
super(PaxNode, self).config(**params)
# Setup iptable rules to drop incoming packets on each interface:
# Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets
# to prevent the OS from handling them and responding.
print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man"
for intf in self.intfList():
self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
# Disable ip_forward because otherwise this still happens, even with the above iptables rules
self.cmd("sysctl -w net.ipv4.ip_forward=0")
def terminate(self):
# Remove iptables rules
for intf in self.intfList():
self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name)
super(PaxNode, self).terminate()
| # coding: latin-1
"""
pax_mininet_node.py: Defines PaxNode which allows Pax to behave as the sole packet hander on a node.
"""
from mininet.node import Node
from mininet.log import info, warn
class PaxNode( Node ):
"PaxNode: A node which allows Pax to behave as the sole packet hander on that node."
def __init__(self, name, **params):
super(PaxNode, self).__init__(name, **params)
def config(self, **params):
super(PaxNode, self).config(**params)
# Setup iptable rules to drop incoming packets on each interface:
# Because Pax only sniffs packets (it doesn't steal them), we need to drop the packets
# to prevent the OS from handling them and responding.
print "Drop all incoming TCP traffic on nat0 so that Pax is effectively the middle-man"
for intf in self.intfList():
self.cmd("iptables -A INPUT -p tcp -i %s -j DROP" % intf.name)
def terminate(self):
# Remove iptables rules
for intf in self.intfList():
self.cmd("iptables -D INPUT -p tcp -i %s -j DROP" % intf.name)
super(PaxNode, self).terminate()
|
Make powerline autodoc add all Segments | # vim:fileencoding=utf-8:noet
from sphinx.ext import autodoc
from inspect import formatargspec
from powerline.lint.inspect import getconfigargspec
from powerline.segments import Segment
try:
from __builtin__ import unicode
except ImportError:
unicode = lambda s, enc: s # NOQA
def formatvalue(val):
if type(val) is str:
return '="' + unicode(val, 'utf-8').replace('"', '\\"').replace('\\', '\\\\') + '"'
else:
return '=' + repr(val)
class ThreadedDocumenter(autodoc.FunctionDocumenter):
'''Specialized documenter subclass for ThreadedSegment subclasses.'''
@classmethod
def can_document_member(cls, member, membername, isattr, parent):
return (isinstance(member, Segment) or
super(ThreadedDocumenter, cls).can_document_member(member, membername, isattr, parent))
def format_args(self):
argspec = getconfigargspec(self.object)
return formatargspec(*argspec, formatvalue=formatvalue).replace('\\', '\\\\')
def setup(app):
autodoc.setup(app)
app.add_autodocumenter(ThreadedDocumenter)
| # vim:fileencoding=utf-8:noet
from sphinx.ext import autodoc
from inspect import formatargspec
from powerline.lint.inspect import getconfigargspec
from powerline.lib.threaded import ThreadedSegment
try:
from __builtin__ import unicode
except ImportError:
unicode = lambda s, enc: s # NOQA
def formatvalue(val):
if type(val) is str:
return '="' + unicode(val, 'utf-8').replace('"', '\\"').replace('\\', '\\\\') + '"'
else:
return '=' + repr(val)
class ThreadedDocumenter(autodoc.FunctionDocumenter):
'''Specialized documenter subclass for ThreadedSegment subclasses.'''
@classmethod
def can_document_member(cls, member, membername, isattr, parent):
return (isinstance(member, ThreadedSegment) or
super(ThreadedDocumenter, cls).can_document_member(member, membername, isattr, parent))
def format_args(self):
argspec = getconfigargspec(self.object)
return formatargspec(*argspec, formatvalue=formatvalue).replace('\\', '\\\\')
def setup(app):
autodoc.setup(app)
app.add_autodocumenter(ThreadedDocumenter)
|
Fix an access key `url` bug if data is empty | from urllib.parse import urlparse
import logbook
from nameko.rpc import rpc
from .logger import LoggingDependency
from .storages import RedisStorage
log = logbook.debug
class MigrationsService(object):
name = 'migrations'
storage = RedisStorage()
logger = LoggingDependency(interval='ms')
@rpc
def delete_urls_for(self, domain):
log('Deleting URLs for domain {domain}'.format(domain=domain))
for url_hash, data in self.storage.get_all_urls():
if data and urlparse(data['url']).netloc == domain:
self.storage.delete_url(url_hash)
@rpc
def split_content_types(self):
log('Splitting content types')
for url_hash, data in self.storage.get_all_urls():
content_type = data.get('content-type')
if content_type and ';' in content_type:
self.storage.store_content_type(url_hash, content_type)
| from urllib.parse import urlparse
import logbook
from nameko.rpc import rpc
from .logger import LoggingDependency
from .storages import RedisStorage
log = logbook.debug
class MigrationsService(object):
name = 'migrations'
storage = RedisStorage()
logger = LoggingDependency(interval='ms')
@rpc
def delete_urls_for(self, domain):
log('Deleting URLs for domain {domain}'.format(domain=domain))
for url_hash, data in self.storage.get_all_urls():
if urlparse(data['url']).netloc == domain:
self.storage.delete_url(url_hash)
@rpc
def split_content_types(self):
log('Splitting content types')
for url_hash, data in self.storage.get_all_urls():
content_type = data.get('content-type')
if content_type and ';' in content_type:
self.storage.store_content_type(url_hash, content_type)
|
Disable test that may have inadvertently triggered daemon spawning. | package daemon
import (
"io"
"testing"
"src.elv.sh/pkg/daemon/daemondefs"
"src.elv.sh/pkg/testutil"
)
func TestActivate_WhenServerExists(t *testing.T) {
setup(t)
startServer(t)
_, err := Activate(io.Discard,
&daemondefs.SpawnConfig{DbPath: "db", SockPath: "sock", RunDir: "."})
if err != nil {
t.Errorf("got error %v, want nil", err)
}
}
func TestActivate_FailsIfCannotStatSock(t *testing.T) {
t.Skip()
setup(t)
testutil.MustCreateEmpty("not-dir")
_, err := Activate(io.Discard,
&daemondefs.SpawnConfig{DbPath: "db", SockPath: "not-dir/sock", RunDir: "."})
if err == nil {
t.Errorf("got error nil, want non-nil")
}
}
func TestActivate_FailsIfCannotDialSock(t *testing.T) {
setup(t)
testutil.MustCreateEmpty("sock")
_, err := Activate(io.Discard,
&daemondefs.SpawnConfig{DbPath: "db", SockPath: "sock", RunDir: "."})
if err == nil {
t.Errorf("got error nil, want non-nil")
}
}
| package daemon
import (
"io"
"testing"
"src.elv.sh/pkg/daemon/daemondefs"
"src.elv.sh/pkg/testutil"
)
func TestActivate_WhenServerExists(t *testing.T) {
setup(t)
startServer(t)
_, err := Activate(io.Discard,
&daemondefs.SpawnConfig{DbPath: "db", SockPath: "sock", RunDir: "."})
if err != nil {
t.Errorf("got error %v, want nil", err)
}
}
func TestActivate_FailsIfCannotStatSock(t *testing.T) {
setup(t)
testutil.MustCreateEmpty("not-dir")
_, err := Activate(io.Discard,
&daemondefs.SpawnConfig{DbPath: "db", SockPath: "not-dir/sock", RunDir: "."})
if err == nil {
t.Errorf("got error nil, want non-nil")
}
}
func TestActivate_FailsIfCannotDialSock(t *testing.T) {
setup(t)
testutil.MustCreateEmpty("sock")
_, err := Activate(io.Discard,
&daemondefs.SpawnConfig{DbPath: "db", SockPath: "sock", RunDir: "."})
if err == nil {
t.Errorf("got error nil, want non-nil")
}
}
|
Make cart class configurable for braintree task | import logging
from celery.decorators import task
from hiicart.models import HiiCart
from hiicart.gateway.braintree.ipn import BraintreeIPN
log = logging.getLogger('hiicart.gateway.braintree.tasks')
@task
def update_payment_status(hiicart_id, transaction_id, tries=0, cart_class=HiiCart):
"""Check the payment status of a Braintree transaction."""
hiicart = cart_class.objects.get(pk=hiicart_id)
handler = BraintreeIPN(hiicart)
done = handler.update_order_status(transaction_id)
# Reschedule the failed payment to run in 4 hours
if not done:
# After 18 tries (72 hours) we will void and fail the payment
if tries >= 18:
handler.void_order(transaction_id)
else:
tries = tries + 1
update_payment_status.apply_async(args=[hiicart_id,
transaction_id,
tries],
countdown=14400)
| import logging
from celery.decorators import task
from hiicart.models import HiiCart
from hiicart.gateway.braintree.ipn import BraintreeIPN
log = logging.getLogger('hiicart.gateway.braintree.tasks')
@task
def update_payment_status(hiicart_id, transaction_id, tries=0):
"""Check the payment status of a Braintree transaction."""
hiicart = HiiCart.objects.get(pk=hiicart_id)
handler = BraintreeIPN(hiicart)
done = handler.update_order_status(transaction_id)
# Reschedule the failed payment to run in 4 hours
if not done:
# After 18 tries (72 hours) we will void and fail the payment
if tries >= 18:
handler.void_order(transaction_id)
else:
tries = tries + 1
update_payment_status.apply_async(args=[hiicart_id,
transaction_id,
tries],
countdown=14400)
|
Fix typo in method name | 'use strict';
var postcssCached = require('postcss-cached');
var through = require('through2');
var applySourceMap = require('vinyl-sourcemaps-apply');
var gulpUtil = require('gulp-util');
module.exports = function(options) {
options = Object(options);
var postcssCachedInstance = postcssCached();
var gulpPlugin = through.obj(function(file, encoding, callback) {
var fileOptions = Object(options);
fileOptions.from = file.path;
fileOptions.map = fileOptions.map || file.sourceMap;
try {
var result = postcssCachedInstance
.process(file.contents.toString('utf8'), fileOptions);
file.contents = new Buffer(result.css);
if (fileOptions.map) {
applySourceMap(file, result.map);
}
this.push(file);
callback();
} catch(e) {
callback(new gulpUtil.PluginError('gulp-postcss-cached', e));
}
});
gulpPlugin.use = function(postcssPlugin) {
postcssCachedInstance.use(postcssPlugin);
return this;
};
return gulpPlugin;
};
| 'use strict';
var postcssCached = require('postcss-cached');
var through = require('through2');
var applySourceMap = require('vinyl-sourcemaps-apply');
var gulpUtil = require('gulp-util');
module.exports = function(options) {
options = Object(options);
var postcssCachedInstance = postcssCached();
var gulpPlugin = through.obj(function(file, encoding, callback) {
var fileOptions = Object(options);
fileOptions.from = file.path;
fileOptions.map = fileOptions.map || file.sourceMap;
try {
var result = postcssCachedInstance
.processCss(file.contents.toString('utf8'), fileOptions);
file.contents = new Buffer(result.css);
if (fileOptions.map) {
applySourceMap(file, result.map);
}
this.push(file);
callback();
} catch(e) {
callback(new gulpUtil.PluginError('gulp-postcss-cached', e));
}
});
gulpPlugin.use = function(postcssPlugin) {
postcssCachedInstance.use(postcssPlugin);
return this;
};
return gulpPlugin;
};
|
Update React-tools to support transform as object
This change adds an additional function to the exported object to support getting access to the transformed result as an object rather than just a string result - the separate function designed to maintain backwards compatibility.
This facilitates tools that want the code separate from the sourcemap or anything else as time goes by. | 'use strict';
var visitors = require('./vendor/fbtransform/visitors');
var transform = require('jstransform').transform;
var Buffer = require('buffer').Buffer;
module.exports = {
transform: function(input, options) {
options = options || {};
var visitorList = getVisitors(options.harmony);
var result = transform(visitorList, input, options);
var output = result.code;
if (options.sourceMap) {
var map = inlineSourceMap(
result.sourceMap,
input,
options.sourceFilename
);
output += '\n' + map;
}
return output;
},
transformAsObject: function(input, options) {
options = options || {};
var visitorList = getVisitors(options.harmony);
var resultRaw = transform(visitorList, input, options);
var result = {
code: resultRaw.code
};
if (options.sourceMap) {
result.sourceMap = resultRaw.sourceMap;
}
return result;
}
};
function getVisitors(harmony) {
if (harmony) {
return visitors.getAllVisitors();
} else {
return visitors.transformVisitors.react;
}
}
function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
var json = sourceMap.toJSON();
json.sources = [sourceFilename];
json.sourcesContent = [sourceCode];
var base64 = Buffer(JSON.stringify(json)).toString('base64');
return '//# sourceMappingURL=data:application/json;base64,' +
base64;
}
| 'use strict';
var visitors = require('./vendor/fbtransform/visitors');
var transform = require('jstransform').transform;
var Buffer = require('buffer').Buffer;
module.exports = {
transform: function(input, options) {
options = options || {};
var visitorList = getVisitors(options.harmony);
var result = transform(visitorList, input, options);
var output = result.code;
if (options.sourceMap) {
var map = inlineSourceMap(
result.sourceMap,
input,
options.sourceFilename
);
output += '\n' + map;
}
return output;
}
};
function getVisitors(harmony) {
if (harmony) {
return visitors.getAllVisitors();
} else {
return visitors.transformVisitors.react;
}
}
function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
var json = sourceMap.toJSON();
json.sources = [sourceFilename];
json.sourcesContent = [sourceCode];
var base64 = Buffer(JSON.stringify(json)).toString('base64');
return '//# sourceMappingURL=data:application/json;base64,' +
base64;
}
|
Travis: Use absolute path instead of relative. | <?php
$server = proc_open(PHP_BINARY . " /home/travis/build/PocketMine-MP/PocketMine-MP.phar --no-wizard --disable-readline", [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
fwrite($pipes[0], "blocksniper\nmakeplugin BlockSniper\nstop\n\n");
while(!feof($pipes[1])) {
echo fgets($pipes[1]);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
echo "\n\nReturn value: " . proc_close($server) . "\n";
if(count(glob('PocketMine-MP/plugins/DevTools/BlockSniper*.phar')) === 0){
echo "The BlockSniper Travis CI build failed.\n";
exit(1);
}
echo "The BlockSniper Travis CI build succeeded.\n";
exit(0); | <?php
$server = proc_open(PHP_BINARY . " PocketMine-MP/PocketMine-MP.phar --no-wizard --disable-readline", [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
fwrite($pipes[0], "blocksniper\nmakeplugin BlockSniper\nstop\n\n");
while(!feof($pipes[1])) {
echo fgets($pipes[1]);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
echo "\n\nReturn value: " . proc_close($server) . "\n";
if(count(glob('PocketMine-MP/plugins/DevTools/BlockSniper*.phar')) === 0){
echo "The BlockSniper Travis CI build failed.\n";
exit(1);
}
echo "The BlockSniper Travis CI build succeeded.\n";
exit(0); |
Make python-isal a requirement on macos as well. | import sys
from setuptools import setup, find_packages
with open('README.rst') as f:
long_description = f.read()
setup(
name='xopen',
use_scm_version={'write_to': 'src/xopen/_version.py'},
setup_requires=['setuptools_scm'], # Support pip versions that don't know about pyproject.toml
author='Marcel Martin',
author_email='mail@marcelm.net',
url='https://github.com/marcelm/xopen/',
description='Open compressed files transparently',
long_description=long_description,
license='MIT',
package_dir={'': 'src'},
packages=find_packages('src'),
package_data={"xopen": ["py.typed"]},
extras_require={
'dev': ['pytest'],
':(sys_platform=="linux" or sys_platform=="darwin") and python_implementation != "PyPy"': ['isal>=0.4.0']
},
python_requires='>=3.6',
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
]
)
| import sys
from setuptools import setup, find_packages
with open('README.rst') as f:
long_description = f.read()
setup(
name='xopen',
use_scm_version={'write_to': 'src/xopen/_version.py'},
setup_requires=['setuptools_scm'], # Support pip versions that don't know about pyproject.toml
author='Marcel Martin',
author_email='mail@marcelm.net',
url='https://github.com/marcelm/xopen/',
description='Open compressed files transparently',
long_description=long_description,
license='MIT',
package_dir={'': 'src'},
packages=find_packages('src'),
package_data={"xopen": ["py.typed"]},
extras_require={
'dev': ['pytest'],
':sys_platform=="linux" and python_implementation != "PyPy"': ['isal>=0.3.0']
},
python_requires='>=3.6',
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
]
)
|
Remove App duplication if only debugger data | <?php
namespace Sober\Controller;
class Blade
{
protected $data;
/**
* Set Data
*
* Remove other array items should last item not include tree
*/
protected function setBladeData($data)
{
// Get __blade/__debugger key
$this->data = $data['__data']['__blade'];
// Get first item from data array
$first = reset($this->data);
// Get last item from data array
if (count($this->data) > 1) {
$last = end($this->data);
}
// If last item does not inherit tree and first class is App
if (!$last->tree && $first->class === 'App') {
// Rewrite $this->data with first (App) and last item in array
$this->data = [$first, $last];
// Else if $last does not inherit tree
} elseif (!$last->tree) {
// Rewrite $this->data with last item in array
$this->data = $last;
}
return $this;
}
}
| <?php
namespace Sober\Controller;
class Blade
{
protected $data;
/**
* Set Data
*
* Remove other array items should last item not include tree
*/
protected function setBladeData($data)
{
// Get __blade/__debugger key
$this->data = $data['__data']['__blade'];
// Get first item from data array
$first = reset($this->data);
// Get last item from data array
$last = end($this->data);
// If last item does not inherit tree and first class is App
if (!$last->tree && $first->class === 'App') {
// Rewrite $this->data with first (App) and last item in array
$this->data = [$first, $last];
// Else if $last does not inherit tree
} elseif (!$last->tree) {
// Rewrite $this->data with last item in array
$this->data = $last;
}
return $this;
}
}
|
[antenna] Remove unnecessary logger configuration from integration tests. | import logging
import os
import colorlog
import extensions
if os.getenv("CLICOLOR_FORCE") == "1":
print "Forcing colors"
import colorama
colorama.deinit()
def _setup_log():
root_logger = logging.getLogger()
handler = colorlog.StreamHandler()
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(asctime)-15s %(levelname)s: [%(name)s] %(message)s",
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
}
)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
root_logger.setLevel(logging.DEBUG)
def setup():
_setup_log()
extensions.initialize_extensions()
extensions.set_up_once()
def tearDown():
extensions.tear_down_once()
| import logging
import os
import colorlog
import extensions
if os.getenv("CLICOLOR_FORCE") == "1":
print "Forcing colors"
import colorama
colorama.deinit()
def _setup_log():
logging.basicConfig()
root_logger = logging.getLogger()
handler = colorlog.StreamHandler()
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(asctime)-15s %(levelname)s: [%(name)s] %(message)s",
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
}
)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
root_logger.setLevel(logging.DEBUG)
def setup():
_setup_log()
extensions.initialize_extensions()
extensions.set_up_once()
def tearDown():
extensions.tear_down_once()
|
Make a PEP-386-compatible version number. | import os
import sys
from setuptools import setup
from setuptools.dist import Distribution
# Do this first, so setuptools installs cffi immediately before trying to do
# the below import
Distribution(dict(setup_requires='cffi'))
# Set this so the imagemagick flags will get sniffed out.
os.environ['SANPERA_BUILD'] = 'yes'
from sanpera._api import ffi
# Depend on backported libraries only if they don't already exist in the stdlib
BACKPORTS = []
if sys.version_info < (3, 4):
BACKPORTS.append('enum34')
setup(
name='sanpera',
version='0.2.dev1',
description='Image manipulation library, powered by ImageMagick',
author='Eevee',
author_email='eevee.sanpera@veekun.com',
url='http://eevee.github.com/sanpera/',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Topic :: Software Development :: Libraries',
],
packages=['sanpera'],
package_data={
'sanpera': ['_api.c', '_api.h'],
},
install_requires=BACKPORTS + [
'cffi',
],
ext_modules=[ffi.verifier.get_extension()],
ext_package='sanpera',
)
| import os
import sys
from setuptools import setup
from setuptools.dist import Distribution
# Do this first, so setuptools installs cffi immediately before trying to do
# the below import
Distribution(dict(setup_requires='cffi'))
# Set this so the imagemagick flags will get sniffed out.
os.environ['SANPERA_BUILD'] = 'yes'
from sanpera._api import ffi
# Depend on backported libraries only if they don't already exist in the stdlib
BACKPORTS = []
if sys.version_info < (3, 4):
BACKPORTS.append('enum34')
setup(
name='sanpera',
version='0.2pre',
description='Image manipulation library, powered by ImageMagick',
author='Eevee',
author_email='eevee.sanpera@veekun.com',
url='http://eevee.github.com/sanpera/',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Programming Language :: Python',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Graphics :: Graphics Conversion',
'Topic :: Software Development :: Libraries',
],
packages=['sanpera'],
package_data={
'sanpera': ['_api.c', '_api.h'],
},
install_requires=BACKPORTS + [
'cffi',
],
ext_modules=[ffi.verifier.get_extension()],
ext_package='sanpera',
)
|
Use base because everyone can use the template view | package edu.northwestern.bioinformatics.studycalendar.web.template;
import edu.northwestern.bioinformatics.studycalendar.web.ReturnSingleObjectController;
import edu.northwestern.bioinformatics.studycalendar.domain.Arm;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.AccessControl;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarProtectionGroup;
/**
* @author Rhett Sutphin
*/
@AccessControl(protectionGroups = StudyCalendarProtectionGroup.BASE)
public class SelectArmController extends ReturnSingleObjectController<Arm> {
public SelectArmController() {
setParameterName("arm");
setViewName("template/ajax/selectArm");
}
@Override
protected Object wrapObject(Arm loaded) {
return new ArmTemplate(loaded);
}
}
| package edu.northwestern.bioinformatics.studycalendar.web.template;
import edu.northwestern.bioinformatics.studycalendar.web.ReturnSingleObjectController;
import edu.northwestern.bioinformatics.studycalendar.domain.Arm;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.AccessControl;
import edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol.StudyCalendarProtectionGroup;
/**
* @author Rhett Sutphin
*/
@AccessControl(protectionGroups = StudyCalendarProtectionGroup.STUDY_COORDINATOR)
public class SelectArmController extends ReturnSingleObjectController<Arm> {
public SelectArmController() {
setParameterName("arm");
setViewName("template/ajax/selectArm");
}
@Override
protected Object wrapObject(Arm loaded) {
return new ArmTemplate(loaded);
}
}
|
Validate plugins with 'check' task
Convention over configuration | package org.shipkit.internal.gradle.plugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.plugins.JavaBasePlugin;
import org.shipkit.gradle.plugin.PluginValidatorTask;
import org.shipkit.internal.gradle.util.JavaPluginUtil;
import org.shipkit.internal.gradle.util.TaskMaker;
/**
* This plugin validates that every plugin has a corresponding .properties file.
*
* <ul>
* <li>Adds 'validatePlugins' task of type {@link PluginValidatorTask}.
* Validates that every plugin has a corresponding .properties file.
* New task is configured as dependency of 'check' task so that when you run 'check', the plugins are validated
* </li>
* </ul>
*/
public class PluginValidationPlugin implements Plugin<Project> {
static final String VALIDATE_PLUGINS = "validatePlugins";
@Override
public void apply(final Project project) {
project.getPlugins().withId("java", plugin -> {
TaskMaker.task(project, VALIDATE_PLUGINS, PluginValidatorTask.class, task -> {
task.setDescription("Validates Gradle Plugins and their properties files");
task.setSourceSet(JavaPluginUtil.getMainSourceSet(project));
project.getTasks().getByName(JavaBasePlugin.CHECK_TASK_NAME).dependsOn(task);
});
});
}
}
| package org.shipkit.internal.gradle.plugin;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.shipkit.gradle.plugin.PluginValidatorTask;
import org.shipkit.internal.gradle.util.JavaPluginUtil;
import org.shipkit.internal.gradle.util.TaskMaker;
/**
* This plugin validates that every plugin has a corresponding .properties file.
*
* Adds tasks:
* <ul>
* <li>'validatePlugins' - of type {@link PluginValidatorTask}.
* Validates that every plugin has a corresponding .properties file.</li>
* </ul>
*/
public class PluginValidationPlugin implements Plugin<Project> {
static final String VALIDATE_PLUGINS = "validatePlugins";
@Override
public void apply(final Project project) {
project.getPlugins().withId("java", plugin -> TaskMaker.task(project, VALIDATE_PLUGINS, PluginValidatorTask.class, task -> {
task.setDescription("Validates Gradle Plugins and their properties files");
task.setSourceSet(JavaPluginUtil.getMainSourceSet(project));
}));
}
}
|
Update plugin version in code. | <?php
namespace Craft;
class ObfuscatorPlugin extends BasePlugin
{
function init()
{
require_once __DIR__.'/vendor/autoload.php';
}
function getName()
{
return Craft::t('Obfuscator');
}
function getVersion()
{
return '0.2';
}
function getDeveloper()
{
return 'Miranj';
}
function getDeveloperUrl()
{
return 'http://miranj.in';
}
public function getReleaseFeedUrl()
{
return 'https://raw.githubusercontent.com/miranj/craft-obfuscator/master/releases.json';
}
public function addTwigExtension()
{
Craft::import('plugins.obfuscator.twigextensions.ObfuscatorTwigExtension');
return new ObfuscatorTwigExtension();
}
}
| <?php
namespace Craft;
class ObfuscatorPlugin extends BasePlugin
{
function init()
{
require_once __DIR__.'/vendor/autoload.php';
}
function getName()
{
return Craft::t('Obfuscator');
}
function getVersion()
{
return '0.1';
}
function getDeveloper()
{
return 'Miranj';
}
function getDeveloperUrl()
{
return 'http://miranj.in';
}
public function getReleaseFeedUrl()
{
return 'https://raw.githubusercontent.com/miranj/craft-obfuscator/master/releases.json';
}
public function addTwigExtension()
{
Craft::import('plugins.obfuscator.twigextensions.ObfuscatorTwigExtension');
return new ObfuscatorTwigExtension();
}
}
|
Make local provider should call parent methods | <?php
namespace Bolt\Extension\Bolt\Members\Oauth2\Handler;
use Symfony\Component\HttpFoundation\Request;
/**
* OAuth local login provider.
*
* Copyright (C) 2014-2016 Gawain Lynch
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
* @copyright Copyright (c) 2014-2016, Gawain Lynch
* @license https://opensource.org/licenses/MIT MIT
*/
class Local extends HandlerBase
{
/**
* {@inheritdoc}
*/
public function login(Request $request)
{
if (parent::login($request)) {
return;
}
}
/**
* {@inheritdoc}
*/
public function process(Request $request, $grantType = 'authorization_code')
{
parent::process($request, $grantType);
}
/**
* {@inheritdoc}
*/
public function logout(Request $request)
{
parent::logout($request);
}
}
| <?php
namespace Bolt\Extension\Bolt\Members\Oauth2\Handler;
use Symfony\Component\HttpFoundation\Request;
/**
* OAuth local login provider.
*
* Copyright (C) 2014-2016 Gawain Lynch
*
* @author Gawain Lynch <gawain.lynch@gmail.com>
* @copyright Copyright (c) 2014-2016, Gawain Lynch
* @license https://opensource.org/licenses/MIT MIT
*/
class Local extends HandlerBase
{
/**
* {@inheritdoc}
*/
public function login(Request $request)
{
}
/**
* {@inheritdoc}
*/
public function process(Request $request, $grantType = 'authorization_code')
{
}
/**
* {@inheritdoc}
*/
public function logout(Request $request)
{
}
}
|
Add object for drawing digits with canvas | 'use strict';
var Utils = require('./Utils');
function DigitCanvas(element, width, height) {
this.canvas = document.getElementById(element);
this.canvas.width = width;
this.canvas.height = height;
this.context = this.canvas.getContext('2d');
this.gridWidth = this.canvas.width/28;
this.gridHeight = this.canvas.height/28;
}
DigitCanvas.prototype.draw = function(valueArray) {
for(var i = 0; i < valueArray.length; i++) {
var cellX = i % 28;
var cellY = Math.floor(i / 28);
this.drawCell(valueArray[i], cellX, cellY);
}
};
DigitCanvas.prototype.drawCell = function(value, cellX, cellY) {
this.context.fillStyle = Utils.rgbToHex(255 - value, 255 - value, 255 - value);
this.context.fillRect(this.gridWidth * cellX, this.gridHeight * cellY,
this.gridWidth, this.gridHeight);
};
module.exports = DigitCanvas;
| 'use strict';
function DigitCanvas(element, width, height) {
this.canvas = document.getElementById(element);
this.canvas.width = width;
this.canvas.height = height;
this.context = this.canvas.getContext('2d');
this.gridWidth = this.canvas.width/28;
this.gridHeight = this.canvas.height/28;
this.draw(testArray);
}
DigitCanvas.prototype.draw = function(valueArray) {
for(var i = 0; i < valueArray.length; i++) {
var cellX = i % 28;
var cellY = Math.floor(i / 28);
this.drawCell(valueArray[i], cellX, cellY);
}
};
DigitCanvas.prototype.drawCell = function(value, cellX, cellY) {
this.context.fillStyle = rgbToHex(255 - value, 255 - value, 255 - value);
this.context.fillRect(this.gridWidth * cellX, this.gridHeight * cellY,
this.gridWidth, this.gridHeight);
};
function componentToHex(c) {
var hex = c.toString(16);
return hex.length === 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
module.exports = DigitCanvas;
|
Remove code that is not needed since do not need to react to bound values | import Component from 'ember-forge-ui/components/ef-list-item';
import Ember from 'ember';
const {
get
} = Ember;
/**
* @module
* @augments ember-forge-ui/components/ef-list-item
*/
export default Component.extend({
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
// Attributes
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
// Events
/**
* init event hook
*
* Apply correct styling to list items
*
* @returns {undefined}
*/
init() {
this._super(...arguments);
this.setContextStyles();
},
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
// Observers
// -------------------------------------------------------------------------
// Methods
/**
* Manage class names dependent on list type and context of usage
*
* Ordered list items do not have any classes applied
* Unordered lists are considered list groups and items have their own class applied
* Unordered lists used as navs have their item's class applied
*
* @private
* @returns {undefined}
*/
setContextStyles() {
let classNames = get(this, 'classNames');
if (!get(this, 'ordered')) {
classNames.addObject((get(this, 'usedAs') === 'nav') ? 'nav-item' : 'list-group-item');
}
}
});
| import Component from 'ember-forge-ui/components/ef-list-item';
import Ember from 'ember';
const {
get
} = Ember;
/**
* @module
* @augments ember-forge-ui/components/ef-list-item
*/
export default Component.extend({
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
// Attributes
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
// Events
/**
* init event hook
*
* Apply correct styling to list items
*
* @returns {undefined}
*/
init() {
this._super(...arguments);
this.setContextStyles();
},
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
// Observers
// -------------------------------------------------------------------------
// Methods
/**
* Manage class names dependent on list type and context of usage
*
* Ordered list items do not have any classes applied
* Unordered lists are considered list groups and items have their own class applied
* Unordered lists used as navs have their items class applied
*
* @private
* @returns {undefined}
*/
setContextStyles() {
let classNames = get(this, 'classNames');
classNames.removeObject('list-group-item');
classNames.removeObject('nav-item');
if (!get(this, 'ordered')) {
classNames.addObject((get(this, 'usedAs') === 'nav') ? 'nav-item' : 'list-group-item');
}
}
});
|
Connect to database before upgrading it
This change ensure we are connected to the database before
we upgrade it.
Change-Id: Ia0be33892a99897ff294d004f4d935f3753e6200 | # 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 oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.connect()
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
| # 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 oslo.config import cfg
from gnocchi.indexer import sqlalchemy as sql_db
from gnocchi.rest import app
from gnocchi import service
def storage_dbsync():
service.prepare_service()
indexer = sql_db.SQLAlchemyIndexer(cfg.CONF)
indexer.upgrade()
def api():
service.prepare_service()
app.build_server()
|
Return created PaymentMethod when user's 401's in /your-account/billing | import Ember from 'ember';
export default Ember.Mixin.create({
errors: [],
showError: false,
syncErrors: function () {
if (this.get('isDestroyed')) return;
this.set('errors', this.get('parentModel.errors.' + this.get('name')));
},
observeErrors: function () {
if (!this.get('parentModel')) return;
this.get('parentModel').addObserver('errors.' + this.get('name'), this, this.syncErrors);
}.on('didInsertElement'),
// Propagate showError changes to parentModel
errorVisibilityForModel: function () {
var parentModel = this.get('parentModel');
if (!parentModel) return;
if (this.get('showError')) {
parentModel.trigger('shouldShowValidationError', this.get('name'));
} else {
parentModel.trigger('shouldDismissValidationError', this.get('name'));
}
}.observes('showError', 'name')
});
| import Ember from 'ember';
export default Ember.Mixin.create({
errors: [],
showError: false,
syncErrors: function () {
if (this.get('isDestroyed')) return;
this.set('errors', this.get('parentModel.errors.' + this.get('name')));
},
observeErrors: function () {
if (!this.get('parentModel')) return;
this.get('parentModel').addObserver('errors.' + this.get('name'), this, this.syncErrors);
}.on('didInsertElement'),
// Propagate showError changes to parentModel
errorVisibilityForModel: function () {
var parentModel = this.get('parentModel');
if (this.get('showError')) {
parentModel.trigger('shouldShowValidationError', this.get('name'));
} else {
parentModel.trigger('shouldDismissValidationError', this.get('name'));
}
}.observes('showError', 'name')
});
|
Convert to new media type layout. | Application.Services.factory("sidebarUtil", sidebarUtilService);
function sidebarUtilService() {
return {
projectSize: function(project) {
if (!('projectSize' in project)) {
project.projectSize = bytesToSizeStr(project.size);
}
return project.projectSize;
},
projectFileCount: function(project) {
if (!('fileCount' in project)) {
var totalFiles = 0;
for (var key in project.mediatypes) {
totalFiles += project.mediatypes[key].count;
}
project.fileCount = numberWithCommas(totalFiles);
}
return project.fileCount;
}
};
}
| Application.Services.factory("sidebarUtil", sidebarUtilService);
function sidebarUtilService() {
return {
projectSize: function(project) {
if (!('projectSize' in project)) {
project.projectSize = bytesToSizeStr(project.size);
}
return project.projectSize;
},
projectFileCount: function(project) {
if (!('fileCount' in project)) {
var totalFiles = 0;
for (var key in project.mediatypes) {
totalFiles += project.mediatypes[key];
}
project.fileCount = numberWithCommas(totalFiles);
}
return project.fileCount;
}
};
}
|
Copy postactivate file to VIRTUALENV directory. | # coding: utf-8
from os.path import join, dirname, pardir, abspath
from shutil import copy
import subprocess
BOOTSTRAP = abspath(dirname(__file__))
ROOT = abspath(join(BOOTSTRAP, pardir))
# Path where venv will be created. It's imported by bootstrapX.Y.py
VIRTUALENV = abspath(join(BOOTSTRAP, pardir))
ACTIVATE = join(VIRTUALENV, 'bin', 'activate_this.py')
WITH_VENV = join(BOOTSTRAP, 'with_venv.sh')
def with_venv(*args):
"""
Runs the given command inside virtualenv.
"""
cmd = list(args)
cmd.insert(0, WITH_VENV)
return subprocess.call(cmd)
def after_install(options, home_dir):
copy(join(BOOTSTRAP, 'postactivate'), VIRTUALENV)
with_venv('pip', 'install', '-r', join(ROOT, 'requirements.txt'))
print "Done! Activate your virtualenv: source bin/activate"
| # coding: utf-8
from os.path import join, dirname, pardir, abspath
import subprocess
BOOTSTRAP = abspath(dirname(__file__))
ROOT = abspath(join(BOOTSTRAP, pardir))
# Path where venv will be created. It's imported by bootstrapX.Y.py
VIRTUALENV = abspath(join(BOOTSTRAP, pardir))
ACTIVATE = join(VIRTUALENV, 'bin', 'activate_this.py')
WITH_VENV = join(BOOTSTRAP, 'with_venv.sh')
def with_venv(*args):
"""
Runs the given command inside virtualenv.
"""
cmd = list(args)
cmd.insert(0, WITH_VENV)
return subprocess.call(cmd)
def after_install(options, home_dir):
with_venv('pip', 'install', '-r', join(ROOT, 'requirements.txt'))
print "Done! Activate your virtualenv: source bin/activate"
|
Fix font test to use unicode font filename for proper loading to allow passing test on windows (and other os's). | #-*- coding: utf-8 -*-
import unittest
class FontTestCase(unittest.TestCase):
def setUp(self):
import os
self.font_name = os.path.join(os.path.dirname(__file__), u'कीवी.ttf')
if not os.path.exists(self.font_name):
from zipfile import ZipFile
with ZipFile(os.path.join(os.path.dirname(__file__),
'unicode_font.zip'), 'r') as myzip:
myzip.extractall(path=os.path.dirname(__file__))
print(self.font_name)
def test_unicode_name(self):
from kivy.core.text import Label
lbl = Label(font_name=self.font_name)
lbl.refresh()
self.assertNotEqual(lbl.get_extents(''), None)
| #-*- coding: utf-8 -*-
import unittest
class FontTestCase(unittest.TestCase):
def setUp(self):
import os
self.font_name = os.path.join(os.path.dirname(__file__), 'कीवी.ttf')
if not os.path.exists(self.font_name):
from zipfile import ZipFile
with ZipFile(os.path.join(os.path.dirname(__file__),
'unicode_font.zip'), 'r') as myzip:
myzip.extractall(path=os.path.dirname(__file__))
print(self.font_name)
def test_unicode_name(self):
from kivy.core.text import Label
lbl = Label(font_name=self.font_name)
lbl.refresh()
self.assertNotEqual(lbl.get_extents(''), None)
|
Modify the infinite loop function
Don't use `while True` b/c BooleanReplacer breaks this function's
test. This is a bit ugly but until Issue #97 is fixed there is
no other way around it. | # A set of function which exercise specific mutation operators. This
# is paired up with a test suite. The idea is that cosmic-ray should
# kill every mutant when that suite is run; if it doesn't, then we've
# got a problem.
def constant_number():
return 42
def constant_true():
return True
def constant_false():
return False
def unary_sub():
return -1
def unary_add():
return +1
def equals(vals):
def constraint(x, y):
return (x == y) ^ (x != y)
return all([constraint(x, y)
for x in vals
for y in vals])
def use_break(limit):
for x in range(limit):
break
return x
def use_continue(limit):
for x in range(limit):
continue
return x
def trigger_infinite_loop():
# When `break` becomes `continue`, this should enter an infinite loop. This
# helps us test timeouts.
# Any object which isn't None passes the truth value testing so here
# we use `while object()` instead of `while True` b/c the later becomes
# `while False` when BooleanReplacer is applied and we don't trigger an
# infinite loop.
while object():
break
| # A set of function which exercise specific mutation operators. This
# is paired up with a test suite. The idea is that cosmic-ray should
# kill every mutant when that suite is run; if it doesn't, then we've
# got a problem.
def constant_number():
return 42
def constant_true():
return True
def constant_false():
return False
def unary_sub():
return -1
def unary_add():
return +1
def equals(vals):
def constraint(x, y):
return (x == y) ^ (x != y)
return all([constraint(x, y)
for x in vals
for y in vals])
def use_break(limit):
for x in range(limit):
break
return x
def use_continue(limit):
for x in range(limit):
continue
return x
def trigger_infinite_loop():
# When `break` becomes `continue`, this should enter an infinite loop. This
# helps us test timeouts.
while True:
break
|
Simplify version command and output | /*
* Copyright 2014 gitblit.com.
*
* 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.gitblit.transport.ssh.commands;
import com.gitblit.Constants;
import com.gitblit.transport.ssh.CommandMetaData;
@CommandMetaData(name="version", description = "Display the Gitblit version")
public class VersionCommand extends SshCommand {
@Override
public void run() {
stdout.println(Constants.getGitBlitVersion());
}
}
| /*
* Copyright 2014 gitblit.com.
*
* 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.gitblit.transport.ssh.commands;
import org.kohsuke.args4j.Option;
import com.gitblit.Constants;
import com.gitblit.transport.ssh.CommandMetaData;
@CommandMetaData(name="version", description = "Print Gitblit version")
public class VersionCommand extends SshCommand {
@Option(name = "--verbose", aliases = {"-v"}, metaVar = "VERBOSE", usage = "Print verbose versions")
private boolean verbose;
@Override
public void run() {
stdout.println(String.format("Version: %s", Constants.getGitBlitVersion(),
verbose));
}
}
|
Support 'sources' in plural as 'src' folder | /* eslint-disable max-len */
exports.extensions = {
supported: [
{ icon: 'bower', extensions: ['bower_components'] },
{ icon: 'dist', extensions: ['dist', 'out', 'export'] },
{ icon: 'git', extensions: ['git', 'github'] },
{ icon: 'haxelib', extensions: ['haxelib'] },
{ icon: 'node', extensions: ['node_modules'] },
{ icon: 'meteor', extensions: ['meteor'] },
{ icon: 'src', extensions: ['src', 'source', 'sources'] },
{ icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] },
{ icon: 'typings', extensions: ['typings'] },
{ icon: 'vscode', extensions: ['vscode'] }
],
parse: function () {
var s = this.replace(/\./g, '_');
if ((/^\d/).test(s)) return 'n' + s;
return s;
}
};
| /* eslint-disable max-len */
exports.extensions = {
supported: [
{ icon: 'bower', extensions: ['bower_components'] },
{ icon: 'dist', extensions: ['dist', 'out', 'export'] },
{ icon: 'git', extensions: ['git', 'github'] },
{ icon: 'haxelib', extensions: ['haxelib'] },
{ icon: 'node', extensions: ['node_modules'] },
{ icon: 'meteor', extensions: ['meteor'] },
{ icon: 'src', extensions: ['src', 'source'] },
{ icon: 'test', extensions: ['tests', 'test', '__tests__', '__test__'] },
{ icon: 'typings', extensions: ['typings'] },
{ icon: 'vscode', extensions: ['vscode'] }
],
parse: function () {
var s = this.replace(/\./g, '_');
if ((/^\d/).test(s)) return 'n' + s;
return s;
}
};
|
Remove unused variables and fix paths issue | var gulp = require('gulp');
var elixir = require('laravel-elixir');
var htmlmin = require('gulp-htmlmin');
/**
* Minify static html pages, useful when using html partials loaded though ajax
* @param {string} src The files to minify
* @param {string|object} outputPath The output path, or an options object
* @param {object} options The options object passed to the minify task
*/
elixir.extend('html', function(src, outputPath, options) {
// If the options object was provided on the outputPath parameter
if (typeof outputPath == 'object') {
options = outputPath;
outputPath = null;
}
// Parse the source and output paths
src = src || 'storage/framework/views/*';
outputPath = outputPath || 'storage/framework/views/';
var paths = {
src: src,
outputPath: outputPath
};
options = typeof options == 'undefined' ? {} : options;
new elixir.Task('minify', function() {
var minifyOptions = options;
return gulp.src(paths.src)
.pipe(htmlmin(minifyOptions))
.pipe(gulp.dest(paths.outputPath))
.pipe(new elixir.Notification('HTML Minified!'));
})
// Register watcher for source path
.watch(paths.src);
}); | var gulp = require('gulp');
var elixir = require('laravel-elixir');
var htmlmin = require('gulp-htmlmin');
var config = elixir.config;
/**
* Minify static html pages, useful when using html partials loaded though ajax
* @param {string} src The files to minify
* @param {string|object} outputPath The output path, or an options object
* @param {object} options The options object passed to the minify task
*/
elixir.extend('html', function(src, outputPath, options) {
// If the options object was provided on the outputPath parameter
if (typeof outputPath == 'object') {
options = outputPath;
outputPath = null;
}
// Parse the source and output paths
var paths = new elixir.GulpPaths()
.src(src || 'storage/framework/views/*')
.output(outputPath || 'storage/framework/views/');
options = typeof options == 'undefined' ? {} : options;
new elixir.Task('minify', function() {
var minifyOptions = options;
return gulp.src(paths.src.path)
.pipe(htmlmin(minifyOptions))
.pipe(gulp.dest(paths.output.path))
.pipe(new elixir.Notification('HTML Minified!'));
})
// Register watcher for source path
.watch(paths.src.path);
}); |
Trim whitespace from API error messages | <?php
namespace Platformsh\Cli\Exception;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use Platformsh\Client\Exception\ApiResponseException;
class HttpException extends \RuntimeException
{
protected $message = 'An API error occurred.';
/**
* @param string $message
* @param RequestInterface $request
* @param ResponseInterface $response
*/
public function __construct($message = null, RequestInterface $request = null, ResponseInterface $response = null)
{
$message = $message ?: $this->message;
if ($request !== null && $response !== null) {
$details = "[url] " . $request->getUrl();
$details .= " [status code] " . $response->getStatusCode();
$details .= " [reason phrase] " . $response->getReasonPhrase();
$details .= ApiResponseException::getErrorDetails($response);
$message .= "\n\nDetails:\n" . wordwrap(trim($details));
}
parent::__construct($message, $this->code);
}
}
| <?php
namespace Platformsh\Cli\Exception;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use Platformsh\Client\Exception\ApiResponseException;
class HttpException extends \RuntimeException
{
protected $message = 'An API error occurred.';
/**
* @param string $message
* @param RequestInterface $request
* @param ResponseInterface $response
*/
public function __construct($message = null, RequestInterface $request = null, ResponseInterface $response = null)
{
$message = $message ?: $this->message;
if ($request !== null && $response !== null) {
$details = "[url] " . $request->getUrl();
$details .= " [status code] " . $response->getStatusCode();
$details .= " [reason phrase] " . $response->getReasonPhrase();
$details .= ApiResponseException::getErrorDetails($response);
$message .= "\n\nDetails:\n" . wordwrap($details);
}
parent::__construct($message, $this->code);
}
}
|
Add missing space to function declaration | import Ember from 'ember';
var $ = Ember.$;
var openDatepicker = function(element) {
$(element).click();
return PikadayInteractor;
};
var PikadayInteractor = {
selectorForMonthSelect: '.pika-select-month',
selectorForYearSelect: '.pika-select-year',
selectDate: function(date) {
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
$(this.selectorForYearSelect + ' option[value="' + year + '"]').attr('selected', 'selected');
triggerNativeEvent($(this.selectorForYearSelect)[0], 'change');
$(this.selectorForMonthSelect + ' option[value="' + month + '"]').attr('selected', 'selected');
triggerNativeEvent($(this.selectorForMonthSelect)[0], 'change');
triggerNativeEvent($('td[data-day="' + day + '"] button')[0], 'mousedown');
},
selectedDay: function() {
return $('.pika-single td.is-selected button').html();
},
selectedMonth: function() {
return $(this.selectorForMonthSelect + ' option:selected').val();
},
selectedYear: function() {
return $(this.selectorForYearSelect + ' option:selected').val();
}
};
function triggerNativeEvent(element, eventName) {
if (element.fireEvent) {
element.fireEvent('on' + eventName);
} else {
var event = document.createEvent('Events');
event.initEvent(eventName, true, false);
element.dispatchEvent(event);
}
}
export { openDatepicker };
| import Ember from 'ember';
var $ = Ember.$;
var openDatepicker =function(element) {
$(element).click();
return PikadayInteractor;
};
var PikadayInteractor = {
selectorForMonthSelect: '.pika-select-month',
selectorForYearSelect: '.pika-select-year',
selectDate: function(date) {
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
$(this.selectorForYearSelect + ' option[value="' + year + '"]').attr('selected', 'selected');
triggerNativeEvent($(this.selectorForYearSelect)[0], 'change');
$(this.selectorForMonthSelect + ' option[value="' + month + '"]').attr('selected', 'selected');
triggerNativeEvent($(this.selectorForMonthSelect)[0], 'change');
triggerNativeEvent($('td[data-day="' + day + '"] button')[0], 'mousedown');
},
selectedDay: function() {
return $('.pika-single td.is-selected button').html();
},
selectedMonth: function() {
return $(this.selectorForMonthSelect + ' option:selected').val();
},
selectedYear: function() {
return $(this.selectorForYearSelect + ' option:selected').val();
}
};
function triggerNativeEvent(element, eventName) {
if (element.fireEvent) {
element.fireEvent('on' + eventName);
} else {
var event = document.createEvent('Events');
event.initEvent(eventName, true, false);
element.dispatchEvent(event);
}
}
export { openDatepicker };
|
Change messages and exceptions throws in dispatch method | <?php
namespace PHPLegends\Routes;
use PHPLegends\Routes\Exceptions\NotFoundException;
use PHPLegends\Routes\Exceptions\InvalidVerbException;
class Dispatcher extends AbstractDispatcher
{
public function __construct($uri, $verbs)
{
$this->uri = $uri;
$this->verbs = $verbs;
}
public function dispatch()
{
$routes = $this->getRouter()->getCollection()->filterByUri($this->uri);
if ($routes->isEmpty())
{
throw new NotFoundException("Unable to find '{$this->uri}'");
}
$route = $routes->findByVerb($this->verbs);
if ($route === null)
{
throw new InvalidVerbException(
sprintf('Invalid verb for route "%s"', $this->uri)
);
}
$result = $this->getRouter()->processRouteFilters($route);
if ($result !== null) return $result;
return call_user_func_array(
$route->getActionAsCallable(), $route->match($this->uri)
);
}
} | <?php
namespace PHPLegends\Routes;
use PHPLegends\Routes\Exceptions\RouteException;
class Dispatcher extends AbstractDispatcher
{
public function __construct($uri, $verbs)
{
$this->uri = $uri;
$this->verbs = $verbs;
}
public function dispatch()
{
$routes = $this->getRouter()->getCollection()->filterByUri($this->uri);
if ($routes->isEmpty())
{
throw new RouteException("Unable to find '{$this->uri}'");
}
$route = $routes->findByVerb($this->verbs);
if ($route === null)
{
throw new RouteException('Unable to find');
}
$result = $this->getRouter()->processRouteFilters($route);
if ($result !== null) return $result;
return call_user_func_array(
$route->getActionAsCallable(), $route->match($this->uri)
);
}
} |
Fix issue with extra slash in Main URL | (function() {
'use strict';
angular
.module('mendel')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: '/main?context',
templateUrl: 'app/main/main.html',
reloadOnSearch : false,
controller: 'MainController',
controllerAs: 'main'
})
.state('login', {
url: '/login',
templateUrl: 'app/login/login.html',
controller: 'LoginController',
controllerAs: 'login'
})
.state('about', {
url: '/about',
templateUrl: 'app/about/about.html',
controller: 'AboutController',
controllerAs: 'about'
})
;
$urlRouterProvider.otherwise('/main');
}
})();
| (function() {
'use strict';
angular
.module('mendel')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: '/main/?context',
templateUrl: 'app/main/main.html',
reloadOnSearch : false,
controller: 'MainController',
controllerAs: 'main'
})
.state('login', {
url: '/login',
templateUrl: 'app/login/login.html',
controller: 'LoginController',
controllerAs: 'login'
})
.state('about', {
url: '/about',
templateUrl: 'app/about/about.html',
controller: 'AboutController',
controllerAs: 'about'
})
;
$urlRouterProvider.otherwise('/main');
}
})();
|
Test fix: always use full cms-models config state as default | <?php
namespace Czim\CmsModels\Test;
abstract class TestCase extends \Orchestra\Testbench\TestCase
{
/**
* {@inheritdoc}
*/
protected function getEnvironmentSetUp($app)
{
$app['config']->set('translatable.locales', [ 'en', 'nl' ]);
$app['config']->set('translatable.use_fallback', true);
$app['config']->set('translatable.fallback_locale', 'en');
$app['config']->set('cms-models', include(realpath(dirname(__DIR__) . '/config/cms-models.php')));
$app['config']->set('cms-models.analyzer.database.class', null);
$app['view']->addNamespace('cms-models', realpath(dirname(__DIR__) . '/resources/views'));
}
}
| <?php
namespace Czim\CmsModels\Test;
abstract class TestCase extends \Orchestra\Testbench\TestCase
{
/**
* {@inheritdoc}
*/
protected function getEnvironmentSetUp($app)
{
$app['config']->set('translatable.locales', [ 'en', 'nl' ]);
$app['config']->set('translatable.use_fallback', true);
$app['config']->set('translatable.fallback_locale', 'en');
$app['config']->set('cms-models.analyzer.traits.listify', [
\Czim\Listify\Listify::class,
]);
$app['view']->addNamespace('cms-models', realpath(dirname(__DIR__) . '/resources/views'));
}
}
|
Add line separator in debug logs | <?php
namespace Kanboard\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BootstrapSubscriber extends \Kanboard\Core\Base implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
'app.bootstrap' => array('setup', 0),
);
}
public function setup()
{
$this->config->setupTranslations();
$this->config->setupTimezone();
}
public function __destruct()
{
if (DEBUG) {
foreach ($this->db->getLogMessages() as $message) {
$this->logger->debug($message);
}
$this->logger->debug('SQL_QUERIES={nb}', array('nb' => $this->container['db']->nbQueries));
$this->logger->debug('RENDERING={time}', array('time' => microtime(true) - $this->request->getStartTime()));
$this->logger->debug('MEMORY='.$this->helper->text->bytes(memory_get_usage()));
$this->logger->debug('URI='.$this->request->getUri());
$this->logger->debug('###############################################');
}
}
}
| <?php
namespace Kanboard\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BootstrapSubscriber extends \Kanboard\Core\Base implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
'app.bootstrap' => array('setup', 0),
);
}
public function setup()
{
$this->config->setupTranslations();
$this->config->setupTimezone();
}
public function __destruct()
{
if (DEBUG) {
foreach ($this->db->getLogMessages() as $message) {
$this->logger->debug($message);
}
$this->logger->debug('SQL_QUERIES={nb}', array('nb' => $this->container['db']->nbQueries));
$this->logger->debug('RENDERING={time}', array('time' => microtime(true) - $this->request->getStartTime()));
$this->logger->debug('MEMORY='.$this->helper->text->bytes(memory_get_usage()));
$this->logger->debug('URI='.$this->request->getUri());
}
}
}
|
Use object literal syntax in mapDispatchToProps | import { PropTypes } from 'react'
import {connect} from 'react-redux'
import {updateTodo, deleteTodo, showDeleteButtonOnTodo} from 'actions/actionCreators'
import TodoPresentation from 'components/TodoPresentation/TodoPresentation'
const mapStateToProps = (state, {todo}) => {
return {
deleteButtonVisible: state.deleteButtonOnTodo === todo.id
}
}
const mapDispatchToProps = (dispatch, {todo}) => {
return {
onCompleted () {
dispatch(updateTodo(todo, {completed: !todo.completed}))
},
onDelete () {
dispatch(deleteTodo(todo))
},
onDeleteButtonShown () {
dispatch(showDeleteButtonOnTodo(todo.id))
},
onDeleteButtonHidden () {
dispatch(showDeleteButtonOnTodo(null))
}
}
}
const Todo = connect(mapStateToProps, mapDispatchToProps)(TodoPresentation)
Todo.propTypes = {
todo: PropTypes.object.isRequired
}
export default Todo
| import { PropTypes } from 'react'
import {connect} from 'react-redux'
import {updateTodo, deleteTodo, showDeleteButtonOnTodo} from 'actions/actionCreators'
import TodoPresentation from 'components/TodoPresentation/TodoPresentation'
const mapStateToProps = (state, {todo}) => {
return {
deleteButtonVisible: state.deleteButtonOnTodo === todo.id
}
}
const mapDispatchToProps = (dispatch, {todo}) => {
return {
onCompleted: () => {
dispatch(updateTodo(todo, {completed: !todo.completed}))
},
onDelete: () => {
dispatch(deleteTodo(todo))
},
onDeleteButtonShown: () => {
dispatch(showDeleteButtonOnTodo(todo.id))
},
onDeleteButtonHidden: () => {
dispatch(showDeleteButtonOnTodo(null))
}
}
}
const Todo = connect(mapStateToProps, mapDispatchToProps)(TodoPresentation)
Todo.propTypes = {
todo: PropTypes.object.isRequired
}
export default Todo
|
Add Login Link to menu at installation | <?php
use App\Menu;
use Illuminate\Database\Seeder;
class MenuTableSeeder extends Seeder
{
public function run()
{
Menu::truncate();
Menu::create([
'name' => 'Home',
'url' => route('home'),
'weight' => '1',
'emplacement' => 'left',
]);
Menu::create([
'name' => 'Blog',
'url' => route('post.index'),
'weight' => '2',
'emplacement' => 'left',
]);
Menu::create([
'name' => 'Login',
'url' => url('auth/login'),
'is_login_link' => true,
'weight' => '0',
'emplacement' => 'right',
]);
}
}
| <?php
use App\Menu;
use Illuminate\Database\Seeder;
class MenuTableSeeder extends Seeder
{
public function run()
{
Menu::truncate();
Menu::create([
'name' => 'Home',
'url' => route('home'),
'weight' => '1',
'emplacement' => 'left',
]);
Menu::create([
'name' => 'Blog',
'url' => route('post.index'),
'weight' => '2',
'emplacement' => 'left',
]);
}
}
|
[impala] Fix test looking for Impala icon
Use regexp in tests for matching white spaces and new lines | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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.
import re
from nose.tools import assert_true, assert_equal, assert_false
from desktop.lib.django_test_util import make_logged_in_client
class TestImpala:
def setUp(self):
self.client = make_logged_in_client()
def test_basic_flow(self):
response = self.client.get("/impala/")
assert_true(re.search('<li id="impalaIcon"\W+class="active', response.content), response.content)
assert_true('Query Editor' in response.content)
response = self.client.get("/impala/execute/")
assert_true('Query Editor' in response.content)
| #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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.
from nose.tools import assert_true, assert_equal, assert_false
from desktop.lib.django_test_util import make_logged_in_client
class TestImpala:
def setUp(self):
self.client = make_logged_in_client()
def test_basic_flow(self):
response = self.client.get("/impala/")
assert_true("""<li id="impalaIcon"
class="active""" in response.content, response.content)
assert_true('Query Editor' in response.content)
response = self.client.get("/impala/execute/")
assert_true('Query Editor' in response.content)
|
Use the pg8000 pure-Python Postgres DBAPI module | from setuptools import setup
setup(
name='tangled.website',
version='0.1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'pg8000>=1.10.6',
'tangled.auth>=0.1a3',
'tangled.session>=0.1a2',
'tangled.site>=0.1a2',
'SQLAlchemy>=1.1.6',
],
extras_require={
'dev': ['coverage'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled.website',
version='0.1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'tangled.auth>=0.1a3',
'tangled.session>=0.1a2',
'tangled.site>=0.1a2',
'SQLAlchemy>=1.1.6',
],
extras_require={
'dev': ['coverage'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Add API endpoint for getting tasks from a list | <?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
Route::auth();
Route::get('/', function () {
return view('welcome');
});
});
Route::group(['middleware' => ['web', 'auth']], function( ){
Route::resource('list', 'ListController', [ 'only' => ['store', 'show', 'edit', 'index', 'create'] ]);
Route::get('/{slug}', ['as' => 'showBySlug', 'uses' => 'ListController@showBySlug']);
Route::get('/{username}/{slug}', ['as' => 'showByUserSlug', 'uses' => 'ListController@showByUserSlug']);
});
Route::group(['middleware' => ['api', 'web'], 'prefix' => 'api'], function( ){
Route::get('list/{encryptedListID}/tasks', ['as' => 'api/list/tasks', 'uses' => 'TaskController@getTasks']);
Route::resource('task', 'TaskController', [ 'only' => ['store', 'update', 'destroy'] ] );
Route::resource('list', 'ListController', [ 'only' => ['update', 'destroy'] ]);
});
| <?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
Route::auth();
Route::get('/', function () {
return view('welcome');
});
});
Route::group(['middleware' => ['web', 'auth']], function( ){
Route::resource('list', 'ListController', [ 'only' => ['store', 'show', 'edit', 'index', 'create'] ]);
Route::get('/{slug}', ['as' => 'showBySlug', 'uses' => 'ListController@showBySlug']);
Route::get('/{username}/{slug}', ['as' => 'showByUserSlug', 'uses' => 'ListController@showByUserSlug']);
});
Route::group(['middleware' => ['api', 'auth']], function( ){
Route::resource('task', 'TaskController', [ 'only' => ['store', 'update', 'destroy'] ] );
Route::resource('list', 'ListController', [ 'only' => ['update', 'destroy'] ]);
});
|
Save mcc-mnc data to WS connector, so monitor is able to print logs for Deployment KPIs | /* jshint node:true */
/**
* PUSH Notification server
* (c) Telefonica Digital, 2012 - All rights reserved
* License: GNU Affero V3 (see LICENSE file)
* Fernando Rodríguez Sela <frsela@tid.es>
* Guillermo Lopez Leal <gll@tid.es>
*/
'use strict';
function ConnectorWebSocket(data, connection) {
this.data = data;
this.connection = connection;
}
ConnectorWebSocket.prototype = {
getType: function() {
return 'WS';
},
getServer: function() {
return process.serverId;
},
getConnection: function() {
return this.connection;
},
getInterface: function() {
return null;
},
getMobileNetwork: function() {
return this.data.mobilenetwork || null;
},
getProtocol: function() {
return 'ws';
},
canBeWakeup: function() {
return false;
},
resetAutoclose: function() {
// nothing to do on this connector
},
notify: function(msgList) {
this.connection.sendUTF(JSON.stringify(msgList));
}
};
module.exports = ConnectorWebSocket; | /* jshint node:true */
/**
* PUSH Notification server
* (c) Telefonica Digital, 2012 - All rights reserved
* License: GNU Affero V3 (see LICENSE file)
* Fernando Rodríguez Sela <frsela@tid.es>
* Guillermo Lopez Leal <gll@tid.es>
*/
'use strict';
function ConnectorWebSocket(data, connection) {
this.data = data;
this.connection = connection;
}
ConnectorWebSocket.prototype = {
getType: function() {
return 'WS';
},
getServer: function() {
return process.serverId;
},
getConnection: function() {
return this.connection;
},
getInterface: function() {
return null;
},
getMobileNetwork: function() {
return null;
},
getProtocol: function() {
return 'ws';
},
canBeWakeup: function() {
return false;
},
resetAutoclose: function() {
// nothing to do on this connector
},
notify: function(msgList) {
this.connection.sendUTF(JSON.stringify(msgList));
}
};
module.exports = ConnectorWebSocket; |
Fix data field for Mailgun | <?php
namespace Swm\Bundle\MailHookBundle\ApiService;
use Swm\Bundle\MailHookBundle\Hook\DefaultHook;
use Swm\Bundle\MailHookBundle\SwmMailHookEvent;
class MailgunApiService extends BaseApiService
{
private $eventAssoc = array(
'delivered' => SwmMailHookEvent::MAILHOOK_SEND,
'opened' => SwmMailHookEvent::MAILHOOK_OPEN,
'clicked' => SwmMailHookEvent::MAILHOOK_CLICK,
'complained' => SwmMailHookEvent::MAILHOOK_SPAM,
'unsubscribed' => SwmMailHookEvent::MAILHOOK_UNSUB,
'failed' => SwmMailHookEvent::MAILHOOK_REJECT,
);
/**
* @param array $hook
* @return HookInterface
*/
private function bindHook(array $hook)
{
return new DefaultHook($hook['event'], $hook['recipient'], 'mailgun', $hook, $this->eventAssoc[$hook['event']]);
}
/**
* @return array<HookInterface>
*/
public function bind()
{
$metaData = json_decode($this->request->getContent(), true);
return array($this->bindHook($metaData['event-data']));
}
}
| <?php
namespace Swm\Bundle\MailHookBundle\ApiService;
use Swm\Bundle\MailHookBundle\Hook\DefaultHook;
use Swm\Bundle\MailHookBundle\SwmMailHookEvent;
class MailgunApiService extends BaseApiService
{
private $eventAssoc = array(
'delivered' => SwmMailHookEvent::MAILHOOK_SEND,
'opened' => SwmMailHookEvent::MAILHOOK_OPEN,
'clicked' => SwmMailHookEvent::MAILHOOK_CLICK,
'complained' => SwmMailHookEvent::MAILHOOK_SPAM,
'unsubscribed' => SwmMailHookEvent::MAILHOOK_UNSUB,
'failed' => SwmMailHookEvent::MAILHOOK_REJECT,
);
/**
* @param array $hook
* @return HookInterface
*/
private function bindHook(array $hook)
{
return new DefaultHook($hook['event'], $hook['recipient'], 'mailgun', $hook, $this->eventAssoc[$hook['event']]);
}
/**
* @return array<HookInterface>
*/
public function bind()
{
$metaData = json_decode($this->request->getContent(), true);
return array($this->bindHook($metaData));
}
}
|
Change directory check to prevent PHP warning | <?php namespace NZTim\Logger\Handlers;
use NZTim\Logger\Entry;
use Monolog\Logger as MonologLogger;
use Monolog\Handler\StreamHandler;
class FileHandler implements Handler
{
/**
* @param Entry $entry
* @return null
*/
public function write(Entry $entry)
{
$log = new MonologLogger($entry->getChannel());
$log->pushHandler(new StreamHandler($this->getPath($entry->getChannel()), $entry->getCode()));
$log->addRecord($entry->getCode(), $entry->getMessage(), $entry->getContext());
}
/**
* @param string $channel
* @return string
*/
protected function getPath($channel)
{
$ds = DIRECTORY_SEPARATOR;
$path = storage_path() . "{$ds}logs{$ds}custom";
if (!is_dir($path) && !file_exists($path)) {
mkdir($path, 0755);
}
return "{$path}{$ds}{$channel}.log";
}
} | <?php namespace NZTim\Logger\Handlers;
use NZTim\Logger\Entry;
use Monolog\Logger as MonologLogger;
use Monolog\Handler\StreamHandler;
class FileHandler implements Handler
{
/**
* @param Entry $entry
* @return null
*/
public function write(Entry $entry)
{
$log = new MonologLogger($entry->getChannel());
$log->pushHandler(new StreamHandler($this->getPath($entry->getChannel()), $entry->getCode()));
$log->addRecord($entry->getCode(), $entry->getMessage(), $entry->getContext());
}
/**
* @param string $channel
* @return string
*/
protected function getPath($channel)
{
$ds = DIRECTORY_SEPARATOR;
$path = storage_path() . "{$ds}logs{$ds}custom";
if (!file_exists($path)) {
mkdir($path, 0755);
}
return "{$path}{$ds}{$channel}.log";
}
} |
Update react-server-gulp-module-tagger to use new interface | var replace = require("gulp-replace")
, forEach = require("gulp-foreach")
, loggerSpec = require("react-server-module-tagger")
// This pattern matches either of these:
// - "__LOGGER__"
// - "__LOGGER__({ /* options */ })"
var isWindows = ('win32' === process.platform)
, REPLACE_TOKEN = /(?:__LOGGER__|__CHANNEL__|__CACHE__)(?:\(\s*(\{[\s\S]*?\})\s*\))?/g
, THIS_MODULE = isWindows
? /(?:[^\\]+\\node_modules\\)?react-server-gulp-module-tagger\\index\.js$/
: /(?:[^\/]+\/node_modules\/)?react-server-gulp-module-tagger\/index\.js$/
module.exports = function(config) {
config || (config = {});
config.basePath = module.filename.replace(THIS_MODULE,'');
return forEach(function(stream, file){
return stream.pipe(replace(REPLACE_TOKEN, (match, optString) => {
return loggerSpec({
filePath: file.path,
basePath: config.basePath,
trim: config.trim, optString,
});
}));
});
}
| var replace = require("gulp-replace")
, forEach = require("gulp-foreach")
, loggerSpec = require("react-server-module-tagger")
// This pattern matches either of these:
// - "__LOGGER__"
// - "__LOGGER__({ /* options */ })"
var isWindows = ('win32' === process.platform)
, REPLACE_TOKEN = /(?:__LOGGER__|__CHANNEL__|__CACHE__)(?:\(\s*(\{[\s\S]*?\})\s*\))?/g
, THIS_MODULE = isWindows
? /(?:[^\\]+\\node_modules\\)?react-server-gulp-module-tagger\\index\.js$/
: /(?:[^\/]+\/node_modules\/)?react-server-gulp-module-tagger\/index\.js$/
module.exports = function(config) {
config || (config = {});
config.basePath = module.filename.replace(THIS_MODULE,'');
return forEach(function(stream, file){
return stream.pipe(replace(REPLACE_TOKEN, loggerSpec.bind({file, config})));
});
}
|
Make 'button' component more obviously private. | 'use strict';
var VNode = require('virtual-dom').VNode;
var VText = require('virtual-dom').VText;
/**
* Button.
* @private
*
* @param {object} props
* @param {string} props.text
* @param {function} [props.onClick]
* @param {string} [props.style=primary]
* @param {string} [props.type=button]
* @returns {VNode}
*/
function _button(props) {
var className = 'coins-logon-widget-button';
var onClick = props.onClick;
var style = props.style || 'primary';
var text = props.text;
var type = props.type || 'button';
className += ' coins-logon-widget-button-' + style;
var properties = {
className: className,
type: type,
};
if (onClick) {
properties.onclick = onClick;
}
return new VNode('button', properties, [new VText(text)]);
}
/**
* Button group.
*
* @see button
*
* @{param} {...object} props Properties passed to `button`
* @returns {VNode}
*/
function buttonGroup(props) {
var children = arguments.length > 1 ?
[].slice.call(arguments).map(_button) :
[_button(props)];
var className = 'coins-logon-widget-button-group';
return new VNode('div', { className: className }, children);
}
module.exports = buttonGroup;
| 'use strict';
var VNode = require('virtual-dom').VNode;
var VText = require('virtual-dom').VText;
/**
* Button.
*
* @param {object} props
* @param {string} props.text
* @param {function} [props.onClick]
* @param {string} [props.style=primary]
* @param {string} [props.type=button]
* @returns {VNode}
*/
function button(props) {
var className = 'coins-logon-widget-button';
var onClick = props.onClick;
var style = props.style || 'primary';
var text = props.text;
var type = props.type || 'button';
className += ' coins-logon-widget-button-' + style;
var properties = {
className: className,
type: type,
};
if (onClick) {
properties.onclick = onClick;
}
return new VNode('button', properties, [new VText(text)]);
}
/**
* Button group.
*
* @see button
*
* @{param} {...object} props Properties passed to `button`
* @returns {VNode}
*/
function buttonGroup(props) {
var children = arguments.length > 1 ?
[].slice.call(arguments).map(button) :
[button(props)];
var className = 'coins-logon-widget-button-group';
return new VNode('div', { className: className }, children);
}
module.exports = buttonGroup;
|
Refactor treenexus logic into a function | def index():
def GET():
return locals()
@request.restful()
def api():
response.view = 'generic.json'
def GET(resource,resource_id):
if not resource=='study': raise HTTP(400)
# return the correct nexson of study_id
return _get_nexson(resource_id)
def POST(resource,resource_id):
if not resource=='study': raise HTTP(400)
# overwrite the nexson of study_id with the POSTed data
# 1) verify that it is valid json
# 2) Update local treenexus git submodule at ./treenexus
# 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully.
# 4) If not, overwrite the correct nexson file on disk
# 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible)
# 6) return successfully
return dict()
return locals()
def _get_nexson(study_id):
# the internal file structure will change soon to study_id/study_id-N.json, where N=0,1,2,3...
nexson_file = file.open("treenexus/study/0/" + study_id + ".json")
return nexson_file.contents()
| def index():
def GET():
return locals()
@request.restful()
def api():
response.view = 'generic.json'
def GET(resource,resource_id):
if not resource=='study': raise HTTP(400)
# return the correct nexson of study_id
return dict()
def POST(resource,resource_id):
if not resource=='study': raise HTTP(400)
# overwrite the nexson of study_id with the POSTed data
# 1) verify that it is valid json
# 2) Update local treenexus git repo at ../treenexus
# 3) See if the hash of the current value of the file matches the hash of the POSTed data. If so, do nothing and return successfully.
# 4) If not, overwrite the correct nexson file on disk
# 5) Make a git commit with the updated nexson (add as much automated metadata to the commit message as possible)
# 6) return successfully
return dict()
return locals()
|
Drop tables for audited before run tests | package audited_test
import (
"fmt"
"testing"
"github.com/jinzhu/gorm"
"github.com/qor/qor/audited"
"github.com/qor/qor/test/utils"
)
type Product struct {
gorm.Model
Name string
audited.AuditedModel
}
type User struct {
gorm.Model
Name string
}
var db *gorm.DB
func init() {
db = utils.TestDB()
db.DropTable(&User{}, &Product{})
db.AutoMigrate(&User{}, &Product{})
audited.RegisterCallbacks(db)
}
func TestCreateUser(t *testing.T) {
user := User{Name: "user1"}
db.Save(&user)
db := db.Set("qor:current_user", user)
product := Product{Name: "product1"}
db.Save(&product)
if product.CreatedBy != fmt.Sprintf("%v", user.ID) {
t.Errorf("created_by is not equal current user")
}
product.Name = "product_new"
db.Save(&product)
if product.UpdatedBy != fmt.Sprintf("%v", user.ID) {
t.Errorf("updated_by is not equal current user")
}
}
| package audited_test
import (
"fmt"
"testing"
"github.com/jinzhu/gorm"
"github.com/qor/qor/audited"
"github.com/qor/qor/test/utils"
)
type Product struct {
gorm.Model
Name string
audited.AuditedModel
}
type User struct {
gorm.Model
Name string
}
var db *gorm.DB
func init() {
db = utils.TestDB()
db.AutoMigrate(&User{}, &Product{})
audited.RegisterCallbacks(db)
}
func TestCreateUser(t *testing.T) {
user := User{Name: "user1"}
db.Save(&user)
db := db.Set("qor:current_user", user)
product := Product{Name: "product1"}
db.Save(&product)
if product.CreatedBy != fmt.Sprintf("%v", user.ID) {
t.Errorf("created_by is not equal current user")
}
product.Name = "product_new"
db.Save(&product)
if product.UpdatedBy != fmt.Sprintf("%v", user.ID) {
t.Errorf("updated_by is not equal current user")
}
}
|
Fix broken submission on Python 3.
- this breaks Python 2, but we don't care any more.
https://trello.com/c/Uak7y047/8-feedback-forms | import requests
from werkzeug.exceptions import ServiceUnavailable
from werkzeug.datastructures import MultiDict
from werkzeug.urls import url_parse
from flask import current_app, request, redirect, flash, Markup
from .. import main
@main.route('/feedback', methods=["POST"])
def send_feedback():
feedback_config = current_app.config['DM_FEEDBACK_FORM']
form_data = MultiDict()
for field, google_form_field in feedback_config['fields'].items():
form_data.setlist(google_form_field, request.form.getlist(field))
result = requests.post(feedback_config['uri'], list(form_data.items(multi=True)))
if result.status_code != 200:
raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code))
came_from = url_parse(request.form['uri'])
# strip netloc and scheme as we should ignore attempts to make us redirect elsewhere
replaced = came_from._replace(scheme='', netloc='')
flash(Markup(
"""Thank you for your message. If you have more extensive feedback, please
<a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or
<a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>.
"""))
return redirect(replaced, code=303)
| import requests
from werkzeug.exceptions import ServiceUnavailable
from werkzeug.datastructures import MultiDict
from werkzeug.urls import url_parse
from flask import current_app, request, redirect, flash, Markup
from .. import main
@main.route('/feedback', methods=["POST"])
def send_feedback():
feedback_config = current_app.config['DM_FEEDBACK_FORM']
form_data = MultiDict()
for field, google_form_field in feedback_config['fields'].items():
form_data.setlist(google_form_field, request.form.getlist(field))
result = requests.post(feedback_config['uri'], list(form_data.iteritems(multi=True)))
if result.status_code != 200:
raise ServiceUnavailable('Google forms submission problem (status %d)'.format(result.status_code))
came_from = url_parse(request.form['uri'])
# strip netloc and scheme as we should ignore attempts to make us redirect elsewhere
replaced = came_from._replace(scheme='', netloc='')
flash(Markup(
"""Thank you for your message. If you have more extensive feedback, please
<a href="mailto:enquiries@digitalmarketplace.service.gov.uk">email us</a> or
<a href="https://airtable.com/shrkFM8L6Wfenzn5Q">take part in our research</a>.
"""))
return redirect(replaced, code=303)
|
Add cookiecutter to install reqs | from setuptools import setup, find_packages
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs')
codecs.register(func)
setup(
name='Matador',
version='1.6.2',
author='Owen Campbell',
author_email='owen.campbell@empiria.co.uk',
entry_points={
'console_scripts': [
'matador = matador.management:execute_command',
],
},
options={
'build_scripts': {
'executable': '/usr/bin/env python3',
},
},
url='http://www.empiria.co.uk',
packages=find_packages(),
setup_requires=['pytest-runner'],
tests_require=['pytest'],
install_requires=['pyyaml', 'dulwich', 'openpyxl', 'cookiecutter'],
license='The MIT License (MIT)',
description='Change management for Agresso systems',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Natural Language :: English'
]
)
| from setuptools import setup, find_packages
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs')
codecs.register(func)
setup(
name='Matador',
version='1.6.2',
author='Owen Campbell',
author_email='owen.campbell@empiria.co.uk',
entry_points={
'console_scripts': [
'matador = matador.management:execute_command',
],
},
options={
'build_scripts': {
'executable': '/usr/bin/env python3',
},
},
url='http://www.empiria.co.uk',
packages=find_packages(),
setup_requires=['pytest-runner'],
tests_require=['pytest'],
install_requires=['pyyaml', 'dulwich', 'openpyxl'],
license='The MIT License (MIT)',
description='Change management for Agresso systems',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Natural Language :: English'
]
)
|
Change to local OpenCPU server as default. | "use strict";
var request = require("request");
function rCall(command, args, callback, options) {
var opts = options || {},
url,
method = Object.keys(args).length ? "POST" : "GET";
opts.server = opts.server || "http://localhost:5307";
opts.root = opts.root || "/ocpu";
url = opts.server + opts.root + command;
request({
method: method,
uri: url,
body: JSON.stringify(args),
headers: { "Content-Type": "application/json" }
}, function (err, response, data) {
err = err || response.statusCode === 400;
if (/json$/.test(url)) {
data = JSON.parse(data);
}
callback(err, data);
});
}
exports.rCall = rCall;
| "use strict";
var request = require("request");
function rCall(command, args, callback, options) {
var opts = options || {},
url,
method = Object.keys(args).length ? "POST" : "GET";
opts.server = opts.server || "https://public.opencpu.org";
opts.root = opts.root || "/ocpu";
url = opts.server + opts.root + command;
request({
method: method,
uri: url,
body: JSON.stringify(args),
headers: { "Content-Type": "application/json" }
}, function (err, response, data) {
err = err || response.statusCode === 400;
if (/json$/.test(url)) {
data = JSON.parse(data);
}
callback(err, data);
});
}
exports.rCall = rCall;
|
Fix some code
변수가 아닌 메서드 사용 | package cloud.swiftnode.kspam.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
/**
* Created by Junhyeong Lim on 2017-01-18.
*/
public class StaticUtil {
private static Random random = new Random();
public static InetAddress getRandomAddr() throws UnknownHostException {
byte[] addrs = new byte[4];
getRandom().nextBytes(addrs);
return InetAddress.getByAddress(addrs);
}
public static String getRandomName() {
int max = 12;
char[] seed = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ".toCharArray();
char[] nameChars = new char[max];
for (int i = 0; i < max; i++) {
nameChars[i] = seed[getRandom().nextInt(seed.length)];
}
return new String(nameChars);
}
public static Random getRandom() {
return random;
}
}
| package cloud.swiftnode.kspam.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
/**
* Created by Junhyeong Lim on 2017-01-18.
*/
public class StaticUtil {
private static Random random = new Random();
public static InetAddress getRandomAddr() throws UnknownHostException {
byte[] addrs = new byte[4];
random.nextBytes(addrs);
return InetAddress.getByAddress(addrs);
}
public static String getRandomName() {
int max = 12;
char[] seed = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ".toCharArray();
char[] nameChars = new char[max];
for (int i = 0; i < max; i++) {
nameChars[i] = seed[random.nextInt(seed.length)];
}
return new String(nameChars);
}
public static Random getRandom() {
return random;
}
}
|
Remove accidentally committed logging statement. | /*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name PlacedItem
*
* @class The PlacedItem class is the base for any items that have a matrix
* associated with them, describing their placement in the project, such as
* {@link Raster} and {@link PlacedSymbol}.
*
* @extends Item
*/
var PlacedItem = this.PlacedItem = Item.extend(/** @lends PlacedItem# */{
// PlacedItem uses strokeBounds for bounds
_boundsType: { bounds: 'strokeBounds' },
_hitTest: function(point, options, matrix) {
point = point.transform(this.matrix);
var hitResult = this._symbol._definition.hitTest(point, options, matrix);
// TODO: When the symbol's definition is a path, should hitResult contain
// information like HitResult#curve?
if (hitResult)
hitResult.item = this;
return hitResult;
}
}); | /*
* Paper.js
*
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
* http://paperjs.org/
* http://scriptographer.org/
*
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name PlacedItem
*
* @class The PlacedItem class is the base for any items that have a matrix
* associated with them, describing their placement in the project, such as
* {@link Raster} and {@link PlacedSymbol}.
*
* @extends Item
*/
var PlacedItem = this.PlacedItem = Item.extend(/** @lends PlacedItem# */{
// PlacedItem uses strokeBounds for bounds
_boundsType: { bounds: 'strokeBounds' },
_hitTest: function(point, options, matrix) {
console.log(point);
point = point.transform(this.matrix);
var hitResult = this._symbol._definition.hitTest(point, options, matrix);
// TODO: When the symbol's definition is a path, should hitResult contain
// information like HitResult#curve?
if (hitResult)
hitResult.item = this;
return hitResult;
}
}); |
Change location of test file | 'use strict';
var <%= safeSlugname %> = require('../index.js');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.<%= safeSlugname %> = {
setUp: function(done) {
// setup here
done();
},
'no args': function(test) {
test.expect(1);
// tests here
test.equal(<%= safeSlugname %>.awesome(), 'awesome', 'should be awesome.');
test.done();
}
};
| 'use strict';
var <%= safeSlugname %> = require('../lib/<%= slugname %>.js');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.<%= safeSlugname %> = {
setUp: function(done) {
// setup here
done();
},
'no args': function(test) {
test.expect(1);
// tests here
test.equal(<%= safeSlugname %>.awesome(), 'awesome', 'should be awesome.');
test.done();
}
};
|
Fix for a wrongly named variable introduced when cleaning up | 'use strict';
function randomIntFromInterval(min,max){return Math.floor(Math.random()*(max-min+1)+min);};
var markovGenerator = {
order: 2,
table:{},
load:function(text){
text = text.toLowerCase();
//text.replace(/[^a-z ]/, '');
for (var i = this.order; i < text.length; i++){
var entry = text.slice(i-this.order, i);
if(Array.isArray(this.table[entry])){
this.table[entry].push(text.charAt(i));
}else{
this.table[entry] = [text.charAt(i)];
}
}
},
generate:function(length, start){
if(length == undefined){
throw 'tooFewArguments';
}
if(start == undefined){
var possibleKeys = Object.keys(this.table);
start = possibleKeys[randomIntFromInterval(0, possibleKeys.length)];
}
var text = start;
while(text.length < length){
var key = text.slice(text.length-this.order, text.length);
var possibilities = this.table[key];
var letter = possibilities[randomIntFromInterval(0, possibilities.length-1)];
text += letter;
}
return text;
}
} | 'use strict';
function randomIntFromInterval(min,max){return Math.floor(Math.random()*(max-min+1)+min);};
var markovGenerator = {
order: 2,
table:{},
load:function(text){
text = text.toLowerCase();
//text.replace(/[^a-z ]/, '');
for (var i = this.settings.order; i < text.length; i++){
var entry = text.slice(i-this.order, i);
if(Array.isArray(this.table[entry])){
this.table[entry].push(text.charAt(i));
}else{
this.table[entry] = [text.charAt(i)];
}
}
},
generate:function(length, start){
if(length == undefined){
throw 'tooFewArguments';
}
if(start == undefined){
var possibleKeys = Object.keys(this.table);
start = possibleKeys[randomIntFromInterval(0, possibleKeys.length)];
}
var text = start;
while(text.length < length){
var key = text.slice(text.length-this.order, text.length);
var possibilities = this.table[key];
var letter = possibilities[randomIntFromInterval(0, possibilities.length-1)];
text += letter;
}
return text;
}
} |
Rewrite Commander interface methods and phpdoc | <?php
/*
* This file is part of the Yodler package.
*
* (c) aes3xs <aes3xs@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Aes3xs\Yodler\Commander;
/**
* Interface to commander.
*
* Commander is actually performs shell commands during deploy.
*/
interface CommanderInterface
{
/**
* Execute command.
*
* Returns command output or false on error.
*
* @param $command
*
* @return string|bool
*/
public function exec($command);
/**
* Upload file.
*
* @param $local
* @param $remote
*
* @return bool
*/
public function send($local, $remote);
/**
* Download file.
*
* @param $remote
* @param $local
*
* @return bool
*/
public function recv($remote, $local);
}
| <?php
/*
* This file is part of the Yodler package.
*
* (c) aes3xs <aes3xs@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Aes3xs\Yodler\Commander;
/**
* Interface to commander.
*
* Commander is actually performs shell commands during deploy.
*/
interface CommanderInterface
{
/**
* Execute command.
*
* @param $command
*/
public function exec($command);
/**
* Upload file.
*
* @param $local
* @param $remote
*/
public function upload($local, $remote);
/**
* Download file.
*
* @param $remote
* @param $local
*/
public function download($remote, $local);
}
|
Change writeMessage example to show arbituary data write | 'use strict';
var async = require('asyncawait/async');
var OrbitClient = require('../OrbitClient');
var Timer = require('../Timer');
var host = 'localhost:3006';
var username = 'testrunner';
var password = '';
let run = (async(() => {
try {
var channel = 'hello-world-test1'
// Connect
var orbit = OrbitClient.connect(host, username, password);
// Delete channel and its data
var result = orbit.channel(channel, '').delete();
var messages = 100;
var i = 0;
while(i < messages) {
var timer = new Timer(true);
// Send a message
var head = orbit.channel(channel, '').send(JSON.stringify({ omg: "hello" }));
console.log(i, head, timer.stop() + "ms");
i ++;
}
} catch(e) {
console.error("error:", e);
console.error(e.stack);
process.exit(1);
}
}))();
module.exports = run;
| 'use strict';
var async = require('asyncawait/async');
var OrbitClient = require('../OrbitClient');
var Timer = require('../Timer');
var host = 'localhost:3006';
var username = 'testrunner';
var password = '';
let run = (async(() => {
try {
var channel = 'hello-world-test1'
// Connect
var orbit = OrbitClient.connect(host, username, password);
// Delete channel and its data
var result = orbit.channel(channel, '').delete();
var messages = 100;
var i = 0;
while(i < messages) {
var timer = new Timer(true);
// Send a message
var head = orbit.channel(channel, '').send('hello');
console.log(i, head, timer.stop() + "ms");
i ++;
}
} catch(e) {
console.error("error:", e);
console.error(e.stack);
process.exit(1);
}
}))();
module.exports = run;
|
Fix bug in nick configuration | from ConfigParser import SafeConfigParser
class ConfReader(object):
def __init__(self, fn):
defaults = {
'nickname': 'pollirio',
'channel': '#polloalforno',
'server_addr': 'calvino.freenode.net',
'server_port': 6667
}
self.__slots__ = defaults.keys()
config = SafeConfigParser(defaults)
config.read(fn)
for name, default in defaults.iteritems():
if type(default) == int:
self.__dict__[name] = config.getint('global', name)
elif type(default) == float:
self.__dict__[name] = config.getfloat('global', name)
else:
self.__dict__[name] = config.get('global', name)
| from ConfigParser import SafeConfigParser
class ConfReader(object):
def __init__(self, fn):
defaults = {
'nick': 'pollirio',
'channel': '#polloalforno',
'server_addr': 'calvino.freenode.net',
'server_port': 6667
}
self.__slots__ = defaults.keys()
config = SafeConfigParser(defaults)
config.read(fn)
for name, default in defaults.iteritems():
if type(default) == int:
self.__dict__[name] = config.getint('global', name)
elif type(default) == float:
self.__dict__[name] = config.getfloat('global', name)
else:
self.__dict__[name] = config.get('global', name)
|
Add notification setting to database migrations. | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEmployersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employers', function (Blueprint $table) {
$table->uuid('id')->unique();
$table->primary('id');
$table->string('name');
$table->string('email')->unique();
$table->string('state');
$table->string('city');
$table->boolean('notifyapply')->default(0);
$table->boolean('notifymarketing')->default(0);
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employers');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEmployersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employers', function (Blueprint $table) {
$table->uuid('id')->unique();
$table->primary('id');
$table->string('name');
$table->string('email')->unique();
$table->string('state');
$table->string('city');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employers');
}
}
|
Fix echo to print SOURCE_NAME | <?php
define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
define("SOURCE_NAME", "David's Alerts");
$alerts = array(
"Coldest Air of the Season Sweeping Through Central and Southern States",
"Belgium on 'high alert'",
"Multiple raids in Brussels as police seek ISIS terrorists",
"Syria fighters may be fueled by amphetamines",
"Alien invasion? Strange sightings in Hong Kong",
"Experts criticise WHO delay in sounding alarm over Ebola outbreak"
);
$alerts_levels = array("low", "medium", "high");
date_default_timezone_set("Europe/Madrid");
header("Content-Type: text/event-stream\n\n");
while (true) {
sleep(SECONDS_BETWEEN_ALERTS);
sendAlert($alerts[rand(0, sizeof($alerts) - 1)],
$alerts_levels[rand(0, sizeof($alerts_levels) - 1)]);
ob_end_flush();
flush();
}
function sendAlert($message, $alert_level) {
$date = date_create();
$timestamp = date_timestamp_get($date);
echo "data: { \"source\": \"" . SOURCE_NAME . "\", \"message\": \"$message\", " .
"\"alertLevel\": \"$alert_level\", \"timestamp\": $timestamp }\n\n";
}
?>
| <?php
define("SECONDS_BETWEEN_ALERTS", rand(10, 60));
define("SOURCE_NAME", "David's Alerts");
$alerts = array(
"Coldest Air of the Season Sweeping Through Central and Southern States",
"Belgium on 'high alert'",
"Multiple raids in Brussels as police seek ISIS terrorists",
"Syria fighters may be fueled by amphetamines",
"Alien invasion? Strange sightings in Hong Kong",
"Experts criticise WHO delay in sounding alarm over Ebola outbreak"
);
$alerts_levels = array("low", "medium", "high");
date_default_timezone_set("Europe/Madrid");
header("Content-Type: text/event-stream\n\n");
while (true) {
sleep(SECONDS_BETWEEN_ALERTS);
sendAlert($alerts[rand(0, sizeof($alerts) - 1)],
$alerts_levels[rand(0, sizeof($alerts_levels) - 1)]);
ob_end_flush();
flush();
}
function sendAlert($message, $alert_level) {
$date = date_create();
$timestamp = date_timestamp_get($date);
echo "data: { \"source\": \"$SOURCE_NAME\", \"message\": \"$message\", " .
"\"alertLevel\": \"$alert_level\", \"timestamp\": $timestamp }\n\n";
}
?>
|
Add babel sourcemaps in dev | var ExtractTextPlugin = require("extract-text-webpack-plugin");
var CopyWebpackPlugin = require("copy-webpack-plugin");
var webpack = require('webpack')
var WebpackNotifierPlugin = require('webpack-notifier')
module.exports = {
entry: ["./web/static/css/app.css", "./web/static/js/app.js"],
output: {
path: "./priv/static",
filename: "js/app.js"
},
resolve: {
modulesDirectories: [ "node_modules", __dirname + "/web/static/js" ]
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel",
query: {
presets: ["es2015", "react"]
}
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract("style", "css")
}]
},
devtool: "source-map",
plugins: [
new WebpackNotifierPlugin({ skipFirstNotification: true }),
new ExtractTextPlugin("css/app.css"),
new CopyWebpackPlugin([{ from: "./web/static/assets" }]),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
]
};
| var ExtractTextPlugin = require("extract-text-webpack-plugin");
var CopyWebpackPlugin = require("copy-webpack-plugin");
var webpack = require('webpack')
var WebpackNotifierPlugin = require('webpack-notifier')
module.exports = {
entry: ["./web/static/css/app.css", "./web/static/js/app.js"],
output: {
path: "./priv/static",
filename: "js/app.js"
},
resolve: {
modulesDirectories: [ "node_modules", __dirname + "/web/static/js" ]
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel",
query: {
presets: ["es2015", "react"]
}
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract("style", "css")
}]
},
plugins: [
new WebpackNotifierPlugin({ skipFirstNotification: true }),
new ExtractTextPlugin("css/app.css"),
new CopyWebpackPlugin([{ from: "./web/static/assets" }]),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
]
};
|
Fix error where book id wasn't cast to string | from datetime import datetime
from django.db import models
class Author(models.Model):
'''Object for book author'''
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
def __unicode__(self):
return self.last_name + ", " + self.first_name
class Book(models.Model):
'''Object for library books'''
title = models.CharField(max_length=128)
isbn = models.CharField(max_length=13)
isbn13 = models.CharField(max_length=13)
description = models.TextField()
authors = models.ManyToManyField(Author)
year_published = models.SmallIntegerField(null=True)
status = models.TextField(default="In")
def __unicode__(self):
return self.title
class Reservation(models.Model):
'''Object for book reservations'''
book_id = models.ForeignKey('Book')
member_name = models.CharField(max_length=128)
email = models.EmailField()
date_created = models.DateTimeField(default=datetime.now())
def __unicode__(self):
return self.member_name + ": " + str(self.book_id)
| from datetime import datetime
from django.db import models
class Author(models.Model):
'''Object for book author'''
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
def __unicode__(self):
return self.last_name + ", " + self.first_name
class Book(models.Model):
'''Object for library books'''
title = models.CharField(max_length=128)
isbn = models.CharField(max_length=13)
isbn13 = models.CharField(max_length=13)
description = models.TextField()
authors = models.ManyToManyField(Author)
year_published = models.SmallIntegerField(null=True)
status = models.TextField(default="In")
def __unicode__(self):
return self.title
class Reservation(models.Model):
'''Object for book reservations'''
book_id = models.ForeignKey('Book')
member_name = models.CharField(max_length=128)
email = models.EmailField()
date_created = models.DateTimeField(default=datetime.now())
def __unicode__(self):
return self.member_name + ":" + self.book_id
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.