text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Set window title in application | package rpi.lmsgrabber;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@SuppressWarnings("restriction")
public class App extends Application {
private static final Logger logger = LogManager.getLogger();
private Stage primaryStage;
private Pane rootLayout;
@Override
public void start(Stage primaryStage) {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/ui_mockup.fxml"));
rootLayout = loader.load();
primaryStage.setTitle("LMSGrabber");
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
logger.error("IOException", e);
}
}
public static void main(String[] args) {
launch(args);
}
}
| package rpi.lmsgrabber;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@SuppressWarnings("restriction")
public class App extends Application {
private static final Logger logger = LogManager.getLogger();
private Stage primaryStage;
private Pane rootLayout;
@Override
public void start(Stage primaryStage) {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/ui_mockup.fxml"));
rootLayout = loader.load();
// Show the scene containing the root layout.
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
logger.error("IOException", e);
}
}
public static void main(String[] args) {
launch(args);
}
}
|
Handle errors in cron notifications | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from api import models
from web.utils import send_email
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
notifications = models.Notification.objects.filter(email_sent=False).select_related('owner', 'owner__preferences')
for notification in notifications:
preferences = notification.owner.preferences
if preferences.is_notification_email_allowed(notification.message):
try:
send_email(
subject=(u'School Idol Tomodachi' + u'✨ ' + u' Notification: ' + notification.english_message),
template_name = 'notification',
to=[notification.owner.email, '[email protected]'],
context={
'notification': notification,
'user': notification.owner,
},
)
print 'Email sent to {}: {}'.format(notification.owner.username, notification.localized_message)
except Exception, e:
print '!! Error when sending email to {} !!'.format(notification.owner.email)
print e
# todo ios push notifications
else:
print ' No email for {}: {}'.format(notification.owner.username, notification.localized_message)
notification.email_sent = True
notification.save()
| # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from api import models
from web.utils import send_email
class Command(BaseCommand):
can_import_settings = True
def handle(self, *args, **options):
notifications = models.Notification.objects.filter(email_sent=False).select_related('owner', 'owner__preferences')
for notification in notifications:
preferences = notification.owner.preferences
if preferences.is_notification_email_allowed(notification.message):
send_email(
subject=(u'School Idol Tomodachi' + u'✨ ' + u' Notification: ' + notification.english_message),
template_name = 'notification',
to=[notification.owner.email, '[email protected]'],
context={
'notification': notification,
'user': notification.owner,
},
)
# todo ios push notifications
print 'Email sent to {}: {}'.format(notification.owner.username, notification.localized_message)
else:
print ' No email for {}: {}'.format(notification.owner.username, notification.localized_message)
notification.email_sent = True
notification.save()
|
Fix issue in refinery contract | <?php
namespace Michaeljennings\Refinery\Contracts;
interface Refinery
{
/**
* Refine the item(s) using the set template.
*
* @param mixed $raw
* @return mixed
*/
public function refine($raw);
/**
* Refine a collection of raw items.
*
* @param mixed $raw
* @return array
*/
public function refineCollection($raw);
/**
* Set the attachments you want to bring with the refined items.
*
* @param string|array $attachments
* @return $this
*/
public function bring($attachments);
/**
* Set the class to be used for the attachment.
*
* @param string $className
* @param callable|bool $callback
* @return array
* @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
*/
public function attach($className, callable $callback = false);
/**
* Alias for the attach method.
*
* @param string $className
* @param callable $callback
* @return array
* @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
*/
public function embed($className, callable $callback = false);
/**
* Alias for the attach method.
*
* @param string $className
* @param callable $callback
* @return array
* @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFoundg
*/
public function nest($className, callable $callback = false);
} | <?php
namespace Michaeljennings\Refinery\Contracts;
interface Refinery
{
/**
* Refine the item(s) using the set template.
*
* @param mixed $raw
* @return mixed
*/
public function refine($raw);
/**
* Refine a collection of raw items.
*
* @param mixed $raw
* @return array
*/
public function refineCollection($raw);
/**
* Set the attachments you want to bring with the refined items.
*
* @param string|array $attachments
* @return $this
*/
public function bring($attachments);
/**
* Set the class to be used for the attachment.
*
* @param string $className
* @param callable|bool $callback
* @return array
* @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
*/
public function attach($className, callable $callback = false);
/**
* Alias for the attach method.
*
* @param string $className
* @param callable $callback
* @return array
* @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
*/
public function embed($className, callable $callback = false);
/**
* Alias for the attach method.
*
* @param string $className
* @param callable $callback
* @return array
* @throws \Michaeljennings\Refinery\Exceptions\AttachmentClassNotFound
*/
public function nest($className, callable $callback = false)
} |
Allow to set items in AST. | from collections import OrderedDict, Mapping
import json
__all__ = ['AST']
class AST(Mapping):
def __init__(self, **kwargs):
self._elements = OrderedDict(**kwargs)
def add(self, key, value):
previous = self._elements.get(key, None)
if previous is None:
self._elements[key] = [value]
else:
previous.append(value)
def update(self, *args, **kwargs):
for dct in args:
for k, v in dct:
self.add(k, v)
for k, v in kwargs.items():
self.add(k, v)
@property
def first(self):
key = self.elements.keys[0]
return self.elements[key]
def __iter__(self):
return iter(self._elements)
def __contains__(self, key):
return key in self._elements
def __len__(self):
return len(self._elements)
def __getitem__(self, key):
if key not in self._elements:
self._elements[key] = list()
return self._elements[key]
def __setitem__(self, key, value):
self._elements[key] = value
def __getattr__(self, key):
return self.__getitem__(key)
if key in self._elements:
return self.__getitem__(key)
raise KeyError(key)
@staticmethod
def serializable(obj):
if isinstance(obj, AST):
return obj._elements
return obj
def __repr__(self):
return self.serializable(self._elements)
def __str__(self):
return json.dumps(self._elements, indent=4, default=self.serializable)
| from collections import OrderedDict, Mapping
import json
class AST(Mapping):
def __init__(self, **kwargs):
self._elements = OrderedDict(**kwargs)
def add(self, key, value):
previous = self._elements.get(key, None)
if previous is None:
self._elements[key] = [value]
else:
previous.append(value)
def update(self, *args, **kwargs):
for dct in args:
for k, v in dct:
self.add(k, v)
for k, v in kwargs.items():
self.add(k, v)
@property
def first(self):
key = self.elements.keys[0]
return self.elements[key]
def __iter__(self):
return iter(self._elements)
def __contains__(self, key):
return key in self._elements
def __len__(self):
return len(self._elements)
def __getitem__(self, key):
if key not in self._elements:
self._elements[key] = list()
return self._elements[key]
def __getattr__(self, key):
return self.__getitem__(key)
if key in self._elements:
return self.__getitem__(key)
raise KeyError(key)
@staticmethod
def serializable(obj):
if isinstance(obj, AST):
return obj._elements
return obj
def __repr__(self):
return self.serializable(self._elements)
def __str__(self):
return json.dumps(self._elements, indent=4, default=self.serializable)
|
Support filtering all test cases without failing the whole test suite
If all test cases in a test suite fails, jest will complain and fail the whole suite. This can be worked around by adding a skipped test if there's no other test. | /* global describe it beforeAll beforeEach afterAll afterEach fail */
const BotiumBindings = require('../BotiumBindings')
const defaultTimeout = 60000
const setupJasmineTestCases = ({ timeout = defaultTimeout, testcaseSelector, bb } = {}) => {
bb = bb || new BotiumBindings()
bb.setupTestSuite(
(testcase, testcaseFunction) => {
if (testcaseSelector && !testcaseSelector(testcase)) return false
it(
testcase.header.name,
(done) => {
testcaseFunction((err) => {
if (err) {
fail(err)
}
done()
})
},
timeout)
return true
},
null,
(err) => fail(err)
)
}
const setupJasmineTestSuite = ({ timeout = defaultTimeout, name, testcaseSelector, bb } = {}) => {
bb = bb || new BotiumBindings()
name = name || bb.getTestSuiteName()
describe(name, () => {
beforeAll((done) => {
bb.beforeAll().then(() => done()).catch(done.fail)
}, timeout)
beforeEach((done) => {
bb.beforeEach().then(() => done()).catch(done.fail)
}, timeout)
afterEach((done) => {
bb.afterEach().then(() => done()).catch(done.fail)
}, timeout)
afterAll((done) => {
bb.afterAll().then(() => done()).catch(done.fail)
}, timeout)
setupJasmineTestCases({ timeout, testcaseSelector, bb })
})
}
module.exports = {
setupJasmineTestCases,
setupJasmineTestSuite
}
| /* global describe it beforeAll beforeEach afterAll afterEach fail */
const BotiumBindings = require('../BotiumBindings')
const defaultTimeout = 60000
const setupJasmineTestCases = ({ timeout = defaultTimeout, testcaseSelector, bb } = {}) => {
bb = bb || new BotiumBindings()
bb.setupTestSuite(
(testcase, testcaseFunction) => {
if (testcaseSelector && !testcaseSelector(testcase)) return
it(
testcase.header.name,
(done) => {
testcaseFunction((err) => {
if (err) {
fail(err)
}
done()
})
},
timeout)
},
null,
(err) => fail(err)
)
}
const setupJasmineTestSuite = ({ timeout = defaultTimeout, name, testcaseSelector, bb } = {}) => {
bb = bb || new BotiumBindings()
name = name || bb.getTestSuiteName()
describe(name, () => {
beforeAll((done) => {
bb.beforeAll().then(() => done()).catch(done.fail)
}, timeout)
beforeEach((done) => {
bb.beforeEach().then(() => done()).catch(done.fail)
}, timeout)
afterEach((done) => {
bb.afterEach().then(() => done()).catch(done.fail)
}, timeout)
afterAll((done) => {
bb.afterAll().then(() => done()).catch(done.fail)
}, timeout)
setupJasmineTestCases({ timeout, testcaseSelector, bb })
})
}
module.exports = {
setupJasmineTestCases,
setupJasmineTestSuite
}
|
Set parameters of serial class to match with kilt | #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=38400,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
except Exception:
print("Bad initialisation! Check the configuration of "
"the serial port!")
exit()
self.ser.open()
self.ser.isOpen()
def loop(self):
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == "exit":
self.ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to
# the characters - this is requested by my device)
self.ser.write(input + "\r\n")
out = ""
# let's wait one second before reading output (let's give
# device time to answer)
time.sleep(1)
while self.ser.inWaiting() > 0:
out += self.ser.read(1)
if out != "":
print ">> " + out
def main():
b = Bumper()
b.loop()
if __name__ == "__main__":
main()
| #!/usr/bin/python
import time
import serial
# configure the serial connections (the parameters differs on the
# device you are connecting to)
class Bumper(object):
def __init__(self):
try:
self.ser = serial.Serial(
port="/dev/ttyS0",
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
except Exception:
print("Bad initialisation! Check the configuration of "
"the serial port!")
exit()
self.ser.open()
self.ser.isOpen()
def loop(self):
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == "exit":
self.ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to
# the characters - this is requested by my device)
self.ser.write(input + "\r\n")
out = ""
# let's wait one second before reading output (let's give
# device time to answer)
time.sleep(1)
while self.ser.inWaiting() > 0:
out += self.ser.read(1)
if out != "":
print ">> " + out
def main():
b = Bumper()
b.loop()
if __name__ == "__main__":
main()
|
Add removed posts as an API attribute | <?php namespace Flarum\Api\Serializers;
class DiscussionBasicSerializer extends BaseSerializer
{
/**
* The resource type.
*
* @var string
*/
protected $type = 'discussions';
/**
* Serialize attributes of a Discussion model for JSON output.
*
* @param Discussion $discussion The Discussion model to serialize.
* @return array
*/
protected function attributes($discussion)
{
$attributes = [
'title' => $discussion->title
];
if (count($discussion->removedPosts)) {
$attributes['removedPosts'] = $discussion->removedPosts;
}
return $this->extendAttributes($discussion, $attributes);
}
public function startUser()
{
return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
}
public function startPost()
{
return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
}
public function lastUser()
{
return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
}
public function lastPost()
{
return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
}
public function posts()
{
return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
}
public function relevantPosts()
{
return $this->hasMany('Flarum\Api\Serializers\PostBasicSerializer');
}
public function addedPosts()
{
return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
}
}
| <?php namespace Flarum\Api\Serializers;
class DiscussionBasicSerializer extends BaseSerializer
{
/**
* The resource type.
*
* @var string
*/
protected $type = 'discussions';
/**
* Serialize attributes of a Discussion model for JSON output.
*
* @param Discussion $discussion The Discussion model to serialize.
* @return array
*/
protected function attributes($discussion)
{
$attributes = [
'title' => $discussion->title
];
return $this->extendAttributes($discussion, $attributes);
}
public function startUser()
{
return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
}
public function startPost()
{
return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
}
public function lastUser()
{
return $this->hasOne('Flarum\Api\Serializers\UserBasicSerializer');
}
public function lastPost()
{
return $this->hasOne('Flarum\Api\Serializers\PostBasicSerializer');
}
public function posts()
{
return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
}
public function relevantPosts()
{
return $this->hasMany('Flarum\Api\Serializers\PostBasicSerializer');
}
public function addedPosts()
{
return $this->hasMany('Flarum\Api\Serializers\PostSerializer');
}
}
|
Add integration test via docker | 'use strict';
/*jslint nomen: true, stupid: true*/
module.exports = function (grunt) {
grunt.registerTask('integration-test', 'Run integration tests', [
'docker-integration-test'
]);
grunt.registerMultiTask('docker-integration-test', function runTask() {
/*eslint-disable no-invalid-this*/
if (String(global.build.options.BuildConfig.nodeMajorVersion) === process.env.DOCKER_INTEGRATION_TEST_NODE_VERSION) {
grunt.log.writeln('Integration test requested.');
var childProcess = require('child_process');
var path = require('path');
var fs = require('fs');
var directory = path.join(__dirname, 'integration');
var file = path.join(directory, 'build.sh');
/*eslint-disable no-sync*/
grunt.log.writeln('Running integration test script.');
fs.fchmodSync(file, 1411);
childProcess.execFileSync(file, {
cwd: directory,
encoding: 'utf8'
});
/*eslint-enable no-sync*/
} else {
grunt.log.writeln('Skipping integration test.');
}
/*eslint-enable no-invalid-this*/
});
return {
tasks: {
'docker-integration-test': {
full: {}
}
}
};
};
| 'use strict';
/*jslint nomen: true, stupid: true*/
module.exports = function (grunt) {
grunt.registerTask('integration-test', 'Run integration tests', [
'docker-integration-test'
]);
grunt.registerMultiTask('docker-integration-test', function runTask() {
/*eslint-disable no-invalid-this*/
if (String(global.build.options.BuildConfig.nodeMajorVersion) === process.env.DOCKER_INTEGRATION_TEST_NODE_VERSION) {
grunt.log.writeln('Integration test requested.');
var childProcess = require('child_process');
var path = require('path');
var directory = path.join(__dirname, 'integration');
var file = path.join(directory, 'build.sh');
/*eslint-disable no-sync*/
grunt.log.writeln('Running integration test script.');
childProcess.execFileSync(file, {
cwd: directory,
encoding: 'utf8'
});
/*eslint-enable no-sync*/
} else {
grunt.log.writeln('Skipping integration test.');
}
/*eslint-enable no-invalid-this*/
});
return {
tasks: {
'docker-integration-test': {
full: {}
}
}
};
};
|
Add new entry in pricetable Print&Copy section. | package io.github.proxyprint.kitchen.controllers.printshops;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import io.github.proxyprint.kitchen.models.printshops.PrintShop;
import io.github.proxyprint.kitchen.models.printshops.pricetable.PaperTableItem;
import io.github.proxyprint.kitchen.models.repositories.PrintShopDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Created by daniel on 27-04-2016.
*/
@RestController
public class ManagerController {
@Autowired
private PrintShopDAO printshops;
private final static Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@RequestMapping(value = "/printshops/{id}/pricetable/newpaperitem", method = RequestMethod.POST)
public String addNewPaperItem(@PathVariable(value = "id") long id, @RequestBody PaperTableItem pti) {
PrintShop pshop = printshops.findOne(id);
JsonObject response = new JsonObject();
if(pshop!=null) {
pshop.insertPaperItemsInPriceTable(pti);
printshops.save(pshop);
response.addProperty("success", true);
return GSON.toJson(response);
}
else{
response.addProperty("success", false);
return GSON.toJson(response);
}
}
}
| package io.github.proxyprint.kitchen.controllers.printshops;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import io.github.proxyprint.kitchen.models.printshops.PrintShop;
import io.github.proxyprint.kitchen.models.printshops.pricetable.PaperTableItem;
import io.github.proxyprint.kitchen.models.repositories.PrintShopDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Created by daniel on 27-04-2016.
*/
@RestController
public class ManagerController {
@Autowired
private PrintShopDAO printshops;
private final static Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@RequestMapping(value = "/printshops/{id}/pricetable/newpaperitem", method = RequestMethod.POST)
public String registerRequest(@PathVariable(value = "id") long id, @RequestBody PaperTableItem pti) {
PrintShop pshop = printshops.findOne(id);
JsonObject response = new JsonObject();
if(pshop!=null) {
pshop.insertPaperItemsInPriceTable(pti);
printshops.save(pshop);
response.addProperty("success", true);
return GSON.toJson(response);
}
else{
response.addProperty("success", false);
return GSON.toJson(response);
}
}
}
|
Send what state is saved | import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
"state": json.loads(experiment_context.current_state)
})
| import datetime
import json
from channels.generic.websocket import JsonWebsocketConsumer
from auth_API.helpers import get_or_create_user_information
from experiment.models import ExperimentAction
class ExperimentConsumer(JsonWebsocketConsumer):
##### WebSocket event handlers
def connect(self):
"""
Called when the websocket is handshaking as part of initial connection.
"""
# Accept the connection
self.accept()
def receive_json(self, content, **kwargs):
"""
Called when we get a text frame. Channels will JSON-decode the payload
for us and pass it as the first argument.
"""
# Get an updated session store
user_info = get_or_create_user_information(self.scope['session'], self.scope['user'], 'EOSS')
if hasattr(user_info, 'experimentcontext'):
experiment_context = user_info.experimentcontext
if content.get('msg_type') == 'add_action':
experiment_stage = experiment_context.experimentstage_set.all().order_by("id")[content['stage']]
ExperimentAction.objects.create(experimentstage=experiment_stage, action=json.dumps(content['action']),
date=datetime.datetime.utcnow())
self.send_json({
'action': content['action'],
'date': datetime.datetime.utcnow().isoformat()
})
elif content.get('msg_type') == 'update_state':
experiment_context.current_state = json.dumps(content['state'])
experiment_context.save()
self.send_json({
"state": content["state"]
})
|
Throw ValidatorExceptions instead of vanilla Exceptions for validation failures. | <?php
/**
* php-binary
* A PHP library for parsing structured binary streams
*
* @package php-binary
* @author Damien Walsh <[email protected]>
*/
namespace Binary\Field;
use Binary\Exception\ValidatorException;
use Binary\Validator\AbstractValidator;
/**
* Field
* Abstract.
*
* @since 1.0
*/
abstract class AbstractField implements FieldInterface
{
/**
* @public Binary\AbstractValidator[] Validators attached to the field.
*/
private $validators = array();
/**
* @public string The name of the field.
*/
public $name = '';
/**
* Attach a validator to the field.
*
* @param AbstractValidator $validator
*/
public function addValidator(AbstractValidator $validator)
{
$this->validators[] = $validator;
}
/**
* Check that the field is currently valid.
*/
public function validate($value)
{
try {
foreach ($this->validators as $validator) {
$validator->validate($value);
}
} catch (ValidatorException $exception) {
// Re-throw with field information
throw new \ValidatorException(
'Field ' . $this->name . ' failed validation: ' .
$exception->getMessage()
);
}
}
}
| <?php
/**
* php-binary
* A PHP library for parsing structured binary streams
*
* @package php-binary
* @author Damien Walsh <[email protected]>
*/
namespace Binary\Field;
use Binary\Exception\ValidatorException;
use Binary\Validator\AbstractValidator;
/**
* Field
* Abstract.
*
* @since 1.0
*/
abstract class AbstractField implements FieldInterface
{
/**
* @public Binary\AbstractValidator[] Validators attached to the field.
*/
private $validators = array();
/**
* @public string The name of the field.
*/
public $name = '';
/**
* Attach a validator to the field.
*
* @param AbstractValidator $validator
*/
public function addValidator(AbstractValidator $validator)
{
$this->validators[] = $validator;
}
/**
* Check that the field is currently valid.
*/
public function validate($value)
{
try {
foreach ($this->validators as $validator) {
$validator->validate($value);
}
} catch (ValidatorException $exception) {
// Re-throw with field information
throw new \Exception(
'Field ' . $this->name . ' failed validation: ' .
$exception->getMessage()
);
}
}
}
|
Add default value parameter when getting an input variable | <?php
/**
* Input handler
*
* Very basic input handler
*
* @author Adric Schreuders
*/
class Input {
private $vars;
public function Input($vars) {
$this->vars = $vars;
}
public function get($name = null, $default = null) {
if ($name === null) {
return $this->vars;
} else if (isset($this->vars[$name]) && $this->vars[$name] !== '') {
return $this->vars[$name];
} else {
return $default;
}
}
public function required($vars, &$errors = null) {
foreach ($vars as $i => $var) {
if (is_int($i)) {
if (!isset($this->vars[$var]) || $this->vars[$var] === '') {
if (is_array($errors)) {
$errors[] = "Missing '$var' parameter";
} else {
return false;
}
}
} else {
if (!isset($this->vars[$i]) || $this->vars[$i] === '') {
if (is_array($errors)) {
$errors[] = "Missing '$i' parameter";
} else {
return false;
}
} else {
// TODO: Input validation rules
}
}
}
if ($errors) {
return false;
}
return true;
}
}
| <?php
/**
* Input handler
*
* Very basic input handler
*
* @author Adric Schreuders
*/
class Input {
private $vars;
public function Input($vars) {
$this->vars = $vars;
}
public function get($name) {
if (isset($this->vars[$name])) {
return $this->vars[$name];
} else {
return null;
}
}
public function required($vars, &$errors = null) {
foreach ($vars as $i => $var) {
if (is_int($i)) {
if (!isset($this->vars[$var]) || $this->vars[$var] === '') {
if (is_array($errors)) {
$errors[] = "Missing '$var' parameter";
} else {
return false;
}
}
} else {
if (!isset($this->vars[$i]) || $this->vars[$i] === '') {
if (is_array($errors)) {
$errors[] = "Missing '$i' parameter";
} else {
return false;
}
} else {
// Input validation rules
}
}
}
if ($errors) {
return false;
}
return true;
}
}
|
Add load config function to Sheldon class | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
class Sheldon:
"""
Main class of the bot.
Run script creating new instance of this class and run it.
"""
def __init__(self, command_line_arguments):
"""
Function for loading bot.
:param command_line_arguments: dict, arguments for start script
:return:
"""
self._load_config(command_line_arguments)
def _load_config(self, command_line_arguments):
"""
Сreate and load bot config.
:param command_line_arguments: dict, arguments for creating config:
config-prefix - prefix of environment
variables.
Default - 'SHELDON_'
:return:
"""
# Config class is imported from sheldon.config
try:
if 'config-prefix' in command_line_arguments:
self.config = Config(prefix=command_line_arguments['config-prefix'])
else:
self.config = Config()
except Exception as error:
logger.error_log_message('Error with loading config:')
logger.error_log_message(str(error.__traceback__))
| # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
class Sheldon:
"""
Main class of the bot.
Run script creating new instance of this class and run it.
"""
def __init__(self, command_line_arguments):
"""
Function for loading bot.
:param command_line_arguments: dict, arguments for start script
:return:
"""
self._load_config(command_line_arguments)
def _load_config(self, command_line_arguments):
"""
Сreate and load bot config.
:param command_line_arguments: dict, arguments for creating config:
config-prefix - prefix of environment
variables.
Default - 'SHELDON_'
:return:
"""
# Config class is imported from sheldon.config
if 'config-prefix' in command_line_arguments:
self.config = Config(prefix=command_line_arguments['config-prefix'])
else:
self.config = Config()
|
Clean up some linter warnings | var hooks = require('hooks');
var async = require('async');
function Renderable(View) {
this.data = {};
this.mode = 'main';
this.view = {};
if (typeof View === 'function') {
this.view = new View();
}
this.render = function(cb) {
// recursively render any Renderable objects inside this.data
// this currently has one flaw, Renderable objects cannot be in nested objects,
// or you need to render them manually
var renders = [];
var item;
for (item in this.data) {
// Intent of hasOwnProperty check is handled by constructor test.
// noinspection JSUnfilteredForInLoop
if (this.data[item].constructor.name === 'Renderable') {
//noinspection JSUnfilteredForInLoop
renders.push(function(item, next) {
// noinspection JSUnfilteredForInLoop
this.data[item].render(function(rendered) {
// noinspection JSUnfilteredForInLoop
this.data[item] = rendered;
next(false);
}.bind(this));
}.bind(this, item));
}
}
async.parallel(
renders,
function(err) {
if (err) {
cb(err)
}
else {
this.view.data(this.data).mode(this.mode).render(cb);
}
}.bind(this));
}
}
for (var k in hooks) {
// Per hooks module documentation
// noinspection JSUnfilteredForInLoop
Renderable[k] = Renderable.prototype[k] = hooks[k];
}
module.exports = Renderable;
| var hooks = require('hooks');
var async = require('async');
function Renderable(View) {
this.data = {};
this.mode = 'main';
this.view = {};
if (typeof View === 'function') {
this.view = new View();
}
this.render = function(cb) {
// recursively render any Renderable objects inside this.data
// this currently has one flaw, Renderable objects cannot be in nested objects,
// or you need to render them manually
var renders = [];
var item;
for (item in this.data) {
// Intent of hasOwnProperty check is handled by constructor test.
// noinspection JSUnfilteredForInLoop
if (this.data[item].constructor.name === 'Renderable') {
renders.push(function(item, next) {
this.data[item].render(function(rendered) {
this.data[item] = rendered;
next(false);
}.bind(this));
}.bind(this, item));
}
}
async.parallel(
renders,
function(err) {
if (err) {
cb(err)
}
else {
this.view.data(this.data).mode(this.mode).render(cb);
}
}.bind(this));
}
}
for (var k in hooks) {
// Per hooks module documentation
// noinspection JSUnfilteredForInLoop
Renderable[k] = Renderable.prototype[k] = hooks[k];
}
module.exports = Renderable;
|
Fix traits boot/destroy method names | <?php
/**
* This file is part of Railt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Railt\Testing\Feature;
/**
* Trait BootableTraits
*/
trait BootableTraits
{
/**
* @return void
*/
protected function setUpTestKernel(): void
{
foreach ($this->traits() as $trait) {
$bootMethod = 'boot' . \class_basename($trait);
if (\method_exists($this, $bootMethod)) {
$this->{$bootMethod}();
}
}
}
/**
* @return \Traversable
*/
private function traits(): \Traversable
{
$traits = [];
$parents = \class_parents(static::class);
$class = static::class;
while ($class !== null) {
$traits = \array_merge(\array_values(\class_uses($class)), $traits);
$class = \count($parents) ? \array_shift($parents) : null;
}
yield from \array_unique($traits);
}
/**
* @return void
*/
protected function tearDownTestKernel(): void
{
foreach ($this->traits() as $trait) {
$destroyMethod = 'destroy' . \class_basename($trait);
if (\method_exists($this, $destroyMethod)) {
$this->{$destroyMethod}();
}
}
}
}
| <?php
/**
* This file is part of Railt package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Railt\Testing\Feature;
/**
* Trait BootableTraits
*/
trait BootableTraits
{
/**
* @return void
*/
protected function setUpTestKernel(): void
{
foreach ($this->traits(true) as $trait) {
$bootMethod = 'boot' . $trait;
if (\method_exists($this, $bootMethod)) {
$this->{$bootMethod}();
}
}
}
/**
* @param bool $shortName
* @return \Traversable
*/
private function traits(bool $shortName = true): \Traversable
{
$traits = [];
$parents = \class_parents(static::class);
$class = static::class;
while ($class !== null) {
$traits = \array_merge(\array_values(\class_uses($class)), $traits);
$class = \count($parents) ? \array_shift($parents) : null;
}
yield from \array_unique($traits);
}
/**
* @return void
*/
protected function tearDownTestKernel(): void
{
foreach ($this->traits(true) as $trait) {
$destroyMethod = 'destroy' . $trait;
if (\method_exists($this, $destroyMethod)) {
$this->{$destroyMethod}();
}
}
}
}
|
Update dumping to osf logic | from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
found, _hash = collision.already_processed(raw_doc)
if found:
return
normalized['meta'] = {
'docHash': _hash
}
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
report_norm['meta']['uids'] = report_hash
resource_norm['meta']['uids'] = resource_hash
if not resource:
resource = crud.create_resource(resource_norm)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
crud.update_node(report, report_norm)
if not report:
report = crud.create_report(report_norm, resource)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
| from scrapi.processing.osf import crud
from scrapi.processing.osf import collision
from scrapi.processing.base import BaseProcessor
class OSFProcessor(BaseProcessor):
NAME = 'osf'
def process_normalized(self, raw_doc, normalized):
if crud.is_event(normalized):
crud.dump_metdata(normalized, {})
return
normalized['collisionCategory'] = crud.get_collision_cat(normalized['source'])
report_norm = normalized
resource_norm = crud.clean_report(normalized)
report_hash = collision.generate_report_hash_list(report_norm)
resource_hash = collision.generate_resource_hash_list(resource_norm)
report = collision.detect_collisions(report_hash)
resource = collision.detect_collisions(resource_hash, is_resource=True)
if not resource:
resource = crud.create_resource(resource_norm, resource_hash)
else:
crud.dump_metadata(resource_norm, {'nid': resource})
if not report:
report = crud.create_report(report_norm, resource, report_hash)
else:
crud.dump_metadata(report_norm, {'nid': report, 'pid': resource})
crud.update_node(report, report_norm)
if not crud.is_claimed(resource):
crud.update_node(resource, resource_norm)
|
Make less verbose as going to try running sep too | <?php
namespace phpSmug\Tests;
/**
* @class
* Test properties of our codebase rather than the actual code.
*/
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testPSR()
{
// If we can't find the command-line tool, we mark the test as skipped
// so it shows as a warning to the developer rather than passing silently.
if (!file_exists('vendor/bin/php-cs-fixer')) {
$this->markTestSkipped(
'Needs linter to check PSR compliance'
);
}
// Let's check all PSR compliance for our code and tests.
// Add any other pass you want to test to this array.
foreach (array('lib/', 'examples/', 'test/') as $path) {
// Run linter in dry-run mode so it changes nothing.
exec(
escapeshellcmd('vendor/bin/php-cs-fixer fix --dry-run '.$_SERVER['PWD']."/$path"),
$output,
$return_var
);
// If we've got output, pop its first item ("Fixed all files...")
// and trim whitespace from the rest so the below makes sense.
if ($output) {
array_pop($output);
$output = array_map('trim', $output);
}
// Check shell return code: if nonzero, report the output as a failure.
$this->assertEquals(
0,
$return_var,
"PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
);
}
}
}
| <?php
namespace phpSmug\Tests;
/**
* @class
* Test properties of our codebase rather than the actual code.
*/
class PsrComplianceTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function testPSR()
{
// If we can't find the command-line tool, we mark the test as skipped
// so it shows as a warning to the developer rather than passing silently.
if (!file_exists('vendor/bin/php-cs-fixer')) {
$this->markTestSkipped(
'Needs linter to check PSR compliance'
);
}
// Let's check all PSR compliance for our code and tests.
// Add any other pass you want to test to this array.
foreach (array('lib/', 'examples/', 'test/') as $path) {
// Run linter in dry-run mode so it changes nothing.
exec(
escapeshellcmd('vendor/bin/php-cs-fixer fix -v --dry-run '.$_SERVER['PWD']."/$path"),
$output,
$return_var
);
// If we've got output, pop its first item ("Fixed all files...")
// and trim whitespace from the rest so the below makes sense.
if ($output) {
array_pop($output);
$output = array_map('trim', $output);
}
// Check shell return code: if nonzero, report the output as a failure.
$this->assertEquals(
0,
$return_var,
"PSR linter reported errors in $path: \n\t".implode("\n\t", $output)
);
}
}
}
|
Change license to MIT to match the project | <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/mit-license.php MIT
*
*/
namespace Aura\Router\Helper;
use Aura\Router\Exception\RouteNotFound;
use Aura\Router\Generator;
/**
*
* Generic Url Helper class
*
* @package Aura.Router
*
*/
class Url
{
/**
*
* The Generator object used by the RouteContainer
*
* @var Generator
*
*/
protected $generator;
/**
*
* Constructor.
*
* @param Generator $generator The generator object to use
*
*/
public function __construct(Generator $generator)
{
$this->generator = $generator;
}
/**
*
* Returns the Generator
*
* @param string|null $name The name of the route to lookup.
*
* @param array $data The data to pass into the route
*
* @return Generator|string|false The generator object, or the results of {Aura\Router\Generator::generate()}
* when $name is null
*
* @throws RouteNotFound When the route cannot be found, thrown by {Aura\Router\Generator::generate()}
*
*/
public function __invoke($name = null, array $data = [])
{
return $name === null
? $this->generator
: $this->generator->generate($name, $data);
}
} | <?php
/**
*
* This file is part of Aura for PHP.
*
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*/
namespace Aura\Router\Helper;
use Aura\Router\Exception\RouteNotFound;
use Aura\Router\Generator;
/**
*
* Generic Url Helper class
*
* @package Aura.Router
*
*/
class Url
{
/**
*
* The Generator object used by the RouteContainer
*
* @var Generator
*
*/
protected $generator;
/**
*
* Constructor.
*
* @param Generator $generator The generator object to use
*
*/
public function __construct(Generator $generator)
{
$this->generator = $generator;
}
/**
*
* Returns the Generator
*
* @param string|null $name The name of the route to lookup.
*
* @param array $data The data to pass into the route
*
* @return Generator|string|false The generator object, or the results of {Aura\Router\Generator::generate()}
* when $name is null
*
* @throws RouteNotFound When the route cannot be found, thrown by {Aura\Router\Generator::generate()}
*
*/
public function __invoke($name = null, array $data = [])
{
return $name === null
? $this->generator
: $this->generator->generate($name, $data);
}
} |
Append version to JS url to avoid caching issues when a new version is released | <?php
namespace BoomCMS\Http\Middleware;
use BoomCMS\Editor\Editor;
use BoomCMS\Support\Facades\BoomCMS;
use BoomCMS\UI;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class DefineCMSViewSharedVariables
{
private $app;
/**
* @var Editor
*/
private $editor;
public function __construct(Application $app, Editor $editor)
{
$this->app = $app;
$this->editor = $editor;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
View::share('button', function ($type, $text, $attrs = []) {
return new UI\Button($type, $text, $attrs);
});
View::share('menu', function () {
return view('boomcms::menu')->render();
});
View::share('menuButton', function () {
return new UI\MenuButton();
});
$jsFile = $this->app->environment('local') ? 'cms.js' : 'cms.min.js';
View::share('boomJS', "<script type='text/javascript' src='/vendor/boomcms/boom-core/js/$jsFile?".BoomCMS::getVersion()."'></script>");
View::share('editor', $this->editor);
return $next($request);
}
}
| <?php
namespace BoomCMS\Http\Middleware;
use BoomCMS\Editor\Editor;
use BoomCMS\UI;
use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class DefineCMSViewSharedVariables
{
private $app;
/**
* @var Editor
*/
private $editor;
public function __construct(Application $app, Editor $editor)
{
$this->app = $app;
$this->editor = $editor;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
View::share('button', function ($type, $text, $attrs = []) {
return new UI\Button($type, $text, $attrs);
});
View::share('menu', function () {
return view('boomcms::menu')->render();
});
View::share('menuButton', function () {
return new UI\MenuButton();
});
$jsFile = $this->app->environment('local') ? 'cms.js' : 'cms.min.js';
View::share('boomJS', "<script type='text/javascript' src='/vendor/boomcms/boom-core/js/$jsFile'></script>");
View::share('editor', $this->editor);
return $next($request);
}
}
|
Rename locale field to language. | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.CharField(
max_length=100,
verbose_name=_('identifier'),
help_text=_('The registered model identifier.'))
object_id = models.IntegerField(
verbose_name=_('The object ID'),
help_text=_('The object ID of this translation'))
language = models.CharField(
max_length=10,
verbose_name=_('locale'),
choices=settings.SUPPORTED_LANGUAGES,
default=settings.DEFAULT_LANGUAGE,
help_text=_('The language for this translation'))
field_name = models.CharField(
max_length=100,
verbose_name=_('field name'),
help_text=_('The model field name for this translation.'))
content = models.TextField(
verbose_name=_('content'),
null=True,
help_text=_('The translated content for the field.'))
class Meta:
abstract = True
app_label = 'linguist'
verbose_name = _('translation')
verbose_name_plural = _('translations')
unique_together = (('identifier', 'object_id', 'language', 'field_name'),)
def __str__(self):
return '%s:%d:%s:%s' % (
self.identifier,
self.object_id,
self.field_name,
self.language)
| # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.CharField(
max_length=100,
verbose_name=_('identifier'),
help_text=_('The registered model identifier.'))
object_id = models.IntegerField(
verbose_name=_('The object ID'),
help_text=_('The object ID of this translation'))
locale = models.CharField(
max_length=10,
verbose_name=_('locale'),
choices=settings.SUPPORTED_LOCALES,
default=settings.DEFAULT_LOCALE,
help_text=_('The locale for this translation'))
field_name = models.CharField(
max_length=100,
verbose_name=_('field name'),
help_text=_('The model field name for this translation.'))
content = models.TextField(
verbose_name=_('content'),
null=True,
help_text=_('The translated content for the field.'))
class Meta:
abstract = True
app_label = 'linguist'
verbose_name = _('translation')
verbose_name_plural = _('translations')
unique_together = (('identifier', 'object_id', 'locale', 'field_name'),)
def __str__(self):
return '%s:%d:%s:%s' % (
self.identifier,
self.object_id,
self.field_name,
self.locale)
|
Add user to auth response | <?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ODADnepr\MockServiceBundle\EventListener;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use JMS\Serializer\Serializer;
/**
* This listener handles ensures that for specific formats AccessDeniedExceptions
* will return a 403 regardless of how the firewall is configured
*
* @author Lukas Kahwe Smith <[email protected]>
*/
class AuthenticationSuccessEventListener
{
private $serializer;
/**
* Constructor.
*
* @param array $formats An array with keys corresponding to request formats or content types
* that must be processed by this listener
*/
public function __construct(Serializer $serializer)
{
$this->serializer = $serializer;
}
public function onAuthenticationSuccess(AuthenticationSuccessEvent $event) {
$data = $event->getData();
$user = $event->getUser();
$data['user'] = json_decode($this->serializer->serialize($user, 'json'), true);
$event->setData($data);
}
public static function getSubscribedEvents()
{
return array(
Events::AUTHENTICATION_SUCCESS => array('onAuthenticationSuccess', 5),
);
}
}
| <?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ODADnepr\MockServiceBundle\EventListener;
use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use JMS\Serializer\Serializer;
/**
* This listener handles ensures that for specific formats AccessDeniedExceptions
* will return a 403 regardless of how the firewall is configured
*
* @author Lukas Kahwe Smith <[email protected]>
*/
class AuthenticationSuccessEventListener
{
private $serializer;
/**
* Constructor.
*
* @param array $formats An array with keys corresponding to request formats or content types
* that must be processed by this listener
*/
public function __construct(Serializer $serializer)
{
$this->serializer = $serializer;
}
public function onAuthenticationSuccess(AuthenticationSuccessEvent $event) {
$data = $event->getData();
$user = $event->getUser();
$data['user'] = $user->getEmail();
$event->setData($data);
}
public static function getSubscribedEvents()
{
return array(
Events::AUTHENTICATION_SUCCESS => array('onAuthenticationSuccess', 5),
);
}
}
|
[chain] Improve enable module:install command execution | <?php
/**
* @file
* Contains \Drupal\Console\EventSubscriber\CallCommandListener.
*/
namespace Drupal\Console\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\Console\Command\Command;
use Symfony\Component\Console\ConsoleEvents;
class CallCommandListener implements EventSubscriberInterface
{
/**
* @param ConsoleTerminateEvent $event
*/
public function callCommands(ConsoleTerminateEvent $event)
{
/**
* @var \Drupal\Console\Command\Command $command
*/
$command = $event->getCommand();
$output = $event->getOutput();
if (!$command instanceof Command) {
return;
}
$application = $command->getApplication();
$commands = $application->getChain()->getCommands();
if (!$commands) {
return;
}
foreach ($commands as $chainedCommand) {
$callCommand = $application->find($chainedCommand['name']);
$input = new ArrayInput($chainedCommand['inputs']);
if (!is_null($chainedCommand['interactive'])) {
$input->setInteractive($chainedCommand['interactive']);
}
$callCommand->run($input, $output);
}
}
/**
* @{@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [ConsoleEvents::TERMINATE => 'callCommands'];
}
}
| <?php
/**
* @file
* Contains \Drupal\Console\EventSubscriber\CallCommandListener.
*/
namespace Drupal\Console\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\Console\Input\ArrayInput;
use Drupal\Console\Command\Command;
use Symfony\Component\Console\ConsoleEvents;
class CallCommandListener implements EventSubscriberInterface
{
/**
* @param ConsoleTerminateEvent $event
*/
public function callCommands(ConsoleTerminateEvent $event)
{
/**
* @var \Drupal\Console\Command\Command $command
*/
$command = $event->getCommand();
$output = $event->getOutput();
if (!$command instanceof Command) {
return;
}
$application = $command->getApplication();
$commands = $application->getChain()->getCommands();
if (!$commands) {
return;
}
foreach ($commands as $chainedCommand) {
if ($chainedCommand['name'] == 'module:install') {
$messageHelper = $application->getMessageHelper();
$translatorHelper = $application->getTranslator();
$messageHelper->addErrorMessage(
$translatorHelper->trans('commands.chain.messages.module_install')
);
continue;
}
$callCommand = $application->find($chainedCommand['name']);
$input = new ArrayInput($chainedCommand['inputs']);
if (!is_null($chainedCommand['interactive'])) {
$input->setInteractive($chainedCommand['interactive']);
}
$callCommand->run($input, $output);
}
}
/**
* @{@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [ConsoleEvents::TERMINATE => 'callCommands'];
}
}
|
feat: Delete condition of type in event as it should always be true | import time
import linkatos.parser as parser
import linkatos.printer as printer
import linkatos.firebase as fb
import linkatos.reaction as react
def is_empty(events):
return ((events is None) or (len(events) == 0))
def is_url(url_message):
return url_message['type'] == 'url'
def event_consumer(expecting_url, expecting_reaction, parsed_url_message,
slack_client, fb_credentials, firebase):
# Read slack events
events = slack_client.rtm_read()
time.sleep(1) # 1 second delay after reading
if is_empty(events):
return (expecting_url, expecting_reaction, parsed_url_message)
for event in events:
print(event)
print('expecting_url: ', expecting_url)
if expecting_url and event['type'] == 'message':
parsed_url_message = parser.parse_url_message(event)
if is_url(parsed_url_message):
printer.ask_confirmation(parsed_url_message, slack_client)
expecting_url = False
if not expecting_url and event['type'] == 'reaction_added':
reaction = parser.parse_reaction_added(event)
if react.is_confirmation(reaction['reaction'],
parsed_url_message['id'],
reaction['to_id']):
react.handle(reaction['reaction'], parsed_url_message['url'],
fb_credentials, firebase)
expecting_url = True
return (expecting_url, expecting_reaction, parsed_url_message)
| import time
import linkatos.parser as parser
import linkatos.printer as printer
import linkatos.firebase as fb
import linkatos.reaction as react
def is_empty(events):
return ((events is None) or (len(events) == 0))
def is_url(url_message):
return url_message['type'] == 'url'
def event_consumer(expecting_url, expecting_reaction, parsed_url_message,
slack_client, fb_credentials, firebase):
# Read slack events
events = slack_client.rtm_read()
time.sleep(1) # 1 second delay after reading
if is_empty(events):
return (expecting_url, expecting_reaction, parsed_url_message)
for event in events:
print(event)
print('expecting_url: ', expecting_url)
print('expecting_reaction: ', expecting_reaction)
if 'type' in event:
if expecting_url and event['type'] == 'message':
parsed_url_message = parser.parse_url_message(event)
if is_url(parsed_url_message):
printer.ask_confirmation(parsed_url_message, slack_client)
expecting_url = False
if not expecting_url and event['type'] == 'reaction_added':
reaction = parser.parse_reaction_added(event)
if react.is_confirmation(reaction['reaction'],
parsed_url_message['id'],
reaction['to_id']):
react.handle(reaction['reaction'], parsed_url_message['url'],
fb_credentials, firebase)
expecting_url = True
return (expecting_url, expecting_reaction, parsed_url_message)
|
FIX | Tirando token para inserção de provas | var ormDic = require('../../util/ormDic');
class OrmProxy {
constructor() {
this._orm = null;
}
setOrm(string) {
this._orm = ormDic[string];
}
add(req, res) {
this._orm.add(req, res);
}
delete(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.delete(req, res);
}
}
get(req, res) {
this._orm.get(req, res);
}
getById(req, res) {
this._orm.getById(req, res);
}
update(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.update(req, res);
}
}
}
module.exports = OrmProxy; | var ormDic = require('../../util/ormDic');
class OrmProxy {
constructor() {
this._orm = null;
}
setOrm(string) {
this._orm = ormDic[string];
}
add(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.add(req, res);
}
}
delete(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.delete(req, res);
}
}
get(req, res) {
this._orm.get(req, res);
}
getById(req, res) {
this._orm.getById(req, res);
}
update(req, res) {
if (req.headers.token === null || req.headers.token !== 'mps10') {
var response = {};
response.message = "Token inválido";
response.token = req.headers.token || '';
res.status(401).send(response);
} else {
this._orm.update(req, res);
}
}
}
module.exports = OrmProxy; |
Update GitHub repos from blancltd to developersociety | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='blanc-basic-podcast',
version='0.3',
description='Blanc Basic Podcast for Django',
long_description=readme,
url='https://github.com/developersociety/blanc-basic-podcast',
maintainer='Blanc Ltd',
maintainer_email='[email protected]',
platforms=['any'],
extras_require={
':python_version == "2.7"': [
'hsaudiotag>=1.1.1',
],
':python_version >= "3.3"': [
'hsaudiotag3k>=1.1.3',
],
},
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
| #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='blanc-basic-podcast',
version='0.3',
description='Blanc Basic Podcast for Django',
long_description=readme,
url='https://github.com/blancltd/blanc-basic-podcast',
maintainer='Blanc Ltd',
maintainer_email='[email protected]',
platforms=['any'],
extras_require={
':python_version == "2.7"': [
'hsaudiotag>=1.1.1',
],
':python_version >= "3.3"': [
'hsaudiotag3k>=1.1.3',
],
},
packages=find_packages(),
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
license='BSD',
)
|
Remove brackets around data and time in logs
Change-Id: Ia424eecb8a30ee9f73b9b007db2fd81f07ab509f
Reviewed-on: http://review.couchbase.org/79748
Well-Formed: Build Bot <[email protected]>
Tested-by: Build Bot <[email protected]>
Reviewed-by: Pavel Paulau <[email protected]> | import logging.config
import sys
import types
LOGGING_CONFIG = {
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s - %(levelname)s - %(message)s',
'datefmt': '%Y-%m-%dT%H:%M:%S',
},
},
'handlers': {
'file': {
'class': 'logging.FileHandler',
'filename': 'perfrunner.log',
'formatter': 'standard',
'mode': 'w',
},
'stream': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
},
},
'loggers': {
'': {
'handlers': ['stream', 'file'],
'level': logging.INFO,
'propagate': True,
},
'paramiko': {
'level': logging.WARNING,
},
'requests': {
'level': logging.ERROR,
},
'urllib3': {
'level': logging.WARNING,
},
},
'version': 1,
}
def error(self, msg, *args, **kwargs):
self.error(msg, *args, **kwargs)
sys.exit(1)
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger()
logger.interrupt = types.MethodType(error, logger)
| import logging.config
import sys
import types
LOGGING_CONFIG = {
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s - %(levelname)s - %(message)s',
'datefmt': '[%Y-%m-%dT%H:%M:%S]',
},
},
'handlers': {
'file': {
'class': 'logging.FileHandler',
'filename': 'perfrunner.log',
'formatter': 'standard',
'mode': 'w',
},
'stream': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
},
},
'loggers': {
'': {
'handlers': ['stream', 'file'],
'level': logging.INFO,
'propagate': True,
},
'paramiko': {
'level': logging.WARNING,
},
'requests': {
'level': logging.ERROR,
},
'urllib3': {
'level': logging.WARNING,
},
},
'version': 1,
}
def error(self, msg, *args, **kwargs):
self.error(msg, *args, **kwargs)
sys.exit(1)
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger()
logger.interrupt = types.MethodType(error, logger)
|
Fix apply microdata for links | <?php
/**
* Created by PhpStorm.
* Date: 2017-02-01
* Time: 23:06
*/
namespace mp\bmicrodata;
use yii\widgets\Breadcrumbs;
/**
* Class BreadcrumbsMicrodata
* @package mp\bmicrodata
*/
class BreadcrumbsMicrodata extends Breadcrumbs
{
/**
* BreadcrumbsMicrodata constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
if (isset($config['homeLink'])) {
$label = isset($config['homeLink']['label']) ? $config['homeLink']['label'] : null;
$url = isset($config['homeLink']['url']) ? $config['homeLink']['url'] : (is_string($config['homeLink']) ? $config['homeLink'] : null);
$config['homeLink'] = BreadcrumbsUtility::getHome($label, $url);
}
if (isset($config['links'])) {
$config['links'] = BreadcrumbsUtility::UseMicroData($config['links']);
}
if (!isset($config['options']['class'])) {
$config['options']['class'] = 'breadcrumb';
}
if (!isset($config['options']['itemscope itemtype'])) {
$config['options']['itemscope itemtype'] = 'http://schema.org/BreadcrumbList';
}
parent::__construct($config);
}
} | <?php
/**
* Created by PhpStorm.
* Date: 2017-02-01
* Time: 23:06
*/
namespace mp\bmicrodata;
use yii\widgets\Breadcrumbs;
/**
* Class BreadcrumbsMicrodata
* @package mp\bmicrodata
*/
class BreadcrumbsMicrodata extends Breadcrumbs
{
/**
* BreadcrumbsMicrodata constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
if (isset($config['homeLink'])) {
$label = isset($config['homeLink']['label']) ? $config['homeLink']['label'] : null;
$url = isset($config['homeLink']['url']) ? $config['homeLink']['url'] : (is_string($config['homeLink']) ? $config['homeLink'] : null);
$config['homeLink'] = BreadcrumbsUtility::getHome($label, $url);
}
if (isset($config['breadcrumbs'])) {
$config['breadcrumbs'] = BreadcrumbsUtility::UseMicroData($config['breadcrumbs']);
}
if (!isset($config['options']['class'])) {
$config['options']['class'] = 'breadcrumb';
}
if (!isset($config['options']['itemscope itemtype'])) {
$config['options']['itemscope itemtype'] = 'http://schema.org/BreadcrumbList';
}
parent::__construct($config);
}
} |
Update @BeforeMethod test to use dependsOnMethods and removed page load | package com.frameworkium.integration.frameworkium.tests;
import com.frameworkium.core.ui.tests.BaseUITest;
import com.frameworkium.integration.frameworkium.pages.JQueryDemoPage;
import com.frameworkium.integration.seleniumhq.pages.SeleniumDownloadPage;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static com.google.common.truth.Truth.assertThat;
// tests if BeforeMethods are run despite not being in this group
@Test(groups = "fw-bugs")
public class FrameworkiumBugsTest extends BaseUITest {
@BeforeMethod(dependsOnMethods = "configureBrowserBeforeTest")
public void configureBrowserBeforeUse_allows_browser_access_in_before_method() {
assertThat(getDriver().getPageSource()).isNotEmpty();
}
public void ensure_jQueryAjaxDone_does_not_fail() {
String headingText =
JQueryDemoPage.open()
.waitForJQuery()
.getHeadingText();
assertThat(headingText).isEqualTo("jQuery UI Demos");
}
public void use_base_page_visibility() {
SeleniumDownloadPage.open()
.hideContent()
.forceVisibleContent()
.waitForContent();
}
@Test(dependsOnMethods = {"use_base_page_visibility"})
public void ensure_BaseUITest_wait_is_updated_after_browser_reset() {
// tests bug whereby BasePage.wait wasn't updated after browser reset
SeleniumDownloadPage.open().waitForContent();
}
public void use_base_page_logger() {
SeleniumDownloadPage.open().log();
}
}
| package com.frameworkium.integration.frameworkium.tests;
import com.frameworkium.core.ui.tests.BaseUITest;
import com.frameworkium.integration.frameworkium.pages.JQueryDemoPage;
import com.frameworkium.integration.seleniumhq.pages.SeleniumDownloadPage;
import com.frameworkium.integration.theinternet.pages.WelcomePage;
import org.testng.annotations.*;
import static com.google.common.truth.Truth.assertThat;
public class FrameworkiumBugsTest extends BaseUITest {
@BeforeMethod//(dependsOnMethods = "configureBrowserBeforeTest")
public void configureBrowserBeforeUse_allows_browser_access_in_before_method() {
configureBrowserBeforeUse();
WelcomePage.open();
tearDownBrowser();
}
public void ensure_jQueryAjaxDone_does_not_fail() {
String headingText =
JQueryDemoPage.open()
.waitForJQuery()
.getHeadingText();
assertThat(headingText).isEqualTo("jQuery UI Demos");
}
public void use_base_page_visibility() {
SeleniumDownloadPage.open()
.hideContent()
.forceVisibleContent()
.waitForContent();
}
@Test(dependsOnMethods = {"use_base_page_visibility"})
public void ensure_BaseUITest_wait_is_updated_after_browser_reset() {
// tests bug whereby BasePage.wait wasn't updated after browser reset
SeleniumDownloadPage.open().waitForContent();
}
public void use_base_page_logger() {
SeleniumDownloadPage.open().log();
}
}
|
Add Id field to ProtoServer
Keep it at uuid.UUID for now. Conversion to string will happen
together with soma and somaadm server implementation/fixes. | package somaproto
import "github.com/satori/go.uuid"
type ProtoRequestServer struct {
Server ProtoServer `json:"server,omitempty"`
Filter ProtoServerFilter `json:"filter,omitempty"`
Purge bool `json:"purge,omitempty"`
}
type ProtoResultServer struct {
Code uint16 `json:"code,omitempty"`
Status string `json:"status,omitempty"`
Text []string `json:"text,omitempty"`
Servers []ProtoServer `json:"servers,omitempty"`
}
type ProtoServer struct {
Id uuid.UUID `json:"id,omitempty"`
AssetId uint64 `json:"assetid,omitempty"`
Datacenter string `json:"datacenter,omitempty"`
Location string `json:"location,omitempty"`
Name string `json:"name,omitempty"`
Online bool `json:"online,omitempty"`
Details *ProtoServerDetails `json:"details,omitempty"`
}
type ProtoServerDetails struct {
CreatedAt string `json:"createdat,omitempty"`
CreatedBy string `json:"createdby,omitempty"`
Nodes []string `json:"nodes,omitempty"`
}
type ProtoServerFilter struct {
Online bool `json:"online,omitempty"`
Deleted bool `json:"deleted,omitempty"`
Datacenter string `json:"datacenter,omitempty"`
Name string `json:"name,omitempty"`
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
| package somaproto
type ProtoRequestServer struct {
Server ProtoServer `json:"server,omitempty"`
Filter ProtoServerFilter `json:"filter,omitempty"`
Purge bool `json:"purge,omitempty"`
}
type ProtoResultServer struct {
Code uint16 `json:"code,omitempty"`
Status string `json:"status,omitempty"`
Text []string `json:"text,omitempty"`
Servers []ProtoServer `json:"servers,omitempty"`
}
type ProtoServer struct {
AssetId uint64 `json:"assetid,omitempty"`
Datacenter string `json:"datacenter,omitempty"`
Location string `json:"location,omitempty"`
Name string `json:"name,omitempty"`
Online bool `json:"online,omitempty"`
Details *ProtoServerDetails `json:"details,omitempty"`
}
type ProtoServerDetails struct {
CreatedAt string `json:"createdat,omitempty"`
CreatedBy string `json:"createdby,omitempty"`
Nodes []string `json:"nodes,omitempty"`
}
type ProtoServerFilter struct {
Online bool `json:"online,omitempty"`
Deleted bool `json:"deleted,omitempty"`
Datacenter string `json:"datacenter,omitempty"`
Name string `json:"name,omitempty"`
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
|
Fix Flashmessage return int instead of Message array
git-svn-id: a31028ace08b9bd728961381d3e3adab14c71477@50 85223511-97c2-6742-acd2-766018259031 | <?php
namespace FMUP\FlashMessenger\Driver;
use FMUP\FlashMessenger\DriverInterface;
use FMUP\FlashMessenger\Message;
/**
* Description of Session
*
* @author sweffling
*/
class Session implements DriverInterface
{
private $session;
/**
* @return \FMUP\Session
*/
private function getSession()
{
if (!$this->session) {
$this->session = \FMUP\Session::getInstance();
}
return $this->session;
}
/**
* @param \FMUP\Session $session
* @return $this
*/
public function setSession(\FMUP\Session $session)
{
$this->session = $session;
return $this;
}
/**
* Add a message in session
* @param Message $flash
* @return $this
*/
public function add(Message $flash)
{
$messages = (array) $this->getSession()->get(__CLASS__);
array_push($messages, $flash);
$this->getSession()->set(__CLASS__, $messages);
return $this;
}
/**
* Get all the messages in the session
* @return array|null $flashes
*/
public function get()
{
return $this->getSession()->get(__CLASS__);
}
/**
* Clear the session from messages
* @return $this
*/
public function clear()
{
$this->getSession()->remove(__CLASS__);
return $this;
}
}
| <?php
namespace FMUP\FlashMessenger\Driver;
use FMUP\FlashMessenger\DriverInterface;
use FMUP\FlashMessenger\Message;
/**
* Description of Session
*
* @author sweffling
*/
class Session implements DriverInterface
{
private $session;
/**
* @return \FMUP\Session
*/
private function getSession()
{
if (!$this->session) {
$this->session = \FMUP\Session::getInstance();
}
return $this->session;
}
/**
* @param \FMUP\Session $session
* @return $this
*/
public function setSession(\FMUP\Session $session)
{
$this->session = $session;
return $this;
}
/**
* Add a message in session
* @param Message $flash
* @return $this
*/
public function add(Message $flash)
{
$messages = (array) $this->getSession()->get(__CLASS__);
$this->getSession()->set(__CLASS__, array_push($messages, $flash));
return $this;
}
/**
* Get all the messages in the session
* @return array|null $flashes
*/
public function get()
{
return $this->getSession()->get(__CLASS__);
}
/**
* Clear the session from messages
* @return $this
*/
public function clear()
{
$this->getSession()->remove(__CLASS__);
return $this;
}
}
|
Use L&F that is available on JDK 1.3
git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1344 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e | package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to serialize. If this works, we're in good shape :)
public void testJTable() {
// Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
JTable original = new JTable();
String originalXml = xstream.toXML(original);
JTable deserialized = (JTable) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
}
public void testDefaultListModel() {
final DefaultListModel original = new DefaultListModel();
final JList list = new JList();
list.setModel(original);
String originalXml = xstream.toXML(original);
DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
list.setModel(deserialized);
}
public void testMetalLookAndFeel() {
LookAndFeel plaf = new MetalLookAndFeel();
String originalXml = xstream.toXML(plaf);
assertBothWays(plaf, originalXml);
}
}
| package com.thoughtworks.acceptance;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;
public class SwingTest extends AbstractAcceptanceTest {
// JTable is one of the nastiest components to serialize. If this works, we're in good shape :)
public void testJTable() {
// Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
JTable original = new JTable();
String originalXml = xstream.toXML(original);
JTable deserialized = (JTable) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
}
public void testDefaultListModel() {
final DefaultListModel original = new DefaultListModel();
final JList list = new JList();
list.setModel(original);
String originalXml = xstream.toXML(original);
DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
String deserializedXml = xstream.toXML(deserialized);
assertEquals(originalXml, deserializedXml);
list.setModel(deserialized);
}
public void testSynthLookAndFeel() {
LookAndFeel plaf = new SynthLookAndFeel();
String originalXml = xstream.toXML(plaf);
assertBothWays(plaf, originalXml);
}
}
|
Add handling for invalid JSON returned | import queryString from "query-string";
class Api {
static get(url, data = {}) {
return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET");
}
static post(url, data = {}) {
return this.request(url, data, "POST");
}
static delete(url, data = {}) {
return this.request(url, data, "DELETE");
}
static patch(url, data = {}) {
return this.request(url, data, "PATCH");
}
static request(url, data, method) {
let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, {
method: method,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
});
return new Promise((resolve, reject) => {
req.then((response) => {
if (response.ok) {
response.json().then((data) => {
if (data.success) {
resolve(data.data);
} else {
let e = new Error(data.message);
e.response = response;
reject(e);
}
}).catch(() => {
let e = new Error('Malformed response');
e.response = response;
reject(e);
})
} else {
let e = new Error(response.statusText);
e.response = response;
reject(e);
}
}).catch((e) => {
reject(new Error(e));
})
});
}
}
export default Api; | import queryString from "query-string";
class Api {
static get(url, data = {}) {
return this.request(url + (Object.keys(data).length > 0 ? ('?' + queryString.stringify(data)) : '' ), undefined, "GET");
}
static post(url, data = {}) {
return this.request(url, data, "POST");
}
static delete(url, data = {}) {
return this.request(url, data, "DELETE");
}
static patch(url, data = {}) {
return this.request(url, data, "PATCH");
}
static request(url, data, method) {
let req = fetch("http://" + window.location.hostname + ':8080/api/' + url, {
method: method,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
});
return new Promise((resolve, reject) => {
req.then((response) => {
if (response.ok) {
response.json().then((data) => {
if (data.success) {
resolve(data.data);
} else {
let e = new Error(data.message);
e.response = response;
reject(e);
}
})
} else {
let e = new Error(response.statusText);
e.response = response;
reject(e);
}
}).catch((e) => {
reject(new Error(e));
})
});
}
}
export default Api; |
Refresh page when creating menus, module bi_view_editor | # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
if self._context.get('active_model') == 'bve.view':
self.ensure_one()
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
self.env['ir.ui.menu'].create({
'name': self.name,
'parent_id': self.menu_id.id,
'action': 'ir.actions.act_window,%d' % (bve_view.action_id,)
})
return {'type': 'ir.actions.client', 'tag': 'reload'}
return super(WizardModelMenuCreate, self).menu_create()
@api.model
def default_get(self, fields_list):
defaults = super(WizardModelMenuCreate, self).default_get(fields_list)
if self._context.get('active_model') == 'bve.view':
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
defaults.setdefault('name', bve_view.name)
return defaults
| # -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
class WizardModelMenuCreate(models.TransientModel):
_inherit = 'wizard.ir.model.menu.create'
@api.multi
def menu_create(self):
if self._context.get('active_model') == 'bve.view':
self.ensure_one()
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
self.env['ir.ui.menu'].create({
'name': self.name,
'parent_id': self.menu_id.id,
'action': 'ir.actions.act_window,%d' % (bve_view.action_id,)
})
return {'type': 'ir.actions.act_window_close'}
return super(WizardModelMenuCreate, self).menu_create()
@api.model
def default_get(self, fields_list):
defaults = super(WizardModelMenuCreate, self).default_get(fields_list)
if self._context.get('active_model') == 'bve.view':
active_id = self._context.get('active_id')
bve_view = self.env['bve.view'].browse(active_id)
defaults.setdefault('name', bve_view.name)
return defaults
|
Fix ivory geocoder reverse method... | <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <[email protected]>
*/
class Geocoder extends BaseGeocoder
{
/**
* {@inheritDoc}
*/
public function geocode($request)
{
if($this->getProvider() instanceof Provider)
{
$result = $this->retrieve($request);
if(is_null($result))
{
$result = $this->getProvider()->getGeocodedData($request);
$this->store($request, $result);
}
return $result;
}
else
return parent::geocode($request);
}
/**
* {@inheritDoc}
*/
public function reverse($latitude, $longitude)
{
if($this->getProvider() instanceof Provider)
{
$value = $latitude.'-'.$longitude;
$result = $this->retrieve($value);
if(is_null($result))
{
$result = $this->getProvider()->getReversedData(array($latitude, $longitude));
$this->store($value, $result);
}
return $result;
}
else
return parent::reverse($latitude, $longitude);
}
}
| <?php
namespace Ivory\GoogleMapBundle\Model\Services\Geocoding;
use Geocoder\Geocoder as BaseGeocoder;
/**
* Geocoder which describes a google map geocoder
*
* @see http://code.google.com/apis/maps/documentation/javascript/reference.html#Geocoder
* @author GeLo <[email protected]>
*/
class Geocoder extends BaseGeocoder
{
/**
* {@inheritDoc}
*/
public function geocode($request)
{
if($this->getProvider() instanceof Provider)
{
$result = $this->retrieve($request);
if(is_null($result))
{
$result = $this->getProvider()->getGeocodedData($request);
$this->store($request, $result);
}
return $result;
}
else
return parent::geocode($request);
}
/**
* {@inheritDoc}
*/
public function reverse($latitude, $longitude)
{
if($this->getProvider() instanceof Provider)
{
$request = new GeocoderRequest();
$request->setCoordinate($latitude, $longitude);
return $this->geocode($request);
}
else
return parent::geocode($request);
}
}
|
Set notification.backends.EmailBackend.sensitivity = 3, so that it has a different sensitivity from the WebBackend | from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
sensitivity = 3
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, recipient):
return recipient.email
def should_send(self, sender, recipient, notice_type, *args, **kwargs):
send = super(EmailBackend, self).should_send(sender, recipient,
notice_type)
return send and self.email_for_user(recipient) != ''
def render_subject(self, label, context):
# Strip newlines from subject
return ''.join(self.render_message(label,
'notification/email_subject.txt', 'short.txt', context
).splitlines())
def send(self, sender, recipient, notice_type, context, *args, **kwargs):
if not self.should_send(sender, recipient, notice_type):
return False
headers = kwargs.get('headers', {})
headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL)
EmailMessage(self.render_subject(notice_type.label, context),
self.render_message(notice_type.label,
'notification/email_body.txt',
'full.txt',
context),
kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL,
[self.email_for_user(recipient)],
headers=headers).send()
return True
| from django.conf import settings
from django.core.mail import EmailMessage
from notification.backends.base import NotificationBackend
class EmailBackend(NotificationBackend):
sensitivity = 2
slug = u'email'
display_name = u'E-mail'
formats = ['short.txt', 'full.txt']
def email_for_user(self, recipient):
return recipient.email
def should_send(self, sender, recipient, notice_type, *args, **kwargs):
send = super(EmailBackend, self).should_send(sender, recipient,
notice_type)
return send and self.email_for_user(recipient) != ''
def render_subject(self, label, context):
# Strip newlines from subject
return ''.join(self.render_message(label,
'notification/email_subject.txt', 'short.txt', context
).splitlines())
def send(self, sender, recipient, notice_type, context, *args, **kwargs):
if not self.should_send(sender, recipient, notice_type):
return False
headers = kwargs.get('headers', {})
headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL)
EmailMessage(self.render_subject(notice_type.label, context),
self.render_message(notice_type.label,
'notification/email_body.txt',
'full.txt',
context),
kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL,
[self.email_for_user(recipient)],
headers=headers).send()
return True
|
Update receiver to catch value error | from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k value-for k-means analysis. (k groups)
max_iter: int # maximum number of iterations.
tolerance: float # relative tolerance, inertia to declare convergence.
init_method: str # method of initialization: "K++" or "random".
class KMeansReceiver(BaseReceiver):
def options_from_front_end(self) -> KMeansOption:
"""Get the K-means option from front end.
:return: a KmeansOption object to hold all the options.
"""
n_init = int(self._front_end_data['n_init'])
max_iter = int(self._front_end_data['max_iter'])
tolerance = float(self._front_end_data['tolerance'])
init_method = self._front_end_data['init']
# Check if no input from front-end, use the default k value.
try:
k_value = int(self._front_end_data['nclusters'])
except ValueError:
k_value = int(len(FileManagerModel().load_file_manager().
get_active_files()) / 2)
return KMeansOption(n_init=n_init,
k_value=k_value,
max_iter=max_iter,
tolerance=tolerance,
init_method=init_method)
| from typing import NamedTuple
from lexos.models.filemanager_model import FileManagerModel
from lexos.receivers.base_receiver import BaseReceiver
class KMeansOption(NamedTuple):
"""The typed tuple to hold kmeans options."""
n_init: int # number of iterations with different centroids.
k_value: int # k value-for k-means analysis. (k groups)
max_iter: int # maximum number of iterations.
tolerance: float # relative tolerance, inertia to declare convergence.
init_method: str # method of initialization: "K++" or "random".
class KMeansReceiver(BaseReceiver):
def options_from_front_end(self) -> KMeansOption:
"""Get the K-means option from front end.
:return: a KmeansOption object to hold all the options.
"""
n_init = int(self._front_end_data['n_init'])
k_value = int(self._front_end_data['nclusters'])
max_iter = int(self._front_end_data['max_iter'])
tolerance = float(self._front_end_data['tolerance'])
init_method = self._front_end_data['init']
# Check if no input, use the default k value.
if k_value == '':
k_value = int(len(FileManagerModel().load_file_manager().
get_active_files()) / 2)
return KMeansOption(n_init=n_init,
k_value=k_value,
max_iter=max_iter,
tolerance=tolerance,
init_method=init_method)
|
Remove unneeded -p from mkdir call | const FS = require('fs');
const Child = require('child_process').execSync;
// Copy local package files
Child('npm run clean');
Child('npm run compile');
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
Child('mkdir dist/npm');
Child('cp -r dist/cjs/* dist/npm/');
Child('cp dist/es/index.module.js dist/npm/module.js');
Child('cp dist/es/index-browser.module.js dist/npm/browser-module.js');
Child(`cp ${__dirname}/../*.md dist/npm`);
Child('npm run compile:webpack');
// Create package.json file
const Pkg = JSON.parse(FS.readFileSync('package.json'));
FS.writeFileSync(
'dist/npm/package.json',
JSON.stringify(
{
...Pkg,
browser: {
...Pkg.browser,
'./module.js': './browser-module.js'
},
devDependencies: undefined,
'jsnext:main': './module.js',
main: './index.js',
module: './module.js',
private: false,
scripts: undefined,
sideEffects: false,
typings: './index'
},
null,
2
)
);
// Create package bundle
Child('cd dist/npm && npm pack');
Child(`mv dist/npm/*.tgz ${__dirname}/../dist/${Pkg.name}.tgz`);
| const FS = require('fs');
const Child = require('child_process').execSync;
// Copy local package files
Child('npm run clean');
Child('npm run compile');
Child('npm run compile:module');
Child('npm run compile:rollup');
Child('npm run compile:rollup-browser');
Child('mkdir -p dist/npm');
Child('cp -r dist/cjs/* dist/npm/');
Child('cp dist/es/index.module.js dist/npm/module.js');
Child('cp dist/es/index-browser.module.js dist/npm/browser-module.js');
Child(`cp ${__dirname}/../*.md dist/npm`);
Child('npm run compile:webpack');
// Create package.json file
const Pkg = JSON.parse(FS.readFileSync('package.json'));
FS.writeFileSync(
'dist/npm/package.json',
JSON.stringify(
{
...Pkg,
browser: {
...Pkg.browser,
'./module.js': './browser-module.js'
},
devDependencies: undefined,
'jsnext:main': './module.js',
main: './index.js',
module: './module.js',
private: false,
scripts: undefined,
sideEffects: false,
typings: './index'
},
null,
2
)
);
// Create package bundle
Child('cd dist/npm && npm pack');
Child(`mv dist/npm/*.tgz ${__dirname}/../dist/${Pkg.name}.tgz`);
|
Rename translations to translations_select, switch to HTTPS | """
VerseBot for reddit
By Matthieu Grieger
webparser.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations attribute and checks if there are any new translations
to add to the database. """
trans = self.find_supported_translations()
if trans is None:
self.translations = None
else:
self.translations = trans.sort(key=len, reverse=True)
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "https://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
soup = BeautifulSoup(page.read())
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations_select = soup.find("select", {"class":"search-translation-select"})
trans = translations_select.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
translations.append(cur_trans)
# Add local translations to supported translations list
translations.append("NJPS")
return translations
| """
VerseBot for reddit
By Matthieu Grieger
webparser.py
Copyright (c) 2015 Matthieu Grieger (MIT License)
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Parser:
""" Parser class for BibleGateway parsing methods. """
def __init__(self):
""" Initializes translations attribute and checks if there are any new translations
to add to the database. """
trans = self.find_supported_translations()
if trans is None:
self.translations = None
else:
self.translations = trans.sort(key=len, reverse=True)
def find_supported_translations(self):
""" Retrieves a list of supported translations from BibleGateway's translation
page. """
url = "http://www.biblegateway.com/versions/"
translations = list()
page = urlopen(url)
soup = BeautifulSoup(page.read())
# It seems that BibleGateway has changed the layout of their versions page. This needs
# to be redone!
translations = soup.find("select", {"class":"search-translation-select"})
trans = translations.findAll("option")
for t in trans:
if t.has_attr("value") and not t.has_attr("class"):
cur_trans = t["value"]
translations.append(cur_trans)
# Add local translations to supported translations list
translations.append("NJPS")
return translations
|
docs: Add source for geolocation function | // use strict:
"use strict";
// Function gets the location of the user provided the user opts in
// function adapted from Sitepoint; https://www.sitepoint.com/html5-geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
alert('Geolocation is not supported in your browser so cannot display your local weather');
}
// Success callback function
function userPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log("User's latitude is " + lat + " User's longitude is " + lon);
// return lat, lon; // how to return two vars?
}
// Error callback function
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
| // use strict:
"use strict";
// Function gets the location of the user provided the user opts in
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
alert('Geolocation is not supported in your browser so cannot display your local weather');
}
// Success callback function
function userPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log("User's latitude is " + lat + " User's longitude is " + lon);
// return lat, lon; // how to return two vars?
}
// Error callback function
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
|
Fix isset POST key for remove and send template | <?php
namespace App\Controller;
class Templates extends \App\Controller\App
{
public function action_index()
{
$this->view->title = 'SMS Templates';
if ($this->request->method == 'POST') {
foreach ($this->request->post('templatesId') as $templateId) {
$template = $this->pixie->orm->get('templates', $templateId);
if ($template->loaded()) {
$postData = $this->request->post();
// remove templates messages
if (isset($postData['delete'])) {
$template->delete();
$this->add_message_success('Templates removed!');
}
// send message from template
if (isset($postData['send'])) {
$this->pixie->send_message($template->to, $template->text)
? $this->add_message_success('Message sent to the queue for sending!')
: $this->add_message_error('Error while sending message!');
}
}
}
}
$templates = $this->pixie->orm->get('templates');
$this->add_view_data('templates', $templates->find_all());
$this->add_view_data('total_templates', (int)$templates->count_all());
}
}
| <?php
namespace App\Controller;
class Templates extends \App\Controller\App
{
public function action_index()
{
$this->view->title = 'SMS Templates';
if ($this->request->method == 'POST') {
foreach ($this->request->post('templatesId') as $templateId) {
$template = $this->pixie->orm->get('templates', $templateId);
if ($template->loaded()) {
// remove templates messages
if ($this->request->post('delete')) {
$template->delete();
$this->add_message_success('Templates removed!');
}
// send message from template
if ($this->request->post('send')) {
$this->pixie->send_message($template->to, $template->text)
? $this->add_message_success('Message sent to the queue for sending!')
: $this->add_message_error('Error while sending message!');
}
}
}
}
$templates = $this->pixie->orm->get('templates');
$this->add_view_data('templates', $templates->find_all());
$this->add_view_data('total_templates', (int)$templates->count_all());
}
}
|
Update slack username for JD | import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty.dawson", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def process_message(data, plugin):
global cursor
if "text" in data:
splits = data['text'].split(" ")
if splits[0] == ":cow:":
if splits[1] == commandname():
try:
while True:
cursor = cursor + 1
if cursor > len(buddies)-1:
cursor = 0
the_buddy = buddies[cursor]
user_id = data['user'] #requester's UID
slack_client = plugin.getbot().get_slack_client()
user = slack_client.server.users.find(user_id)
if not user == None:
if not the_buddy == user.name:
break
else:
break
outputs.append([data['channel'], "*cow kicks*: @{0}".format(the_buddy)])
except:
raise
outputs.append([data['channel'], usage()])
| import time
import random
crontable = []
outputs = []
buddies = ["tim.jenks", "mark.simpson", "scott", "malcolm.brown", "ian.hutchinson", "jonty", "oliver.norton", "vimarsh.raina", "paul.harris", "john.bell"]
cursor = -1
def usage():
return "usage: :cow: buddy"
def commandname():
return "buddy"
def process_message(data, plugin):
global cursor
if "text" in data:
splits = data['text'].split(" ")
if splits[0] == ":cow:":
if splits[1] == commandname():
try:
while True:
cursor = cursor + 1
if cursor > len(buddies)-1:
cursor = 0
the_buddy = buddies[cursor]
user_id = data['user'] #requester's UID
slack_client = plugin.getbot().get_slack_client()
user = slack_client.server.users.find(user_id)
if not user == None:
if not the_buddy == user.name:
break
else:
break
outputs.append([data['channel'], "*cow kicks*: @{0}".format(the_buddy)])
except:
raise
outputs.append([data['channel'], usage()])
|
Move $app['storage.metadata']->setDefaultAlias into storage extend | <?php
namespace Bolt\Extension;
use Pimple as Container;
/**
* Storage helpers.
*
* @author Gawain Lynch <[email protected]>
*/
trait StorageTrait
{
/**
* Return a list of entities to map to repositories.
*
* <pre>
* return [
* 'alias' => [\Entity\Class\Name => \Repository\Class\Name],
* ];
* </pre>
*
* @return array
*/
protected function registerRepositoryMappings()
{
return [];
}
/**
* Call this in register method.
*
* @internal
*/
final protected function extendRepositoryMapping()
{
$app = $this->getContainer();
$app['storage'] = $app->share(
$app->extend(
'storage',
function ($entityManager) use ($app) {
foreach ($this->registerRepositoryMappings() as $alias => $map) {
$app['storage.repositories'] += $map;
$app['storage.metadata']->setDefaultAlias($app['schema.prefix'] . $alias, key($map));
$entityManager->setRepository(key($map), current($map));
}
return $entityManager;
}
)
);
}
/** @return Container */
abstract protected function getContainer();
}
| <?php
namespace Bolt\Extension;
use Pimple as Container;
/**
* Storage helpers.
*
* @author Gawain Lynch <[email protected]>
*/
trait StorageTrait
{
/**
* Return a list of entities to map to repositories.
*
* <pre>
* return [
* 'alias' => [\Entity\Class\Name => \Repository\Class\Name],
* ];
* </pre>
*
* @return array
*/
protected function registerRepositoryMappings()
{
return [];
}
/**
* Call this in register method.
*
* @internal
*/
final protected function extendRepositoryMapping()
{
$app = $this->getContainer();
$app['storage.metadata'] = $app->share(
$app->extend(
'storage.metadata',
function ($storageMetadata) use ($app) {
foreach ($this->registerRepositoryMappings() as $alias => $map) {
$storageMetadata->setDefaultAlias($app['schema.prefix'] . $alias, key($map));
}
return $storageMetadata;
}
)
);
$app['storage'] = $app->share(
$app->extend(
'storage',
function ($entityManager) use ($app) {
foreach ($this->registerRepositoryMappings() as $alias => $map) {
$app['storage.repositories'] += $map;
$entityManager->setRepository(key($map), current($map));
}
return $entityManager;
}
)
);
}
/** @return Container */
abstract protected function getContainer();
}
|
Add default view for camera | from traits.api import HasTraits, Int, Str, Tuple, Array, Range
from traitsui.api import View, Label
class CameraError(Exception):
def __init__(self, msg, cam):
self.msg = msg
self.camera_number = cam
def __str__(self):
return '{0} on camera {1}'.format(self.msg, self.camera_number)
class Camera(HasTraits):
camera_number = Int(-1)
id_string = Str()
resolution = Tuple(Int(), Int())
roi = Tuple(Int(), Int(), Int(), Int())
frame_rate = Range(1, 500, 30)
frame = Array()
# Default configuration panel
view = View(Label('No settings to configure'))
def __enter__(self):
self.open()
return self
def __exit__(self, *args):
self.close()
return False # don't suppress exceptions
def open(self):
raise NotImplementedError()
def close(self):
raise NotImplementedError()
def query_frame(self):
raise NotImplementedError()
def find_resolutions(self):
'''
Returns a list of resolution tuples that this camera supports.
'''
# Default: return the camera's own default resolution
return [self.resolution]
def configure(self):
"""Opens a dialog to set the camera's parameters."""
pass
| from traits.api import HasTraits, Int, Str, Tuple, Array, Range
class CameraError(Exception):
def __init__(self, msg, cam):
self.msg = msg
self.camera_number = cam
def __str__(self):
return '{0} on camera {1}'.format(self.msg, self.camera_number)
class Camera(HasTraits):
camera_number = Int(-1)
id_string = Str()
resolution = Tuple(Int(), Int())
roi = Tuple(Int(), Int(), Int(), Int())
frame_rate = Range(1, 500, 30)
frame = Array()
def __enter__(self):
self.open()
return self
def __exit__(self, *args):
self.close()
return False # don't suppress exceptions
def open(self):
raise NotImplementedError()
def close(self):
raise NotImplementedError()
def query_frame(self):
raise NotImplementedError()
def find_resolutions(self):
'''
Returns a list of resolution tuples that this camera supports.
'''
# Default: return the camera's own default resolution
return [self.resolution]
def configure(self):
"""Opens a dialog to set the camera's parameters."""
pass
|
Fix bug in sentiment calculation
Signed-off-by: Itai Koren <[email protected]> | // Include The 'require.async' Module
require("require.async")(require);
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize (input) {
return input
.replace(/[^a-zA-Z ]+/g, "")
.replace("/ {2,}/", " ")
.toLowerCase()
.split(" ");
}
/**
* Performs sentiment analysis on the provided input "term".
*
* @param {String} Input term
*
* @return {Object}
*/
module.exports = function (term, callback) {
// Include the AFINN Dictionary JSON asynchronously
require.async("./AFINN.json", function(afinn) {
// Split line term to letters only words array
var words = tokenize(term || "");
var score = 0;
var rate;
var i = 0;
function calculate(word) {
// Get the word rate from the AFINN dictionary
rate = afinn[word];
if (rate) {
// Add current word rate to the final calculated sentiment score
score += rate;
}
// Defer next turn execution (Etheration)
setImmediate(function() {
// Use callback for completion
if (i === (words.length - 1)) {
callback(null, score);
}
else {
// Invoke next turn
calculate(words[++i]);
}
});
}
// Start calculating
calculate(words[i]);
});
};
| // Include The 'require.async' Module
require("require.async")(require);
/**
* Tokenizes an input string.
*
* @param {String} Input
*
* @return {Array}
*/
function tokenize (input) {
return input
.replace(/[^a-zA-Z ]+/g, "")
.replace("/ {2,}/", " ")
.toLowerCase()
.split(" ");
}
/**
* Performs sentiment analysis on the provided input "term".
*
* @param {String} Input term
*
* @return {Object}
*/
module.exports = function (term, callback) {
// Include the AFINN Dictionary JSON asynchronously
require.async("./AFINN.json", function(afinn) {
// Split line term to letters only words array
var words = tokenize(term || "");
var score = 0;
var rate;
var i = 0;
function calculate(word) {
// Get the word rate from the AFINN dictionary
rate = afinn[word];
if (rate) {
// Add current word rate to the final calculated sentiment score
score += rate;
}
// Defer next turn execution (Etheration)
setImmediate(function() {
// Use callback for completion
if (i === (words.length - 1)) {
callback(null, score);
}
else {
// Invoke next turn
calculate(words[++i]);
}
});
}
// Start calculating
calculate(i);
});
};
|
Add test names for parametrized tests | import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import R from 'ramda';
import { Link } from 'react-router';
import EntityListItem from '../../../src/components/EntityListItem';
describe('EntityListItem', function () {
function createDefaultProps() {
return {
name: 'any name'
};
}
function createComponent(props = {}) {
const mergedProps = R.merge(createDefaultProps(), props);
return <EntityListItem {...mergedProps} />;
}
const testCases = [
{ name: 'a', expected: 'a' },
{ name: 'A', expected: 'a' },
{ name: 'a b', expected: 'ab' },
{ name: 'äb', expected: 'b' },
{ name: '#a', expected: 'a' },
{ name: 'a3', expected: 'a3' }
];
testCases.forEach((testCase) => {
it(`should remove non-word characters and lower-case the result for ${testCase.name}`, function () {
const { name, expected } = testCase;
const expectedUri = `/entities/${expected}`;
const entityListItem = shallow(createComponent({ name }));
const link = entityListItem.find(Link);
expect(link.prop('to')).to.equal(expectedUri);
expect(link.children().text()).to.equal(expected);
});
});
});
| import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import R from 'ramda';
import { Link } from 'react-router';
import EntityListItem from '../../../src/components/EntityListItem';
describe('EntityListItem', function () {
function createDefaultProps() {
return {
name: 'any name'
};
}
function createComponent(props = {}) {
const mergedProps = R.merge(createDefaultProps(), props);
return <EntityListItem {...mergedProps} />;
}
const testCases = [
{ name: 'a', expected: 'a' },
{ name: 'A', expected: 'a' },
{ name: 'a b', expected: 'ab' },
{ name: 'äb', expected: 'b' },
{ name: '#a', expected: 'a' },
{ name: 'a3', expected: 'a3' }
];
testCases.forEach((testCase) => {
it('should remove non-word characters and lower-case the result', function () {
const { name, expected } = testCase;
const expectedUri = `/entities/${expected}`;
const entityListItem = shallow(createComponent({ name }));
const link = entityListItem.find(Link);
expect(link.prop('to')).to.equal(expectedUri);
expect(link.children().text()).to.equal(expected);
});
});
});
|
Remove tox and pep8 from "install" requires.
https://github.com/jdowner/requires-provides/issues/2 | #!/usr/bin/env python
import setuptools
setuptools.setup(
name='requires-provides',
version='0.1',
description='Flexible dependency decorators',
license='MIT',
author='Joshua Downer',
author_email='[email protected]',
url='http://github.com/jdowner/requires-provides',
keywords='python decorator dependencies requires provides',
packages=['dependency'],
package_data={
'': ['*.rst', 'LICENSE'],
},
extra_requires=[
'pep8',
'tox',
],
platforms=['Unix'],
test_suite="tests",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
]
)
| #!/usr/bin/env python
import setuptools
setuptools.setup(
name='requires-provides',
version='0.1',
description='Flexible dependency decorators',
license='MIT',
author='Joshua Downer',
author_email='[email protected]',
url='http://github.com/jdowner/requires-provides',
keywords='python decorator dependencies requires provides',
packages=['dependency'],
package_data={
'': ['*.rst', 'LICENSE'],
},
install_requires=[
'pep8',
'tox',
],
platforms=['Unix'],
test_suite="tests",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development',
]
)
|
Fix error with minified JS | /* This file is part of Indico.
* Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
*
* Indico 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.
*
* Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
*/
var ndServices = angular.module('ndServices', []);
ndServices.provider('url', function() {
var baseUrl = Indico.Urls.Base;
var modulePath = '';
// XXX: don't remove the () around `+Date.now()`
// the minifier converts this to `'?'++Date.now()` which is a syntax error
var debug = $('body').data('debug') ? '?' + (+Date.now()) : '';
return {
setModulePath: function(path) {
if (path.substr(-1) == '/') {
path = path.substr(0, path.length - 1);
}
modulePath = path;
},
$get: function() {
return {
tpl: function(path) {
return baseUrl + modulePath + '/tpls/' + path + debug;
}
};
}
};
});
| /* This file is part of Indico.
* Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
*
* Indico 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.
*
* Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>.
*/
var ndServices = angular.module('ndServices', []);
ndServices.provider('url', function() {
var baseUrl = Indico.Urls.Base;
var modulePath = '';
var debug = $('body').data('debug') ? '?' + +Date.now() : '';
return {
setModulePath: function(path) {
if (path.substr(-1) == '/') {
path = path.substr(0, path.length - 1);
}
modulePath = path;
},
$get: function() {
return {
tpl: function(path) {
return baseUrl + modulePath + '/tpls/' + path + debug;
}
};
}
};
});
|
Make NickServIdentify play nice with service specific configs | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
import logging
class NickServIdentify(BotModule):
implements(IPlugin, IBotModule)
name = "NickServIdentify"
def hookBot(self, bot):
self.bot = bot
def actions(self):
return [ ("welcome", 1, self.identify) ]
def identify(self, serverName):
if not self.bot.moduleHandler.useModuleOnServer(self.name, serverName):
return
if "nickserv_nick" not in self.bot.config and "nickserv_nick" not in self.bot.config["servers"][serverName]:
nick = "NickServ"
self.bot.servers[serverName].log("No valid NickServ nickname was found; defaulting to NickServ...",
level=logging.WARNING)
else:
nick = self.bot.config.serverItemWithDefault(serverName, "nickserv_nick", "NickServ")
if "nickserv_pass" not in self.bot.config and "nickserv_pass" not in self.bot.config["servers"][serverName]:
self.bot.servers[serverName].log("No NickServ password found. Aborting authentication...",
level=logging.ERROR)
return
password = self.bot.config.serverItemWithDefault(serverName, "nickserv_pass", None)
self.bot.servers[serverName].outputHandler.cmdPRIVMSG(nick, "IDENTIFY {}".format(password))
nickServID = NickServIdentify()
| from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
import logging
class NickServIdentify(BotModule):
implements(IPlugin, IBotModule)
name = "NickServIdentify"
def hookBot(self, bot):
self.bot = bot
def actions(self):
return [ ("welcome", 1, self.identify) ]
def identify(self, serverName):
if not self.bot.moduleHandler.useModuleOnServer(self.name, serverName):
return
if "nickserv_nick" not in self.bot.config:
nick = "NickServ"
self.bot.servers[serverName].log("No valid NickServ nickname was found; defaulting to NickServ...",
level=logging.WARNING)
else:
nick = self.bot.config["nickserv_nick"]
if "nickserv_pass" not in self.bot.config:
self.bot.servers[serverName].log("No NickServ password found. Aborting authentication...",
level=logging.ERROR)
return
password = self.bot.config["nickserv_pass"]
self.bot.servers[serverName].outputHandler.cmdPRIVMSG(nick, "IDENTIFY {}".format(password))
nickServID = NickServIdentify()
|
Add missing requirement for libvirt-python
libvirt-python is missing from setup.py
Change-Id: I41c2e29d612ba0b45f94c2340b9a6a3472d5bbdc
Closes-bug: #1385439 | # Copyright 2013 - 2014 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.
import os
from setuptools import find_packages
from setuptools import setup
setup(
name='devops',
version='2.5.2',
description='Library for creating and manipulating virtual environments',
author='Mirantis, Inc.',
author_email='[email protected]',
url='http://mirantis.com',
keywords='devops virtual environment mirantis',
zip_safe=False,
include_package_data=True,
packages=find_packages(),
data_files=[
(os.path.expanduser('~/.devops'), ['devops/log.yaml']),
(os.path.expanduser('~/.devops/log'), [])],
scripts=['bin/dos.py'],
install_requires=[
'xmlbuilder',
'ipaddr',
'paramiko',
'django<1.7',
'psycopg2',
'south',
'PyYAML',
'mock',
'libvirt-python',
]
)
| # Copyright 2013 - 2014 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.
import os
from setuptools import find_packages
from setuptools import setup
setup(
name='devops',
version='2.5.2',
description='Library for creating and manipulating virtual environments',
author='Mirantis, Inc.',
author_email='[email protected]',
url='http://mirantis.com',
keywords='devops virtual environment mirantis',
zip_safe=False,
include_package_data=True,
packages=find_packages(),
data_files=[
(os.path.expanduser('~/.devops'), ['devops/log.yaml']),
(os.path.expanduser('~/.devops/log'), [])],
scripts=['bin/dos.py'],
install_requires=[
'xmlbuilder',
'ipaddr',
'paramiko',
'django<1.7',
'psycopg2',
'south',
'PyYAML',
'mock',
]
)
|
Prepare elements for new styles | import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';
import SelectGender from './components/SelectGender.js';
import store from './store.js';
import Restart from './components/Restart.js';
import Action from './components/Action.js';
import AcceptedList from './components/AcceptedList.js';
import RejectedList from './components/RejectedList.js';
import { Switch, Route } from 'react-router-dom'
class App extends Component {
constructor(props) {
super(props);
}
render() {
let display = null;
if (this.props.gender.selected == null) {
display = <SelectGender></SelectGender>
} else {
display = <div>
<Restart></Restart>
<ul className="tab-menu">
<li><a href="./nei">Nei</a></li>
<li><a href="./navn">Navn</a></li>
<li><a href="./ja">Ja</a></li>
</ul>
<div className="action-container">
<Switch>
<Route exact path='/navn' component={Action}/>
<Route path='/nei' component={RejectedList}/>
<Route path='/ja' component={AcceptedList}/>
</Switch>
</div>
</div>;
}
return (
<div className="App">
{display}
</div>
);
}
}
const mapStateToProps = function(store) {
return {
gender: store.gender
};
}
export default connect(mapStateToProps)(App);
| import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';
import SelectGender from './components/SelectGender.js';
import store from './store.js';
import Restart from './components/Restart.js';
import Action from './components/Action.js';
import AcceptedList from './components/AcceptedList.js';
import RejectedList from './components/RejectedList.js';
import { Switch, Route } from 'react-router-dom'
class App extends Component {
constructor(props) {
super(props);
}
render() {
let display = null;
if (this.props.gender.selected == null) {
display = <SelectGender></SelectGender>
} else {
display = <div>
<Restart></Restart>
<ul className="tab-menu">
<li><a href="./nei">Nei</a></li>
<li><a href="./navn">Navn</a></li>
<li><a href="./ja">Ja</a></li>
</ul>
<Switch>
<Route exact path='/navn' component={Action}/>
<Route path='/nei' component={RejectedList}/>
<Route path='/ja' component={AcceptedList}/>
</Switch>
</div>;
}
return (
<div className="App container">
{display}
</div>
);
}
}
const mapStateToProps = function(store) {
return {
gender: store.gender
};
}
export default connect(mapStateToProps)(App);
|
Reduce number of database queries | from django import forms
from django.conf import settings
from django.utils.dateparse import parse_datetime
import os
from .saltedge import SaltEdge
from .models import Transaction, Category
from decimal import Decimal
class ImportTransactionsForm(forms.Form):
def import_transactions(self):
app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem")
url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"])
response = app.get(url)
data = response.json()
uncategorized = Category.objects.get(name="Uncategorized")
for imported_transaction in data['data']:
imported_id = int(imported_transaction['id'])
escaped_category = imported_transaction["category"].replace("_", " ")
category = Category.objects.filter(name__iexact=escaped_category)
category = category[0] if category else uncategorized
t, created = Transaction.objects.update_or_create(
external_id=imported_id,
defaults={
"date": imported_transaction['made_on'],
"amount": imported_transaction['amount'],
"payee": "",
"category": category,
"description": imported_transaction['description'],
}
)
| from django import forms
from django.conf import settings
from django.utils.dateparse import parse_datetime
import os
from .saltedge import SaltEdge
from .models import Transaction, Category
from decimal import Decimal
class ImportTransactionsForm(forms.Form):
def import_transactions(self):
app = SaltEdge(os.environ["APP_ID"], os.environ["SECRET"], "transactions/private.pem")
url = "https://www.saltedge.com/api/v5/transactions?connection_id={}&account_id={}".format(os.environ["CONNECTION_ID"], os.environ["ACCOUNT_ID"])
response = app.get(url)
data = response.json()
for imported_transaction in data['data']:
imported_id = int(imported_transaction['id'])
escaped_category = imported_transaction["category"].replace("_", " ")
category = Category.objects.filter(name__iexact=escaped_category)
category = category[0] if category else Category.objects.get(name="Uncategorized")
t, created = Transaction.objects.update_or_create(
external_id=imported_id,
defaults={
"date": imported_transaction['made_on'],
"amount": imported_transaction['amount'],
"payee": "",
"category": category,
"description": imported_transaction['description'],
}
)
|
Use spree/spree source for spec | import * as React from 'react'
import { RedocStandalone } from 'redoc'
import Layout from '../../components/Layout'
const IndexPage = () => (
<Layout activeRootSection="api/v2">
<RedocStandalone
specUrl="https://raw.githubusercontent.com/spree/spree/master/api/docs/v2/storefront/index.yaml"
options={{
disableSearch: true,
scrollYOffset: 80,
hideDownloadButton: true,
theme: {
colors: {
primary: {
main: '#0066CC'
},
success: {
main: '#99CC00'
},
border: {
dark: '#EEE'
}
},
typography: {
smoothing: 'unset',
fontSize: '16px',
fontFamily: '"IBM Plex Sans", sans-serif;',
headings: {
fontFamily: '"IBM Plex Sans", sans-serif;'
},
code: {
fontSize: '16px',
fontFamily: '"IBM Plex Mono", monospace;',
fontWeight: 400,
backgroundColor: '#0066CC',
color: '#FFF'
}
},
rightPanel: {
backgroundColor: '#444'
},
menu: {
width: '19rem',
backgroundColor: '#FFF'
}
}
}}
/>
</Layout>
)
export default IndexPage
| import * as React from 'react'
import { RedocStandalone } from 'redoc'
import Layout from '../../components/Layout'
const IndexPage = () => (
<Layout activeRootSection="api/v2">
<RedocStandalone
specUrl="https://raw.githubusercontent.com/spark-solutions/spree/master/api/docs/v2/storefront/index.yaml"
options={{
disableSearch: true,
scrollYOffset: 80,
hideDownloadButton: true,
theme: {
colors: {
primary: {
main: '#0066CC'
},
success: {
main: '#99CC00'
},
border: {
dark: '#EEE'
}
},
typography: {
smoothing: 'unset',
fontSize: '16px',
fontFamily: '"IBM Plex Sans", sans-serif;',
headings: {
fontFamily: '"IBM Plex Sans", sans-serif;'
},
code: {
fontSize: '16px',
fontFamily: '"IBM Plex Mono", monospace;',
fontWeight: 400,
backgroundColor: '#0066CC',
color: '#FFF'
}
},
rightPanel: {
backgroundColor: '#444'
},
menu: {
width: '19rem',
backgroundColor: '#FFF'
}
}
}}
/>
</Layout>
)
export default IndexPage
|
Add neighbrhood property to row | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%m/%d/%Y').date()
def _get_date_or_cast(self, s, attr):
if getattr(self, attr) is None:
setattr(self, attr, self._cast_date(s))
return getattr(self, attr)
@property
def start_date(self):
return self._get_date_or_cast(
self['DATE ISSUED'],
'_start_date',
)
@property
def end_date(self):
return self._get_date_or_cast(
self['LICENSE TERM EXPIRATION DATE'],
'_end_date',
)
@property
def account_number(self):
return self['ACCOUNT NUMBER']
@property
def neighborhood(self):
return self['NEIGHBORHOOD']
class RawReader(csv.DictReader):
def __iter__(self, *args, **kwargs):
row = self.next()
while row:
yield Row(row)
row = self.next()
class RawWriter(csv.DictWriter):
pass
| import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%m/%d/%Y').date()
def _get_date_or_cast(self, s, attr):
if getattr(self, attr) is None:
setattr(self, attr, self._cast_date(s))
return getattr(self, attr)
@property
def start_date(self):
return self._get_date_or_cast(
self['DATE ISSUED'],
'_start_date',
)
@property
def end_date(self):
return self._get_date_or_cast(
self['LICENSE TERM EXPIRATION DATE'],
'_end_date',
)
@property
def account_number(self):
return self['ACCOUNT NUMBER']
class RawReader(csv.DictReader):
def __iter__(self, *args, **kwargs):
row = self.next()
while row:
yield Row(row)
row = self.next()
class RawWriter(csv.DictWriter):
pass
|
MB-13234: Make `top` work on Ubuntu 12.04
The `top` in Ubuntu12.04 seems to do different command line parsing
than the one on CentOS. Separating the parameters should work on
both.
Change-Id: I8f9ec022bcb8e0158316fdaac226acbfb0d9d004
Reviewed-on: http://review.couchbase.org/50126
Reviewed-by: Dave Rigby <[email protected]>
Reviewed-by: Michael Wiederhold <[email protected]>
Tested-by: Volker Mische <[email protected]> | from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
def __init__(self, hosts, user, password):
super(PSStats, self).__init__(hosts, user, password)
self.ps_cmd = "ps -eo pid,rss,vsize,comm | " \
"grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
self.top_cmd = "top -bn2 -d1 -p {} | grep {}"
@multi_node_task
def get_samples(self, process):
samples = {}
stdout = run(self.ps_cmd.format(process))
if stdout:
for i, value in enumerate(stdout.split()[1:1+len(self.METRICS)]):
metric, multiplier = self.METRICS[i]
title = "{}_{}".format(process, metric)
samples[title] = float(value) * multiplier
pid = stdout.split()[0]
else:
return samples
stdout = run(self.top_cmd.format(pid, process))
if stdout:
title = "{}_cpu".format(process)
samples[title] = float(stdout.split()[8])
return samples
| from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class PSStats(RemoteStats):
METRICS = (
("rss", 1024), # kB -> B
("vsize", 1024),
)
def __init__(self, hosts, user, password):
super(PSStats, self).__init__(hosts, user, password)
self.ps_cmd = "ps -eo pid,rss,vsize,comm | " \
"grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
self.top_cmd = "top -bn2d1 -p {} | grep {}"
@multi_node_task
def get_samples(self, process):
samples = {}
stdout = run(self.ps_cmd.format(process))
if stdout:
for i, value in enumerate(stdout.split()[1:1+len(self.METRICS)]):
metric, multiplier = self.METRICS[i]
title = "{}_{}".format(process, metric)
samples[title] = float(value) * multiplier
pid = stdout.split()[0]
else:
return samples
stdout = run(self.top_cmd.format(pid, process))
if stdout:
title = "{}_cpu".format(process)
samples[title] = float(stdout.split()[8])
return samples
|
Handle compatibility for symfony <= 2.5 | <?php
namespace JBen87\ParsleyBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* @author Benoit Jouhaud <[email protected]>
*/
class ParsleyTypeExtension extends AbstractTypeExtension
{
/**
* @var string
*/
protected $triggerEvent;
/**
* @param string $triggerEvent
*/
public function __construct($triggerEvent)
{
$this->triggerEvent = $triggerEvent;
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
if (method_exists($resolver, 'setDefined')) {
$resolver->setDefined(['parsley_trigger_event']);
} else {
$resolver->setOptional(['parsley_trigger_event']);
}
}
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$triggerEvent = $this->triggerEvent;
if (isset($options['parsley_trigger_event'])) {
$triggerEvent = $options['parsley_trigger_event'];
}
$view->vars['attr']['data-parsley-trigger'] = $triggerEvent;
}
/**
* {@inheritdoc}
*/
public function getExtendedType()
{
return 'form';
}
}
| <?php
namespace JBen87\ParsleyBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* @author Benoit Jouhaud <[email protected]>
*/
class ParsleyTypeExtension extends AbstractTypeExtension
{
/**
* @var string
*/
protected $triggerEvent;
/**
* @param string $triggerEvent
*/
public function __construct($triggerEvent)
{
$this->triggerEvent = $triggerEvent;
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setOptional(['parsley_trigger_event']);
}
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$triggerEvent = $this->triggerEvent;
if (isset($options['parsley_trigger_event'])) {
$triggerEvent = $options['parsley_trigger_event'];
}
$view->vars['attr']['data-parsley-trigger'] = $triggerEvent;
}
/**
* {@inheritdoc}
*/
public function getExtendedType()
{
return 'form';
}
}
|
IFS-5827: Hide button for single applicant | package org.innovateuk.ifs.application.overview.viewmodel;
import org.innovateuk.ifs.application.viewmodel.AssignButtonsViewModel;
import java.util.Optional;
/**
* View model for each row with a link in the application overview page.
*/
public class ApplicationOverviewRowViewModel {
private final String title;
private final String url;
private final boolean complete;
private final AssignButtonsViewModel assignButtonsViewModel;
private final boolean showStatus;
public ApplicationOverviewRowViewModel(String title, String url, boolean complete, AssignButtonsViewModel assignButtonsViewModel, boolean showStatus) {
this.title = title;
this.url = url;
this.complete = complete;
this.assignButtonsViewModel = assignButtonsViewModel;
this.showStatus = showStatus;
}
public ApplicationOverviewRowViewModel(String title, String url, boolean complete, boolean showStatus) {
this.title = title;
this.url = url;
this.complete = complete;
this.assignButtonsViewModel = null;
this.showStatus = showStatus;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public boolean isComplete() {
return complete;
}
public Optional<AssignButtonsViewModel> getAssignButtonsViewModel() {
return Optional.ofNullable(assignButtonsViewModel);
}
public boolean isAssignable() {
return getAssignButtonsViewModel().isPresent() &&
getAssignButtonsViewModel().get().getAssignableApplicants().size() > 1;
}
public boolean isShowStatus() {
return showStatus;
}
} | package org.innovateuk.ifs.application.overview.viewmodel;
import org.innovateuk.ifs.application.viewmodel.AssignButtonsViewModel;
import java.util.Optional;
/**
* View model for each row with a link in the application overview page.
*/
public class ApplicationOverviewRowViewModel {
private final String title;
private final String url;
private final boolean complete;
private final AssignButtonsViewModel assignButtonsViewModel;
private final boolean showStatus;
public ApplicationOverviewRowViewModel(String title, String url, boolean complete, AssignButtonsViewModel assignButtonsViewModel, boolean showStatus) {
this.title = title;
this.url = url;
this.complete = complete;
this.assignButtonsViewModel = assignButtonsViewModel;
this.showStatus = showStatus;
}
public ApplicationOverviewRowViewModel(String title, String url, boolean complete, boolean showStatus) {
this.title = title;
this.url = url;
this.complete = complete;
this.assignButtonsViewModel = null;
this.showStatus = showStatus;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
public boolean isComplete() {
return complete;
}
public Optional<AssignButtonsViewModel> getAssignButtonsViewModel() {
return Optional.ofNullable(assignButtonsViewModel);
}
public boolean isAssignable() {
return getAssignButtonsViewModel().isPresent();
}
public boolean isShowStatus() {
return showStatus;
}
} |
Add subordinate pages to Entry page in navigation. | <?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initViewHeadTitle()
{
$this->bootstrap('view');
/* @var $view Zend_View_Abstract */
$view = $this->getResource('view');
$view->headTitle()->setSeparator(' :: ');
$view->headTitle()->prepend('Postr');
}
protected function _initPagination()
{
Zend_View_Helper_PaginationControl::setDefaultViewPartial(
'paginator.phtml'
);
}
protected function _initNavigation()
{
$this->bootstrap('frontController');
$pages = array(
array(
'label' => 'Home',
'id' => 'index',
'action' => 'index',
'controller' => 'index',
),
array(
'label' => 'Entries',
'id' => 'entry',
'action' => 'index',
'controller' => 'entry',
'pages' => array(
array(
'action' => 'get',
'controller' => 'entry',
'visible' => false,
),
array(
'action' => 'post',
'controller' => 'entry',
'visible' => false,
),
array(
'action' => 'put',
'controller' => 'entry',
'visible' => false,
),
array(
'action' => 'delete',
'controller' => 'entry',
'visible' => false,
),
),
),
);
$resource = new Zend_Application_Resource_Navigation(
array(
'pages' => $pages,
)
);
$resource->setBootstrap($this);
return $resource->init();
}
}
| <?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initViewHeadTitle()
{
$this->bootstrap('view');
/* @var $view Zend_View_Abstract */
$view = $this->getResource('view');
$view->headTitle()->setSeparator(' :: ');
$view->headTitle()->prepend('Postr');
}
protected function _initPagination()
{
Zend_View_Helper_PaginationControl::setDefaultViewPartial(
'paginator.phtml'
);
}
protected function _initNavigation()
{
$this->bootstrap('frontController');
$pages = array(
array(
'label' => 'Home',
'id' => 'index',
'action' => 'index',
'controller' => 'index',
),
array(
'label' => 'Entries',
'id' => 'entry',
'action' => 'index',
'controller' => 'entry',
),
);
$resource = new Zend_Application_Resource_Navigation(
array(
'pages' => $pages,
)
);
$resource->setBootstrap($this);
return $resource->init();
}
}
|
Introduce variable for plan id. formatting. | <?php
require_once('./config.php');
var_dump($_POST);
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
$recurring = $_POST['recurring'];
// validate the amount
$plan_id = "monthly{$amount}";
$plan_name = "Monthly {$amount}";
if ( !empty($recurring) ) {
try {
$plan = Stripe_Plan::retrieve("monthly{$amount}");
} catch (Stripe_InvalidRequestError $error) {
$plan = Stripe_Plan::create(array(
"amount" => $amount * 100,
"interval" => "month",
"name" => $plan_name,
"currency" => "usd",
"id" => $plan_id)
);
}
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan_id
));
echo "<h1>Successful subscription for {$amount}/month!</h1>";
} else {
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount * 100,
'currency' => 'usd',
'description' => 'donation, amount supplied by customer'
));
echo "<h1>Successfully charged {$amount}!</h1>";
}
?> | <?php
require_once('./config.php');
var_dump($_POST);
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$amount = $_POST['amount'];
$recurring = $_POST['recurring'];
// validate the amount
if ( !empty($recurring) ) {
try {
$plan = Stripe_Plan::retrieve("monthly{$amount}");
} catch (Stripe_InvalidRequestError $error) {
$plan = Stripe_Plan::create(array(
"amount" => $amount * 100,
"interval" => "month",
"name" => "Monthly {$amount}",
"currency" => "usd",
"id" => "monthly{$amount}")
);
}
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => "monthly{$amount}"
));
echo "<h1>Successful subscription for {$amount}/month!</h1>";
} else {
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount * 100,
'currency' => 'usd',
'description' => 'donation, amount supplied by customer'
));
echo "<h1>Successfully charged {$amount}!zz</h1>";
}
?> |
Fix unit test for when robotframework is not installed. | import unittest
import robotide.lib.robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
def test_invalid_argument(self):
try:
self.assertRaisesRegex(robotide.lib.robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
except AttributeError: # Python2
self.assertRaisesRegexp(robotide.lib.robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
def test_valid_argument_short(self):
self._working_arguments('-T')
def _working_arguments(self, args):
self.assertEqual(None, self._profile._get_invalid_message(args))
def test_valid_argument_long(self):
self._working_arguments('--timestampoutputs')
def test_valid_argument_with_value(self):
self._working_arguments('--log somelog.html')
def test_runfailed_argument_works(self):
self._working_arguments('--runfailed output.xml')
if __name__ == '__main__':
unittest.main()
| import unittest
import robot.errors
from robotide.contrib.testrunner.runprofiles import PybotProfile
class TestPybotArgumentsValidation(unittest.TestCase):
def setUp(self):
self._profile = PybotProfile(lambda:0)
@unittest.expectedFailure # No more DataError, better argument detection
def test_invalid_argument(self):
try:
self.assertRaisesRegex(robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
except AttributeError: # Python2
self.assertRaisesRegexp(robot.errors.DataError,
'option --invalidargument not recognized',
self._profile._get_invalid_message,
'--invalidargument')
def test_valid_argument_short(self):
self._working_arguments('-T')
def _working_arguments(self, args):
self.assertEqual(None, self._profile._get_invalid_message(args))
def test_valid_argument_long(self):
self._working_arguments('--timestampoutputs')
def test_valid_argument_with_value(self):
self._working_arguments('--log somelog.html')
def test_runfailed_argument_works(self):
self._working_arguments('--runfailed output.xml')
if __name__ == '__main__':
unittest.main()
|
Select top most version if non selected for top crashers | $(document).ready(function () {
var url_base = $("#url_base").val(),
url_site = $("#url_site").val(),
product,
product_version,
report;
$("#q").focus(function () {
$(this).attr('value', '');
});
// Used to handle the selection of specific product.
if ($("#products_select")) {
$("#products_select").change(function () {
product = $("#products_select").val();
window.location = url_site + 'products/' + product;
});
}
// Used to handle the selection of a specific version of a specific product.
if ($("#product_version_select")) {
$("#product_version_select").change(function () {
product_version = $("#product_version_select").val();
if (product_version == 'Current Versions') {
window.location = url_base;
} else {
window.location = url_base + '/versions/' + product_version;
}
});
}
// Used to handle the selection of a specific report.
if ($("#report_select")) {
$("#report_select").change(function () {
report = $("#report_select").val();
// Handle top crasher selection. If no version was selected in the version drop-down
// select the top most version and append to the URL.
if(report.indexOf('topcrasher') !== -1) {
var selectedVersion = $("#product_version_select").val();
if(selectedVersion === "Current Versions") {
selectedVersion = $("#product_version_select").find("option:eq(1)").val();
window.location = report + selectedVersion;
} else {
window.location = report;
}
} else if (report !== 'More Reports') {
window.location = report;
}
});
}
});
| $(document).ready(function () {
var url_base = $("#url_base").val(),
url_site = $("#url_site").val(),
product,
product_version,
report;
$("#q").focus(function () {
$(this).attr('value', '');
});
// Used to handle the selection of specific product.
if ($("#products_select")) {
$("#products_select").change(function () {
product = $("#products_select").val();
window.location = url_site + 'products/' + product;
});
}
// Used to handle the selection of a specific version of a specific product.
if ($("#product_version_select")) {
$("#product_version_select").change(function () {
product_version = $("#product_version_select").val();
if (product_version == 'Current Versions') {
window.location = url_base;
} else {
window.location = url_base + '/versions/' + product_version;
}
});
}
// Used to handle the selection of a specific report.
if ($("#report_select")) {
$("#report_select").change(function () {
report = $("#report_select").val();
if (report !== 'More Reports') {
window.location = report;
}
});
}
});
|
Add source elements url + jwt to resource model | <?php
namespace Hub\Client\Model;
class Resource
{
protected $type;
protected $shares = array();
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
private $properties = array();
public function addProperty(Property $property)
{
$this->properties[$property->getName()] = $property;
return $this;
}
public function hasProperty($name)
{
return isset($this->properties[$name]);
}
public function getProperty($name)
{
return $this->properties[$name];
}
public function getPropertyValue($name)
{
return $this->getProperty($name)->getValue();
}
public function addPropertyValue($name, $value)
{
$name = (string)$name;
$value = (string)$value;
$property = new Property($name, $value);
$this->addProperty($property);
return $this;
}
public function addShare(Share $share)
{
$this->shares[] = $share;
return $this;
}
public function getShares()
{
return $this->shares;
}
private $sourceUrl;
public function getSourceUrl()
{
return $this->sourceUrl;
}
public function setSourceUrl($sourceUrl)
{
$this->sourceUrl = $sourceUrl;
return $this;
}
private $sourceJwt;
public function getSourceJwt()
{
return $this->sourceJwt;
}
public function setSourceJwt($sourceJwt)
{
$this->sourceJwt = $sourceJwt;
return $this;
}
}
| <?php
namespace Hub\Client\Model;
class Resource
{
protected $type;
protected $shares = array();
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
private $properties = array();
public function addProperty(Property $property)
{
$this->properties[$property->getName()] = $property;
return $this;
}
public function hasProperty($name)
{
return isset($this->properties[$name]);
}
public function getProperty($name)
{
return $this->properties[$name];
}
public function getPropertyValue($name)
{
return $this->getProperty($name)->getValue();
}
public function addPropertyValue($name, $value)
{
$name = (string)$name;
$value = (string)$value;
$property = new Property($name, $value);
$this->addProperty($property);
return $this;
}
public function addShare(Share $share)
{
$this->shares[] = $share;
return $this;
}
public function getShares()
{
return $this->shares;
}
}
|
Add function to get profile. Refactor. | /*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");
class FBMessenger {
constructor(token) {
this._fbBase = "https://graph.facebook.com/v2.6/";
this._token = token;
this._q = qs.stringify({access_token: token});
this._wreck = Wreck.defaults({
baseUrl: this._fbBase
});
}
sendMessage(userid, msg) {
let payload = "";
payload = JSON.stringify({
recipient: { id: userid },
message: msg
});
return this._makeRequest(`/me/messages?${this._q}`,payload);
}
getUserProfile(userid, fields) {
let params = {
access_token: this._token
};
let q = "";
fields = (Array.isArray(fields)) ? fields.join(",") : fields;
if(fields) {
params.fields = fields;
}
q = qs.stringify(params);
return this._makeRequest(`/${userid}?${q}`);
}
_makeRequest(url, payload) {
let method = "GET";
let opts = {};
if(payload) {
method = "POST";
opts.payload = payload;
}
return new Promise((resolve, reject) => {
this._wreck.request(
method,
url,
opts,
(err, response) => {
if(err) {
return reject(err);
}
if(response.body.error) {
return reject(response.body.error);
}
return resolve(response.body);
}
);
});
}
}
module.exports = FBMessenger;
| /*jshint strict: true, esnext: true, node: true*/
"use strict";
const Wreck = require("wreck");
const qs = require("querystring");
class FBMessenger {
constructor(token) {
this._fbBase = "https://graph.facebook.com/v2.6/me/";
this._token = token;
this._q = qs.stringify({access_token: token});
this._wreck = Wreck.defaults({
baseUrl: this._fbBase
});
}
sendMessage(userid, msg) {
let payload = "";
payload = JSON.stringify({
recipient: { id: userid },
message: msg
});
return new Promise(function(resolve, reject) {
this._wreck.request(
"POST",
`/messages?${this._q}`,
{
payload: payload
},
(err, response) => {
if(err) {
return reject(err);
}
if(response.body.error) {
return reject(response.body.error);
}
return resolve(response.body);
}
);
});
}
}
module.exports = FBMessenger;
|
Add level attribute and proper sorting. | <?php
namespace common\models\comments;
class AdjacencyListComment extends Comment
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%comment_al}}';
}
public static function findByPostInternal($postId)
{
$comments = static::find()
->select(['id', 'parent_id', 'author_id', 'text', 'created_at'])
->where(['post_id' => $postId])
->orderBy('created_at DESC')
->asArray()
->all();
$root = ['id' => null, 'children' => []];
static::prepareComments($root, $comments);
unset($comments);
return $root['children'];
}
private static function prepareComments(&$parentNode, &$comments, $level = 1)
{
foreach ($comments as $i => &$childNode) {
if (is_integer($childNode['id'])) {
continue;
}
if (!isset($childNode['children'])) {
$childNode['children'] = [];
}
if ($parentNode['id'] == $childNode['parent_id']) {
$parentNode['children'][] = &$childNode;
$childNode['level'] = $level;
$childNode['id'] = (integer)$childNode['id'];
$childNode['parent_id'] = (integer)$childNode['parent_id'];
$childNode['author_id'] = (integer)$childNode['author_id'];
$childNode['created_at'] = (integer)$childNode['created_at'];
}
}
foreach ($parentNode['children'] as $i => &$childNode) {
static::prepareComments($childNode, $comments, $level + 1);
}
}
}
| <?php
namespace common\models\comments;
class AdjacencyListComment extends Comment
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%comment_al}}';
}
public static function findByPostInternal($postId)
{
$comments = static::find()
->select(['id', 'parent_id', 'author_id', 'text', 'created_at'])
->where(['post_id' => $postId])
->asArray()
->all();
$root = ['id' => null, 'children' => []];
static::prepareComments($root, $comments);
unset($comments);
return $root['children'];
}
private static function prepareComments(&$parentNode, &$comments)
{
foreach ($comments as $i => &$childNode) {
if (is_integer($childNode['id'])) {
continue;
}
if (!isset($childNode['children'])) {
$childNode['children'] = [];
}
if ($parentNode['id'] == $childNode['parent_id']) {
$parentNode['children'][] = &$childNode;
$childNode['id'] = (integer)$childNode['id'];
$childNode['parent_id'] = (integer)$childNode['parent_id'];
$childNode['author_id'] = (integer)$childNode['author_id'];
$childNode['created_at'] = (integer)$childNode['created_at'];
}
}
foreach ($parentNode['children'] as $i => &$childNode) {
static::prepareComments($childNode, $comments);
}
}
}
|
Fix regex for pyflakes output format since `2.2.0` | from SublimeLinter.lint import PythonLinter
import re
class Pyflakes(PythonLinter):
cmd = 'pyflakes'
regex = r'''(?x)
^(?P<filename>.+):(?P<line>\d+):((?P<col>\d+):?)?\s
# The rest of the line is the error message.
# Within that, capture anything within single quotes as `near`.
(?P<message>[^\'\n\r]*(?P<near>\'.+?\')?.*)
'''
multiline = True
# stderr has all syntax errors, parse it via our regex
on_stderr = None
defaults = {
'selector': 'source.python'
}
def reposition_match(self, line, col, match, vv):
if 'imported but unused' in match.message:
# Consider:
# from foo import bar
# import foo.bar
# In both cases `pyflakes` reports `'foo.bar' ... unused`.
import_id = re.escape(match.near[1:-1]) # unquote
last_part = import_id.split('.')[-1]
# So we match either `bar` or `foo.bar` against the line content
text = vv.select_line(line)
pattern = r"\s({}|{})".format(last_part, import_id)
re_match = re.search(pattern, text)
if re_match:
return line, re_match.start(1), re_match.end(1)
return super().reposition_match(line, col, match, vv)
| from SublimeLinter.lint import PythonLinter
import re
class Pyflakes(PythonLinter):
cmd = 'pyflakes'
regex = r'''(?x)
^(?P<filename>[^:\n]+):(?P<line>\d+):((?P<col>\d+):)?\s
# The rest of the line is the error message.
# Within that, capture anything within single quotes as `near`.
(?P<message>[^\'\n\r]*(?P<near>\'.+?\')?.*)
'''
multiline = True
# stderr has all syntax errors, parse it via our regex
on_stderr = None
defaults = {
'selector': 'source.python'
}
def reposition_match(self, line, col, match, vv):
if 'imported but unused' in match.message:
# Consider:
# from foo import bar
# import foo.bar
# In both cases `pyflakes` reports `'foo.bar' ... unused`.
import_id = re.escape(match.near[1:-1]) # unquote
last_part = import_id.split('.')[-1]
# So we match either `bar` or `foo.bar` against the line content
text = vv.select_line(line)
pattern = r"\s({}|{})".format(last_part, import_id)
re_match = re.search(pattern, text)
if re_match:
return line, re_match.start(1), re_match.end(1)
return super().reposition_match(line, col, match, vv)
|
Fix source and destination paths for installing plugins from local disk
They were installing into eg. my.plugin.id/plugman_dir_basename/*
instead of just my.plugin.id/*. | var shell = require('shelljs'),
fs = require('fs'),
plugins = require('./util/plugins'),
xml_helpers = require('./util/xml-helpers'),
path = require('path');
module.exports = function fetchPlugin(plugin_dir, plugins_dir, link, subdir, callback) {
// Ensure the containing directory exists.
shell.mkdir('-p', plugins_dir);
subdir = subdir || '.';
// clone from git repository
if(plugin_dir.indexOf('https://') == 0 || plugin_dir.indexOf('git://') == 0) {
if (link) {
var err = new Error('--link is not supported for git URLs');
if (callback) callback(err);
else throw err;
} else {
plugins.clonePluginGitRepo(plugin_dir, plugins_dir, subdir, callback);
}
} else {
// Copy from the local filesystem.
// First, read the plugin.xml and grab the ID.
plugin_dir = path.join(plugin_dir, subdir);
var xml = xml_helpers.parseElementtreeSync(path.join(plugin_dir, 'plugin.xml'));
var plugin_id = xml.getroot().attrib.id;
var dest = path.join(plugins_dir, plugin_id);
shell.rm('-rf', dest);
if (link) {
fs.symlinkSync(plugin_dir, dest, 'dir');
} else {
shell.mkdir('-p', dest);
shell.cp('-R', path.join(plugin_dir, '*') , dest);
}
if (callback) callback(null, dest);
}
};
| var shell = require('shelljs'),
fs = require('fs'),
plugins = require('./util/plugins'),
xml_helpers = require('./util/xml-helpers'),
path = require('path');
module.exports = function fetchPlugin(plugin_dir, plugins_dir, link, subdir, callback) {
// Ensure the containing directory exists.
shell.mkdir('-p', plugins_dir);
subdir = subdir || '.';
// clone from git repository
if(plugin_dir.indexOf('https://') == 0 || plugin_dir.indexOf('git://') == 0) {
if (link) {
var err = new Error('--link is not supported for git URLs');
if (callback) callback(err);
else throw err;
} else {
plugins.clonePluginGitRepo(plugin_dir, plugins_dir, subdir, callback);
}
} else {
// Copy from the local filesystem.
// First, read the plugin.xml and grab the ID.
plugin_dir = path.join(plugin_dir, subdir);
var xml = xml_helpers.parseElementtreeSync(path.join(plugin_dir, 'plugin.xml'));
var plugin_id = xml.getroot().attrib.id;
var dest = path.join(plugins_dir, plugin_id);
shell.rm('-rf', dest);
if (link) {
fs.symlinkSync(plugin_dir, dest, 'dir');
} else {
shell.cp('-R', plugin_dir, dest);
}
if (callback) callback(null, dest);
}
};
|
Add attributes for 'font' tag to the whitelist | package com.fsck.k9.message.html;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;
public class HtmlSanitizer {
private final HeadCleaner headCleaner;
private final Cleaner cleaner;
HtmlSanitizer() {
Whitelist whitelist = Whitelist.relaxed()
.addTags("font", "hr", "ins", "del")
.addAttributes("font", "color", "face", "size")
.addAttributes("table", "align", "background", "bgcolor", "border", "cellpadding", "cellspacing",
"width")
.addAttributes("tr", "align", "bgcolor", "valign")
.addAttributes("th",
"align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted",
"valign", "width")
.addAttributes("td",
"align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
"width")
.addAttributes(":all", "class", "style", "id")
.addProtocols("img", "src", "http", "https", "cid", "data");
cleaner = new Cleaner(whitelist);
headCleaner = new HeadCleaner();
}
public Document sanitize(String html) {
Document dirtyDocument = Jsoup.parse(html);
Document cleanedDocument = cleaner.clean(dirtyDocument);
headCleaner.clean(dirtyDocument, cleanedDocument);
return cleanedDocument;
}
}
| package com.fsck.k9.message.html;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;
public class HtmlSanitizer {
private final HeadCleaner headCleaner;
private final Cleaner cleaner;
HtmlSanitizer() {
Whitelist whitelist = Whitelist.relaxed()
.addTags("font", "hr", "ins", "del")
.addAttributes("table", "align", "background", "bgcolor", "border", "cellpadding", "cellspacing",
"width")
.addAttributes("tr", "align", "bgcolor", "valign")
.addAttributes("th",
"align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted",
"valign", "width")
.addAttributes("td",
"align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
"width")
.addAttributes(":all", "class", "style", "id")
.addProtocols("img", "src", "http", "https", "cid", "data");
cleaner = new Cleaner(whitelist);
headCleaner = new HeadCleaner();
}
public Document sanitize(String html) {
Document dirtyDocument = Jsoup.parse(html);
Document cleanedDocument = cleaner.clean(dirtyDocument);
headCleaner.clean(dirtyDocument, cleanedDocument);
return cleanedDocument;
}
}
|
requireTrailingComma: Fix incorrect option name in error message | var assert = require('assert');
var tokenHelper = require('../token-helper');
module.exports = function() {};
module.exports.prototype = {
configure: function(requireTrailingComma) {
if (typeof requireTrailingComma === 'object') {
assert(
requireTrailingComma.ignoreSingleValue === true,
'requireTrailingComma option ignoreSingleValue requires true value or should be removed'
);
this._ignoreSingleValue = true;
} else {
assert(
requireTrailingComma === true,
'requireTrailingComma option requires true value or should be removed'
);
}
},
getOptionName: function() {
return 'requireTrailingComma';
},
check: function(file, errors) {
var _this = this;
file.iterateNodesByType(['ObjectExpression', 'ArrayExpression'], function(node) {
var isObject = node.type === 'ObjectExpression';
var message = 'Missing comma before closing ' + (isObject ? ' curly brace' : ' bracket');
var entities = isObject ? node.properties : node.elements;
var last;
var hasTrailingComma;
if (entities.length) {
if (_this._ignoreSingleValue && entities.length === 1) {
return;
}
last = entities[entities.length - 1];
hasTrailingComma = tokenHelper.getTokenByRangeStartIfPunctuator(file, last.range[1], ',');
if (!hasTrailingComma) {
errors.add(message, node.loc.end);
}
}
});
}
};
| var assert = require('assert');
var tokenHelper = require('../token-helper');
module.exports = function() {};
module.exports.prototype = {
configure: function(requireTrailingComma) {
if (typeof requireTrailingComma === 'object') {
assert(
requireTrailingComma.ignoreSingleValue === true,
'requireTrailingComma option skipSingleValue requires true value or should be removed'
);
this._ignoreSingleValue = true;
} else {
assert(
requireTrailingComma === true,
'requireTrailingComma option requires true value or should be removed'
);
}
},
getOptionName: function() {
return 'requireTrailingComma';
},
check: function(file, errors) {
var _this = this;
file.iterateNodesByType(['ObjectExpression', 'ArrayExpression'], function(node) {
var isObject = node.type === 'ObjectExpression';
var message = 'Missing comma before closing ' + (isObject ? ' curly brace' : ' bracket');
var entities = isObject ? node.properties : node.elements;
var last;
var hasTrailingComma;
if (entities.length) {
if (_this._ignoreSingleValue && entities.length === 1) {
return;
}
last = entities[entities.length - 1];
hasTrailingComma = tokenHelper.getTokenByRangeStartIfPunctuator(file, last.range[1], ',');
if (!hasTrailingComma) {
errors.add(message, node.loc.end);
}
}
});
}
};
|
Use game.queue.is_turn(name) to build player or enemies | import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, game):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in game.state.players.items():
print(name, player, game.state.json)
if game.queue.is_turn(name):
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
| import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, state):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in state.players.items():
print(name, player, state)
is_current_player = False # TODO: Determine current player from state?
if is_current_player:
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
Update local Date automatically each 60s | import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: '[email protected]',
picture: '//icons.iconarchive.com/icons/graphicloads/flat-finance/256/person-icon.png',
lists: [
{
name: 'Study',
timers: [
{
name: 'Timer 1',
time: '1500'
},
{
name: 'Timer 2',
time: '1500'
},
{
name: 'Timer 3',
time: '1500'
}
]
},
{
name: 'Piano',
timers: [
{
name: 'Timer 4',
time: '1500'
},
{
name: 'Timer 5',
time: '1500'
}
]
}
]
};
}
updateDate () {
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
}, 60000);
}
}
export default NavbarController;
| import moment from 'moment';
class NavbarController {
constructor() {
this.name = 'navbar';
}
$onInit(){
this.moment = moment().format('dddd HH:mm');
this.updateDate();
this.user =
{
name: 'Jesus Garcia',
mail: '[email protected]',
picture: '//icons.iconarchive.com/icons/graphicloads/flat-finance/256/person-icon.png',
lists: [
{
name: 'Study',
timers: [
{
name: 'Timer 1',
time: '1500'
},
{
name: 'Timer 2',
time: '1500'
},
{
name: 'Timer 3',
time: '1500'
}
]
},
{
name: 'Piano',
timers: [
{
name: 'Timer 4',
time: '1500'
},
{
name: 'Timer 5',
time: '1500'
}
]
}
]
};
}
updateDate () {
setTimeout(() => {
this.moment = moment().format('dddd HH:mm');
this.updateDate();
}, 1000);
}
}
export default NavbarController;
|
Use self instead of class name | <?php
namespace MicroFW\Templates;
use MicroFW\Core\TemplateDoesNotExistException;
class Template
{
/** @var string */
private $templatePath;
/** @var array */
private $context;
/** @var MicroFW\Core\IConfigurator */
private static $configurator;
/**
* @param $templatePath string
* @param $context array
*/
public function __construct($templatePath, $context = [])
{
$this->templatePath = $templatePath;
$this->context = $context;
}
/**
* @param $configurator MicroFW\Core\IConfigurator
* @return void
*/
public static function init($configurator)
{
self::$configurator = $configurator;
}
/**
* Render template and return it.
* @return string
*/
public function render()
{
$templateDir = self::$configurator['TEMPLATE_DIR'];
$fullPath = $templateDir . '/' . $this->templatePath;
if (file_exists($fullPath)) {
$content = file_get_contents($fullPath);
} else {
throw new TemplateDoesNotExistException(
"$this->templatePath does not exist."
);
}
return $content;
}
}
| <?php
namespace MicroFW\Templates;
use MicroFW\Core\TemplateDoesNotExistException;
class Template
{
/** @var string */
private $templatePath;
/** @var array */
private $context;
/** @var MicroFW\Core\IConfigurator */
private static $configurator;
/**
* @param $templatePath string
* @param $context array
*/
public function __construct($templatePath, $context = [])
{
$this->templatePath = $templatePath;
$this->context = $context;
}
/**
* @param $configurator MicroFW\Core\IConfigurator
* @return void
*/
public static function init($configurator)
{
Template::$configurator = $configurator;
}
/**
* Render template and return it.
* @return string
*/
public function render()
{
$templateDir = self::$configurator['TEMPLATE_DIR'];
$fullPath = $templateDir . '/' . $this->templatePath;
if (file_exists($fullPath)) {
$content = file_get_contents($fullPath);
} else {
throw new TemplateDoesNotExistException(
"$this->templatePath does not exist."
);
}
return $content;
}
}
|
Fix potential bug when key returns null | <?php
namespace Styde\Html\Alert;
use Illuminate\Session\Store as Session;
class SessionHandler implements Handler
{
/**
* Laravel's component to handle sessions
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* Reserved session key for this component
*
* @var string $key
*/
protected $key;
/**
* Creates a new SessionHandler instance.
*
* This class will allow us to persist the alert messages to the next
* request using the Laravel's Session component.
*
* @param Session $session
* @param $key
*/
public function __construct(Session $session, $key)
{
$this->session = $session;
$this->key = $key;
}
/**
* Get the messages from the previous request(s)
*
* @return array
*/
public function getPreviousMessages()
{
$result = $this->session->get($this->key);
return is_array($result) ? $result : [];
}
/**
* Save the messages to the session
* This will be typically called through the Middleware's terminate method.
*
* @param array $messages
*/
public function push(array $messages)
{
$this->session->put($this->key, $messages);
}
/**
* Clear all the messages from the session.
* Useful once the messages has been rendered.
*/
public function clean()
{
$this->session->put($this->key, null);
}
}
| <?php
namespace Styde\Html\Alert;
use Illuminate\Session\Store as Session;
class SessionHandler implements Handler
{
/**
* Laravel's component to handle sessions
*
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* Reserved session key for this component
*
* @var string $key
*/
protected $key;
/**
* Creates a new SessionHandler instance.
*
* This class will allow us to persist the alert messages to the next
* request using the Laravel's Session component.
*
* @param Session $session
* @param $key
*/
public function __construct(Session $session, $key)
{
$this->session = $session;
$this->key = $key;
}
/**
* Get the messages from the previous request(s)
*
* @return array
*/
public function getPreviousMessages()
{
return $this->session->get($this->key, []);
}
/**
* Save the messages to the session
* This will be typically called through the Middleware's terminate method.
*
* @param array $messages
*/
public function push(array $messages)
{
$this->session->put($this->key, $messages);
}
/**
* Clear all the messages from the session.
* Useful once the messages has been rendered.
*/
public function clean()
{
$this->session->put($this->key, null);
}
}
|
Print devices example - change out format | # import PyOpenCL and Numpy. An OpenCL-enabled GPU is not required,
# OpenCL kernels can be compiled on most CPUs thanks to the Intel SDK for OpenCL
# or the AMD APP SDK.
import pyopencl as cl
def main():
dev_type_str = {}
for dev_type in ['ACCELERATOR', 'ALL', 'CPU', 'CUSTOM', 'DEFAULT', 'GPU']:
dev_type_str[getattr(cl.device_type, dev_type)] = dev_type
for platform_index, platform in enumerate(cl.get_platforms()):
print 'platform: %s' % platform_index
print '%s' % platform.name
print '%s' % platform.profile
print '%s' % platform.vendor
print '%s' % platform.version
for device in platform.get_devices():
print ' device: %s' % platform_index
for param in ['NAME', 'BUILT_IN_KERNELS', 'MAX_COMPUTE_UNITS',
'GLOBAL_MEM_SIZE', 'MAX_MEM_ALLOC_SIZE', 'TYPE',
'MAX_WORK_GROUP_SIZE']:
try:
value = device.get_info(getattr(cl.device_info, param))
except (cl.LogicError, AttributeError):
continue
print ' ',
if param == 'TYPE':
value = '%s (%s)' % (
value,
dev_type_str.get(value, 'UNDEF')
)
print '%s:\t%s' % (
param,
value
)
print ''
if __name__ == '__main__':
main()
| # import PyOpenCL and Numpy. An OpenCL-enabled GPU is not required,
# OpenCL kernels can be compiled on most CPUs thanks to the Intel SDK for OpenCL
# or the AMD APP SDK.
import pyopencl as cl
def main():
dev_type_str = {}
for dev_type in ['ACCELERATOR', 'ALL', 'CPU', 'CUSTOM', 'DEFAULT', 'GPU']:
dev_type_str[getattr(cl.device_type, dev_type)] = dev_type
for platform_index, platform in enumerate(cl.get_platforms()):
print 'ID: %s' % platform_index
print platform.name
print platform.profile
print platform.vendor
print platform.version
for device in platform.get_devices():
for param in ['NAME', 'BUILT_IN_KERNELS', 'MAX_COMPUTE_UNITS',
'GLOBAL_MEM_SIZE', 'MAX_MEM_ALLOC_SIZE', 'TYPE',
'MAX_WORK_GROUP_SIZE']:
try:
value = device.get_info(getattr(cl.device_info, param))
except (cl.LogicError, AttributeError):
continue
print '\t',
if param == 'TYPE':
value = '%s (%s)' % (
value,
dev_type_str.get(value, 'UNDEF')
)
print '%s:\t%s' % (
param,
value
)
print ''
if __name__ == '__main__':
main()
|
Rename class attribute, method and variable | <?php
namespace Bauhaus;
use InvalidArgumentException;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class Application
{
private $middlewareStack = [];
public function stackUp($middleware): void
{
if (false === $this->canStackUp($middleware)) {
throw new InvalidArgumentException('Can only stack up PSR-15 middlewares');
}
$this->middlewareStack[] = $middleware;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$firstHandler = $this->buildChain();
return $firstHandler->process($request);
}
private function canStackUp($middleware): bool
{
if (is_object($middleware)) {
return $middleware instanceof MiddlewareInterface;
}
if (false === is_string($middleware)) {
return false;
}
if (false === class_exists($middleware)) {
return false;
}
$implementedInterfaces = class_implements($middleware);
return in_array(MiddlewareInterface::class, $implementedInterfaces);
}
private function buildChain(): DelegateInterface
{
$currentDelegator = new GroundDelegator();
foreach($this->middlewareStack as $middleware) {
$currentDelegator = new Delegator($middleware, $currentDelegator);
}
return $currentDelegator;
}
}
| <?php
namespace Bauhaus;
use InvalidArgumentException;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class Application
{
private $stack = [];
public function stackUp($middleware): void
{
if (false === $this->canStackUp($middleware)) {
throw new InvalidArgumentException('Can only stack up PSR-15 middlewares');
}
$this->stack[] = $middleware;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$headDelegator = $this->buildDelegatorChain();
return $headDelegator->process($request);
}
private function canStackUp($middleware): bool
{
if (is_object($middleware)) {
return $middleware instanceof MiddlewareInterface;
}
if (false === is_string($middleware)) {
return false;
}
if (false === class_exists($middleware)) {
return false;
}
$implementedInterfaces = class_implements($middleware);
return in_array(MiddlewareInterface::class, $implementedInterfaces);
}
private function buildDelegatorChain(): DelegateInterface
{
$currentDelegator = new GroundDelegator();
foreach($this->stack as $middleware) {
$currentDelegator = new Delegator($middleware, $currentDelegator);
}
return $currentDelegator;
}
}
|
Fix form field custom kwarg | # coding=utf-8
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.itercompat import is_iterable
from six import string_types
from . import settings
from .forms import StdnumField
__all__ = [
'StdNumField',
]
class StdNumField(models.CharField):
"""Model field that can store an stdnum value"""
def __init__(self, formats, *args, **kwargs):
if formats is None:
raise ImproperlyConfigured('StdNumField defined without formats')
if not is_iterable(formats) or isinstance(formats, string_types):
formats = [formats]
for format in formats:
if format not in settings.DEFAULT_FORMATS:
raise ValueError(
'Unknown format for StdNumField: "{}". Is it missing from '
'settings.STDNUMFIELD["DEFAULT_FORMATS"]?'.format(
format,
))
self.formats = formats
# TODO make dynamic when/if stdnum provides this data:
kwargs["max_length"] = 254
super(StdNumField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(StdNumField, self).deconstruct()
kwargs['formats'] = self.formats
del kwargs["max_length"]
return name, path, args, kwargs
def get_internal_type(self):
return 'CharField'
def formfield(self, **kwargs):
defaults = {
'form_class': StdnumField,
'formats': self.formats,
}
defaults.update(kwargs)
return super(StdNumField, self).formfield(**defaults)
| # coding=utf-8
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.itercompat import is_iterable
from six import string_types
from . import settings
from .forms import StdnumField
__all__ = [
'StdNumField',
]
class StdNumField(models.CharField):
"""Model field that can store an stdnum value"""
def __init__(self, formats, *args, **kwargs):
if formats is None:
raise ImproperlyConfigured('StdNumField defined without formats')
if not is_iterable(formats) or isinstance(formats, string_types):
formats = [formats]
for format in formats:
if format not in settings.DEFAULT_FORMATS:
raise ValueError(
'Unknown format for StdNumField: "{}". Is it missing from '
'settings.STDNUMFIELD["DEFAULT_FORMATS"]?'.format(
format,
))
self.formats = formats
# TODO make dynamic when/if stdnum provides this data:
kwargs["max_length"] = 254
super(StdNumField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(StdNumField, self).deconstruct()
kwargs['formats'] = self.formats
del kwargs["max_length"]
return name, path, args, kwargs
def get_internal_type(self):
return 'CharField'
def formfield(self, **kwargs):
defaults = {'form_class': StdnumField}
defaults.update(kwargs)
return super(StdNumField, self).formfield(**defaults)
|
Fix debug mode on application | <?php
namespace HeyDoc;
use dflydev\markdown\MarkdownExtraParser;
use HeyDoc\Exception\NotFoundException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
class Application
{
/** @var **/
protected $container;
/** @var **/
protected $page;
/**
* Contruct
*
* @param Request $request Request to perform (Move it into run() method?)
*/
public function __construct(Request $request)
{
$this->container = new Container();
$this->container->setRequest($request);
$this->container->load();
if ($this->container->get('config')->get('debug') == true) {
ErrorHandler::register(true);
}
else {
ErrorHandler::quiet();
}
}
/**
* Run the application
*/
public function run()
{
try {
$this->prepare();
$this->process();
}
catch (NotFoundException $e) {
Response::createAndSend($e->getMessage(), 404);
}
}
/**
* Prepare
*/
protected function prepare()
{
$this->page = $this->container->get('router')->process();
}
/**
* Process
*/
protected function process()
{
$response = new Response();
$response->setContent(
$this->container->get('renderer')->render($this->page)
);
$response->send();
}
}
| <?php
namespace HeyDoc;
use dflydev\markdown\MarkdownExtraParser;
use HeyDoc\Exception\NotFoundException;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
class Application
{
/** @var **/
protected $container;
/** @var **/
protected $page;
/**
* Contruct
*
* @param Request $request Request to perform (Move it into run() method?)
*/
public function __construct(Request $request)
{
$this->container = new Container();
$this->container->setRequest($request);
$this->container->load();
if ($this->container->get('config')->get('debug') === true) {
ErrorHandler::register(true);
}
else {
ErrorHandler::quiet();
}
}
/**
* Run the application
*/
public function run()
{
try {
$this->prepare();
$this->process();
}
catch (NotFoundException $e) {
Response::createAndSend($e->getMessage(), 404);
}
}
/**
* Prepare
*/
protected function prepare()
{
$this->page = $this->container->get('router')->process();
}
/**
* Process
*/
protected function process()
{
$response = new Response();
$response->setContent(
$this->container->get('renderer')->render($this->page)
);
$response->send();
}
}
|
Increase watermark by one everytime when an entry is written | package uk.gov;
import org.postgresql.util.PGobject;
import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class DestinationPostgresDB extends PostgresDB {
private final String indexedEntriesTableName;
private final String waterMarkTableName;
public DestinationPostgresDB(String connectionString) throws SQLException {
super(connectionString);
this.indexedEntriesTableName = "ordered_entry_index";
this.waterMarkTableName = "streamed_entries";
}
public void write(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) {
statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY")));
statement.executeUpdate();
}
try (PreparedStatement statement = connection.prepareStatement("UPDATE " + waterMarkTableName + " SET ID = ID + 1")) {
statement.executeUpdate();
}
connection.setAutoCommit(true);
}
}
public int currentWaterMark() throws SQLException {
try (Statement statement = connection.createStatement()) {
try(ResultSet resultSet = statement.executeQuery("SELECT ID FROM " + waterMarkTableName)){
return resultSet.next() ? resultSet.getInt("ID") : 0;
}
}
}
private PGobject jsonbObject(byte[] value) {
try {
PGobject pGobject = new PGobject();
pGobject.setType("jsonb");
pGobject.setValue(new String(value, Charset.forName("UTF-8")));
return pGobject;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
| package uk.gov;
import org.postgresql.util.PGobject;
import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class DestinationPostgresDB extends PostgresDB {
private final String indexedEntriesTableName;
private final String waterMarkTableName;
public DestinationPostgresDB(String connectionString) throws SQLException {
super(connectionString);
this.indexedEntriesTableName = "ordered_entry_index";
this.waterMarkTableName = "streamed_entries";
}
public void write(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) {
statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY")));
statement.executeUpdate();
}
}
}
public int currentWaterMark() throws SQLException {
try (Statement statement = connection.createStatement()) {
try(ResultSet resultSet = statement.executeQuery("SELECT ID FROM " + waterMarkTableName)){
return resultSet.next() ? resultSet.getInt("ID") : 0;
}
}
}
private PGobject jsonbObject(byte[] value) {
try {
PGobject pGobject = new PGobject();
pGobject.setType("jsonb");
pGobject.setValue(new String(value, Charset.forName("UTF-8")));
return pGobject;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
|
Fix element lookup and add docstrings | /*jslint browser:true */
/*global $, Spinner*/
(function mplStyleGallery() {
'use strict';
/**
* Create simple lightbox for viewing images.
*
* @param {JQuery} Target lightbox div containing single `img` element.
*/
function createLightbox($el) {
var ESCAPE_KEY = 27,
lightboxFacade;
// Press ESCAPE to hide the lightbox window.
$(document).keyup(function (event) {
if (event.keyCode === ESCAPE_KEY) {
$el.hide();
}
});
// The public interface for lighbox.
lightboxFacade = {
// Replace anchor targets with lightbox display.
display : function (event) {
var imageHref = $(this).attr('href'); // clicked link target
// Prevent default (hyperlink) action
event.preventDefault();
// Set lightbox image source to the clicked image.
$el.children('img').attr('src', imageHref);
$el.show();
}
};
return lightboxFacade;
}
$(document).ready(function () {
var lightbox = createLightbox($('#lightbox'));
// Stylesheet input fires spinner since there's a noticeable delay.
$('input').click(function (event) {
$(this).after(new Spinner({}).spin().el);
});
// Click on any lightbox-viewable to open lightbox window.
$('a.lightbox-viewable').click(lightbox.display);
});
}());
| /*jslint browser:true */
/*global $, Spinner*/
(function mplStyleGallery() {
'use strict';
function createLightbox($el) {
var ESCAPE_KEY = 27,
lightboxFacade;
// Press ESCAPE to hide the lightbox window.
$(document).keyup(function (event) {
if (event.keyCode === ESCAPE_KEY) {
$el.hide();
}
});
lightboxFacade = {
display : function (event) {
// Replace anchor targets with lightbox display
var imageHref = $(this).attr('href'); // clicked link target
// Prevent default (hyperlink) action
event.preventDefault();
// Set lightbox image source to the clicked image.
$('#lightbox img').attr('src', imageHref);
$el.show();
}
};
return lightboxFacade;
}
$(document).ready(function () {
var lightbox = createLightbox($('#lightbox'));
$('input').click(function (event) {
$(this).after(new Spinner({}).spin().el);
});
// click on any lightbox-viewable to open lightbox window.
$('a.lightbox-viewable').click(lightbox.display);
});
}());
|
Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <[email protected]> | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
try:
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
except IOError:
sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
| from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
s = Shell(params.hosts,
params.connect_timeout,
setup_readline=params.run_once == "")
if params.run_once != "":
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
intro = "Welcome to zk-shell (%s)" % (__version__)
first = True
while True:
try:
s.run(intro if first else None)
except KeyboardInterrupt:
done = raw_input("\nExit? (y|n) ")
if done == "y":
break
first = False
def get_params(self):
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=int,
default=10,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
return parser.parse_args()
|
Set action to information when routing to workshop details | // Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopController from './workshop.controller';
import WorkshopHeaderController from './workshop-header.controller';
import { workshop } from './workshop.resolve';
import { carBrands } from '../home/home.resolve';
/**
* @ngInject
* @param RouterHelper
* @param WorkshopSharedDataService
*/
export default function routing(RouterHelper, WorkshopSharedDataService) {
const states = [{
state: 'modules.workshop',
config: {
url: '/korjaamot/:id',
title: 'Korjaamo',
params: {
id: null,
selected: null,
},
data: {
access: UserRoles.ROLE_ANON,
},
views: {
'content@': {
template: require('./partials/workshop.html'),
controller: WorkshopController,
controllerAs: 'vm',
resolve: {
_workshop: workshop,
_carBrands: carBrands,
_sharedData() {
// Set action to information when routing to workshop details
WorkshopSharedDataService.action = 'information';
},
},
},
'header@': {
template: require('./partials/header.html'),
controller: WorkshopHeaderController,
controllerAs: 'vm',
resolve: {
_workshop: workshop,
},
},
},
},
}];
RouterHelper.configureStates(states);
}
| // Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopController from './workshop.controller';
import WorkshopHeaderController from './workshop-header.controller';
import { workshop } from './workshop.resolve';
import { carBrands } from '../home/home.resolve';
/**
* @ngInject
* @param RouterHelper
*/
export default function routing(RouterHelper) {
const states = [{
state: 'modules.workshop',
config: {
url: '/korjaamot/:id',
title: 'Korjaamo',
params: {
id: null,
selected: null,
},
data: {
access: UserRoles.ROLE_ANON,
},
views: {
'content@': {
template: require('./partials/workshop.html'),
controller: WorkshopController,
controllerAs: 'vm',
resolve: {
_workshop: workshop,
_carBrands: carBrands,
},
},
'header@': {
template: require('./partials/header.html'),
controller: WorkshopHeaderController,
controllerAs: 'vm',
resolve: {
_workshop: workshop,
},
},
},
},
}];
RouterHelper.configureStates(states);
}
|
CHANGE the refs of dev-kit example to the next branch | module.exports = {
stories: ['./stories/*.*'],
refs: {
ember: {
id: 'ember',
title: 'Ember',
url: 'https://next--storybookjs.netlify.app/ember-cli',
},
cra: 'https://next--storybookjs.netlify.app/cra-ts-kitchen-sink',
},
webpack: async (config) => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
resolve: {
...config.resolve,
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
managerWebpack: async (config) => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /manager\.js$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
}),
};
| module.exports = {
stories: ['./stories/*.*'],
refs: {
ember: {
id: 'ember',
title: 'Ember',
url: 'https://deploy-preview-9210--storybookjs.netlify.app/ember-cli',
},
cra: 'https://deploy-preview-9210--storybookjs.netlify.app/cra-ts-kitchen-sink',
},
webpack: async (config) => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(ts|tsx)$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
resolve: {
...config.resolve,
extensions: [...(config.resolve.extensions || []), '.ts', '.tsx'],
},
}),
managerWebpack: async (config) => ({
...config,
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /manager\.js$/,
loader: require.resolve('babel-loader'),
options: {
presets: [['react-app', { flow: false, typescript: true }]],
},
},
],
},
}),
};
|
Mark the py.test test as not to be run in nose. | """Tests of the test-runner plugins."""
import py
import unittest
from nose.plugins import PluginTester
from coverage.runners.noseplugin import Coverage
class TestCoverage(PluginTester, unittest.TestCase):
"""Test the nose plugin."""
activate = '--with-coverage' # enables the plugin
plugins = [Coverage()]
args = ['--cover-report=report']
@py.test.mark.skipif(True) # "requires nose test runner"
def test_output(self):
assert "Processing Coverage..." in self.output, (
"got: %s" % self.output)
def makeSuite(self):
class TC(unittest.TestCase):
def runTest(self):
raise ValueError("Coverage down")
return unittest.TestSuite([TC()])
pytest_plugins = ['pytester']
def test_functional(testdir):
"""Test the py.test plugin."""
testdir.makepyfile("""
def f():
x = 42
def test_whatever():
pass
""")
result = testdir.runpytest("--cover-report=annotate")
assert result.ret == 0
assert result.stdout.fnmatch_lines([
'*Processing Coverage*'
])
coveragefile = testdir.tmpdir.join(".coverage")
assert coveragefile.check()
# XXX try loading it?
# Keep test_functional from running in nose:
test_functional.__test__ = False
| """Tests of the test-runner plugins."""
import py
import unittest
from nose.plugins import PluginTester
from coverage.runners.noseplugin import Coverage
class TestCoverage(PluginTester, unittest.TestCase):
"""Test the nose plugin."""
activate = '--with-coverage' # enables the plugin
plugins = [Coverage()]
args = ['--cover-report=report']
@py.test.mark.skipif(True) # "requires nose test runner"
def test_output(self):
assert "Processing Coverage..." in self.output, (
"got: %s" % self.output)
def makeSuite(self):
class TC(unittest.TestCase):
def runTest(self):
raise ValueError("Coverage down")
return unittest.TestSuite([TC()])
pytest_plugins = ['pytester']
def test_functional(testdir):
"""Test the py.test plugin."""
testdir.makepyfile("""
def f():
x = 42
def test_whatever():
pass
""")
result = testdir.runpytest("--cover-report=annotate")
assert result.ret == 0
assert result.stdout.fnmatch_lines([
'*Processing Coverage*'
])
coveragefile = testdir.tmpdir.join(".coverage")
assert coveragefile.check()
# XXX try loading it?
|
Use dictionary update instead of addition | import re
from regparser.layer.layer import Layer
import settings
class Meta(Layer):
shorthand = 'meta'
def __init__(self, tree, cfr_title, version, **context):
super(Meta, self).__init__(tree, **context)
self.cfr_title = cfr_title
self.version = version
def process(self, node):
"""If this is the root element, add some 'meta' information about
this regulation, including its cfr title, effective date, and any
configured info"""
if len(node.label) != 1:
return
layer = {
'cfr_title_number': self.cfr_title,
'cfr_title_text': settings.CFR_TITLES[self.cfr_title]
}
if node.title:
# up till the paren
match = re.search('part \d+[^\w]*([^\(]*)', node.title, re.I)
if match:
layer['statutory_name'] = match.group(1).strip()
match = re.search('\(regulation (\w+)\)', node.title, re.I)
if match:
layer['reg_letter'] = match.group(1)
effective_date = self.effective_date()
if effective_date:
layer['effective_date'] = effective_date
result = {}
result.update(layer)
result.update(settings.META)
return [result]
def effective_date(self):
if self.version and self.version.effective:
return self.version.effective.isoformat()
| import re
from regparser.layer.layer import Layer
import settings
class Meta(Layer):
shorthand = 'meta'
def __init__(self, tree, cfr_title, version, **context):
super(Meta, self).__init__(tree, **context)
self.cfr_title = cfr_title
self.version = version
def process(self, node):
"""If this is the root element, add some 'meta' information about
this regulation, including its cfr title, effective date, and any
configured info"""
if len(node.label) != 1:
return
layer = {
'cfr_title_number': self.cfr_title,
'cfr_title_text': settings.CFR_TITLES[self.cfr_title]
}
if node.title:
# up till the paren
match = re.search('part \d+[^\w]*([^\(]*)', node.title, re.I)
if match:
layer['statutory_name'] = match.group(1).strip()
match = re.search('\(regulation (\w+)\)', node.title, re.I)
if match:
layer['reg_letter'] = match.group(1)
effective_date = self.effective_date()
if effective_date:
layer['effective_date'] = effective_date
return [dict(layer.items() + settings.META.items())]
def effective_date(self):
if self.version and self.version.effective:
return self.version.effective.isoformat()
|
Append nominator user id when nominating a household | <?php
namespace App\Http\Controllers\Admin;
use App\Base\Controllers\AdminController;
use App\Http\Controllers\Api\DataTables\HouseholdDataTable;
use App\Http\Requests\Admin\HouseholdRequest;
use App\Household;
use Auth;
class HouseholdController extends AdminController
{
/**
* Display a listing of the users.
*
* @param UserDataTable $dataTable
*/
public function index(HouseholdDataTable $dataTable)
{
return $dataTable->render($this->viewPath());
}
/**
* Store a newly created user in storage
*/
public function store(HouseholdRequest $request)
{
$request['nominator_user_id'] = Auth::user()->id;
return $this->createFlashRedirect(Household::class, $request);
}
/**
* Display the specified user.
*/
public function show(Household $household)
{
return $this->viewPath("show", $household);
}
/**
* Show the form for editing the specified user.
*/
public function edit(Household $household)
{
$household->child;
return $this->getForm($household);
}
/**
* Update the specified user in storage.
*/
public function update(Household $household, HouseholdRequest $request)
{
return $this->saveFlashRedirect($household, $request);
}
/**
* Remove the specified user from storage.
*/
public function destroy(Household $user)
{
# TODO: Not sure we want to do this... :S
}
} | <?php
namespace App\Http\Controllers\Admin;
use App\Base\Controllers\AdminController;
use App\Http\Controllers\Api\DataTables\HouseholdDataTable;
use App\Http\Requests\Admin\HouseholdRequest;
use App\Household;
use Auth;
class HouseholdController extends AdminController
{
/**
* Display a listing of the users.
*
* @param UserDataTable $dataTable
*/
public function index(HouseholdDataTable $dataTable)
{
return $dataTable->render($this->viewPath());
}
/**
* Store a newly created user in storage
*/
public function store(HouseholdRequest $request)
{
return $this->createFlashRedirect(Household::class, $request, $this->imageColumn);
}
/**
* Display the specified user.
*/
public function show(Household $household)
{
return $this->viewPath("show", $household);
}
/**
* Show the form for editing the specified user.
*/
public function edit(Household $household)
{
$household->child;
return $this->getForm($household);
}
/**
* Update the specified user in storage.
*/
public function update(Household $household, HouseholdRequest $request)
{
return $this->saveFlashRedirect($household, $request);
}
/**
* Remove the specified user from storage.
*/
public function destroy(Household $user)
{
# TODO: Not sure we want to do this... :S
}
} |
chore: Refactor Bukkit to MCPR conversion so that it is readable | const slugify = require('./slug.js')
const bukkitApi = require('./bukkitApi')
const convertModel = async bukkitPlugins => {
try {
const processPlugins = bukkitPlugins.map(async bukkitPlugin => {
const data = await Promise.all([
bukkitApi.getPlugin(bukkitPlugin.slug),
bukkitApi.getPluginFiles(bukkitPlugin.slug)
])
const plugin = data[0]
const files = data[1]
const latestFiles = files[0]
const keywords = []
for (const cat of bukkitPlugin.categories) {
keywords.push(slugify(cat.name))
}
const mcprPlugin = {
_id: bukkitPlugin.slug,
short_description: plugin.shortdescription,
title: plugin.title,
author: plugin.authors[0].name,
latest_version_date: plugin.lastrelease,
latest_version: latestFiles.name,
latest_version_file: latestFiles,
downloads: latestFiles.downloads,
readme: plugin.description,
keywords,
externalUrl: plugin.url,
external: true,
namespace: '@bukkitdev'
}
return mcprPlugin
})
const plugins = await Promise.all(processPlugins)
return plugins
} catch (err) {
throw err
}
}
module.exports = convertModel
| const slugify = require('./slug.js')
const bukkitApi = require('./bukkitApi')
function convertModel (bukkit) {
return new Promise(function (resolve, reject) {
let plugins = []
let itemsProcessed = 0
for (let i = 0; i < bukkit.length; i++) {
;(() => {
let bukkitPlugin = bukkit[i]
return bukkitApi
.getPlugin(bukkitPlugin.slug)
.then(res => {
return bukkitApi
.getPluginFiles(bukkitPlugin.slug)
.then(files => {
let latestFiles = files[0]
let keywords = []
for (let i = 0; i < bukkitPlugin.categories.length; i++) {
;(() => {
let slug = slugify(bukkitPlugin.categories[i].name)
keywords.push(slug)
})()
}
let plugin = {
_id: bukkitPlugin.slug,
short_description: res.shortdescription,
title: res.title,
author: res.authors[0].name,
latest_version_date: res.lastrelease,
latest_version: latestFiles.name,
latest_version_file: latestFiles,
downloads: latestFiles.downloads,
readme: res.description,
keywords: keywords,
externalUrl: res.url,
external: true,
namespace: '@bukkitdev'
}
plugins.push(plugin)
itemsProcessed++
if (itemsProcessed === bukkit.length) {
return resolve(plugins)
}
})
.catch(err => {
reject(err)
})
})
.catch(err => {
reject(err)
})
})()
}
})
}
module.exports = convertModel
|
Remove a debug statement (1/0.) | from __future__ import print_function
import sys, os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
INSTALL_REQUIRES = [l.strip() for l in f.readlines() if l]
try:
import numpy
except ImportError:
print('numpy is required during installation')
sys.exit(1)
try:
import scipy
except ImportError:
print('scipy is required during installation')
sys.exit(1)
# Get version and release info, which is all stored in sklforestci/version.py
ver_file = os.path.join('sklforestci', 'version.py')
with open(ver_file) as f:
exec(f.read())
opts = dict(name=NAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
url=URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
classifiers=CLASSIFIERS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
platforms=PLATFORMS,
version=VERSION,
packages=find_packages(),
install_requires=INSTALL_REQUIRES)
if __name__ == '__main__':
setup(**opts)
| from __future__ import print_function
import sys, os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
INSTALL_REQUIRES = [l.strip() for l in f.readlines() if l]
try:
import numpy
except ImportError:
print('numpy is required during installation')
sys.exit(1)
try:
import scipy
except ImportError:
print('scipy is required during installation')
sys.exit(1)
# Get version and release info, which is all stored in sklforestci/version.py
ver_file = os.path.join('sklforestci', 'version.py')
with open(ver_file) as f:
exec(f.read())
1/0.
opts = dict(name=NAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
url=URL,
download_url=DOWNLOAD_URL,
license=LICENSE,
classifiers=CLASSIFIERS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
platforms=PLATFORMS,
version=VERSION,
packages=find_packages(),
install_requires=INSTALL_REQUIRES)
if __name__ == '__main__':
setup(**opts)
|
Print stack traces on failure | var RSVP = require('rsvp'),
utils = require('./lib')
fs = require('fs'),
GoogleSpreadsheet = require("google-spreadsheet"),
config = require('./config.js'),
doc = new GoogleSpreadsheet(config['google_spreadsheet_key']);
RSVP.hash({
currentItems: utils.getWishlistFromAmazon(config['amazon_wishlist_id']),
previousItems: utils.getPreviousWishlist(),
spreadsheetAuthenticated: utils.authenticateServiceAccount(doc, {
private_key: config['google_private_key'],
client_email: config['google_client_email']
})
})
.then(function(wishlist){
var itemsAdded = utils.getDifference(wishlist.previousItems, wishlist.currentItems),
rowValues = itemsAdded.map(function(item){
return {
Image: '=IMAGE("' + item.picture + '")',
Title: '=HYPERLINK("' + item.link + '", "' + item.name + '")'
};
}),
rowAddPromises = rowValues.map(function(rowObj){
return utils.addRowsToDriveSpreadsheet(doc, 1, rowObj);
});
rowAddPromises.push(utils.savePreviousWishlist(wishlist.currentItems));
return RSVP.all(rowAddPromises);
}, function(err){
console.log(err.stack);
})
.then(function(){
console.log('Success adding rows to spreadsheet!');
}, function(err){
console.log(err.stack);
}); | var RSVP = require('rsvp'),
utils = require('./lib')
fs = require('fs'),
GoogleSpreadsheet = require("google-spreadsheet"),
config = require('./config.js'),
doc = new GoogleSpreadsheet(config['google_spreadsheet_key']);
RSVP.hash({
currentItems: utils.getWishlistFromAmazon(config['amazon_wishlist_id']),
previousItems: utils.getPreviousWishlist(),
spreadsheetAuthenticated: utils.authenticateServiceAccount(doc, {
private_key: config['google_private_key'],
client_email: config['google_client_email']
})
})
.then(function(wishlist){
var itemsAdded = utils.getDifference(wishlist.previousItems, wishlist.currentItems),
rowValues = itemsAdded.map(function(item){
return {
Image: '=IMAGE("' + item.picture + '")',
Title: '=HYPERLINK("' + item.link + '", "' + item.name + '")'
};
}),
rowAddPromises = rowValues.map(function(rowObj){
return utils.addRowsToDriveSpreadsheet(doc, 1, rowObj);
});
rowAddPromises.push(utils.savePreviousWishlist(wishlist.currentItems));
return RSVP.all(rowAddPromises);
}, function(){
console.log('Error finding wishlists or authenticating to drive!')
})
.then(function(){
console.log('Success adding rows to spreadsheet!');
}, function(){
console.log('Error adding rows to spreadsheet!');
}); |
FIX withholdings computation when payment come from invoices | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, fields
class AccountPaymentGroup(models.Model):
_inherit = "account.payment.group"
withholdings_amount = fields.Monetary(
compute='_compute_withholdings_amount'
)
@api.multi
@api.depends(
'payment_ids.tax_withholding_id',
'payment_ids.amount',
)
def _compute_withholdings_amount(self):
for rec in self:
rec.withholdings_amount = sum(
rec.payment_ids.filtered(
lambda x: x.tax_withholding_id).mapped('amount'))
@api.multi
def compute_withholdings(self):
for rec in self:
if rec.partner_type != 'supplier':
continue
# limpiamos el type por si se paga desde factura ya que el en ese
# caso viene in_invoice o out_invoice y en search de tax filtrar
# por impuestos de venta y compra (y no los nuestros de pagos
# y cobros)
self.env['account.tax'].with_context(type=None).search([
('type_tax_use', '=', rec.partner_type),
('company_id', '=', rec.company_id.id),
]).create_payment_withholdings(rec)
@api.multi
def confirm(self):
res = super(AccountPaymentGroup, self).confirm()
for rec in self:
if rec.company_id.automatic_withholdings:
rec.compute_withholdings()
return res
| # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, api, fields
class AccountPaymentGroup(models.Model):
_inherit = "account.payment.group"
withholdings_amount = fields.Monetary(
compute='_compute_withholdings_amount'
)
@api.multi
@api.depends(
'payment_ids.tax_withholding_id',
'payment_ids.amount',
)
def _compute_withholdings_amount(self):
for rec in self:
rec.withholdings_amount = sum(
rec.payment_ids.filtered(
lambda x: x.tax_withholding_id).mapped('amount'))
@api.multi
def compute_withholdings(self):
for rec in self:
if rec.partner_type != 'supplier':
continue
self.env['account.tax'].search([
('type_tax_use', '=', rec.partner_type),
('company_id', '=', rec.company_id.id),
]).create_payment_withholdings(rec)
@api.multi
def confirm(self):
res = super(AccountPaymentGroup, self).confirm()
for rec in self:
if rec.company_id.automatic_withholdings:
rec.compute_withholdings()
return res
|
Use Request instead of input comment out examples | <?php
namespace Kordy\Ticketit\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
class UserSearchController extends Controller {
public function userSearch(Request $request) {
$keyword = $request->get('q');
// If you wanted to search multiple Terms you could do something like the following
//$searchRaw = Input::get('q');
//$keywords = explode(" ", $searchRaw);
$user_list = User::Where('users.name', 'LIKE', '%' . $keyword . '%');
// This is where you put additional fields to be searched through
$user_list->orWhere(function ($query) use ($keyword) {
$query->orWhere('users.email', 'LIKE', '%' . $keyword . '%');
// $query->orWhere('users.last_name', 'LIKE', '%' . $keyword . '%');
// $query->orWhere('users.first_name', 'LIKE', '%' . $keyword . '%');
// $query->orWhere('users.business_name', 'LIKE', '%' . $keyword . '%');
// $query->orWhere('users.phone_1', 'LIKE', '%' . $keyword . '%');
// $query->orWhere('users.phone_2', 'LIKE', '%' . $keyword . '%');
});
$data = $user_list->get();
echo json_encode($data);
}
}
| <?php
namespace Kordy\Ticketit\Controllers;
use App\Http\Controllers\Controller;
use Input;
use App\User;
class UserSearchController extends Controller {
public function userSearch() {
$keyword = Input::get('q');
// If you wanted to search multiple Terms you could do something like the following
//$searchRaw = Input::get('q');
//$keywords = explode(" ", $searchRaw);
$user_list = User::Where('users.name', 'LIKE', '%' . $keyword . '%');
// This is where you put additional fields to be searched through
$user_list->orWhere(function ($query) use ($keyword) {
$query->orWhere('users.email', 'LIKE', '%' . $keyword . '%');
$query->orWhere('users.last_name', 'LIKE', '%' . $keyword . '%');
$query->orWhere('users.first_name', 'LIKE', '%' . $keyword . '%');
$query->orWhere('users.business_name', 'LIKE', '%' . $keyword . '%');
$query->orWhere('users.phone_1', 'LIKE', '%' . $keyword . '%');
$query->orWhere('users.phone_2', 'LIKE', '%' . $keyword . '%');
});
$data = $user_list->get();
echo json_encode($data);
}
}
|
Fix bug with fan turning itself off
This would happen when the service was restarted. In the stopping code,
I added a call to clean up. | import logging
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.UART as UART
import serial
DYLOS_POWER_PIN = "P8_10"
LOGGER = logging.getLogger(__name__)
class Dylos:
def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5):
self.running = True
# Setup UART
UART.setup("UART1")
# Make sure Dylos sensor is turned on
GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT)
GPIO.output(DYLOS_POWER_PIN, GPIO.LOW)
self.ser = serial.Serial(port=port,
baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=timeout)
if not self.ser.isOpen():
self.ser.open()
def read(self):
# Keep reading from serial port until we get some data
while True:
line = self.ser.readline()
if not self.running:
raise Exception("Stop reading from serial port")
if line != b'':
break
LOGGER.debug("Read from serial port: %s", line)
small, large = [int(x.strip()) for x in line.split(b',')]
LOGGER.debug("Small: %s, Large: %s", small, large)
return {"small": small, "large": large}
def stop(self):
self.running = False
GPIO.cleanup(DYLOS_POWER_PIN)
self.ser.close()
| import logging
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.UART as UART
import serial
DYLOS_POWER_PIN = "P8_10"
LOGGER = logging.getLogger(__name__)
class Dylos:
def __init__(self, port='/dev/ttyO1', baudrate=9600, timeout=5):
self.running = True
# Setup UART
UART.setup("UART1")
# Make sure Dylos sensor is turned on
GPIO.setup(DYLOS_POWER_PIN, GPIO.OUT)
GPIO.output(DYLOS_POWER_PIN, GPIO.LOW)
self.ser = serial.Serial(port=port,
baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=timeout)
if not self.ser.isOpen():
self.ser.open()
def read(self):
# Keep reading from serial port until we get some data
while True:
line = self.ser.readline()
if not self.running:
raise Exception("Stop reading from serial port")
if line != b'':
break
LOGGER.debug("Read from serial port: %s", line)
small, large = [int(x.strip()) for x in line.split(b',')]
LOGGER.debug("Small: %s, Large: %s", small, large)
return {"small": small, "large": large}
def stop(self):
self.running = False
self.ser.close()
|
Fix FF issues with doghouse.
Dog House loading for latest versions of FF, Chrome and even IE (likely works on safari too). Basically make it so that the popstate event is ignored on the first load of the page (which is what FF does)...that made all the other browsers fall in line. | require(
[
"domReady",
"rexster/history",
"rexster/template/template",
"rexster/ui/main-menu",
"order!has",
"order!has-detect-features"
],
function (domReady, history, template, mainMenu) {
domReady(function () {
// only make this feature available to browsers that support it
if (has("native-history-state")) {
window.onpopstate = function(event) {
var popped = ('state' in window.history), initialURL = location.href
$(window).bind('popstate', function(event) {
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL
popped = true
if ( initialPop ) return
restoreApplication();
});
};
}
function restoreApplication() {
// compile the templates
template.initTemplates();
// build the main menu. this action will initialize the
// first enabled panel
mainMenu.initMainMenu();
}
// determine if the state is already established
var state = history.getApplicationState();
if (!state.hasOwnProperty("menu")) {
// since there is no menu selected initialized the graph page first.
history.historyPush("/doghouse/main/graph");
}
restoreApplication();
});
}); | require(
[
"domReady",
"rexster/history",
"rexster/template/template",
"rexster/ui/main-menu",
"order!has",
"order!has-detect-features"
],
function (domReady, history, template, mainMenu) {
domReady(function () {
// only make this feature available to browsers that support it
if (has("native-history-state")) {
window.onpopstate = function(event) {
restoreApplication();
};
}
function restoreApplication() {
// compile the templates
template.initTemplates();
// build the main menu. this action will initialize the
// first enabled panel
mainMenu.initMainMenu();
}
// determine if the state is already established
var state = history.getApplicationState();
if (!state.hasOwnProperty("menu")) {
// since there is no menu selected initialized the graph page first.
history.historyPush("/doghouse/main/graph");
if (!has("native-history-state")) {
restoreApplication()
}
} else {
if (!has("native-history-state")) {
restoreApplication()
}
}
});
}); |
Drop unnecessary reference to popped elements to allow finalization through GC (XSTR-264). | package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
return value;
}
public void popSilently() {
stack[--pointer] = null;
}
public Object pop() {
final Object result = stack[--pointer];
stack[pointer] = null;
return result;
}
public Object peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public boolean hasStuff() {
return pointer > 0;
}
public Object get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Object[] newStack = new Object[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < pointer; i++) {
if (i > 0) {
result.append(", ");
}
result.append(stack[i]);
}
result.append(']');
return result.toString();
}
}
| package com.thoughtworks.xstream.core.util;
public final class FastStack {
private Object[] stack;
private int pointer;
public FastStack(int initialCapacity) {
stack = new Object[initialCapacity];
}
public Object push(Object value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
return value;
}
public void popSilently() {
pointer--;
}
public Object pop() {
return stack[--pointer];
}
public Object peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public boolean hasStuff() {
return pointer > 0;
}
public Object get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Object[] newStack = new Object[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < pointer; i++) {
if (i > 0) {
result.append(", ");
}
result.append(stack[i]);
}
result.append(']');
return result.toString();
}
}
|
Add better commenting to floorMult filter. | /* Filter for finding the next-smallest multiple of input number */
angular.module('sknFloorMultFilter', []).filter('floorMult', function() {
return function(input, multSize) {
/* if input is already a multiple of multSize, return */
if(input % multSize === 0) {
return input;
}
else {
/* Ensure input is a whole number */
var inputFloor = Math.floor(input);
/* if inputFloor is a multiple of multSize, return inputFloor */
if(inputFloor % multSize === 0) {
return inputFloor;
}
else {
/* subtract 1 from inputFloor until inputFloor
is a mulple of multSize. Return modified inputFloor.*/
for(var i = 1; i < multSize; ++i) {
if((inputFloor - i) % multSize === 0) {
return inputFloor - i;
}
}
}
return input;
}
}
});
/*Filter for month day, year from WP REST API date*/
angular.module('sknDateFilter', []).filter('date', function() {
return function(input) {
var months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
var year = input.substr(0, 4);
var month = months[parseInt(input.substr(5, 2)) - 1];
var day = input.substr(8, 2);
var dateString = day + " " + month + " " + year;
return dateString;
}
});
| /* Filter for finding the next-smallest multiple of input number */
angular.module('sknFloorMultFilter', []).filter('floorMult', function() {
return function(input, multSize) {
if(input % multSize === 0) {
return input;
}
else {
var inputFloor = Math.floor(input);
if(inputFloor % multSize === 0) {
return inputFloor;
}
else {
for(var i = 1; i < multSize; ++i) {
if((inputFloor - i) % multSize === 0) {
return inputFloor - i;
}
}
}
return input;
}
}
});
/*Filter for month day, year from WP REST API date*/
angular.module('sknDateFilter', []).filter('date', function() {
return function(input) {
var months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
var year = input.substr(0, 4);
var month = months[parseInt(input.substr(5, 2)) - 1];
var day = input.substr(8, 2);
var dateString = day + " " + month + " " + year;
return dateString;
}
});
|
Fix the `firstofas` template tag returning '' too early. | # -*- coding: utf-8 -*-
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, args, variable_name=None):
self.vars = args
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
print('FOUND %s: %s' % (self.variable_name, value))
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
@register.tag
def firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
| # -*- coding: utf-8 -*-
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, vars, variable_name=None):
self.vars = vars
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
@register.tag(name="firstofas")
def do_firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
|
Remove unused moment locales from webpack bundle | var path = require('path');
var fs = require('fs');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
module.exports = {
entry: path.join(__dirname, 'src/frontend/app'),
cache: true,
output: {
path: path.join(__dirname, '/public/'),
filename: 'bundle.[hash].js'
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.jsx?$/, loader: "babel-loader", exclude: /node_modules/ },
{ test: /\.less$/, loader: "style-loader!css-loader!less-loader" },
{ test: /\.(ttf|eot|otf|svg|woff|woff2)(\?.+)?$/, loader: "url-loader?limit=10000" },
{ test: /\.scss$/, loader: "style!css!sass?includePaths[]=" + (path.resolve(__dirname, "./node_modules")) }
]
},
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /nb$/),
new ExtractTextPlugin('bundle.[hash].css'),
function() {
this.plugin('done', function(stats) {
fs.writeFile(path.resolve(__dirname, './public/hash'), stats.hash);
});
}
],
devtool: 'source-map'
};
| var path = require('path');
var fs = require('fs');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: path.join(__dirname, 'src/frontend/app'),
cache: true,
output: {
path: path.join(__dirname, '/public/'),
filename: 'bundle.[hash].js'
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
{ test: /\.jsx?$/, loader: "babel-loader", exclude: /node_modules/ },
{ test: /\.less$/, loader: "style-loader!css-loader!less-loader" },
{ test: /\.(ttf|eot|otf|svg|woff|woff2)(\?.+)?$/, loader: "url-loader?limit=10000" },
{ test: /\.scss$/, loader: "style!css!sass?includePaths[]=" + (path.resolve(__dirname, "./node_modules")) }
]
},
plugins: [
new ExtractTextPlugin('bundle.[hash].css'),
function() {
this.plugin('done', function(stats) {
fs.writeFile(path.resolve(__dirname, './public/hash'), stats.hash);
});
}
],
devtool: 'source-map'
};
|
Add main app module first to js files that will be concatenated | (function() {
'use strict';
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('bundle', bundle);
gulp.task('start-webserver', startWebServer);
gulp.task('watch', watch);
gulp.task('default', ['bundle', 'start-webserver', 'watch']);
/////////////////////////
var jsFiles = [
'app/**/*.js',
'!app/bower_components/**/*',
'!app/content/bundle.js'
];
function bundle() {
return gulp.src(jsFiles)
.pipe(plugins.plumber()) // restart gulp on error
.pipe(plugins.sourcemaps.init()) // let sourcemap watch this pipeline
.pipe(plugins.babel()) // transpile into ES5
.pipe(plugins.order([
'app/app.module.js',
'app/**/*.module.js',
'app/**/*.js',
], { base: './' })) // order the files before concatenation
.pipe(plugins.print()) // print files to the console
.pipe(plugins.concat('bundle.js')) // concatenate all JS files
.pipe(plugins.sourcemaps.write('.')) // emits sourcemap bundle.js.map for debug
.pipe(gulp.dest('app/content')) // save bundle.js and bundle.js.map
}
function startWebServer() {
plugins.connect.server({ root: 'app' });
}
function watch() {
gulp.watch('app/**/*', ['bundle']);
}
})();
| (function() {
'use strict';
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
gulp.task('bundle', bundle);
gulp.task('start-webserver', startWebServer);
gulp.task('watch', watch);
gulp.task('default', ['bundle', 'start-webserver', 'watch']);
/////////////////////////
var jsFiles = [
'app/**/*.js',
'!app/bower_components/**/*',
'!app/content/bundle.js'
];
function bundle() {
return gulp.src(jsFiles)
.pipe(plugins.plumber()) // restart gulp on error
.pipe(plugins.sourcemaps.init()) // let sourcemap watch this pipeline
.pipe(plugins.babel()) // transpile into ES5
.pipe(plugins.order([
'app/**/*.module.js',
'app/**/*.js',
], { base: './' })) // order the files before concatenation
.pipe(plugins.print()) // print files to the console
.pipe(plugins.concat('bundle.js')) // concatenate all JS files
.pipe(plugins.sourcemaps.write('.')) // emits sourcemap bundle.js.map for debug
.pipe(gulp.dest('app/content')) // save bundle.js and bundle.js.map
}
function startWebServer() {
plugins.connect.server({ root: 'app' });
}
function watch() {
gulp.watch('app/**/*', ['bundle']);
}
})();
|
Fix lightbox on two col page. | <?php
/*
Template Name: 2 Spalten und Bilder
*/
?>
<div class="row">
<div class="medium-8 small-12 column">
<div class="white-bg vines">
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/page', 'header'); ?>
<ul class="large-block-grid-2 medium-block-grid-2 small-block-grid-1">
<li>
<?php get_template_part('templates/content', 'page'); ?>
<?php endwhile ?>
</li>
<li>
<?php the_field('2-col-pics-text_col2'); ?>
</li>
</ul>
</div>
</div>
<div class="medium-4 small-12 column image-list">
<?php if( have_rows('2-col-pics_pictures') ) { ?>
<ul>
<?php while ( have_rows('2-col-pics_pictures') ) { the_row(); ?>
<li>
<?php $sub = get_sub_field('2-col-pics_picture'); ?>
<img src="<?php echo $sub['url']; ?>" rel="lightbox[pp_gal]">
</li>
<?php } ?>
</ul>
<?php } ?>
</div>
</div> | <?php
/*
Template Name: 2 Spalten und Bilder
*/
?>
<div class="row">
<div class="medium-8 small-12 column">
<div class="white-bg vines">
<?php while (have_posts()) : the_post(); ?>
<?php get_template_part('templates/page', 'header'); ?>
<ul class="large-block-grid-2 medium-block-grid-2 small-block-grid-1">
<li>
<?php get_template_part('templates/content', 'page'); ?>
<?php endwhile ?>
</li>
<li>
<?php the_field('2-col-pics-text_col2'); ?>
</li>
</ul>
</div>
</div>
<div class="medium-4 small-12 column image-list">
<?php if( have_rows('2-col-pics_pictures') ) { ?>
<ul>
<?php while ( have_rows('2-col-pics_pictures') ) { the_row(); ?>
<li>
<?php $sub = get_sub_field('2-col-pics_picture'); ?>
<img src="<?php echo $sub['url']; ?>">
</li>
<?php } ?>
</ul>
<?php } ?>
</div>
</div> |
Use constants with "getRepository()" methods. | <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\Slug;
use Darvin\ContentBundle\Entity\SlugMapItem;
use Darvin\Utils\Sluggable\SlugHandlerInterface;
use Doctrine\ORM\EntityManager;
/**
* Unique slug handler
*/
class UniqueSlugHandler implements SlugHandlerInterface
{
/**
* {@inheritdoc}
*/
public function handle(&$slug, &$suffix, EntityManager $em)
{
$similarSlugs = $this->getSlugMapItemRepository($em)->getSimilarSlugs($slug);
if (empty($similarSlugs) || !in_array($slug, $similarSlugs)) {
return;
}
$originalSlug = $slug;
$index = 0;
do {
$index++;
$slug = $originalSlug.'-'.$index;
} while (in_array($slug, $similarSlugs));
$suffix.='-'.$index;
}
/**
* @param \Doctrine\ORM\EntityManager $em Entity manager
*
* @return \Darvin\ContentBundle\Repository\SlugMapItemRepository
*/
private function getSlugMapItemRepository(EntityManager $em)
{
return $em->getRepository(SlugMapItem::SLUG_MAP_ITEM_CLASS);
}
}
| <?php
/**
* @author Igor Nikolaev <[email protected]>
* @copyright Copyright (c) 2015, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\ContentBundle\Slug;
use Darvin\Utils\Sluggable\SlugHandlerInterface;
use Doctrine\ORM\EntityManager;
/**
* Unique slug handler
*/
class UniqueSlugHandler implements SlugHandlerInterface
{
/**
* {@inheritdoc}
*/
public function handle(&$slug, &$suffix, EntityManager $em)
{
$similarSlugs = $this->getSlugMapItemRepository($em)->getSimilarSlugs($slug);
if (empty($similarSlugs) || !in_array($slug, $similarSlugs)) {
return;
}
$originalSlug = $slug;
$index = 0;
do {
$index++;
$slug = $originalSlug.'-'.$index;
} while (in_array($slug, $similarSlugs));
$suffix.='-'.$index;
}
/**
* @param \Doctrine\ORM\EntityManager $em Entity manager
*
* @return \Darvin\ContentBundle\Repository\SlugMapItemRepository
*/
private function getSlugMapItemRepository(EntityManager $em)
{
return $em->getRepository('DarvinContentBundle:SlugMapItem');
}
}
|
Revert "Revert "update to remove client type hinting""
This reverts commit 4442314687fb05190a7dd6dfeb58ae4a6c4e87e9. | <?php
namespace hceudevs\RateLimitBundle\Service\Storage;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;
class Redis implements StorageInterface
{
/**
* @var \Predis\Client
*/
protected $client;
public function __construct($client)
{
$this->client = $client;
}
public function getRateInfo($key)
{
$info = $this->client->hgetall($key);
$rateLimitInfo = new RateLimitInfo();
$rateLimitInfo->setLimit($info['limit']);
$rateLimitInfo->setCalls($info['calls']);
$rateLimitInfo->setResetTimestamp($info['reset']);
return $rateLimitInfo;
}
public function limitRate($key)
{
if (! $this->client->hexists($key, 'limit')) {
return false;
}
$this->client->hincrby($key, 'calls', 1);
return $this->getRateInfo($key);
}
public function createRate($key, $limit, $period)
{
$this->client->hset($key, 'limit', $limit);
$this->client->hset($key, 'calls', 1);
$this->client->hset($key, 'reset', time() + $period);
$this->client->expire($key, $period);
return $this->getRateInfo($key);
}
public function resetRate($key)
{
$this->client->hdel($key);
return true;
}
}
| <?php
namespace hceudevs\RateLimitBundle\Service\Storage;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;
class Redis implements StorageInterface
{
/**
* @var \Predis\Client
*/
protected $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function getRateInfo($key)
{
$info = $this->client->hgetall($key);
$rateLimitInfo = new RateLimitInfo();
$rateLimitInfo->setLimit($info['limit']);
$rateLimitInfo->setCalls($info['calls']);
$rateLimitInfo->setResetTimestamp($info['reset']);
return $rateLimitInfo;
}
public function limitRate($key)
{
if (! $this->client->hexists($key, 'limit')) {
return false;
}
$this->client->hincrby($key, 'calls', 1);
return $this->getRateInfo($key);
}
public function createRate($key, $limit, $period)
{
$this->client->hset($key, 'limit', $limit);
$this->client->hset($key, 'calls', 1);
$this->client->hset($key, 'reset', time() + $period);
$this->client->expire($key, $period);
return $this->getRateInfo($key);
}
public function resetRate($key)
{
$this->client->hdel($key);
return true;
}
}
|
Make addon lookup external data same as YUIDoc tool
YUIDoc tool and the addon will both find "external.data" at the top-level
of yuidoc.json, but unfortunately the YUIDoc documentation says it's
support to go in "options". The tool will find it here, but this addon
won't. This fixes that and makes the lookup order the same. | 'use strict';
var getVersion = require('git-repo-version');
var fs = require('fs');
var Y = require('yuidocjs');
module.exports = {
generate: function generateYuidocOptions(){
var config;
var exclusions = [
'.DS_Store',
'.git',
'node_modules',
'vendor',
'bower_components',
'tmp',
'tests'
];
try {
config = JSON.parse(fs.readFileSync('yuidoc.json'));
} catch(e){
console.log("No yuidoc.json file in root folder. Run `ember g ember-cli-yuidoc` to generate one.");
process.exit(1);
}
if (exclusions.indexOf(config.options.exclude) === -1){
exclusions.push(config.options.exclude)
}
var outDir = config.options.outdir || 'docs';
var options = Y.Project.init({
outdir: outDir,
destDir: outDir,
paths: config.options.paths || '.',
version: getVersion(),
external: config.external || config.options.external || {},
yuidoc: {
linkNatives: true,
quiet: true,
parseOnly: false,
lint: false,
exclude: exclusions.join(',')
}
});
return options;
}
}
| 'use strict';
var getVersion = require('git-repo-version');
var fs = require('fs');
var Y = require('yuidocjs');
module.exports = {
generate: function generateYuidocOptions(){
var config;
var exclusions = [
'.DS_Store',
'.git',
'node_modules',
'vendor',
'bower_components',
'tmp',
'tests'
];
try {
config = JSON.parse(fs.readFileSync('yuidoc.json'));
} catch(e){
console.log("No yuidoc.json file in root folder. Run `ember g ember-cli-yuidoc` to generate one.");
process.exit(1);
}
if (exclusions.indexOf(config.options.exclude) === -1){
exclusions.push(config.options.exclude)
}
var outDir = config.options.outdir || 'docs';
var options = Y.Project.init({
outdir: outDir,
destDir: outDir,
paths: config.options.paths || '.',
version: getVersion(),
external: config.external || {},
yuidoc: {
linkNatives: true,
quiet: true,
parseOnly: false,
lint: false,
exclude: exclusions.join(',')
}
});
return options;
}
}
|
Add basic test for read_file method | import unittest
import tempfile
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
'\n' + \
'[section2]\n' + \
'bar = "baz"\n'
cf = JSONConfigParser()
cf.read_string(string)
self.assertEqual(cf.get('section', 'foo'), 'bar')
def test_read_file(self):
string = '[section]\n' + \
'foo = "bar"'
fp = tempfile.NamedTemporaryFile('w+')
fp.write(string)
fp.seek(0)
cf = JSONConfigParser()
cf.read_file(fp)
self.assertEqual(cf.get('section', 'foo'), 'bar')
def test_get(self):
cf = JSONConfigParser()
cf.add_section('section')
cf.set('section', 'section', 'set-in-section')
self.assertEqual(cf.get('section', 'section'), 'set-in-section')
cf.set(cf.default_section, 'defaults', 'set-in-defaults')
self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults')
self.assertEqual(cf.get('section', 'vars',
vars={'vars': 'set-in-vars'}),
'set-in-vars')
self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback')
suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
| import unittest
from jsonconfigparser import JSONConfigParser
class JSONConfigTestCase(unittest.TestCase):
def test_init(self):
JSONConfigParser()
def test_read_string(self):
string = '[section]\n' + \
'# comment comment\n' + \
'foo = "bar"\n' + \
'\n' + \
'[section2]\n' + \
'bar = "baz"\n'
cf = JSONConfigParser()
cf.read_string(string)
self.assertEqual(cf.get('section', 'foo'), 'bar')
def test_get(self):
cf = JSONConfigParser()
cf.add_section('section')
cf.set('section', 'section', 'set-in-section')
self.assertEqual(cf.get('section', 'section'), 'set-in-section')
cf.set(cf.default_section, 'defaults', 'set-in-defaults')
self.assertEqual(cf.get('section', 'defaults'), 'set-in-defaults')
self.assertEqual(cf.get('section', 'vars',
vars={'vars': 'set-in-vars'}),
'set-in-vars')
self.assertEqual(cf.get('section', 'unset', 'fallback'), 'fallback')
suite = unittest.TestLoader().loadTestsFromTestCase(JSONConfigTestCase)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.