text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Change default value for adapter | <?php
namespace Sellsy\ApiBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Class Configuration
*
* @package Sellsy\ApiBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sellsy_api');
$rootNode
->children()
->scalarNode('adapter')->isRequired()->cannotBeEmpty()->defaultValue('mapper')
->validate()
->ifNotInArray(array('base', 'mapper'))
->thenInvalid('Configuration "adapter" is required and can have one of the following values: base, mapper')
->end()
->end()
->arrayNode('authentication')
->isRequired()
->cannotBeEmpty()
->children()
->scalarNode('consumer_token')->isRequired()->cannotBeEmpty()->end()
->scalarNode('consumer_secret')->isRequired()->cannotBeEmpty()->end()
->scalarNode('user_token')->isRequired()->cannotBeEmpty()->end()
->scalarNode('user_secret')->isRequired()->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
| <?php
namespace Sellsy\ApiBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Class Configuration
*
* @package Sellsy\ApiBundle\DependencyInjection
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sellsy_api');
$rootNode
->children()
->scalarNode('adapter')->isRequired()->cannotBeEmpty()->defaultValue('base')
->validate()
->ifNotInArray(array('base', 'mapper'))
->thenInvalid('Configuration "adapter" is required and can have one of the following values: base, mapper')
->end()
->end()
->arrayNode('authentication')
->isRequired()
->cannotBeEmpty()
->children()
->scalarNode('consumer_token')->isRequired()->cannotBeEmpty()->end()
->scalarNode('consumer_secret')->isRequired()->cannotBeEmpty()->end()
->scalarNode('user_token')->isRequired()->cannotBeEmpty()->end()
->scalarNode('user_secret')->isRequired()->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
|
Add template var for model generation | <?php namespace Way\Generators\Commands;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class ModelGeneratorCommand extends GeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a model';
/**
* The path where the file will be created
*
* @return mixed
*/
protected function getFileGenerationPath()
{
$path = $this->getPathByOptionOrConfig('path', 'model_target_path');
return $path. '/' . ucwords($this->argument('modelName')) . '.php';
}
/**
* Fetch the template data
*
* @return array
*/
protected function getTemplateData()
{
return [
'NAME' => ucwords($this->argument('modelName')),
'NAMESPACE' => $this->getNamespace('root')
];
}
/**
* Get path to the template for the generator
*
* @return mixed
*/
protected function getTemplatePath()
{
return $this->getPathByOptionOrConfig('templatePath', 'model_template_path');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['modelName', InputArgument::REQUIRED, 'The name of the desired Eloquent model']
];
}
}
| <?php namespace Way\Generators\Commands;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class ModelGeneratorCommand extends GeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:model';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a model';
/**
* The path where the file will be created
*
* @return mixed
*/
protected function getFileGenerationPath()
{
$path = $this->getPathByOptionOrConfig('path', 'model_target_path');
return $path. '/' . ucwords($this->argument('modelName')) . '.php';
}
/**
* Fetch the template data
*
* @return array
*/
protected function getTemplateData()
{
return [
'NAME' => ucwords($this->argument('modelName'))
];
}
/**
* Get path to the template for the generator
*
* @return mixed
*/
protected function getTemplatePath()
{
return $this->getPathByOptionOrConfig('templatePath', 'model_template_path');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['modelName', InputArgument::REQUIRED, 'The name of the desired Eloquent model']
];
}
}
|
Fix to the mapper related entities when null | <?php
namespace FS\SolrBundle\Doctrine\Mapper\Mapping;
use FS\SolrBundle\Doctrine\Annotation\Field;
use FS\SolrBundle\Doctrine\Mapper\MetaInformationInterface;
use Doctrine\Common\Collections\Collection;
/**
* command maps all fields of the entity
*
* uses parent method for mapping of document_name and id
*/
class MapAllFieldsCommand extends AbstractDocumentCommand
{
/**
* @param MetaInformationInterface $meta
*
* @return null|\Solarium\QueryType\Update\Query\Document\Document
*/
public function createDocument(MetaInformationInterface $meta)
{
$fields = $meta->getFields();
if (count($fields) == 0) {
return null;
}
$document = parent::createDocument($meta);
foreach ($fields as $field) {
if (!$field instanceof Field) {
continue;
}
$value = $field->getValue();
$getter = $field->getGetterName();
if (!empty($getter)) {
if ($value instanceof Collection) {
$values = array();
foreach ($value as $relatedObj) {
$values[] = $relatedObj->{$getter}();
}
$document->addField($field->getNameWithAlias(), $values, $field->getBoost());
} elseif (is_object($value) && method_exists($value, $getter)) {
$document->addField($field->getNameWithAlias(), $value->{$getter}(), $field->getBoost());
}
} else {
$document->addField($field->getNameWithAlias(), $field->getValue(), $field->getBoost());
}
}
return $document;
}
}
| <?php
namespace FS\SolrBundle\Doctrine\Mapper\Mapping;
use FS\SolrBundle\Doctrine\Annotation\Field;
use FS\SolrBundle\Doctrine\Mapper\MetaInformationInterface;
use Doctrine\Common\Collections\Collection;
/**
* command maps all fields of the entity
*
* uses parent method for mapping of document_name and id
*/
class MapAllFieldsCommand extends AbstractDocumentCommand
{
/**
* @param MetaInformationInterface $meta
*
* @return null|\Solarium\QueryType\Update\Query\Document\Document
*/
public function createDocument(MetaInformationInterface $meta)
{
$fields = $meta->getFields();
if (count($fields) == 0) {
return null;
}
$document = parent::createDocument($meta);
foreach ($fields as $field) {
if (!$field instanceof Field) {
continue;
}
$value = $field->getValue();
$getter = $field->getGetterName();
if (!empty($getter)) {
if ($value instanceof Collection) {
$values = array();
foreach ($value as $relatedObj) {
$values[] = $relatedObj->{$getter}();
}
$document->addField($field->getNameWithAlias(), $values, $field->getBoost());
} else {
$document->addField($field->getNameWithAlias(), $value->{$getter}(), $field->getBoost());
}
} else {
$document->addField($field->getNameWithAlias(), $field->getValue(), $field->getBoost());
}
}
return $document;
}
}
|
Lib: Add `ERROR` prefix to error messages | /**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var config = require('../plot_api/plot_config');
var loggers = module.exports = {};
/**
* ------------------------------------------
* debugging tools
* ------------------------------------------
*/
/* eslint-disable no-console */
loggers.log = function() {
if(config.logging > 1) {
var messages = ['LOG:'];
for(var i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
if(console.trace) {
console.trace.apply(console, messages);
} else {
console.log.apply(console, messages);
}
}
};
loggers.warn = function() {
if(config.logging > 0) {
var messages = ['WARN:'];
for(var i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
if(console.trace) {
console.trace.apply(console, messages);
} else {
console.log.apply(console, messages);
}
}
};
loggers.error = function() {
if(config.logging > 0) {
var messages = ['ERROR:'];
for(var i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
console.error.apply(console, arguments);
}
};
/* eslint-enable no-console */
| /**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var config = require('../plot_api/plot_config');
var loggers = module.exports = {};
/**
* ------------------------------------------
* debugging tools
* ------------------------------------------
*/
/* eslint-disable no-console */
loggers.log = function() {
if(config.logging > 1) {
var messages = ['LOG:'];
for(var i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
if(console.trace) {
console.trace.apply(console, messages);
} else {
console.log.apply(console, messages);
}
}
};
loggers.warn = function() {
if(config.logging > 0) {
var messages = ['WARN:'];
for(var i = 0; i < arguments.length; i++) {
messages.push(arguments[i]);
}
if(console.trace) {
console.trace.apply(console, messages);
} else {
console.log.apply(console, messages);
}
}
};
loggers.error = function() {
if(config.logging > 0) {
console.error.apply(console, arguments);
}
};
/* eslint-enable no-console */
|
Disable the creation of new scripts in certain environments (prod). | package whelk.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RunOrCreatePanel extends WizardCard implements ActionListener
{
private JRadioButton rCreate;
private JRadioButton rRun;
public RunOrCreatePanel(Wizard wizard)
{
super(wizard);
this.setLayout(new GridBagLayout());
boolean creationForbidden = System.getProperty("creationForbidden") != null &&
System.getProperty("creationForbidden").equals("true");
Box vbox = Box.createVerticalBox();
if (creationForbidden)
{
rCreate = new JRadioButton("Skapa en körning (ej tillåtet i denna miljö).");
rCreate.setEnabled(false);
}
else
{
rCreate = new JRadioButton("Skapa en körning.");
rCreate.addActionListener(this);
rCreate.setSelected(true);
}
rRun = new JRadioButton("Kör en tidigare skapad körning.");
rRun.addActionListener(this);
ButtonGroup group = new ButtonGroup();
group.add(rCreate);
group.add(rRun);
vbox.add(rCreate);
vbox.add(rRun);
this.add(vbox);
}
@Override
void onShow(Object parameterFromPreviousCard)
{
chooseNextCard();
}
@Override
public void actionPerformed(ActionEvent actionEvent)
{
chooseNextCard();
}
private void chooseNextCard()
{
if (! rRun.isSelected())
setNextCard(Wizard.CREATE_WHAT);
else
setNextCard(Wizard.SELECT_SCRIPT);
}
}
| package whelk.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RunOrCreatePanel extends WizardCard implements ActionListener
{
private JRadioButton rCreate;
private JRadioButton rRun;
public RunOrCreatePanel(Wizard wizard)
{
super(wizard);
this.setLayout(new GridBagLayout());
Box vbox = Box.createVerticalBox();
rCreate = new JRadioButton("Skapa en körning.");
rCreate.addActionListener(this);
rRun = new JRadioButton("Kör en tidigare skapad körning.");
rRun.addActionListener(this);
rCreate.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(rCreate);
group.add(rRun);
vbox.add(rCreate);
vbox.add(rRun);
this.add(vbox);
}
@Override
void onShow(Object parameterFromPreviousCard)
{
chooseNextCard();
}
@Override
public void actionPerformed(ActionEvent actionEvent)
{
chooseNextCard();
}
private void chooseNextCard()
{
if (! rRun.isSelected())
setNextCard(Wizard.CREATE_WHAT);
else
setNextCard(Wizard.SELECT_SCRIPT);
}
}
|
Use newer Message Broker publish method. | <?php
namespace VotingApp\Services;
use MessageBroker as MessageBrokerConnection;
class MessageBroker
{
/**
* Serialize and send payload to the Message Broker using a
* given routing key.
*
* @param array $payload
* @param string $routingKey
*/
public function publishRaw($payload, $routingKey)
{
// Don't send messages locally.
if (app()->environment('local', 'testing')) {
return;
}
// Configure the message broker connection
$credentials = config('services.message_broker.credentials');
$config = config('services.message_broker.config');
$broker = new MessageBrokerConnection($credentials, $config);
$serializedPayload = serialize($payload);
$broker->publish($serializedPayload, $routingKey);
}
/**
* Append expected configuration variables to the payload, and
* then send to the Message Broker.
*
* @param string $activity
* @param array $payload
* @param string $routingKey
*/
public function publish($activity, $payload, $routingKey)
{
// Set common configuration values:
$payload['application_id'] = env('MESSAGE_BROKER_APPLICATION_ID');
$payload['mc_opt_in_path_id'] = env('MC_OPT_IN_PATH');
$payload['mailchimp_list_id'] = env('MAILCHIMP_LIST_ID');
// Add activity type and timestamp
$payload['activity'] = $activity;
$payload['activity_timestamp'] = time();
$this->publishRaw($payload, $routingKey);
}
}
| <?php
namespace VotingApp\Services;
use MessageBroker as MessageBrokerConnection;
class MessageBroker
{
/**
* Serialize and send payload to the Message Broker using a
* given routing key.
*
* @param array $payload
* @param string $routingKey
*/
public function publishRaw($payload, $routingKey)
{
// Don't send messages locally.
if (app()->environment('local', 'testing')) {
return;
}
// Configure the message broker connection
$credentials = config('services.message_broker.credentials');
$config = config('services.message_broker.config');
$config['routingKey'] = $routingKey;
$broker = new MessageBrokerConnection($credentials, $config);
$serializedPayload = serialize($payload);
$broker->publishMessage($serializedPayload);
}
/**
* Append expected configuration variables to the payload, and
* then send to the Message Broker.
*
* @param string $activity
* @param array $payload
* @param string $routingKey
*/
public function publish($activity, $payload, $routingKey)
{
// Set common configuration values:
$payload['application_id'] = env('MESSAGE_BROKER_APPLICATION_ID');
$payload['mc_opt_in_path_id'] = env('MC_OPT_IN_PATH');
$payload['mailchimp_list_id'] = env('MAILCHIMP_LIST_ID');
// Add activity type and timestamp
$payload['activity'] = $activity;
$payload['activity_timestamp'] = time();
$this->publishRaw($payload, $routingKey);
}
}
|
initial-push: Allow factories to call factories, allow document, allow window, allow empty selector | (function() {
const domQuery = (function () {
function $(selector) {
let collection = (!selector ? [] :
(typeof selector === 'string') ? document.querySelectorAll(selector) :
(selector instanceof DQ) ? selector :
(typeof selector === 'object' && (selector.nodeType === 1 || selector.nodeType === 9)) ? [selector] : [] ),
instance = new DQ(collection, selector);
return instance;
}
function DQ(collection, selector) {
let i = 0,
len = collection.length;
for (;i<len;i++) {
this[i] = collection[i];
}
this.length = len;
this.splice = [].splice;
this.each = [].forEach;
this.indexOf = [].indexOf;
this.some = [].some;
}
$.extend = function (obj) {
let that = this, i;
if (arguments.length > 2) {
return Error('$.extend expects at most 2 arguments. Old object and New object');
}
if (arguments.length > 1) {
that = arguments[0];
obj = arguments[1];
}
for(let i in obj) {
if(obj.hasOwnProperty(i)) {
that[i] = obj[i];
}
}
};
$.plugin = function (name, func) {
DQ.prototype[name] = func;
};
return $;
})();
window.$ === undefined && (window.$ = domQuery);
window.domQuery === undefined && (window.domQuery = domQuery);
})();
| (function() {
const domQuery = (function () {
function $(selector) {
let collection = ((typeof selector === 'string') ? document.querySelectorAll(selector) :
(typeof selector === 'object' && (selector.nodeType === 1 || selector.nodeType === 9)) ? [selector] : [] ),
instance = new DQ(collection, selector);
return instance;
}
// This is our functional factory
function DQ(collection, selector) {
let i = 0,
len = collection.length;
for (;i<len;i++) {
this[i] = collection[i];
}
this.length = len;
this.splice = [].splice;
this.each = [].forEach;
this.indexOf = [].indexOf;
this.some = [].some;
}
// $.extend allows plugins to work on top of our existing base.
$.extend = function (obj) {
let that = this, i;
if (arguments.length > 2) {
return Error('$.extend expects at most 2 arguments. Old object and New object');
}
if (arguments.length > 1) {
that = arguments[0];
obj = arguments[1];
}
for(let i in obj) {
if(obj.hasOwnProperty(i)) {
that[i] = obj[i];
}
}
};
// $.plugin and $.extend are very similar, however plugin applies only to nodes.
$.plugin = function (name, func) {
DQ.prototype[name] = func;
};
return $;
})();
window.$ === undefined && (window.$ = domQuery);
window.domQuery === undefined && (window.domQuery = domQuery);
})();
|
Update score lookup to not load dataset file | import json
""" Input: Loaded dataset, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(dataset, songs_lst):
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(dataset[song]['lyrics'][line])):
word = dataset[song]['lyrics'][line][word_idx]
score = dataset[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
| import json
""" Input: the path of the dataset file, a list of song and line indices
Output: List of tuples of words with highest tf-idf scores
Given a list of song-line tuple (song_index, line_index),
returns a list of a word-score tuple, with the word with highest score
at the head of the list.
"""
def score_lookup(data_filename, songs_lst):
fo = open(data_filename, 'r')
lyrics = json.loads(fo.read())
fo.close()
tfidf_sum = {}
tfidf_count = {}
tfidf_scores = []
for song, line in songs_lst:
for word_idx in range(len(lyrics[song]['lyrics'][line])):
word = lyrics[song]['lyrics'][line][word_idx]
score = lyrics[song]['tfidf_scores'][line][word_idx]
if word.isalpha():
if tfidf_sum.has_key(word.lower()):
tfidf_sum[word.lower()] += score
tfidf_count[word.lower()] += 1
else:
tfidf_sum[word.lower()] = score
tfidf_count[word.lower()] = 1
for word, sum in tfidf_sum.items():
tfidf_scores.append((word, sum / tfidf_count[word]))
return sorted(tfidf_scores, key=lambda x: x[1], reverse=True)
|
Fix ValueError in IMUParser with non-ints in input | from tsparser.parser import BaseParser
class IMUParser(BaseParser):
def __init__(self):
self.gyro = None
self.accel = None
self.magnet = None
self.pressure = None
def parse(self, line, data_id, *values):
if data_id == '$GYRO':
self.gyro = [int(x) for x in values]
elif data_id == '$ACCEL':
self.accel = [int(x) for x in values]
elif data_id == '$MAGNET':
self.magnet = [int(x) for x in values]
elif data_id == '$MBAR':
self.pressure = int(values[0])
else:
return False
if all([self.gyro, self.accel, self.magnet, self.pressure]):
# todo send it instead of just printing
print(self.generate_data())
self.gyro = self.accel = self.magnet = self.pressure = None
return True
def generate_data(self):
return {
'timestamp': BaseParser.timestamp,
'gyro_x': self.gyro[0],
'gyro_y': self.gyro[1],
'gyro_z': self.gyro[2],
'accel_x': self.accel[0],
'accel_y': self.accel[1],
'accel_z': self.accel[2],
'magnet_x': self.magnet[0],
'magnet_y': self.magnet[1],
'magnet_z': self.magnet[2],
'pressure': self.pressure
}
| from tsparser.parser import BaseParser
class IMUParser(BaseParser):
def __init__(self):
self.gyro = None
self.accel = None
self.magnet = None
self.pressure = None
def parse(self, line, data_id, *values):
values = [int(x) for x in values]
if data_id == '$GYRO':
self.gyro = values
elif data_id == '$ACCEL':
self.accel = values
elif data_id == '$MAGNET':
self.magnet = values
elif data_id == '$MBAR':
self.pressure = values[0]
else:
return False
if all([self.gyro, self.accel, self.magnet, self.pressure]):
# todo send it instead of just printing
print(self.generate_data())
self.gyro = self.accel = self.magnet = self.pressure = None
return True
def generate_data(self):
return {
'timestamp': BaseParser.timestamp,
'gyro_x': self.gyro[0],
'gyro_y': self.gyro[1],
'gyro_z': self.gyro[2],
'accel_x': self.accel[0],
'accel_y': self.accel[1],
'accel_z': self.accel[2],
'magnet_x': self.magnet[0],
'magnet_y': self.magnet[1],
'magnet_z': self.magnet[2],
'pressure': self.pressure
}
|
Add reference to memory to base role. | 'use strict';
let counts = require('counts');
class BaseRole {
constructor(creep) {
this.creep = creep;
this.spawn = Game.spawns[creep.memory.spawnName];
this.memory = creep.memory;
}
static wantsToBuild(level) {
let want = this.LEVEL_INFO[level || 0].count || 0,
typeKey = this.key(),
have = counts[typeKey] || 0;
return want < have;
}
static getCreep(level) {
return {
parts: this.LEVEL_INFO[level],
memory: {
role: this.key()
}
};
}
getRally() {
let rallyPoint = this.spawn.pos;
if (Game.flags.BoushleyRally) {
rallyPoint = Game.flags.BoushleyRally.pos;
}
let newCoords = {
x: rallyPoint.x,
y: rallyPoint.y
};
// On this map up is the back-side direction
if (this.creep.getActiveBodyparts(Game.ATTACK) > 0) {
newCoords.y += 1;
} else {
newCoords.y -= 1;
}
return this.creep.room.getPositionAt(newCoords.x, newCoords.y);
}
getDefensivePosition() {
return this.creep.pos.findClosest(Game.MY_STRUCTURES, {
filter: s => s.structureType === Game.STRUCTURE_RAMPART
}).pos;
}
}
module.exports = BaseRole;
| 'use strict';
let counts = require('counts');
class BaseRole {
constructor(creep) {
this.creep = creep;
this.spawn = Game.spawns[creep.memory.spawnName];
}
static wantsToBuild(level) {
let want = this.LEVEL_INFO[level || 0].count || 0,
typeKey = this.key(),
have = counts[typeKey] || 0;
return want < have;
}
static getCreep(level) {
return {
parts: this.LEVEL_INFO[level],
memory: {
role: this.key()
}
};
}
getRally() {
let rallyPoint = this.spawn.pos;
if (Game.flags.BoushleyRally) {
rallyPoint = Game.flags.BoushleyRally.pos;
}
let newCoords = {
x: rallyPoint.x,
y: rallyPoint.y
};
// On this map up is the back-side direction
if (this.creep.getActiveBodyparts(Game.ATTACK) > 0) {
newCoords.y += 1;
} else {
newCoords.y -= 1;
}
return this.creep.room.getPositionAt(newCoords.x, newCoords.y);
}
getDefensivePosition() {
return this.creep.pos.findClosest(Game.MY_STRUCTURES, {
filter: s => s.structureType === Game.STRUCTURE_RAMPART
}).pos;
}
}
module.exports = BaseRole;
|
Fix syntax error in service_status | import logging
from django.utils.translation import ugettext as _
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import *
logger = logging.getLogger("molly.apps.service_status.views")
class IndexView(BaseView):
"""
View to display service status information
"""
# TODO Remove specific references to OUCS and OLIS
def get_metadata(self, request):
return {
'title': _('Service Status'),
'additional': _('Check whether OUCS and OLIS services are available'),
}
@BreadcrumbFactory
def breadcrumb(self, request, context):
return Breadcrumb('service_status', None,
_('Service Status'),
lazy_reverse('index'))
def handle_GET(self, request, context):
services = []
for provider in self.conf.providers:
try:
status = provider.get_status()
except Exception, e:
logger.warn("Failed to load service status", exc_info=True)
else:
services.append((
provider.slug, provider.name,
status['lastBuildDate'], status['services'],
provider.get_announcements(),
))
context['services'] = services
return self.render(request, context, 'service_status/index')
| import logging
from django.utils.translation import ugettext as _
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import *
logger = logging.getLogger("molly.apps.service_status.views")
class IndexView(BaseView):
"""
View to display service status information
"""
# TODO Remove specific references to OUCS and OLIS
def get_metadata(self, request):
return {
'title': _('Service Status', )
'additional': _('Check whether OUCS and OLIS services are available'),
}
@BreadcrumbFactory
def breadcrumb(self, request, context):
return Breadcrumb('service_status', None,
_('Service Status'),
lazy_reverse('index'))
def handle_GET(self, request, context):
services = []
for provider in self.conf.providers:
try:
status = provider.get_status()
except Exception, e:
logger.warn("Failed to load service status", exc_info=True)
else:
services.append((
provider.slug, provider.name,
status['lastBuildDate'], status['services'],
provider.get_announcements(),
))
context['services'] = services
return self.render(request, context, 'service_status/index')
|
Add util.keys as Object.keys shim | if (typeof buster == "undefined") {
var buster = {};
}
buster.util = (function () {
var toString = Object.prototype.toString;
var div = typeof document != "undefined" && document.createElement("div");
return {
isNode: function (obj) {
if (!div) {
return false;
}
try {
div.appendChild(obj);
div.removeChild(obj);
} catch (e) {
return false;
}
return true;
},
isElement: function (obj) {
return obj && this.isNode(obj) && obj.nodeType === 1;
},
isArguments: function (obj) {
if (typeof obj != "object" || typeof obj.length != "number" ||
toString.call(obj) == "[object Array]") {
return false;
}
if (typeof obj.callee == "function") {
return true;
}
try {
obj[obj.length] = 6;
delete obj[obj.length];
} catch (e) {
return true;
}
return false;
},
keys: Object.keys || function (object) {
var keys = [];
for (var prop in object) {
if (Object.prototype.hasOwnProperty.call(object, prop)) {
keys.push(prop);
}
}
return keys;
}
};
}());
if (typeof module != "undefined") {
module.exports = buster.util;
}
| if (typeof buster == "undefined") {
var buster = {};
}
buster.util = (function () {
var toString = Object.prototype.toString;
var div = typeof document != "undefined" && document.createElement("div");
return {
isNode: function (obj) {
if (!div) {
return false;
}
try {
div.appendChild(obj);
div.removeChild(obj);
} catch (e) {
return false;
}
return true;
},
isElement: function (obj) {
return obj && this.isNode(obj) && obj.nodeType === 1;
},
isArguments: function (obj) {
if (typeof obj != "object" || typeof obj.length != "number" ||
toString.call(obj) == "[object Array]") {
return false;
}
if (typeof obj.callee == "function") {
return true;
}
try {
obj[obj.length] = 6;
delete obj[obj.length];
} catch (e) {
return true;
}
return false;
}
};
}());
if (typeof module != "undefined") {
module.exports = buster.util;
}
|
Remove PHP 7.1 specific code | <?php
/*
* This file is part of the Active Collab Bootstrap project.
*
* (c) A51 doo <[email protected]>. All rights reserved.
*/
namespace ActiveCollab\Bootstrap\Controller;
use ActiveCollab\Authentication\AuthenticatedUser\AuthenticatedUserInterface;
use ActiveCollab\Authentication\AuthenticationResult\AuthenticationResultInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* @package ActiveCollab\Bootstrap\Controller
*/
trait ControllerTrait
{
/**
* Return authenticated user.
*
* @param ServerRequestInterface $request
* @return AuthenticatedUserInterface|null
*/
protected function getAuthenticatedUser(ServerRequestInterface $request)
{
return $request->getAttribute($this->getAuthenticatedUserAttributeName());
}
/**
* Return authenticated user request attribute name.
*
* @return string
*/
protected function getAuthenticatedUserAttributeName() : string
{
return 'authenticated_user';
}
/**
* Return authentication method instance (token or session).
*
* @param ServerRequestInterface $request
* @return AuthenticationResultInterface|null
*/
protected function getAuthenticatedWith(ServerRequestInterface $request)
{
return $request->getAttribute($this->getAuthenticatedWithAttributeName());
}
/**
* Return name of the request attribute where authentication method is stored.
*
* @return string
*/
protected function getAuthenticatedWithAttributeName() : string
{
return 'authenticated_with';
}
}
| <?php
/*
* This file is part of the Active Collab Bootstrap project.
*
* (c) A51 doo <[email protected]>. All rights reserved.
*/
namespace ActiveCollab\Bootstrap\Controller;
use ActiveCollab\Authentication\AuthenticatedUser\AuthenticatedUserInterface;
use ActiveCollab\Authentication\AuthenticationResult\AuthenticationResultInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* @package ActiveCollab\Bootstrap\Controller
*/
trait ControllerTrait
{
/**
* Return authenticated user.
*
* @param ServerRequestInterface $request
* @return AuthenticatedUserInterface|null
*/
protected function getAuthenticatedUser(ServerRequestInterface $request): ? AuthenticatedUserInterface
{
return $request->getAttribute($this->getAuthenticatedUserAttributeName());
}
/**
* Return authenticated user request attribute name.
*
* @return string
*/
protected function getAuthenticatedUserAttributeName() : string
{
return 'authenticated_user';
}
/**
* Return authentication method instance (token or session).
*
* @param ServerRequestInterface $request
* @return AuthenticationResultInterface|null
*/
protected function getAuthenticatedWith(ServerRequestInterface $request): ? AuthenticationResultInterface
{
return $request->getAttribute($this->getAuthenticatedWithAttributeName());
}
/**
* Return name of the request attribute where authentication method is stored.
*
* @return string
*/
protected function getAuthenticatedWithAttributeName() : string
{
return 'authenticated_with';
}
}
|
:wrench: Improve logical on deserialize listener | <?php
namespace OAuthBundle\EventListener;
use ApiPlatform\Core\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
final class DeserializeListener
{
private $decorated;
private $denormalizer;
private $serializerContextBuilder;
public function __construct(DenormalizerInterface $denormalizer, SerializerContextBuilderInterface $serializerContextBuilder, DecoratedListener $decorated)
{
$this->denormalizer = $denormalizer;
$this->serializerContextBuilder = $serializerContextBuilder;
$this->decorated = $decorated;
}
public function onKernelRequest(GetResponseEvent $event) {
$request = $event->getRequest();
if ($request->isMethodSafe() || $request->isMethod(Request::METHOD_DELETE)) {
return;
}
if ('POST' === $request->getMethod() && $request->get("_route") === "_token") {
$this->denormalizeFormRequest($request);
} else {
$this->decorated->onKernelRequest($event);
}
}
private function denormalizeFormRequest(Request $request)
{
try {
$body = $request->getContent();
if(is_string($body)){
$body = json_decode($body);
}
foreach ($body as $key => $value) {
$request->request->set($key, $value);
}
} catch (RuntimeException $e) {
return;
}
}
} | <?php
namespace OAuthBundle\EventListener;
use ApiPlatform\Core\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
final class DeserializeListener
{
private $decorated;
private $denormalizer;
private $serializerContextBuilder;
public function __construct(DenormalizerInterface $denormalizer, SerializerContextBuilderInterface $serializerContextBuilder, DecoratedListener $decorated)
{
$this->denormalizer = $denormalizer;
$this->serializerContextBuilder = $serializerContextBuilder;
$this->decorated = $decorated;
}
public function onKernelRequest(GetResponseEvent $event) {
$request = $event->getRequest();
if ($request->isMethodSafe() || $request->isMethod(Request::METHOD_DELETE)) {
return;
}
if ('POST' === $request->getMethod() && $request->get("_route") === "_token") {
$this->denormalizeFormRequest($request);
} else {
$this->decorated->onKernelRequest($event);
}
}
private function denormalizeFormRequest(Request $request)
{
try {
$body = json_decode($request->getContent());
foreach ($body as $key => $value) {
$request->request->set($key, $value);
}
} catch (RuntimeException $e) {
return;
}
}
} |
Revert "MacOSX - Suppress EDT exception in NoInputEventQueue.drain()"
This reverts commit 98807717fd5f0153ad1ce918236ea7ab8ad5be40. | /* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.utils.awt;
import java.awt.EventQueue;
import java.util.EmptyStackException;
import java.lang.reflect.InvocationTargetException;
/**
* A <code>PoppableEventQueue</code> is-an {@link EventQueue} that merely
* makes the ordinarily <code>protected</code> method <code>pop()</code>
* <code>public</code>.
*
* @author Paul J. Lucas [[email protected]]
*/
public class PoppableEventQueue extends EventQueue {
/**
* {@inheritDoc}
*/
public void pop() throws EmptyStackException {
super.pop();
}
// Enqueue a placeholder task and wait until it (and all preceding tasks)
// are dequeued. This helps prevent tasks from running after the pop().
public static void drain() {
if (EventQueue.isDispatchThread()) {
throw new IllegalThreadStateException(
"Can't drain the event queue from the event thread."
);
}
try {
EventQueue.invokeAndWait(
new Runnable() {
public void run() {
// do nothing
}
}
);
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
/* vim:set et sw=4 ts=4: */ | /* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.utils.awt;
import java.awt.EventQueue;
import java.util.EmptyStackException;
import java.lang.reflect.InvocationTargetException;
/**
* A <code>PoppableEventQueue</code> is-an {@link EventQueue} that merely
* makes the ordinarily <code>protected</code> method <code>pop()</code>
* <code>public</code>.
*
* @author Paul J. Lucas [[email protected]]
*/
public class PoppableEventQueue extends EventQueue {
/**
* {@inheritDoc}
*/
public void pop() throws EmptyStackException {
super.pop();
}
// Enqueue a placeholder task and wait until it (and all preceding tasks)
// are dequeued. This helps prevent tasks from running after the pop().
public static void drain() {
if (EventQueue.isDispatchThread()) {
String msg = "Can't drain the event queue from the event thread.";
// throw new IllegalThreadStateException(msg);
System.err.println(msg);
return;
}
try {
EventQueue.invokeAndWait(
new Runnable() {
public void run() {
// do nothing
}
}
);
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
/* vim:set et sw=4 ts=4: */
|
Add parameter to app as executable file | /**
* Project RSA Algorithm.
* Copyright Michał Szczygieł.
* Created at Feb 24, 2014.
*/
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* This class is resposnible for testing and representation data for RSA
* encryption algorithm.
*
* @author Michał Szczygieł <[email protected]>
*
*/
public class Main {
/**
* This logger is responsible for the registration of events.
*/
static final Logger logger = LogManager.getLogger(Main.class.getName());
/**
* This method sets up configuration for loggers.
*/
private static void loggerSetup() {
// BasicConfigurator.configure();
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 1) {
loggerSetup();
RSA rsa = new RSA(1024);
try {
OutputStream encryptedStream = IOOperations.encryptStream(
IOOperations.readFile(args[0]), rsa, RSA.BLOCK_SIZE);
logger.info(encryptedStream.toString());
logger.info(IOOperations.decryptStream(encryptedStream, rsa,
RSA.BLOCK_SIZE));
} catch (IOException e) {
logger.debug(e);
logger.error(e);
}
} else {
logger.warn("The application needs 1 argument as file to encrypt");
}
}
}
| /**
* Project RSA Algorithm.
* Copyright Michał Szczygieł.
* Created at Feb 24, 2014.
*/
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* This class is resposnible for testing and representation data for RSA
* encryption algorithm.
*
* @author Michał Szczygieł <[email protected]>
*
*/
public class Main {
/**
* This logger is responsible for the registration of events.
*/
static final Logger logger = LogManager.getLogger(Main.class.getName());
/**
* This method sets up configuration for loggers.
*/
private static void loggerSetup() {
// BasicConfigurator.configure();
}
/**
* @param args
*/
public static void main(String[] args) {
loggerSetup();
RSA rsa = new RSA(1024);
try {
OutputStream encryptedStream = IOOperations.encryptStream(
IOOperations.readFile("data.txt"), rsa, RSA.BLOCK_SIZE);
logger.info(encryptedStream.toString());
logger.info(IOOperations.decryptStream(encryptedStream, rsa,
RSA.BLOCK_SIZE));
} catch (IOException e) {
logger.debug(e);
logger.error(e);
}
}
}
|
Fix compilation issue on not latest JDKs | /*
* (c) 2015 CenturyLink. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centurylink.cloud.sdk.tests.mocks;
import com.centurylink.cloud.sdk.tests.TestModule;
import org.mockito.Spy;
import java.lang.reflect.Field;
import java.util.stream.Stream;
/**
* @author Ilya Drabenia
*/
public class BindSpiesModule extends TestModule {
private final Object target;
public BindSpiesModule(Object target) {
this.target = target;
}
@Override
protected void configure() {
overrideSpyBinding();
}
private void overrideSpyBinding() {
Stream
.of(declaredFields())
.filter(f -> f.isAnnotationPresent(Spy.class))
.forEach(f ->
bind(f.getType()).toProvider(new SpyProvider(f.getType())
)
);
}
private Field[] declaredFields() {
return target
.getClass()
.getDeclaredFields();
}
}
| /*
* (c) 2015 CenturyLink. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.centurylink.cloud.sdk.tests.mocks;
import com.centurylink.cloud.sdk.tests.TestModule;
import org.mockito.Spy;
import java.lang.reflect.Field;
import java.util.stream.Stream;
/**
* @author Ilya Drabenia
*/
public class BindSpiesModule extends TestModule {
private final Object target;
public BindSpiesModule(Object target) {
this.target = target;
}
@Override
protected void configure() {
overrideSpyBinding();
}
private void overrideSpyBinding() {
Stream
.of(declaredFields())
.filter(f -> f.isAnnotationPresent(Spy.class))
.forEach(f -> bind(f.getType())
.toProvider(new SpyProvider<>(f.getType()))
);
}
private Field[] declaredFields() {
return target
.getClass()
.getDeclaredFields();
}
}
|
Use IoC bound model rather than hard coding | <?php
declare(strict_types=1);
namespace Cortex\Fort\Http\Controllers\Userarea;
use Illuminate\Http\Request;
use Cortex\Foundation\Http\Controllers\AuthenticatedController;
class AccountSessionsController extends AuthenticatedController
{
/**
* Show the account sessions.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('cortex/fort::userarea.account.sessions');
}
/**
* Flush the given session.
*
* @param string|null $id
*
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
public function flush(Request $request, $id = null)
{
$status = '';
if ($id) {
app('rinvex.fort.session')->find($id)->delete();
$status = trans('cortex/fort::messages.auth.session.flushed');
} elseif ($request->get('confirm')) {
app('rinvex.fort.session')->where('user_id', $request->user($this->getGuard())->id)->delete();
$status = trans('cortex/fort::messages.auth.session.flushedall');
}
return intend([
'back' => true,
'with' => ['warning' => $status],
]);
}
}
| <?php
declare(strict_types=1);
namespace Cortex\Fort\Http\Controllers\Userarea;
use Illuminate\Http\Request;
use Rinvex\Fort\Models\Session;
use Cortex\Foundation\Http\Controllers\AuthenticatedController;
class AccountSessionsController extends AuthenticatedController
{
/**
* Show the account sessions.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('cortex/fort::userarea.account.sessions');
}
/**
* Flush the given session.
*
* @param string|null $id
*
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
public function flush(Request $request, $id = null)
{
$status = '';
if ($id) {
Session::find($id)->delete();
$status = trans('cortex/fort::messages.auth.session.flushed');
} elseif ($request->get('confirm')) {
Session::where('user_id', $request->user($this->getGuard())->id)->delete();
$status = trans('cortex/fort::messages.auth.session.flushedall');
}
return intend([
'back' => true,
'with' => ['warning' => $status],
]);
}
}
|
Delete require cache rather than create endless directories | 'use strict'
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const assign = require('lodash.assign')
const makeTemplate = require('./make-template.js')
const defaultDirectives = require('./default-directives.js')
module.exports = function (directory, settings) {
settings = settings || {}
directory = path.resolve(process.cwd(), directory) + '/'
settings.cacheDirectory = settings.cacheDirectory || directory + 'compiled/'
var directives = assign({}, defaultDirectives, settings.directives || {})
var promises = {}
return function load (name) {
if (!promises[name]) {
promises[name] = new Promise(function (resolve, reject) {
fs.readFile(directory + name, { encoding: 'utf-8' }, function (err, result) {
if (err) throw err
makeTemplate(result, load, directives, function (err, result) {
if (err) throw err
mkdirp(path.dirname(settings.cacheDirectory + name + '.js'), function (err) {
if (err) throw err
fs.writeFile(settings.cacheDirectory + name + '.js', result, function (err) {
if (err) throw err
resolve(settings.cacheDirectory + name + '.js')
})
})
})
})
})
}
return promises[name].then(function (path) {
delete require.cache[path]
var Template = require(path)
return Promise.resolve(function (content) {
return (new Template()).render(content)
})
})
}
}
| 'use strict'
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')
const assign = require('lodash.assign')
const makeTemplate = require('./make-template.js')
const defaultDirectives = require('./default-directives.js')
module.exports = function (directory, settings) {
settings = settings || {}
directory = path.resolve(process.cwd(), directory) + '/'
settings.cacheDirectory = settings.cacheDirectory || directory + 'compiled/' + (new Date()).getTime() + '/'
var directives = assign({}, defaultDirectives, settings.directives || {})
var promises = {}
return function load (name) {
if (!promises[name]) {
promises[name] = new Promise(function (resolve, reject) {
fs.readFile(directory + name, { encoding: 'utf-8' }, function (err, result) {
if (err) throw err
makeTemplate(result, load, directives, function (err, result) {
if (err) throw err
mkdirp(path.dirname(settings.cacheDirectory + name + '.js'), function (err) {
if (err) throw err
fs.writeFile(settings.cacheDirectory + name + '.js', result, function (err) {
if (err) throw err
resolve(settings.cacheDirectory + name + '.js')
})
})
})
})
})
}
return promises[name].then(function (path) {
var Template = require(path)
return Promise.resolve(function (content) {
return (new Template()).render(content)
})
})
}
}
|
Update watchers before adding widget | 'use strict';
angular.module('Teem')
.factory('needWidget', [
'$compile', '$timeout',
function($compile, $timeout) {
var editor, scope;
function init (e, s) {
editor = e;
scope = s;
editor.registerWidget('need', {
onInit: function(parent, needId) {
var element = angular.element(document.createElement('need-widget')),
compiled = $compile(element)(scope),
need = scope.project.findNeed(needId),
stopEvents = ['keypress', 'keyup', 'keydown'],
isolateScope;
function stopEvent (e) { e.stopPropagation(); }
stopEvents.forEach(function (eventName) {
parent.addEventListener(eventName, stopEvent);
});
$timeout(function() {
isolateScope = element.isolateScope();
isolateScope.project = scope.project;
isolateScope.need = need;
});
angular.element(parent).append(compiled);
}
});
}
function add () {
var need = {
text: ''
};
scope.project.addNeed(need);
$timeout(() => {
editor.addWidget('need', need._id);
});
$timeout(() => {
var textarea = document.querySelector('.need-form-' + need._id + ' textarea');
if (textarea) {
textarea.focus();
}
}, 500);
}
return {
init,
add
};
}]);
| 'use strict';
angular.module('Teem')
.factory('needWidget', [
'$compile', '$timeout',
function($compile, $timeout) {
var editor, scope;
function init (e, s) {
editor = e;
scope = s;
editor.registerWidget('need', {
onInit: function(parent, needId) {
var element = angular.element(document.createElement('need-widget')),
compiled = $compile(element)(scope),
need = scope.project.findNeed(needId),
stopEvents = ['keypress', 'keyup', 'keydown'],
isolateScope;
function stopEvent (e) { e.stopPropagation(); }
stopEvents.forEach(function (eventName) {
parent.addEventListener(eventName, stopEvent);
});
$timeout(function() {
isolateScope = element.isolateScope();
isolateScope.project = scope.project;
isolateScope.need = need;
});
angular.element(parent).append(compiled);
}
});
}
function add () {
var need = {
text: ''
};
scope.project.addNeed(need);
editor.addWidget('need', need._id);
$timeout(() => {
var textarea = document.querySelector('.need-form-' + need._id + ' textarea');
if (textarea) {
textarea.focus();
}
}, 500);
}
return {
init,
add
};
}]);
|
Change MENU to new loader format | define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(item) {
return item.getBytes().then(function(bytes) {
var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
var dataObject = {
id: dv.getUint16(0, false),
definitionProcedureResourceID: dv.getUint16(6, false),
enabledState: dv.getUint32(10, false),
title: macintoshRoman(bytes, 15, bytes[14]),
};
var pos = 15 + bytes[14];
if (dataObject.definitionProcedureResourceID === 0) {
delete dataObject.definitionProcedureResourceID;
dataObject.items = [];
while (pos < bytes.length && bytes[pos] !== 0) {
var text = macintoshRoman(bytes, pos + 1, bytes[pos]);
pos += 1 + text.length;
var item = {
text: text,
iconNumberOrScriptCode: bytes[pos],
keyboardEquivalent: bytes[pos + 1],
markingCharacterOrSubmenuID: bytes[pos + 2],
style: bytes[pos + 3],
};
dataObject.items.push(item);
pos += 4;
}
}
else {
dataObject.itemData = atob(String.fromCharCode.apply(null, bytes.subarray(pos)));
}
item.setDataObject(dataObject);
});
};
});
| define(['mac/roman'], function(macintoshRoman) {
'use strict';
return function(resource) {
var dv = new DataView(resource.data.buffer, resource.data.byteOffset, resource.data.byteLength);
resource.dataObject = {
id: dv.getUint16(0, false),
definitionProcedureResourceID: dv.getUint16(6, false),
enabledState: dv.getUint32(10, false),
title: macintoshRoman(resource.data, 15, resource.data[14]),
};
var pos = 15 + resource.data[14];
if (resource.dataObject.definitionProcedureResourceID === 0) {
delete resource.dataObject.definitionProcedureResourceID;
resource.dataObject.items = [];
while (pos < resource.data.length && resource.data[pos] !== 0) {
var text = macintoshRoman(resource.data, pos + 1, resource.data[pos]);
pos += 1 + text.length;
var item = {
text: text,
iconNumberOrScriptCode: resource.data[pos],
keyboardEquivalent: resource.data[pos + 1],
markingCharacterOrSubmenuID: resource.data[pos + 2],
style: resource.data[pos + 3],
};
resource.dataObject.items.push(item);
pos += 4;
}
}
else {
resource.dataObject.itemData = atob(String.fromCharCode.apply(null, resource.data.subarray(pos)));
}
};
});
|
Make the GSample field protected for use by sub classes | package ganglia;
import ganglia.gmetric.GMetricSlope;
import ganglia.gmetric.GMetricType;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
public abstract class GSampler implements Runnable {
private static Logger log =
Logger.getLogger(GSampler.class.getName());
/*
* The internal data structure is a hashmap of key=mbean name
*/
private int delay;
private int initialDelay;
private Publisher publisher = null;
protected String process = null ;
/**
* Creates a GSampler
* @param delay the sample interval in seconds
* @param process the process name that is appended to metrics
*/
public GSampler(int initialDelay, int delay, String process ) {
this.initialDelay = initialDelay ;
this.delay = delay;
this.process = process;
}
/**
* Returns the sample interval
* @return the sample interval in seconds
*/
public int getDelay() {
return delay;
}
/**
* Returns the initial delay before sampling begins
* @return the delay in seconds
*/
public int getInitialDelay() {
return initialDelay;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
}
| package ganglia;
import ganglia.gmetric.GMetricSlope;
import ganglia.gmetric.GMetricType;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
public abstract class GSampler implements Runnable {
private static Logger log =
Logger.getLogger(GSampler.class.getName());
/*
* The internal data structure is a hashmap of key=mbean name
*/
private int delay;
private int initialDelay;
private Publisher publisher = null;
private String process = null ;
/**
* Creates a GSampler
* @param delay the sample interval in seconds
* @param process the process name that is appended to metrics
*/
public GSampler(int initialDelay, int delay, String process ) {
this.initialDelay = initialDelay ;
this.delay = delay;
this.process = process;
}
/**
* Returns the sample interval
* @return the sample interval in seconds
*/
public int getDelay() {
return delay;
}
/**
* Returns the initial delay before sampling begins
* @return the delay in seconds
*/
public int getInitialDelay() {
return initialDelay;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
}
|
Add helper for home page content | var fs, path, markdown;
fs = require('fs');
path = require("path");
markdown = require( "markdown" ).markdown;
module.exports = {
publicClasses: function(context, options) {
'use strict';
var ret = "";
for(var i=0; i < context.length; i++) {
if(!context[i].itemtype && context[i].access === 'public') {
ret = ret + options.fn(context[i]);
} else if (context[i].itemtype) {
ret = ret + options.fn(context[i]);
}
}
return ret;
},
search : function(classes, modules) {
'use strict';
var ret = '';
for(var i=0; i < classes.length; i++) {
if(i > 0) {
ret += ', ';
}
ret += "\"" + 'classes/' + classes[i].displayName + "\"";
}
if(ret.length > 0 && modules.length > 0) {
ret += ', ';
}
for(var j=0; j < modules.length; j++) {
if(j > 0) {
ret += ', ';
}
ret += "\"" + 'modules/' + modules[j].displayName + "\"";
}
return ret;
},
homeContent : function () {
var config = path.join(process.cwd(), 'yuidoc');
if (fs.existsSync(config + '.json') === true) {
config = require(config);
}
var content = config.theme.home
if (typeof content === 'string' && content !== '') {
content = path.join(process.cwd(), content);
} else {
content = path.join(process.cwd(), 'README.md');
}
if (fs.existsSync(content) === true) {
content = fs.readFileSync(content, {encoding: "utf8"});
content = markdown.toHTML(content);
} else {
content = '';
}
return content;
}
};
| fs = require('fs');
module.exports = {
publicClasses: function(context, options) {
'use strict';
var ret = "";
for(var i=0; i < context.length; i++) {
if(!context[i].itemtype && context[i].access === 'public') {
ret = ret + options.fn(context[i]);
} else if (context[i].itemtype) {
ret = ret + options.fn(context[i]);
}
}
return ret;
},
search : function(classes, modules) {
'use strict';
var ret = '';
for(var i=0; i < classes.length; i++) {
if(i > 0) {
ret += ', ';
}
ret += "\"" + 'classes/' + classes[i].displayName + "\"";
}
if(ret.length > 0 && modules.length > 0) {
ret += ', ';
}
for(var j=0; j < modules.length; j++) {
if(j > 0) {
ret += ', ';
}
ret += "\"" + 'modules/' + modules[j].displayName + "\"";
}
return ret;
}
};
|
Clear proxy dir before generating new proxies | <?php
namespace Isolate\Symfony\IsolateBundle\Command;
use Isolate\LazyObjects\Proxy\Adapter\OcramiusProxyManager\Factory\LazyObjectsFactory;
use Isolate\LazyObjects\Proxy\Definition;
use Isolate\Symfony\IsolateBundle\LazyObject\DefinitionCollection;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
class GenerateLazyObjectProxyCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('isolate:lazy-objects:generate:proxies')
->setDescription('Generate proxy classes for Isolate lazy objects.')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/* @var DefinitionCollection $lazyObjectDefinitions */
/* @var LazyObjectsFactory $factory */
/* @var Definition $definition */
$lazyObjectDefinitions = $this->getContainer()->get('isolate.lazy_objects.definition.collection');
$factory = $this->getContainer()->get('isolate.lazy_objects.wrapper.proxy.adapter.factory');
$proxyDir = $this->getContainer()->getParameter('isolate.lazy_objects.proxy_dir');
$fs = new Filesystem();
$fs->remove($proxyDir);
$fs->mkdir($proxyDir);
foreach ($lazyObjectDefinitions as $definition) {
$factory->createProxyClass((string) $definition->getClassName());
$output->writeln(PHP_EOL . sprintf('<fg=green>Proxy class generated for "%s"</fg=green>', (string) $definition->getClassName()));
}
}
}
| <?php
namespace Isolate\Symfony\IsolateBundle\Command;
use Isolate\LazyObjects\Proxy\Adapter\OcramiusProxyManager\Factory\LazyObjectsFactory;
use Isolate\LazyObjects\Proxy\Definition;
use Isolate\Symfony\IsolateBundle\LazyObject\DefinitionCollection;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class GenerateLazyObjectProxyCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('isolate:lazy-objects:generate:proxies')
->setDescription('Generate proxy classes for Isolate lazy objects.')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
/* @var DefinitionCollection $lazyObjectDefinitions */
/* @var LazyObjectsFactory $factory */
/* @var Definition $definition */
$lazyObjectDefinitions = $this->getContainer()->get('isolate.lazy_objects.definition.collection');
$factory = $this->getContainer()->get('isolate.lazy_objects.wrapper.proxy.adapter.factory');
foreach ($lazyObjectDefinitions as $definition) {
$factory->createProxyClass((string) $definition->getClassName());
$output->writeln(PHP_EOL . sprintf('<fg=green>Proxy class generated for "%s"</fg=green>', (string) $definition->getClassName()));
}
}
}
|
Apply upper to the argument value | """
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from typing import Callable, Optional
from ._null_logger import NullLogger
MODULE_NAME = "subprocrunner"
DEFAULT_ERROR_LOG_LEVEL = "WARNING"
try:
from loguru import logger
LOGURU_INSTALLED = True
logger.disable(MODULE_NAME)
except ImportError:
LOGURU_INSTALLED = False
logger = NullLogger() # type: ignore
def get_logging_method(log_level: Optional[str] = None) -> Callable:
if not LOGURU_INSTALLED:
return logger.debug
if log_level is None:
log_level = "DEBUG"
method_table = {
"QUIET": lambda _x: None,
"TRACE": logger.trace,
"DEBUG": logger.debug,
"INFO": logger.info,
"SUCCESS": logger.success,
"WARNING": logger.warning,
"ERROR": logger.error,
"CRITICAL": logger.critical,
}
method = method_table.get(log_level.upper())
if method is None:
raise ValueError("unknown log level: {}".format(log_level))
return method
def set_logger(is_enable: bool, propagation_depth: int = 1) -> None:
if is_enable:
logger.enable(MODULE_NAME)
else:
logger.disable(MODULE_NAME)
def set_log_level(log_level):
# deprecated
return
| """
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from typing import Callable, Optional
from ._null_logger import NullLogger
MODULE_NAME = "subprocrunner"
DEFAULT_ERROR_LOG_LEVEL = "WARNING"
try:
from loguru import logger
LOGURU_INSTALLED = True
logger.disable(MODULE_NAME)
except ImportError:
LOGURU_INSTALLED = False
logger = NullLogger() # type: ignore
def get_logging_method(log_level: Optional[str] = None) -> Callable:
if not LOGURU_INSTALLED:
return logger.debug
if log_level is None:
log_level = "DEBUG"
method_table = {
"QUIET": lambda _x: None,
"TRACE": logger.trace,
"DEBUG": logger.debug,
"INFO": logger.info,
"SUCCESS": logger.success,
"WARNING": logger.warning,
"ERROR": logger.error,
"CRITICAL": logger.critical,
}
method = method_table.get(log_level)
if method is None:
raise ValueError("unknown log level: {}".format(log_level))
return method
def set_logger(is_enable: bool, propagation_depth: int = 1) -> None:
if is_enable:
logger.enable(MODULE_NAME)
else:
logger.disable(MODULE_NAME)
def set_log_level(log_level):
# deprecated
return
|
Simplify webpack, unsuccessfull at fixing sourcemap output | const path = require('path');
const webpack = require('webpack');
const WebpackNotifierPlugin = require('webpack-notifier');
const styleLintPlugin = require('stylelint-webpack-plugin');
const env = process.env.NODE_ENV;
module.exports = {
devtool: env === 'production' ? 'source-map' : 'eval',
entry: './src',
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js',
},
plugins: env === 'production' ? [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
] : [
new styleLintPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new WebpackNotifierPlugin({ title: 'Next-gen Build' }),
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint' },
{ test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' },
],
},
};
| const path = require('path');
const webpack = require('webpack');
const WebpackNotifierPlugin = require('webpack-notifier');
const styleLintPlugin = require('stylelint-webpack-plugin');
const autoprefixer = require('autoprefixer');
const env = process.env.NODE_ENV;
module.exports = {
devtool: env === 'production' ? 'source-map' : 'eval',
entry: './src',
output: {
path: path.join(__dirname, 'dist'),
filename: 'app.js',
publicPath: '/',
},
plugins: env === 'production' ? [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
// dead_code: true,
},
}),
] : [
new styleLintPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new WebpackNotifierPlugin({ title: 'Next-gen Build' }),
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' },
{ test: /\.css$/, exclude: /node_modules/, loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]' },
{ test: /\.js$/, exclude: /node_modules/, loader: 'eslint' },
],
// noParse: /babel/,
},
postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ],
};
|
Fix path parsing when a bucket prefix is not specified
This allows the registry to be written to the root of a bucket and thus be accessible using S3's static website hosting feature | <?php
namespace Jalle19\VagrantRegistryGenerator\Configuration;
use Symfony\Component\Console\Input\InputInterface;
/**
* Class Parser
* @package Jalle19\VagrantRegistryGenerator\Configuration
*/
class Parser
{
/**
* @param InputInterface $input
*
* @return Configuration
*/
public static function parseConfiguration(InputInterface $input)
{
$configuration = new Configuration();
$outputPath = $input->getArgument('outputPath');
$configuration
->setRegistryPath($input->getArgument('registryPath'))
->setOutputPath($outputPath)
->setAwsAccessKey($input->getOption('awsAccessKey'))
->setAwsSecretKey($input->getOption('awsSecretKey'))
->setAwsRegion($input->getOption('awsRegion'));
if (Configuration::getFilesystemType($outputPath) === Configuration::FILESYSTEM_TYPE_LOCAL) {
// Convert to absolute path
if (substr($outputPath, 0, 1) !== '/') {
$configuration->setOutputPath(getcwd() . '/' . $outputPath);
}
}
return $configuration;
}
/**
* @param string $path
*
* @return array
*/
public static function parseBucketPrefix($path)
{
$url = parse_url($path);
$bucket = $url['host'];
$prefix = '';
// Prefix is optional
if (isset($url['path'])) {
$prefix = trim($url['path'], '/');
}
return [$bucket, $prefix];
}
}
| <?php
namespace Jalle19\VagrantRegistryGenerator\Configuration;
use Symfony\Component\Console\Input\InputInterface;
/**
* Class Parser
* @package Jalle19\VagrantRegistryGenerator\Configuration
*/
class Parser
{
/**
* @param InputInterface $input
*
* @return Configuration
*/
public static function parseConfiguration(InputInterface $input)
{
$configuration = new Configuration();
$outputPath = $input->getArgument('outputPath');
$configuration
->setRegistryPath($input->getArgument('registryPath'))
->setOutputPath($outputPath)
->setAwsAccessKey($input->getOption('awsAccessKey'))
->setAwsSecretKey($input->getOption('awsSecretKey'))
->setAwsRegion($input->getOption('awsRegion'));
if (Configuration::getFilesystemType($outputPath) === Configuration::FILESYSTEM_TYPE_LOCAL) {
// Convert to absolute path
if (substr($outputPath, 0, 1) !== '/') {
$configuration->setOutputPath(getcwd() . '/' . $outputPath);
}
}
return $configuration;
}
/**
* @param string $path
*
* @return array
*/
public static function parseBucketPrefix($path)
{
$url = parse_url($path);
$bucket = $url['host'];
$prefix = trim($url['path'], '/');
return [$bucket, $prefix];
}
}
|
Revert change for lower versions to still work. | <?php
namespace Ambta\DoctrineEncryptBundle\Encryptors;
use \ParagonIE\Halite\HiddenString;
use \ParagonIE\Halite\KeyFactory;
/**
* Class for encrypting and decrypting with the halite library
*
* @author Michael de Groot <[email protected]>
*/
class HaliteEncryptor implements EncryptorInterface
{
private $encryptionKey;
private $keyFile;
/**
* {@inheritdoc}
*/
public function __construct(string $keyFile)
{
$this->keyFile = $keyFile;
}
/**
* {@inheritdoc}
*/
public function encrypt($data)
{
return \ParagonIE\Halite\Symmetric\Crypto::encrypt(new HiddenString($data), $this->getKey());
}
/**
* {@inheritdoc}
*/
public function decrypt($data)
{
$data = \ParagonIE\Halite\Symmetric\Crypto::decrypt($data, $this->getKey());
if ($data instanceof HiddenString)
{
$data = $data->getString();
}
return $data;
}
private function getKey()
{
if ($this->encryptionKey === null) {
try {
$this->encryptionKey = \ParagonIE\Halite\KeyFactory::loadEncryptionKey($this->keyFile);
} catch (\ParagonIE\Halite\Alerts\CannotPerformOperation $e) {
$this->encryptionKey = KeyFactory::generateEncryptionKey();
\ParagonIE\Halite\KeyFactory::save($this->encryptionKey, $this->keyFile);
}
}
return $this->encryptionKey;
}
}
| <?php
namespace Ambta\DoctrineEncryptBundle\Encryptors;
use \ParagonIE\HiddenString\HiddenString;
use \ParagonIE\Halite\KeyFactory;
/**
* Class for encrypting and decrypting with the halite library
*
* @author Michael de Groot <[email protected]>
*/
class HaliteEncryptor implements EncryptorInterface
{
private $encryptionKey;
private $keyFile;
/**
* {@inheritdoc}
*/
public function __construct(string $keyFile)
{
$this->keyFile = $keyFile;
}
/**
* {@inheritdoc}
*/
public function encrypt($data)
{
return \ParagonIE\Halite\Symmetric\Crypto::encrypt(new HiddenString($data), $this->getKey());
}
/**
* {@inheritdoc}
*/
public function decrypt($data)
{
$data = \ParagonIE\Halite\Symmetric\Crypto::decrypt($data, $this->getKey());
if ($data instanceof HiddenString)
{
$data = $data->getString();
}
return $data;
}
private function getKey()
{
if ($this->encryptionKey === null) {
try {
$this->encryptionKey = \ParagonIE\Halite\KeyFactory::loadEncryptionKey($this->keyFile);
} catch (\ParagonIE\Halite\Alerts\CannotPerformOperation $e) {
$this->encryptionKey = KeyFactory::generateEncryptionKey();
\ParagonIE\Halite\KeyFactory::save($this->encryptionKey, $this->keyFile);
}
}
return $this->encryptionKey;
}
}
|
Fix requests-mock version requirement (>=1.2.0) | #!/usr/bin/env python
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='mock-services',
version=open(os.path.join(here, 'VERSION')).read().strip(),
description='Mock services.',
long_description=open(os.path.join(here, 'README.rst')).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords=[
'http',
'mock',
'requests',
'rest',
],
author='Florent Pigout',
author_email='[email protected]',
url='https://github.com/novafloss/mock-services',
license='MIT',
install_requires=[
'attrs',
'funcsigs',
'requests-mock>=1.2.0',
],
extras_require={
'test': [
'flake8'
],
'release': [
'wheel',
'zest.releaser'
],
},
packages=[
'mock_services'
],
)
| #!/usr/bin/env python
import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='mock-services',
version=open(os.path.join(here, 'VERSION')).read().strip(),
description='Mock services.',
long_description=open(os.path.join(here, 'README.rst')).read(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords=[
'http',
'mock',
'requests',
'rest',
],
author='Florent Pigout',
author_email='[email protected]',
url='https://github.com/novafloss/mock-services',
license='MIT',
install_requires=[
'attrs',
'funcsigs',
'requests-mock<2.0.0',
],
extras_require={
'test': [
'flake8'
],
'release': [
'wheel',
'zest.releaser'
],
},
packages=[
'mock_services'
],
)
|
Switch to normal pox instead of betta | from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controller
command_line = ('''./pox.py --verbose sts.syncproto.pox_syncer '''
'''openflow.discovery forwarding.l2_multi '''
'''sts.util.socket_mux.pox_monkeypatcher '''
'''openflow.of_01 --address=__address__ --port=__port__''')
controllers = [ControllerConfig(command_line, cwd="pox", sync="tcp:localhost:18899")]
topology_class = MeshTopology
topology_params = "num_switches=2"
dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace"
simulation_config = SimulationConfig(controller_configs=controllers,
topology_class=topology_class,
topology_params=topology_params,
dataplane_trace=dataplane_trace,
multiplex_sockets=True)
control_flow = Fuzzer(simulation_config, check_interval=80,
halt_on_violation=False,
input_logger=InputLogger(),
invariant_check=InvariantChecker.check_loops)
#control_flow = Interactive(simulation_config, input_logger=InputLogger())
| from experiment_config_lib import ControllerConfig
from sts.topology import MeshTopology
from sts.control_flow import Fuzzer, Interactive
from sts.input_traces.input_logger import InputLogger
from sts.invariant_checker import InvariantChecker
from sts.simulation_state import SimulationConfig
# Use POX as our controller
command_line = ('''./pox.py --verbose openflow.debug ''' #sts.syncproto.pox_syncer '''
'''forwarding.l2_multi '''
#'''sts.util.socket_mux.pox_monkeypatcher '''
'''openflow.of_01 --address=__address__ --port=__port__''')
controllers = [ControllerConfig(command_line, cwd="betta")]
topology_class = MeshTopology
topology_params = "num_switches=2"
dataplane_trace = "dataplane_traces/ping_pong_same_subnet.trace"
simulation_config = SimulationConfig(controller_configs=controllers,
topology_class=topology_class,
topology_params=topology_params,
dataplane_trace=dataplane_trace,
multiplex_sockets=False)
control_flow = Fuzzer(simulation_config, check_interval=80,
halt_on_violation=False,
input_logger=InputLogger(),
invariant_check=InvariantChecker.check_connectivity)
#control_flow = Interactive(simulation_config, input_logger=InputLogger())
|
Adjust test for returned name | from common import *
class TestBasicCreate(TestCase):
def test_create_default_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
spec = dict(name=mini_uuid())
proj = sg.create(type_, spec)
print proj
self.assertIsNot(spec, proj)
self.assertEqual(len(proj), 3)
self.assertEqual(proj['type'], type_)
self.assertEqual(proj['name'], spec['name'])
self.assert_(proj['id'])
def test_create_additional_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
name = mini_uuid()
proj = sg.create(type_, dict(name=name), ['name'])
self.assertEqual(len(proj), 3)
self.assertEqual(proj['type'], type_)
self.assert_(proj['id'])
self.assertEqual(proj['name'], name)
def test_create_missing_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
name = mini_uuid()
proj = sg.create(type_, dict(name=name), ['name', 'does_not_exist'])
self.assertEqual(len(proj), 3)
self.assertEqual(proj['type'], type_)
self.assert_(proj['id'])
self.assertEqual(proj['name'], name)
| from common import *
class TestBasicCreate(TestCase):
def test_create_default_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
spec = dict(name=mini_uuid())
proj = sg.create(type_, spec)
self.assertIsNot(spec, proj)
self.assertEqual(len(proj), 2)
self.assertEqual(proj['type'], type_)
self.assert_(proj['id'])
def test_create_additional_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
name = mini_uuid()
proj = sg.create(type_, dict(name=name), ['name'])
self.assertEqual(len(proj), 3)
self.assertEqual(proj['type'], type_)
self.assert_(proj['id'])
self.assertEqual(proj['name'], name)
def test_create_missing_return(self):
sg = Shotgun()
type_ = 'Dummy' + mini_uuid().upper()
name = mini_uuid()
proj = sg.create(type_, dict(name=name), ['name', 'does_not_exist'])
self.assertEqual(len(proj), 3)
self.assertEqual(proj['type'], type_)
self.assert_(proj['id'])
self.assertEqual(proj['name'], name)
|
Fix bug in previous comit. |
/*
* Copyright (C) 2012 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.pobj;
import java.util.Set;
import javax.validation.ConstraintViolation;
/**
* Runtime exception thrown during {@link PersistentObject} operations.
*/
@SuppressWarnings("serial")
public class PersistentObjectValidationException extends PersistentObjectException {
private final Set<ConstraintViolation<?>> violations;
/**
* Constructor.
*
* @param violations set of violations
* @throws IllegalArgumentException if {@code violations} is null
*/
public PersistentObjectValidationException(Set<ConstraintViolation<?>> violations) {
super(PersistentObjectValidationException.generateMessage(violations));
this.violations = violations;
}
/**
* Get the set of constraint violations.
*/
public Set<ConstraintViolation<?>> getViolations() {
return this.violations;
}
private static String generateMessage(Set<ConstraintViolation<?>> violations) {
if (violations == null)
throw new IllegalArgumentException("null violations");
StringBuilder buf = new StringBuilder("object failed to validate with " + violations.size() + " violation(s): ");
boolean first = true;
for (ConstraintViolation<?> violation : violations) {
if (first)
first = false;
else
buf.append("; ");
buf.append("[" + violation.getPropertyPath() + "]: " + violation.getMessage());
}
return buf.toString();
}
}
|
/*
* Copyright (C) 2012 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.pobj;
import java.util.Set;
import javax.validation.ConstraintViolation;
/**
* Runtime exception thrown during {@link PersistentObject} operations.
*/
@SuppressWarnings("serial")
public class PersistentObjectValidationException extends PersistentObjectException {
private final Set<ConstraintViolation<?>> violations;
/**
* Constructor.
*
* @param violations set of violations
* @throws IllegalArgumentException if {@code violations} is null
*/
public PersistentObjectValidationException(Set<ConstraintViolation<?>> violations) {
this.violations = violations;
}
/**
* Get the set of constraint violations.
*/
public Set<ConstraintViolation<?>> getViolations() {
return this.violations;
}
private static String generateMessage(Set<ConstraintViolation<?>> violations) {
if (violations == null)
throw new IllegalArgumentException("null violations");
StringBuilder buf = new StringBuilder("object failed to validate with " + violations.size() + " violation(s): ");
boolean first = true;
for (ConstraintViolation<?> violation : violations) {
if (first)
first = false;
else
buf.append("; ");
buf.append("[" + violation.getPropertyPath() + "]: " + violation.getMessage());
}
return buf.toString();
}
}
|
Remove ending '.' in hostname. (for those fucking libs that knows nothing about RFC) | import dns.resolver
import dns.query
from dns.exception import DNSException
# Resolve service from mesos-dns SRV record
# return dict {"servicename": [{"name": "service.f.q.d.n.", "port": 9999}]}
def resolve(app, conf):
hosts = {}
services = app['services']
domain = conf['domain']
group = None
if app['env'].get('SUROK_DISCOVERY_GROUP') is not None:
group = app['env']['SUROK_DISCOVERY_GROUP']
for service in services:
hosts[service['name']] = []
# Check group configuration
if group is not None:
pass
else:
# Load group from service config
# /etc/surok/conf.d/service_conf.json
group = service['group']
fqdn = '_' + service['name'] + '.' + group + '._tcp.' + domain
hosts[service['name']] = do_query(fqdn)
return hosts
# Do SRV queries
# Return array: [{"name": "f.q.d.n", "port": 8876}]
def do_query(fqdn):
servers = []
try:
query = dns.resolver.query(fqdn, 'SRV')
query.lifetime = 1.0
for rdata in query:
info = str(rdata).split()
server = {'name': info[3][:-1], 'port': info[2]}
servers.append(server)
except DNSException:
print("Could not resolve " + fqdn)
return servers
| import dns.resolver
import dns.query
from dns.exception import DNSException
# Resolve service from mesos-dns SRV record
# return dict {"servicename": [{"name": "service.f.q.d.n.", "port": 9999}]}
def resolve(app, conf):
hosts = {}
services = app['services']
domain = conf['domain']
group = None
if app['env'].get('SUROK_DISCOVERY_GROUP') is not None:
group = app['env']['SUROK_DISCOVERY_GROUP']
for service in services:
hosts[service['name']] = []
# Check group configuration
if group is not None:
pass
else:
# Load group from service config
# /etc/surok/conf.d/service_conf.json
group = service['group']
fqdn = '_' + service['name'] + '.' + group + '._tcp.' + domain
hosts[service['name']] = do_query(fqdn)
return hosts
# Do SRV queries
# Return array: [{"name": "f.q.d.n", "port": 8876}]
def do_query(fqdn):
servers = []
try:
query = dns.resolver.query(fqdn, 'SRV')
query.lifetime = 1.0
for rdata in query:
info = str(rdata).split()
server = {'name': info[3], 'port': info[2]}
servers.append(server)
except DNSException:
print("Could not resolve " + fqdn)
return servers
|
Fix checking correct component class | <?php
class Kwc_Directories_TopChoose_Component extends Kwc_Directories_Top_Component
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['showDirectoryClass'] = 'Kwc_Directories_Item_Directory_Component'; // nur für form
$ret['ownModel'] = 'Kwc_Directories_TopChoose_Model';
$ret['extConfig'] = 'Kwf_Component_Abstract_ExtConfig_Form';
return $ret;
}
public static function getItemDirectoryClasses($directoryClass)
{
$ret = array();
$class = self::getSetting($directoryClass, 'showDirectoryClass');
foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($class) as $component) {
$ret[] = $component->componentClass;
}
return $ret;
}
protected function _getItemDirectory()
{
$row = $this->_getRow();
if ($row && $row->directory_component_id) {
$component = Kwf_Component_Data_Root::getInstance()
->getComponentByDbId($row->directory_component_id);
if (is_instance_of($component->componentClass, 'Kwc_Directories_Item_DirectoryNoAdmin_Component')) {
return $component;
}
}
return null;
}
}
| <?php
class Kwc_Directories_TopChoose_Component extends Kwc_Directories_Top_Component
{
public static function getSettings()
{
$ret = parent::getSettings();
$ret['showDirectoryClass'] = 'Kwc_Directories_Item_Directory_Component'; // nur für form
$ret['ownModel'] = 'Kwc_Directories_TopChoose_Model';
$ret['extConfig'] = 'Kwf_Component_Abstract_ExtConfig_Form';
return $ret;
}
public static function getItemDirectoryClasses($directoryClass)
{
$ret = array();
$class = self::getSetting($directoryClass, 'showDirectoryClass');
foreach (Kwf_Component_Data_Root::getInstance()->getComponentsByClass($class) as $component) {
$ret[] = $component->componentClass;
}
return $ret;
}
protected function _getItemDirectory()
{
$row = $this->_getRow();
if ($row && $row->directory_component_id) {
$component = Kwf_Component_Data_Root::getInstance()
->getComponentByDbId($row->directory_component_id);
if (is_instance_of($component, 'Kwc_Directories_Item_DirectoryNoAdmin_Component')) {
return $component;
}
}
return null;
}
}
|
Remove unnecessary u on string | import argparse
import sys
from pipreq.command import Command
def create_parser():
parser = argparse.ArgumentParser(
description='Manage Python package requirements across multiple environments using '
'per-environment requirements files.')
parser.add_argument('-g', '--generate', action='store_true', default=False,
help='Generate requirements files')
parser.add_argument('-c', '--create', action='store_true', default=False,
help='Create or update rc file (requires list of packages)')
parser.add_argument('-U', '--upgrade', action='store_true', default=False,
help='Upgrade packages (requires list of packages)')
parser.add_argument('packages', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
return parser
def verify_args(args):
if not args.create and not args.generate and not args.upgrade:
return 'Must specify generate (-g) or create/upgrade (-[cu]) with packages'
return None
def error(parser, message):
parser.print_help()
parser.exit(message="\nERROR: %s\n" % message)
def main():
try:
parser = create_parser()
parsed_args = parser.parse_args()
error_message = verify_args(parsed_args)
if error_message:
error(parser, error_message)
command = Command(parsed_args, ".requirementsrc")
command.run()
except KeyboardInterrupt:
sys.exit()
| import argparse
import sys
from pipreq.command import Command
def create_parser():
parser = argparse.ArgumentParser(
description='Manage Python package requirements across multiple environments using '
'per-environment requirements files.')
parser.add_argument('-g', '--generate', action='store_true', default=False,
help='Generate requirements files')
parser.add_argument('-c', '--create', action='store_true', default=False,
help='Create or update rc file (requires list of packages)')
parser.add_argument('-U', '--upgrade', action='store_true', default=False,
help='Upgrade packages (requires list of packages)')
parser.add_argument('packages', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
return parser
def verify_args(args):
if not args.create and not args.generate and not args.upgrade:
return u'Must specify generate (-g) or create/upgrade (-[cu]) with packages'
return None
def error(parser, message):
parser.print_help()
parser.exit(message="\nERROR: %s\n" % message)
def main():
try:
parser = create_parser()
parsed_args = parser.parse_args()
error_message = verify_args(parsed_args)
if error_message:
error(parser, error_message)
command = Command(parsed_args, ".requirementsrc")
command.run()
except KeyboardInterrupt:
sys.exit()
|
Support accessing a long value after being closed for graceful shutdown | /*
* Copyright 2016-2020 Chronicle Software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.core.values;
public interface LongValue {
long getValue();
void setValue(long value);
long getVolatileValue();
default long getVolatileValue(long closedValue) {
return getVolatileValue();
}
void setVolatileValue(long value);
void setOrderedValue(long value);
long addValue(long delta);
long addAtomicValue(long delta);
boolean compareAndSwapValue(long expected, long value);
default void setMaxValue(long value) {
for (; ; ) {
long pos = getVolatileValue();
if (pos >= value)
break;
if (compareAndSwapValue(pos, value))
break;
}
}
default void setMinValue(long value) {
for (; ; ) {
long pos = getVolatileValue();
if (pos <= value)
break;
if (compareAndSwapValue(pos, value))
break;
}
}
}
| /*
* Copyright 2016-2020 Chronicle Software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.core.values;
public interface LongValue {
long getValue();
void setValue(long value);
long getVolatileValue();
void setVolatileValue(long value);
void setOrderedValue(long value);
long addValue(long delta);
long addAtomicValue(long delta);
boolean compareAndSwapValue(long expected, long value);
default void setMaxValue(long value) {
for (; ; ) {
long pos = getVolatileValue();
if (pos >= value)
break;
if (compareAndSwapValue(pos, value))
break;
}
}
default void setMinValue(long value) {
for (; ; ) {
long pos = getVolatileValue();
if (pos <= value)
break;
if (compareAndSwapValue(pos, value))
break;
}
}
}
|
Use INTL_IDNA_VARIANT_UTS46 instead of INTL_IDNA_VARIANT_2003 | <?php
/**
* @author AIZAWA Hina <[email protected]>
* @copyright 2015-2019 by AIZAWA Hina <[email protected]>
* @license https://github.com/fetus-hina/yii2-extra-validator/blob/master/LICENSE MIT
* @since 1.0.1
*/
namespace jp3cki\yii2\validators;
use yii\validators\FilterValidator;
use function idn_to_ascii;
use const INTL_IDNA_VARIANT_UTS46;
/**
* The filter validator which converts IDN to Punycoded domain name
*/
class IdnToPunycodeFilterValidator extends FilterValidator
{
/** @inheritdoc */
public function init()
{
$this->filter = function (string $value): string {
if (strpos($value, '/') === false) {
return strtolower(static::idnToAscii($value));
}
if (strpos($value, '//') !== false) {
return preg_replace_callback(
'!(?<=//)([^/:]+)!',
function (array $match): string {
return strtolower(static::idnToAscii($match[1]));
},
$value,
1
);
}
return preg_replace_callback(
'!^([^/:]+)!',
function (array $match): string {
return strtolower(static::idnToAscii($match[1]));
},
$value,
1
);
};
parent::init();
}
protected static function idnToAscii(string $value): string
{
return idn_to_ascii($value, 0, INTL_IDNA_VARIANT_UTS46);
}
}
| <?php
/**
* @author AIZAWA Hina <[email protected]>
* @copyright 2015-2019 by AIZAWA Hina <[email protected]>
* @license https://github.com/fetus-hina/yii2-extra-validator/blob/master/LICENSE MIT
* @since 1.0.1
*/
namespace jp3cki\yii2\validators;
use yii\validators\FilterValidator;
/**
* The filter validator which converts IDN to Punycoded domain name
*/
class IdnToPunycodeFilterValidator extends FilterValidator
{
/** @inheritdoc */
public function init()
{
$this->filter = function ($value) {
if (strpos($value, '/') === false) {
return strtolower(idn_to_ascii($value));
}
if (strpos($value, '//') !== false) {
return preg_replace_callback(
'!(?<=//)([^/:]+)!',
function ($match) {
return strtolower(idn_to_ascii($match[1]));
},
$value,
1
);
}
return preg_replace_callback(
'!^([^/:]+)!',
function ($match) {
return strtolower(idn_to_ascii($match[1]));
},
$value,
1
);
};
parent::init();
}
}
|
Fix test for inline toolbar | import React, { Component } from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import Toolbar from '../index';
describe('Toolbar', () => {
it('allows children to override the content', (done) => {
const structure = [class Child extends Component {
componentDidMount() {
setTimeout(() => {
this.props.onOverrideContent(() => {
setTimeout(() => {
this.props.onOverrideContent(undefined);
});
return <span className="overridden" />;
});
});
}
render() {
return <span className="initial" />;
}
}];
const theme = { toolbarStyles: {} };
const store = {
subscribeToItem() {},
unsubscribeFromItem() {},
getItem: (name) => ({
getEditorState: () => ({
getSelection: () => ({ isCollapsed: () => true, getHasFocus: () => true })
})
}[name])
};
const wrapper = mount(
<Toolbar
store={store}
theme={theme}
structure={structure}
/>
);
expect(wrapper.find('.initial').length).to.equal(1);
setTimeout(() => {
expect(wrapper.find('.initial').length).to.equal(0);
expect(wrapper.find('.overridden').length).to.equal(1);
setTimeout(() => {
expect(wrapper.find('.initial').length).to.equal(1);
expect(wrapper.find('.overridden').length).to.equal(0);
done();
});
});
});
});
| import React, { Component } from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import Toolbar from '../index';
describe('Toolbar', () => {
it('allows children to override the content', (done) => {
const structure = [class Child extends Component {
componentDidMount() {
setTimeout(() => {
this.props.onOverrideContent(() => {
setTimeout(() => {
this.props.onOverrideContent(undefined);
});
return <span className="overridden" />;
});
});
}
render() {
return <span className="initial" />;
}
}];
const theme = { toolbarStyles: {} };
const store = {
subscribeToItem() {},
unsubscribeFromItem() {},
getItem: (name) => ({
getEditorState: () => ({
getSelection: () => ({ isCollapsed: () => true })
})
}[name])
};
const wrapper = mount(
<Toolbar
store={store}
theme={theme}
structure={structure}
/>
);
expect(wrapper.find('.initial').length).to.equal(1);
setTimeout(() => {
expect(wrapper.find('.initial').length).to.equal(0);
expect(wrapper.find('.overridden').length).to.equal(1);
setTimeout(() => {
expect(wrapper.find('.initial').length).to.equal(1);
expect(wrapper.find('.overridden').length).to.equal(0);
done();
});
});
});
});
|
Fix share via email link
Former-commit-id: cef1ba1359496c484c06881a6593952d514cab96 | <?php
namespace Concrete\Core\Sharing\ShareThisPage;
use Concrete\Core\Sharing\SocialNetwork\Service as SocialNetworkService;
use Config;
class Service extends SocialNetworkService
{
public static function getByHandle($ssHandle)
{
$services = ServiceList::get();
foreach($services as $s) {
if ($s->getHandle() == $ssHandle) {
return $s;
}
}
}
public function getServiceLink()
{
$c = \Page::getCurrentPage();
if (is_object($c) && !$c->isError()) {
$url = urlencode($c->getCollectionLink(true));
switch($this->getHandle()) {
case 'facebook':
return "https://www.facebook.com/sharer/sharer.php?u=$url";
case 'twitter':
return "https://www.twitter.com/intent/tweet?url=$url";
case 'linkedin':
$title = urlencode($c->getCollectionName());
return "https://www.linkedin.com/shareArticle?mini-true&url={$url}&title={$title}";
case 'reddit':
return "https://www.reddit.com/submit?url={$url}";
case 'email':
$body = rawurlencode(t("Check out this article on %s:\n\n%s\n%s", Config::get('concrete.site'), $c->getCollectionName(), urldecode($url)));
$subject = rawurlencode(t('Thought you\'d enjoy this article.'));
return "mailto:?body={$body}&subject={$subject}";
}
}
}
} | <?php
namespace Concrete\Core\Sharing\ShareThisPage;
use Concrete\Core\Sharing\SocialNetwork\Service as SocialNetworkService;
class Service extends SocialNetworkService
{
public static function getByHandle($ssHandle)
{
$services = ServiceList::get();
foreach($services as $s) {
if ($s->getHandle() == $ssHandle) {
return $s;
}
}
}
public function getServiceLink()
{
$c = \Page::getCurrentPage();
if (is_object($c) && !$c->isError()) {
$url = urlencode($c->getCollectionLink(true));
switch($this->getHandle()) {
case 'facebook':
return "https://www.facebook.com/sharer/sharer.php?u=$url";
case 'twitter':
return "https://www.twitter.com/intent/tweet?url=$url";
case 'linkedin':
$title = urlencode($c->getCollectionName());
return "https://www.linkedin.com/shareArticle?mini-true&url={$url}&title={$title}";
case 'reddit':
return "https://www.reddit.com/submit?url={$url}";
case 'email':
$body = urlencode(t("Check out this article on %s:\n\n%s\n%s", SITE, $title, urldecode($url)));
$subject = urlencode(t('Thought you\'d enjoy this article.'));
return "mailto:?body={$body}&subject={$subject}";
}
}
}
} |
Add MPD_SERVER_PASSWORD to list of relevant frontend settings | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
The MPD frontend.
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
- :attr:`mopidy.settings.MPD_SERVER_PASSWORD`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
def __init__(self, *args, **kwargs):
super(MpdFrontend, self).__init__(*args, **kwargs)
self.thread = None
self.dispatcher = MpdDispatcher(self.backend)
def start(self):
"""Starts the MPD server."""
self.thread = MpdThread(self.core_queue)
self.thread.start()
def destroy(self):
"""Destroys the MPD server."""
self.thread.destroy()
def process_message(self, message):
"""
Processes messages with the MPD frontend as destination.
:param message: the message
:type message: dict
"""
assert message['to'] == 'frontend', \
u'Message recipient must be "frontend".'
if message['command'] == 'mpd_request':
response = self.dispatcher.handle_request(message['request'])
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
pass # Ignore messages for other frontends
| import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.thread import MpdThread
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
The MPD frontend.
**Settings:**
- :attr:`mopidy.settings.MPD_SERVER_HOSTNAME`
- :attr:`mopidy.settings.MPD_SERVER_PORT`
"""
def __init__(self, *args, **kwargs):
super(MpdFrontend, self).__init__(*args, **kwargs)
self.thread = None
self.dispatcher = MpdDispatcher(self.backend)
def start(self):
"""Starts the MPD server."""
self.thread = MpdThread(self.core_queue)
self.thread.start()
def destroy(self):
"""Destroys the MPD server."""
self.thread.destroy()
def process_message(self, message):
"""
Processes messages with the MPD frontend as destination.
:param message: the message
:type message: dict
"""
assert message['to'] == 'frontend', \
u'Message recipient must be "frontend".'
if message['command'] == 'mpd_request':
response = self.dispatcher.handle_request(message['request'])
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
pass # Ignore messages for other frontends
|
Add the last line to the info message | from collections import defaultdict
from logging import getLogger
from pip._vendor.resolvelib.reporters import BaseReporter
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import DefaultDict
from .base import Candidate
logger = getLogger(__name__)
class PipReporter(BaseReporter):
def __init__(self):
# type: () -> None
self.backtracks_by_package = defaultdict(int) # type: DefaultDict[str, int]
self._messages_at_backtrack = {
1: (
"pip is looking at multiple versions of this package to determine "
"which version is compatible with other requirements. "
"This could take a while."
),
8: (
"pip is looking at multiple versions of this package to determine "
"which version is compatible with other requirements. "
"This could take a while."
),
13: (
"This is taking longer than usual. You might need to provide the "
"dependency resolver with stricter constraints to reduce runtime."
"If you want to abort this run, you can press Ctrl + C to do so."
"To improve how pip performs, tell us that this happened here: "
"https://pip.pypa.io/surveys/backtracking"
)
}
def backtracking(self, candidate):
# type: (Candidate) -> None
self.backtracks_by_package[candidate.name] += 1
count = self.backtracks_by_package[candidate.name]
if count not in self._messages_at_backtrack:
return
message = self._messages_at_backtrack[count]
logger.info("INFO: %s", message)
| from collections import defaultdict
from logging import getLogger
from pip._vendor.resolvelib.reporters import BaseReporter
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import DefaultDict
from .base import Candidate
logger = getLogger(__name__)
class PipReporter(BaseReporter):
def __init__(self):
# type: () -> None
self.backtracks_by_package = defaultdict(int) # type: DefaultDict[str, int]
self._messages_at_backtrack = {
1: (
"pip is looking at multiple versions of this package to determine "
"which version is compatible with other requirements. "
"This could take a while."
),
8: (
"pip is looking at multiple versions of this package to determine "
"which version is compatible with other requirements. "
"This could take a while."
),
13: (
"This is taking longer than usual. You might need to provide the "
"dependency resolver with stricter constraints to reduce runtime."
"If you want to abort this run, you can press Ctrl + C to do so."
)
}
def backtracking(self, candidate):
# type: (Candidate) -> None
self.backtracks_by_package[candidate.name] += 1
count = self.backtracks_by_package[candidate.name]
if count not in self._messages_at_backtrack:
return
message = self._messages_at_backtrack[count]
logger.info("INFO: %s", message)
|
Improve ESLint options for Webpack | 'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
cache: true,
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
fix: true,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
| 'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports = {
cache: true,
devtool: '#source-map',
entry: [
path.resolve(__dirname, 'src', 'index.js')
],
module: {
rules: [
{
enforce: 'pre',
include: [
path.resolve(__dirname, 'src')
],
loader: 'eslint-loader',
options: {
configFile: '.eslintrc',
failOnError: true,
failOnWarning: false,
formatter: require('eslint-friendly-formatter')
},
test: /\.js$/
}, {
include: [
path.resolve(__dirname, 'src')
],
options: {
babelrc: false,
plugins: [
'syntax-flow',
'transform-flow-strip-types'
],
presets: [
['env', {
loose: true,
modules: false
}],
'stage-2'
]
},
test: /\.js$/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'moize.js',
library: 'moize',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
umdNamedDefine: true
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
])
],
resolve: {
modules: [
path.join(__dirname, 'src'),
'node_modules'
]
}
};
|
Update balancers entry point to be coordinators. | from setuptools import setup, find_packages
from lighthouse import __version__
classifiers = []
with open("classifiers.txt") as fd:
classifiers = fd.readlines()
setup(
name="lighthouse",
version=__version__,
description="Service discovery tool focused on ease-of-use and resiliency",
author="William Glass",
author_email="[email protected]",
url="http://github.com/wglass/lighthouse",
license="MIT",
classifiers=classifiers,
packages=find_packages(exclude=["tests", "tests.*"]),
include_package_data=True,
package_data={
"lighthouse": ["haproxy/*.json"],
},
install_requires=[
"watchdog",
"pyyaml",
"kazoo",
"six",
],
extras_require={
"redis": [
"redis"
]
},
entry_points={
"console_scripts": [
"lighthouse-reporter = lighthouse.scripts.reporter:run",
"lighthouse-writer = lighthouse.scripts.writer:run"
],
"lighthouse.coordinators": [
"haproxy = lighthouse.haproxy.coordinator:HAProxy",
],
"lighthouse.discovery": [
"zookeeper = lighthouse.zookeeper:ZookeeperDiscovery",
],
"lighthouse.checks": [
"http = lighthouse.checks.http:HTTPCheck",
"redis = lighthouse.redis.check:RedisCheck [redis]",
]
},
tests_require=[
"nose",
"mock",
"coverage",
"flake8",
],
)
| from setuptools import setup, find_packages
from lighthouse import __version__
classifiers = []
with open("classifiers.txt") as fd:
classifiers = fd.readlines()
setup(
name="lighthouse",
version=__version__,
description="Service discovery tool focused on ease-of-use and resiliency",
author="William Glass",
author_email="[email protected]",
url="http://github.com/wglass/lighthouse",
license="MIT",
classifiers=classifiers,
packages=find_packages(exclude=["tests", "tests.*"]),
include_package_data=True,
package_data={
"lighthouse": ["haproxy/*.json"],
},
install_requires=[
"watchdog",
"pyyaml",
"kazoo",
"six",
],
extras_require={
"redis": [
"redis"
]
},
entry_points={
"console_scripts": [
"lighthouse-reporter = lighthouse.scripts.reporter:run",
"lighthouse-writer = lighthouse.scripts.writer:run"
],
"lighthouse.balancers": [
"haproxy = lighthouse.haproxy.balancer:HAProxy",
],
"lighthouse.discovery": [
"zookeeper = lighthouse.zookeeper:ZookeeperDiscovery",
],
"lighthouse.checks": [
"http = lighthouse.checks.http:HTTPCheck",
"redis = lighthouse.redis.check:RedisCheck [redis]",
]
},
tests_require=[
"nose",
"mock",
"coverage",
"flake8",
],
)
|
Add config check to memcache resource provider | <?php
/**
* Provides resource to access memcache server.
*
* Parameters:
* - [memcache.host]
* - [memcache.port]
* - [memcache.unix_socket]
* - [memcache.namespace]
*
* Services:
* - [memcache] instance of CacheCollection
**/
namespace Ob_Ivan\DropboxProxy\ResourceProvider;
use Ob_Ivan\Cache\Driver\MemcacheDriver;
use Ob_Ivan\Cache\CacheCollection;
use Ob_Ivan\ResourceContainer\ResourceContainer;
use Ob_Ivan\ResourceContainer\ResourceProviderInterface;
class MemcacheResourceProvider implements ResourceProviderInterface
{
function populate(ResourceContainer $container)
{
$container->register('memcache', function ($container) {
$params = [];
if (isset($container['memcache.unix_socket'])) {
$params['host'] = 'unix://' . $container['memcache.unix_socket'];
$params['port'] = 0;
} elseif (isset($container['memcache.host']) && isset($container['memcache.port'])) {
$params['host'] = $container['memcache.host'];
$params['port'] = $container['memcache.port'];
} else {
throw new Exception('No server parameters provided for memcache resource.');
}
return new CacheCollection(
new MemcacheDriver($params),
isset($container['memcache.namespace'])
? $container['memcache.namespace']
: ''
);
});
}
}
| <?php
/**
* Provides resource to access memcache server.
*
* Parameters:
* - [memcache.host]
* - [memcache.port]
* - [memcache.unix_socket]
* - [memcache.namespace]
*
* Services:
* - [memcache] instance of CacheCollection
**/
namespace Ob_Ivan\DropboxProxy\ResourceProvider;
use Ob_Ivan\Cache\Driver\MemcacheDriver;
use Ob_Ivan\Cache\CacheCollection;
use Ob_Ivan\ResourceContainer\ResourceContainer;
use Ob_Ivan\ResourceContainer\ResourceProviderInterface;
class MemcacheResourceProvider implements ResourceProviderInterface
{
function populate(ResourceContainer $container)
{
$container->register('memcache', function ($container) {
$params = [];
if (isset($container['memcache.unix_socket'])) {
$params['host'] = 'unix://' . $container['memcache.unix_socket'];
$params['port'] = 0;
} elseif (isset($container['memcache.host']) && isset($container['memcache.port'])) {
$params['host'] = $container['memcache.host'];
$params['port'] = $container['memcache.port'];
}
return new CacheCollection(
new MemcacheDriver($params),
$container['memcache.namespace']
);
});
}
}
|
Add basic http authentication for all http requests on testserver | "use strict";
// Load the libraries and modules
var assets = require(__dirname + '/data/assets.json');
var config = {
npm: __dirname + '/node_modules/',
libraries: {
nodejs: {},
npm: {}
},
directory: __dirname + '/modules/',
modules: {
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
auth: {
realm: process.env.AUTH_REALM,
user: process.env.AUTH_USER,
password: process.env.AUTH_PASSWORD
},
bower: {
libraries: [],
path: __dirname + '/bower_components/'
},
header: {
'X-UA-Compatible': 'IE=edge,chrome=1',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'X-Powered-By': null
},
language: {
default: 'en',
languages: ['de', 'en'],
path: __dirname + '/languages/'
},
static: { path: __dirname + '/web/' },
swig: { views: __dirname + '/views/' }
}
},
directory: {
detail: { assets: assets },
list: { assets: assets }
}
}
};
require('dragonnodejs')(config);
| "use strict";
// Load the libraries and modules
var assets = require(__dirname + '/data/assets.json');
var config = {
npm: __dirname + '/node_modules/',
libraries: {
nodejs: {},
npm: {}
},
directory: __dirname + '/modules/',
modules: {
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
bower: {
libraries: [],
path: __dirname + '/bower_components/'
},
header: {
'X-UA-Compatible': 'IE=edge,chrome=1',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'X-Powered-By': null
},
language: {
default: 'en',
languages: ['de', 'en'],
path: __dirname + '/languages/'
},
static: { path: __dirname + '/web/' },
swig: { views: __dirname + '/views/' }
}
},
directory: {
detail: { assets: assets },
list: { assets: assets }
}
}
};
require('dragonnodejs')(config);
|
Reset the request instance after the tests complete | <?php
require_once __DIR__ . "/ResolverTestCase.php";
class CanonicalUrlResolverTest extends ResolverTestCase
{
protected function setUp()
{
$this->urlResolver = new \Concrete\Core\Url\Resolver\CanonicalUrlResolver();
}
public function testConfig()
{
$canonical = "http://example.com:1337";
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', $canonical);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl($canonical)->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
}
public function testFromRequest()
{
$mock = $this->getMock('\Concrete\Core\Http\RequestBase');
$mock->expects($this->once())->method('getScheme')->willReturn('http');
$mock->expects($this->once())->method('getHost')->willReturn('somehost');
$old_instance = \Request::getInstance();
\Request::setInstance($mock);
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', null);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl("http://somehost")->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
\Request::setInstance($old_instance);
}
}
| <?php
require_once __DIR__ . "/ResolverTestCase.php";
class CanonicalUrlResolverTest extends ResolverTestCase
{
protected function setUp()
{
$this->urlResolver = new \Concrete\Core\Url\Resolver\CanonicalUrlResolver();
}
public function testConfig()
{
$canonical = "http://example.com:1337";
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', $canonical);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl($canonical)->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
}
public function testFromRequest()
{
$mock = $this->getMock('\Concrete\Core\Http\RequestBase');
$mock->expects($this->once())->method('getScheme')->willReturn('http');
$mock->expects($this->once())->method('getHost')->willReturn('somehost');
\Request::setInstance($mock);
$old_value = \Config::get('concrete.seo.canonical_url');
\Config::set('concrete.seo.canonical_url', null);
$this->assertEquals(
(string) \Concrete\Core\Url\Url::createFromUrl("http://somehost")->setPath(\Core::getApplicationRelativePath()),
(string) $this->urlResolver->resolve(array()));
\Config::set('concrete.seo.canonical_url', $old_value);
}
}
|
Replace nbsp in plain text
ref #33 | var plain_text_clone = null;
function toggle_plain_text() {
var lines = document.querySelectorAll("td.code_line"),
line_len = lines.length,
text = "",
plain_pre = document.querySelectorAll("pre.simple_code_page"),
orig_pre, pre, i, j, spans, span_len, span;
if (plain_pre.length > 0) {
document.body.removeChild(plain_pre[0]);
document.body.appendChild(plain_text_clone);
document.body.className = "code_page";
} else {
var re = new RegExp(String.fromCharCode(160), "g");
for (i = 0; i < line_len; i++) {
spans = lines[i].querySelectorAll("span.real_text");
span_len = spans.length;
for (j = 0; j < span_len; j++) {
span = spans[j];
if ("textContent" in span) {
text += span.textContent.replace(re, ' ');
} else {
text += span.innerText.replace(re, ' ');
}
}
text += "\n";
}
orig_pre = document.querySelectorAll("pre.code_page")[0];
plain_text_clone = orig_pre.cloneNode(true);
pre = document.createElement('pre');
pre.className = "simple_code_page";
pre.appendChild(document.createTextNode(text));
document.body.removeChild(orig_pre);
document.body.appendChild(pre);
document.body.className = "simple_code_page";
}
}
| var plain_text_clone = null;
function toggle_plain_text() {
var lines = document.querySelectorAll("td.code_line"),
line_len = lines.length,
text = "",
plain_pre = document.querySelectorAll("pre.simple_code_page"),
orig_pre, pre, i, j, spans, span_len, span;
if (plain_pre.length > 0) {
document.body.removeChild(plain_pre[0]);
document.body.appendChild(plain_text_clone);
document.body.className = "code_page";
} else {
for (i = 0; i < line_len; i++) {
spans = lines[i].querySelectorAll("span.real_text");
span_len = spans.length;
for (j = 0; j < span_len; j++) {
span = spans[j];
if ("textContent" in span) {
text += span.textContent;
} else {
text += span.innerText;
}
}
text += "\n";
}
orig_pre = document.querySelectorAll("pre.code_page")[0];
plain_text_clone = orig_pre.cloneNode(true);
pre = document.createElement('pre');
pre.className = "simple_code_page";
pre.appendChild(document.createTextNode(text));
document.body.removeChild(orig_pre);
document.body.appendChild(pre);
document.body.className = "simple_code_page";
}
}
|
Add the default options for the salt master | '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {'interface': '0.0.0.0',
'publish_port': 7777,
'worker_threads': 5,
'worker_port': 7778,
'ret_port': 7776,
'local_threads': 5,
'local_port': 7775,
'local_worker_port': 7774,
'cachedir': '/var/cache/salt'}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
| '''
All salt configuration loading and defaults should be in this module
'''
# Import python modules
import os
import sys
import socket
# Import third party libs
import yaml
def minion_config(path):
'''
Reads in the minion configuration file and sets up special options
'''
opts = {'master': 'mcp',
'master_port': '7777',
'pki_dir': '/etc/salt/pki',
'hostname': socket.getfqdn(),
}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The minon configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
opts['master_uri'] = 'tcp://' + opts['master'] + ':' + opts['master_port']
return opts
def master_config(path):
'''
Reads in the master configuration file and sets up default options
'''
opts = {}
if os.path.isfile(path):
try:
opts.update(yaml.load(open(path, 'r')))
except:
err = 'The master configuration file did not parse correctly,'\
+ ' please check your configuration file.\nUsing defaults'
sys.stderr.write(err + '\n')
return opts
|
Move status into initial check; fails when instance is stopped already | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(security_groups, list):
security_groups = [security_groups]
ec2 = boto.ec2.connect_to_region(region)
reserve = ec2.run_instances(image_id, key_name=key_name,
instance_type=instance_type,
security_groups=security_groups,
user_data=user_data)
inst = reserve.instances[0]
while inst.state == u'pending':
time.sleep(10)
inst.update()
if initial_check:
# Wait for the status checks first
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
time.sleep(10)
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
return inst
# ec2.get_instance_attribute('i-336b69f6', 'instanceType')
| # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(security_groups, list):
security_groups = [security_groups]
ec2 = boto.ec2.connect_to_region(region)
reserve = ec2.run_instances(image_id, key_name=key_name,
instance_type=instance_type,
security_groups=security_groups,
user_data=user_data)
inst = reserve.instances[0]
while inst.state == u'pending':
time.sleep(10)
inst.update()
# Wait for the status checks first
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
if initial_check:
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
time.sleep(10)
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
return inst
# ec2.get_instance_attribute('i-336b69f6', 'instanceType')
|
Remove rebajado label if product is out of stock | <?php setup_postdata($post); ?>
<figure class="product-wrap thumbnail">
<?php if ( fik_product_stock_quantity() == 0) { ?>
<span class="label label-warning product-state">Out of stock</span>
<?php } ?>
<?php if ( get_fik_previous_price() && fik_product_stock_quantity() != 0) { ?>
<span class="label label-info product-state">Rebajado</span>
<?php } ?>
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) { ?>
<?php the_post_thumbnail( 'store-product-custom-thumbnail', array('class' => 'img-responsive') ); ?>
<?php } ?>
</a>
<figcaption class="caption">
<h3 class="title">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span class="product-price"><?php the_fik_previous_price(); ?><?php the_fik_price(); ?></span>
</h3>
<?php echo get_the_tag_list( '<p class="tags"><span>', '</span>, <span>', '</span></p>') ?>
</figcaption>
</figure>
| <?php setup_postdata($post); ?>
<figure class="product-wrap thumbnail">
<?php if ( fik_product_stock_quantity() == 0) { ?>
<span class="label label-warning product-state">Out of stock</span>
<?php } ?>
<?php if ( get_fik_previous_price() ) { ?>
<span class="label label-info product-state">Rebajado</span>
<?php } ?>
<a href="<?php the_permalink(); ?>">
<?php if ( has_post_thumbnail() ) { ?>
<?php the_post_thumbnail( 'store-product-custom-thumbnail', array('class' => 'img-responsive') ); ?>
<?php } ?>
</a>
<figcaption class="caption">
<h3 class="title">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<span class="product-price"><?php the_fik_previous_price(); ?><?php the_fik_price(); ?></span>
</h3>
<?php echo get_the_tag_list( '<p class="tags"><span>', '</span>, <span>', '</span></p>') ?>
</figcaption>
</figure>
|
Support Symfony Process 2.3 "process timed-out" exception message | <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
$informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);
$output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
$output->method('write');
$context = Context::getInstance();
$context->setService('information-collector', $informationCollector);
$context->setService('output', $output);
}
/** @test */
public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
{
$check = new TestsCheck(array('command' => 'echo OK'));
$check->execute();
}
/** @test */
public function succeeds_when_command_finished_within_configured_timeout()
{
$check = new TestsCheck(array('command' => 'echo OK', 'timeout' => 0.100));
$check->execute();
}
/** @test */
public function fails_when_the_command_exceeds_the_timeout()
{
$this->setExpectedExceptionRegExp('Exception', '~process.*time.*out~');
$check = new TestsCheck(array('command' => 'sleep 1', 'timeout' => 0.100));
$check->execute();
}
}
| <?php
namespace Liip\RMT\Tests\Functional;
use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;
class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
$informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);
$output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
$output->method('write');
$context = Context::getInstance();
$context->setService('information-collector', $informationCollector);
$context->setService('output', $output);
}
/** @test */
public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
{
$check = new TestsCheck(array('command' => 'echo OK'));
$check->execute();
}
/** @test */
public function succeeds_when_command_finished_within_configured_timeout()
{
$check = new TestsCheck(array('command' => 'echo OK', 'timeout' => 0.100));
$check->execute();
}
/** @test */
public function fails_when_the_command_exceeds_the_timeout()
{
$this->setExpectedExceptionRegExp('Exception', 'process.*time.*out');
$check = new TestsCheck(array('command' => 'sleep 1', 'timeout' => 0.100));
$check->execute();
}
}
|
Include java 11 to supported list | /*
* Copyright 2017 ThoughtWorks, 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.
*/
package com.thoughtworks.go.utils;
import java.util.Arrays;
import java.util.TreeSet;
public class AssertJava8 {
private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList(
JavaVersion.VERSION_1_8,
JavaVersion.VERSION_1_9,
JavaVersion.VERSION_1_10,
JavaVersion.VERSION_11
));
public static void assertVMVersion() {
checkSupported(JavaVersion.current());
}
private static void checkSupported(JavaVersion currentJavaVersion) {
if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) {
System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() +
" and <= " + SUPPORTED_VERSIONS.last() +
". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!");
System.exit(1);
}
}
}
| /*
* Copyright 2017 ThoughtWorks, 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.
*/
package com.thoughtworks.go.utils;
import java.util.Arrays;
import java.util.TreeSet;
public class AssertJava8 {
private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList(
JavaVersion.VERSION_1_8,
JavaVersion.VERSION_1_9,
JavaVersion.VERSION_1_10
));
public static void assertVMVersion() {
checkSupported(JavaVersion.current());
}
private static void checkSupported(JavaVersion currentJavaVersion) {
if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) {
System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() +
" and <= " + SUPPORTED_VERSIONS.last() +
". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!");
System.exit(1);
}
}
}
|
Hide basket table if no search assets. | import { Util } from "../../util.js";
export class BasketTemplate {
static update(render, state, events) {
const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-white";
const trClasses = "pv1 pr1 bb b--black-20";
/* eslint-disable indent */
render`
<h2>Basket</h2>
<input id="assetsSearch" size="32" oninput="${events}" placeholder="What assets to be added?">
<table style="${Util.show(state.assetsSearch.length)}" class="f7 mw8 pa2" cellpsacing="0">
<thead>
<th class="${headerClasses}">Symbol</th>
<th class="${headerClasses}">Description</th>
<th class="${headerClasses}">Type</th>
<th class="${headerClasses}">Market</th>
</thead>
<tbody onclick="${events}" >${state.assetsSearch.map(asset =>
`<tr>
<td id="assetSearch-${asset.symbol}"
class="${trClasses} pointer dim"
data-value='${escape(JSON.stringify(asset))}'
title="Click to add the asset">${asset.symbol}</td>
<td class="${trClasses}">${asset.name}</td>
<td class="${trClasses}">${asset.type}</td>
<td class="${trClasses}">${asset.exchDisp}</td>
</tr>`)
}</tbody>
</table>
`;
/* eslint-enable indent */
}
}
| export class BasketTemplate {
static update(render, state, events) {
const headerClasses = "fw6 bb b--black-20 tl pb1 pr1 bg-white";
const trClasses = "pv1 pr1 bb b--black-20";
/* eslint-disable indent */
render`
<h2>Basket</h2>
<input id="assetsSearch" size="32" oninput="${events}" placeholder="What assets to be added?">
<table class="f7 mw8 pa2" cellpsacing="0">
<thead>
<th class="${headerClasses}">Symbol</th>
<th class="${headerClasses}">Description</th>
<th class="${headerClasses}">Type</th>
<th class="${headerClasses}">Market</th>
</thead>
<tbody onclick="${events}" >${state.assetsSearch.map(asset =>
`<tr>
<td id="assetSearch-${asset.symbol}"
class="${trClasses} pointer dim"
data-value='${escape(JSON.stringify(asset))}'
title="Click to add the asset">${asset.symbol}</td>
<td class="${trClasses}">${asset.name}</td>
<td class="${trClasses}">${asset.type}</td>
<td class="${trClasses}">${asset.exchDisp}</td>
</tr>`)
}</tbody>
</table>
`;
/* eslint-enable indent */
}
}
|
Add a maximum hue for link color | define([
'./module',
'jquery',
'text!./link.html'
], function(directives, $, linkTpl) {
'use strict';
directives.directive('zoriLink', ['$interval',
function($interval) {
function link(scope, element, attrs) {
var timeoutId;
var $link = $(element).find('a');
function update() {
var nbClick = scope.link.nbClick;
var height = nbClick * 30 + 30;
var hue = Math.min(nbClick * 10, 100);
var style = {
height : height + 'px',
'margin-top': -(height / 2) + 'px'
};
if (nbClick > 0) {
style.background = 'linear-gradient(to bottom, hsl(' + hue + ', 99%, 65%) 50%, hsl(' + hue + ', 99%, 30%) 51%)';
}
$link.css(style);
}
scope.$watch(attrs.myCurrentTime, function(value) {
update();
});
element.on('$destroy', function() {
$interval.cancel(timeoutId);
});
timeoutId = $interval(function() {
update();
}, 1000);
}
return {
restrict: 'A',
template: linkTpl,
link: link
};
}
]);
});
| define([
'./module',
'jquery',
'text!./link.html'
], function(directives, $, linkTpl) {
'use strict';
directives.directive('zoriLink', ['$interval',
function($interval) {
function link(scope, element, attrs) {
var timeoutId;
var $link = $(element).find('a');
function update() {
var nbClick = scope.link.nbClick;
var height = nbClick * 30 + 30;
var hue = nbClick * 10 + 10;
var style = {
height : height + 'px',
'margin-top': -(height / 2) + 'px',
background : 'linear-gradient(to bottom, hsl(' + hue + ', 99%, 65%) 50%, hsl(' + hue + ', 99%, 30%) 51%)'
};
$link.css(style);
}
scope.$watch(attrs.myCurrentTime, function(value) {
update();
});
element.on('$destroy', function() {
$interval.cancel(timeoutId);
});
timeoutId = $interval(function() {
update();
}, 1000);
}
return {
restrict: 'A',
template: linkTpl,
link: link
};
}
]);
});
|
Use LazyStrings instance in container.
The command uses the LazyStrings instance in the container for the deployment command. | <?php namespace Nobox\LazyStrings\Commands;
use Nobox\LazyStrings\LazyStrings;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class LazyDeployCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'lazy:deploy';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Deploy LazyStrings.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->info('Deploying...');
$lazyStrings = $this->laravel['lazy-strings'];
$lazyStrings->generateStrings();
$this->info('Lazy Strings is now deployed.');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array();
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array();
}
}
| <?php namespace Nobox\LazyStrings\Commands;
use Nobox\LazyStrings\LazyStrings;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class LazyDeployCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'lazy:deploy';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Deploy LazyStrings.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$this->info('Deploying...');
$lazyStrings = new LazyStrings();
$lazyStrings->generateStrings();
$this->info('Lazy Strings is now deployed.');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array();
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array();
}
}
|
Add constant; fix var name | import { _SUCCESS, _ERROR } from 'constants'
const pending = {} // requestIDs to timeoutIDs
let nextRequestID = 0
export default function createSocketMiddleware (socket, prefix) {
return ({ dispatch }) => {
// dispatch incoming actions sent by the server
socket.on('action', dispatch)
return next => action => {
const { type, meta } = action
// only apply to socket.io requests
if (!type || type.indexOf(prefix) !== 0) {
return next(action)
}
const requestID = nextRequestID++
// fire request action
next(action)
// error action if socket.io callback timeout
if (!(meta && meta.requireAck === false)) {
pending[requestID] = setTimeout(() => {
next({
type: type + _ERROR,
meta: {
error: `Server didn't respond; check network [${type}]`,
}
})
delete pending[requestID]
}, 1000)
}
// emit along with our acknowledgement callback (3rd arg)
// that receives data when the server calls ctx.acknowledge(data)
// in our case the data should be a *_SUCCESS or *_ERROR action
socket.emit('action', action, responseAction => {
clearTimeout(pending[requestID])
delete pending[requestID]
next(responseAction)
})
}
}
}
| import { _ERROR } from 'constants'
const pendingIds = {} // requestIDs to timeoutIDs
let nextRequestID = 0
export default function createSocketMiddleware (socket, prefix) {
return ({ dispatch }) => {
// dispatch incoming actions sent by the server
socket.on('action', dispatch)
return next => action => {
const { type, meta } = action
// only apply to socket.io requests
if (!type || type.indexOf(prefix) !== 0) {
return next(action)
}
const requestID = nextRequestID++
// fire request action
next(action)
// error action if socket.io callback timeout
if (!(meta && meta.requireAck === false)) {
pending[requestID] = setTimeout(() => {
next({
type: type + _ERROR,
meta: {
error: `Server didn't respond; check network [${type}]`,
}
})
delete pending[requestID]
}, 1000)
}
// emit along with our acknowledgement callback (3rd arg)
// that receives data when the server calls ctx.acknowledge(data)
// in our case the data should be a *_SUCCESS or *_ERROR action
socket.emit('action', action, responseAction => {
clearTimeout(pending[requestID])
delete pending[requestID]
next(responseAction)
})
}
}
}
|
Change karma browser for tests from Chrome to PhantomJS | var path = require('path');
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
coverageReporter: {
reporters: [
{
type: 'html',
subdir: 'html'
}, {
type: 'lcovonly',
subdir: '.'
}
]
},
files: [
'node_modules/babel-polyfill/dist/polyfill.js', 'tests.webpack.js'
],
frameworks: ['jasmine'],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
reporters: [
'progress', 'coverage'
],
webpack: {
cache: true,
devtool: 'inline-source-map',
module: {
preLoaders: [
{
test: /.spec\.js$/,
include: /calculations/,
exclude: /(bower_components|node_modules)/,
loader: 'babel',
query: {
cacheDirectory: true
}
}, {
test: /\.js?$/,
include: /calculations/,
exclude: /(node_modules|bower_components|__spec__)/,
loader: 'babel-istanbul',
query: {
cacheDirectory: true
}
}
],
loaders: [
{
test: /\.js$/,
include: path.resolve(__dirname, '../calculations'),
exclude: /(bower_components|node_modules|__spec__)/,
loader: 'babel',
query: {
cacheDirectory: true
}
}
]
}
}
});
};
| var path = require('path');
module.exports = function(config) {
config.set({
browsers: ['Chrome'],
coverageReporter: {
reporters: [
{
type: 'html',
subdir: 'html'
}, {
type: 'lcovonly',
subdir: '.'
}
]
},
files: [
'node_modules/babel-polyfill/dist/polyfill.js', 'tests.webpack.js'
],
frameworks: ['jasmine'],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap']
},
reporters: [
'progress', 'coverage'
],
webpack: {
cache: true,
devtool: 'inline-source-map',
module: {
preLoaders: [
{
test: /.spec\.js$/,
include: /calculations/,
exclude: /(bower_components|node_modules)/,
loader: 'babel',
query: {
cacheDirectory: true
}
}, {
test: /\.js?$/,
include: /calculations/,
exclude: /(node_modules|bower_components|__spec__)/,
loader: 'babel-istanbul',
query: {
cacheDirectory: true
}
}
],
loaders: [
{
test: /\.js$/,
include: path.resolve(__dirname, '../calculations'),
exclude: /(bower_components|node_modules|__spec__)/,
loader: 'babel',
query: {
cacheDirectory: true
}
}
]
}
}
});
};
|
Make brand link a router link | var React = require('react');
var title = "Orion's Belt BattleGrounds";
var Router = require('react-router');
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,
Link=Router.Link, RouteHandler = Router.RouteHandler;
var CurrentUserMenu = require('../users/CurrentUserMenu.react.js');
var Header = React.createClass({
render: function () {
return (
<div className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<Link to="root" className="navbar-brand">{title}</Link>
<button className="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse" id="navbar-main">
{/*<ul className="nav navbar-nav">
<li><a href="../help/">Help</a></li>
</ul>*/}
<ul className="nav navbar-nav navbar-right">
<CurrentUserMenu />
</ul>
</div>
</div>
</div>
);
}
});
module.exports = Header;
| var React = require('react');
var title = "Orion's Belt BattleGrounds";
var Router = require('react-router');
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,
Link=Router.Link, RouteHandler = Router.RouteHandler;
var CurrentUserMenu = require('../users/CurrentUserMenu.react.js');
var Header = React.createClass({
render: function () {
return (
<div className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<a href="/" className="navbar-brand">{title}</a>
<button className="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse" id="navbar-main">
{/*<ul className="nav navbar-nav">
<li><a href="../help/">Help</a></li>
</ul>*/}
<ul className="nav navbar-nav navbar-right">
<CurrentUserMenu />
</ul>
</div>
</div>
</div>
);
}
});
module.exports = Header;
|
Fix in test result renderer. | 'use strict';
var Component = require('../ui/Component');
function ResultItem() {
ResultItem.super.apply(this, arguments);
}
ResultItem.Prototype = function() {
this.shouldRerender = function() {
return false;
};
this.render = function($$) {
var test = this.props.test;
var result = this.props.result;
var el = $$('div').addClass('sc-test-result');
var header = $$('div');
if (!test._skip) {
if (result.ok) {
header.append($$('span').addClass('se-status sm-ok').append("\u2713"));
} else {
header.append($$('span').addClass('se-status sm-not-ok').append("\u26A0"));
}
}
header.append($$('span').addClass('se-description').append(String(result.name)));
el.append(header);
if (!test._skip && !result.ok && result.operator === "equal") {
var diff = $$('div').addClass('se-diff');
var expected = $$('div').addClass('se-expected')
.append('Expected:')
.append($$('pre').append(String(result.expected)));
var actual = $$('div').addClass('se-actual')
.append('Actual:')
.append($$('pre').append(String(result.actual)));
diff.append(expected, actual);
el.append(diff);
}
return el;
};
};
Component.extend(ResultItem);
module.exports = ResultItem;
| 'use strict';
var Component = require('../ui/Component');
function ResultItem() {
ResultItem.super.apply(this, arguments);
}
ResultItem.Prototype = function() {
this.shouldRerender = function() {
return false;
};
this.render = function($$) {
var test = this.props.test;
var result = this.props.result;
var el = $$('div').addClass('sc-test-result');
var header = $$('div');
if (!test._skip) {
if (result.ok) {
header.append($$('span').addClass('se-status sm-ok').append("\u2713"));
} else {
header.append($$('span').addClass('se-status sm-not-ok').append("\u26A0"));
}
}
header.append($$('span').addClass('se-description').append(result.name));
el.append(header);
if (!test._skip && !result.ok && result.operator === "equal") {
var diff = $$('div').addClass('se-diff');
var expected = $$('div').addClass('se-expected')
.append('Expected:')
.append($$('pre').append(String(result.expected)));
var actual = $$('div').addClass('se-actual')
.append('Actual:')
.append($$('pre').append(String(result.actual)));
diff.append(expected, actual);
el.append(diff);
}
return el;
};
};
Component.extend(ResultItem);
module.exports = ResultItem;
|
Upgrade ldap3 0.9.9.1 => 0.9.9.2 | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'cas': [
'django-cas-client>=1.2.0',
],
'ldap': [
'ldap3>=0.9.9.2',
],
'dev': [
'django>=1.7',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'cas': [
'django-cas-client>=1.2.0',
],
'ldap': [
'ldap3>=0.9.9.1',
],
'dev': [
'django>=1.7',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Allow other packages to use `out` (for example the intelliJ plugin) | package com.redhat.ceylon.compiler.typechecker.treegen;
public class Util {
public static java.io.PrintStream out = System.out;
public static String className(String nodeName) {
return toJavaIdentifier(nodeName, true);
}
public static String fieldName(String nodeName) {
return toJavaIdentifier(nodeName, false);
}
public static String toJavaIdentifier(String nodeName, boolean boundary) {
StringBuilder result = new StringBuilder();
for (char c: nodeName.toCharArray()) {
if (c=='_') {
boundary=true;
}
else if (boundary) {
result.append(c);
boundary=false;
}
else {
result.append(Character.toLowerCase(c));
}
}
return result.toString();
}
public static String initialUpper(String s) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static String description(String nodeName) {
return nodeName.toLowerCase().replace('_', ' ');
}
public static void print(String text) {
out.print(text);
}
public static void println(String text) {
out.println(text);
}
}
| package com.redhat.ceylon.compiler.typechecker.treegen;
public class Util {
static java.io.PrintStream out = System.out;
public static String className(String nodeName) {
return toJavaIdentifier(nodeName, true);
}
public static String fieldName(String nodeName) {
return toJavaIdentifier(nodeName, false);
}
public static String toJavaIdentifier(String nodeName, boolean boundary) {
StringBuilder result = new StringBuilder();
for (char c: nodeName.toCharArray()) {
if (c=='_') {
boundary=true;
}
else if (boundary) {
result.append(c);
boundary=false;
}
else {
result.append(Character.toLowerCase(c));
}
}
return result.toString();
}
public static String initialUpper(String s) {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static String description(String nodeName) {
return nodeName.toLowerCase().replace('_', ' ');
}
public static void print(String text) {
out.print(text);
}
public static void println(String text) {
out.println(text);
}
}
|
Handle case where function caller is null | (function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('stack-generator', ['stackframe'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('stackframe'));
} else {
root.StackGenerator = factory(root.StackFrame);
}
}(this, function(StackFrame) {
return {
backtrace: function StackGenerator$$backtrace(opts) {
var stack = [];
var maxStackSize = 10;
if (typeof opts === 'object' && typeof opts.maxStackSize === 'number') {
maxStackSize = opts.maxStackSize;
}
var curr = arguments.callee;
while (curr && stack.length < maxStackSize) {
if (!curr['arguments']) {
break;
}
// Allow V8 optimizations
var args = new Array(curr['arguments'].length);
for (var i = 0; i < args.length; ++i) {
args[i] = curr['arguments'][i];
}
if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
stack.push(new StackFrame({functionName: RegExp.$1 || undefined, args: args}));
} else {
stack.push(new StackFrame({args: args}));
}
try {
curr = curr.caller;
} catch (e) {
break;
}
}
return stack;
}
};
}));
| (function(root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('stack-generator', ['stackframe'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('stackframe'));
} else {
root.StackGenerator = factory(root.StackFrame);
}
}(this, function(StackFrame) {
return {
backtrace: function StackGenerator$$backtrace(opts) {
var stack = [];
var maxStackSize = 10;
if (typeof opts === 'object' && typeof opts.maxStackSize === 'number') {
maxStackSize = opts.maxStackSize;
}
var curr = arguments.callee;
while (curr && stack.length < maxStackSize) {
// Allow V8 optimizations
var args = new Array(curr['arguments'].length);
for (var i = 0; i < args.length; ++i) {
args[i] = curr['arguments'][i];
}
if (/function(?:\s+([\w$]+))+\s*\(/.test(curr.toString())) {
stack.push(new StackFrame({functionName: RegExp.$1 || undefined, args: args}));
} else {
stack.push(new StackFrame({args: args}));
}
try {
curr = curr.caller;
} catch (e) {
break;
}
}
return stack;
}
};
}));
|
Test that .info() and .warn() set the correct event type.
Former-commit-id: 14a833f5c8c252e2e09d8c7ea3e154c3978c403f [formerly 17449ebde702c82594b0d592047ae7c684f14fc9]
Former-commit-id: 3b45559df0c8bdc6d5fec59793a9981c71e62e33 | package org.gem.log;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;
public class AMQPAppenderTest {
private DummyChannel dummyChannel;
private DummyAppender dummyAppender;
private Logger logger = Logger.getLogger(AMQPAppenderTest.class);
void tearDown() {
dummyChannel = null;
dummyAppender = null;
// this closes the RabbitMQ connections
BasicConfigurator.resetConfiguration();
}
private void setUpDummyAppender() {
dummyAppender = new DummyAppender();
dummyAppender.setLayout(new PatternLayout());
BasicConfigurator.configure(dummyAppender);
}
@Test
public void basicLogging() {
setUpDummyAppender();
logger.info("Test1");
logger.warn("Test2");
dummyChannel = (DummyChannel) dummyAppender.getChannel();
assertThat(dummyChannel.entries.size(), is(equalTo(2)));
DummyChannel.Entry entry1 = dummyChannel.entries.get(0);
assertThat(entry1.exchange, is(equalTo("")));
assertThat(entry1.routingKey, is(equalTo("")));
assertThat(entry1.properties.getType(), is(equalTo("INFO")));
assertThat(entry1.body, is(equalTo("Test1\n")));
DummyChannel.Entry entry2 = dummyChannel.entries.get(1);
assertThat(entry2.exchange, is(equalTo("")));
assertThat(entry2.routingKey, is(equalTo("")));
assertThat(entry2.properties.getType(), is(equalTo("WARN")));
assertThat(entry2.body, is(equalTo("Test2\n")));
}
}
| package org.gem.log;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;
public class AMQPAppenderTest {
private DummyChannel dummyChannel;
private DummyAppender dummyAppender;
private Logger logger = Logger.getLogger(AMQPAppenderTest.class);
void tearDown() {
dummyChannel = null;
dummyAppender = null;
// this closes the RabbitMQ connections
BasicConfigurator.resetConfiguration();
}
private void setUpDummyAppender() {
dummyAppender = new DummyAppender();
dummyAppender.setLayout(new PatternLayout());
BasicConfigurator.configure(dummyAppender);
}
@Test
public void basicLogging() {
setUpDummyAppender();
logger.info("Test");
dummyChannel = (DummyChannel) dummyAppender.getChannel();
assertThat(dummyChannel.entries.size(), is(equalTo(1)));
DummyChannel.Entry entry = dummyChannel.entries.get(0);
assertThat(entry.exchange, is(equalTo("")));
assertThat(entry.routingKey, is(equalTo("")));
assertThat(entry.properties.getType(), is(equalTo("INFO")));
assertThat(entry.body, is(equalTo("Test\n")));
}
}
|
Make link property optional on a slide | import React from 'react';
import styles from './Slide.css';
import {hashHistory} from 'react-router'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import NeufundLogo from '../../../images/NeuFund_icon_light.png';
class Slide extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
if (this.props.linkTo) {
hashHistory.push(this.props.linkTo);
}
}
render() {
return (
<MuiThemeProvider>
<div onClick={this.onClick} className={styles.slide}>
<div className={styles.slideHeader}>
<img className={styles.logo} src={NeufundLogo}/>
<a href="/about">About</a>
<a href="/faq">FAQ</a>
<a href="/support">Support</a>
</div>
<div className={styles.slideContent}>
{this.props.children}
</div>
</div>
</MuiThemeProvider>
)
}
}
export default Slide; | import React from 'react';
import styles from './Slide.css';
import {hashHistory} from 'react-router'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import NeufundLogo from '../../../images/NeuFund_icon_light.png';
class Slide extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
hashHistory.push(this.props.linkTo);
}
render() {
return (
<MuiThemeProvider>
<div onClick={this.onClick} className={styles.slide}>
<div className={styles.slideHeader}>
<img className={styles.logo} src={NeufundLogo}/>
<a href="/about">About</a>
<a href="/faq">FAQ</a>
<a href="/support">Support</a>
</div>
<div className={styles.slideContent}>
{this.props.children}
</div>
</div>
</MuiThemeProvider>
)
}
}
export default Slide; |
Fix url to transaciton sound | 'use strict';
angular.module('insight.address').controller('AddressController',
function($scope, $rootScope, $routeParams, $location, Global, Address, getSocket) {
$scope.global = Global;
var socket = getSocket($scope);
var _startSocket = function () {
socket.on('bitcoind/addresstxid', function(tx) {
$rootScope.$broadcast('tx', tx);
var base = document.querySelector('base');
var baseUrl = base && base.href || '';
var beep = new Audio(baseUrl + '/sound/transaction.mp3');
beep.play();
});
socket.emit('subscribe', 'bitcoind/addresstxid', [$routeParams.addrStr]);
};
socket.on('connect', function() {
_startSocket();
});
$scope.params = $routeParams;
$scope.findOne = function() {
$rootScope.currentAddr = $routeParams.addrStr;
_startSocket();
Address.get({
addrStr: $routeParams.addrStr
},
function(address) {
$rootScope.titleDetail = address.addrStr.substring(0, 7) + '...';
$rootScope.flashMessage = null;
$scope.address = address;
},
function(e) {
if (e.status === 400) {
$rootScope.flashMessage = 'Invalid Address: ' + $routeParams.addrStr;
} else if (e.status === 503) {
$rootScope.flashMessage = 'Backend Error. ' + e.data;
} else {
$rootScope.flashMessage = 'Address Not Found';
}
$location.path('/');
});
};
});
| 'use strict';
angular.module('insight.address').controller('AddressController',
function($scope, $rootScope, $routeParams, $location, Global, Address, getSocket) {
$scope.global = Global;
var socket = getSocket($scope);
var _startSocket = function () {
socket.on('bitcoind/addresstxid', function(tx) {
$rootScope.$broadcast('tx', tx);
var beep = new Audio('/sound/transaction.mp3');
beep.play();
});
socket.emit('subscribe', 'bitcoind/addresstxid', [$routeParams.addrStr]);
};
socket.on('connect', function() {
_startSocket();
});
$scope.params = $routeParams;
$scope.findOne = function() {
$rootScope.currentAddr = $routeParams.addrStr;
_startSocket();
Address.get({
addrStr: $routeParams.addrStr
},
function(address) {
$rootScope.titleDetail = address.addrStr.substring(0, 7) + '...';
$rootScope.flashMessage = null;
$scope.address = address;
},
function(e) {
if (e.status === 400) {
$rootScope.flashMessage = 'Invalid Address: ' + $routeParams.addrStr;
} else if (e.status === 503) {
$rootScope.flashMessage = 'Backend Error. ' + e.data;
} else {
$rootScope.flashMessage = 'Address Not Found';
}
$location.path('/');
});
};
});
|
Add jQuery plugin on page load, not domready
The phileo plugin was added to jQuery in the domready event callback. As
this plugin could be loaded at the bottom of a page - AFTER phileo
widget scripts - it was possible for the phileo plugin to not be
loaded when the widgets were initialized in the domready event. As the
phileo plugin does not need the DOM to be ready to set itself up, the
plugin now loads as the page is loading. This allows phileo widgets to
be inserted before the phileo plugin script and for everything to still
work. | !function($){
"use strict";
var PhileoLikes = function(form, options) {
this.options = $.extend({}, $.fn.phileo.defaults, options);
this.$form = $(form);
this.$count = $(this.options.count);
var self = this;
this.$form.submit(function(event) {
event.preventDefault();
$.ajax({
url: self.$form.attr('action'),
type: "POST",
data: self.$form.serialize(),
statusCode: {
200: function(data, textStatus, jqXHR) {
self.$count.text(data.likes_count);
self.$form[data.liked ? 'addClass' : 'removeClass'](self.options.toggle_class);
}
}
});
});
};
$.fn.phileo = function(options) {
$(this).each(function(i, el) {
var phileo = new PhileoLikes(el, options);
$(el).data('Phileo', {instance: phileo});
});
return this;
};
$.fn.phileo.defaults = {
toggle_class: 'phileo-liked',
count: false
};
}( window.jQuery || window.ender );
| jQuery(function($) {
var PhileoLikes = function(form, options) {
this.options = $.extend({}, $.fn.phileo.defaults, options);
this.$form = $(form);
this.$count = $(this.options.count);
var self = this;
this.$form.submit(function(event) {
event.preventDefault();
$.ajax({
url: self.$form.attr('action'),
type: "POST",
data: self.$form.serialize(),
statusCode: {
200: function(data, textStatus, jqXHR) {
self.$count.text(data.likes_count);
self.$form[data.liked ? 'addClass' : 'removeClass'](self.options.toggle_class);
}
}
});
});
};
$.fn.phileo = function(options) {
$(this).each(function(i, el) {
var phileo = new PhileoLikes(el, options);
$(el).data('Phileo', {instance: phileo});
});
return this;
};
$.fn.phileo.defaults = {
toggle_class: 'phileo-liked',
count: false
};
});
|
Change option 'Processos Seletivos' to dropdown item | <?php
/**
*Class for processing framework with HTML standards.
*
*@package Html
*@author Vinicius Pinheiro <[email protected]>
*@license MIT License
*@link http://eletronjun.com.br/class/html/communityMenu.php
*/
namespace html{
include_once __DIR__ . "/../autoload.php";
use \utilities\Session as Session;
use \html\Page as Page;
use \html\Menu as Menu;
use \configuration\Globals as Globals;
use \dao\CategoryDao as CategoryDao;
class CommunityMenu extends Menu
{
public function __construct()
{
parent::startMenu();
}
public function construct()
{
parent::addItem(PROJECT_ROOT ."/enterprise.php", "A Empresa");
parent::addItem(PROJECT_ROOT ."/projects.php", "Projetos");
parent::addItem(PROJECT_ROOT ."/events.php", "Eventos");
$this->selectiveProcessOptions();
$this->publicationOptions();
parent::endMenu();
}
private function publicationOptions()
{
parent::startDropdown("Publicações");
foreach (CategoryDao::returnActiveCategories() as $code => $name) {
parent::addItem(PROJECT_ROOT . "categories.php?code={$code}", $name);
}
parent::endDropdown();
}
private function selectiveProcessOptions()
{
parent::startDropdown("Processos Seletivos");
parent::addItem(PROJECT_ROOT . "selective_process2015.php", "Processo Seletivo 2015");
parent::addItem(PROJECT_ROOT . "selective_process2016.php", "Processo Seletivo 2016");
parent::endDropdown();
}
}
}
| <?php
/**
*Class for processing framework with HTML standards.
*
*@package Html
*@author Vinicius Pinheiro <[email protected]>
*@license MIT License
*@link http://eletronjun.com.br/class/html/communityMenu.php
*/
namespace html{
include_once __DIR__ . "/../autoload.php";
use \utilities\Session as Session;
use \html\Page as Page;
use \html\Menu as Menu;
use \configuration\Globals as Globals;
use \dao\CategoryDao as CategoryDao;
class CommunityMenu extends Menu
{
public function __construct()
{
parent::startMenu();
}
public function construct()
{
parent::addItem(PROJECT_ROOT ."/enterprise.php", "A Empresa");
parent::addItem(PROJECT_ROOT ."/projects.php", "Projetos");
parent::addItem(PROJECT_ROOT ."/events.php", "Eventos");
parent::addItem(PROJECT_ROOT ."/selective_process.php", "Processos Seletivos");
$this->publicationOptions();
parent::endMenu();
}
private function publicationOptions()
{
parent::startDropdown("Publicações");
foreach (CategoryDao::returnActiveCategories() as $code => $name) {
parent::addItem(PROJECT_ROOT . "categories.php?code={$code}", $name);
}
parent::endDropdown();
}
}
}
|
fix: Add parser to ts overrides | module.exports = {
plugins: ['@typescript-eslint'],
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
parser: '@typescript-eslint/parser',
rules: {
// typescript will handle this so no need for it
'no-undef': 'off',
'no-unused-vars': 'off',
'no-use-before-define': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-use-before-define': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-expect-error': 'allow-with-description',
'ts-ignore': 'allow-with-description',
'ts-nocheck': true,
'ts-check': false,
minimumDescriptionLength: 3,
},
],
},
},
],
};
| module.exports = {
plugins: ['@typescript-eslint'],
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
// typescript will handle this so no need for it
'no-undef': 'off',
'no-unused-vars': 'off',
'no-use-before-define': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-use-before-define': 'error',
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/ban-ts-comment': [
'error',
{
'ts-expect-error': 'allow-with-description',
'ts-ignore': 'allow-with-description',
'ts-nocheck': true,
'ts-check': false,
minimumDescriptionLength: 3,
},
],
},
},
],
};
|
:bug: Fix the specific chars not shown on post data | (() => {
"use strict";
let settings = {
baseurl: "",
accessToken: "",
};
chrome.storage.sync.get(settings, function(storage) {
settings.baseurl = storage.baseurl;
settings.accessToken = storage.accessToken;
});
document.querySelector("#toot").addEventListener("click", toot);
document.addEventListener("keydown", function(event) {
if (((event.ctrlKey && !event.metaKey) || (event.metaKey && !event.ctrlKey)) && event.key === 'Enter') {
toot();
}
});
function toot() {
let xhr = new XMLHttpRequest();
let baseurl = settings.baseurl + "/api/v1/statuses";
let accessToken = settings.accessToken;
let content = document.querySelector("#content").value;
xhr.open("POST", baseurl, true);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
document.querySelector("#content").value = "";
let status = document.querySelector("#status");
status.textContent = "Tootted successfully!";
setTimeout(function() {
status.textContent = "";
}, 1500);
}
else {
let status = document.querySelector("#status");
status.textContent = "Toot failed.";
setTimeout(function() {
status.textContent = "";
}, 1500);
}
}
xhr.send("status=" + encodeURIComponent(content));
}
})();
| (() => {
"use strict";
let settings = {
baseurl: "",
accessToken: "",
};
chrome.storage.sync.get(settings, function(storage) {
settings.baseurl = storage.baseurl;
settings.accessToken = storage.accessToken;
});
document.querySelector("#toot").addEventListener("click", toot);
document.addEventListener("keydown", function(event) {
if (((event.ctrlKey && !event.metaKey) || (event.metaKey && !event.ctrlKey)) && event.key === 'Enter') {
toot();
}
});
function toot() {
let xhr = new XMLHttpRequest();
let baseurl = settings.baseurl + "/api/v1/statuses";
let accessToken = settings.accessToken;
let content = document.querySelector("#content").value;
xhr.open("POST", baseurl, true);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
document.querySelector("#content").value = "";
let status = document.querySelector("#status");
status.textContent = "Tootted successfully!";
setTimeout(function() {
status.textContent = "";
}, 1500);
}
else {
let status = document.querySelector("#status");
status.textContent = "Toot failed.";
setTimeout(function() {
status.textContent = "";
}, 1500);
}
}
xhr.send("status=" + content);
}
})();
|
Add more files to ignore for production task | module.exports = {
folder: {
tasks: 'tasks',
src: 'src',
build: 'assets',
prod: 'production'
},
task: {
htmlHint: 'html-hint',
jsHint: 'js-hint',
buildCustomJs: 'build-custom-js',
buildJsVendors: 'build-js-vendors',
buildSass: 'build-sass',
buildSassProd: 'build-sass-production',
buildStylesVendors: 'build-styles-vendors',
imageMin: 'image-min',
imageClean: 'image-clean',
cleanProd: 'clean-production',
copyFonts: 'copy-fonts',
browserSync: 'browser-sync-server',
watch: 'watch',
},
autoprefixer: {
versions: 'last 4 versions'
},
ignore: function() {
return [
`!${this.folder.src}/`,
`!${this.folder.src}/**/*`,
'!bower/',
'!bower/**/*',
'!node_modules/**/*',
'!node_modules/',
`!${this.folder.build}/css/**.map`,
`!${this.folder.build}/images/info.txt`,
'!.bowerrc',
'!bower.json',
'!.gitignore',
'!gulpfile.js',
'!LICENSE',
'!package.json',
`!${this.folder.prod}`,
'!README.md',
'!CONTRIBUTING.md',
'!gulp-config.js',
'!docs/',
'!docs/**/*',
'!tasks/',
'!tasks/**/*'
];
}
}; | module.exports = {
folder: {
tasks: 'tasks',
src: 'src',
build: 'assets',
prod: 'production'
},
task: {
htmlHint: 'html-hint',
jsHint: 'js-hint',
buildCustomJs: 'build-custom-js',
buildJsVendors: 'build-js-vendors',
buildSass: 'build-sass',
buildSassProd: 'build-sass-production',
buildStylesVendors: 'build-styles-vendors',
imageMin: 'image-min',
imageClean: 'image-clean',
cleanProd: 'clean-production',
copyFonts: 'copy-fonts',
browserSync: 'browser-sync-server',
watch: 'watch',
},
autoprefixer: {
versions: 'last 4 versions'
},
ignore: function() {
return [
'!bower/',
'!bower/**/*',
'!node_modules/**/*',
'!node_modules/',
`!${this.folder.build}/css/**.map`,
`!${this.folder.build}/images/info.txt`,
'!.bowerrc',
'!bower.json',
'!.gitignore',
'!gulpfile.js',
'!LICENSE',
'!package.json',
`!${this.folder.prod}`,
'!README.md',
'!CONTRIBUTING.md',
'!gulp-config.js',
'!docs/',
'!docs/**/*'
];
}
}; |
Fix result loading for novel mutations | from models import Protein, Mutation
from database import get_or_create
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
state['mutation'], created = get_or_create(
Mutation,
protein=state['protein'],
**state['mutation_kwargs']
)
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
| from models import Protein, Mutation
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
state['mutation'] = Mutation.query.filter_by(
protein=state['protein'],
**state['mutation_kwargs']
).one()
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
|
Add pytest-mock to the dependencies | from setuptools import setup
setup(
name='webcomix',
version=1.3,
description='Webcomic downloader',
long_description='webcomix is a webcomic downloader that can additionally create a .cbz file once downloaded.',
url='https://github.com/J-CPelletier/webcomix',
author='Jean-Christophe Pelletier',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet :: WWW/HTTP',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent'
],
packages=[
"webcomix"
],
install_requires=[
'Click',
'lxml',
'requests',
'fake-useragent',
'scrapy'
],
extras_require={
'dev': [
'pytest',
'pytest-cov',
'pytest-mock',
'coveralls'
]
},
python_requires='>=3.5',
entry_points='''
[console_scripts]
webcomix=webcomix.main:cli
''',
)
| from setuptools import setup
setup(
name='webcomix',
version=1.3,
description='Webcomic downloader',
long_description='webcomix is a webcomic downloader that can additionally create a .cbz file once downloaded.',
url='https://github.com/J-CPelletier/webcomix',
author='Jean-Christophe Pelletier',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: End Users/Desktop',
'Topic :: Internet :: WWW/HTTP',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent'
],
packages=[
"webcomix"
],
install_requires=[
'Click',
'lxml',
'requests',
'fake-useragent',
'scrapy'
],
extras_require={
'dev': [
'pytest',
'pytest-cov',
'coveralls'
]
},
python_requires='>=3.5',
entry_points='''
[console_scripts]
webcomix=webcomix.main:cli
''',
)
|
Fix test extraction in FileReaderDecorator. | # Copyright (c) 2017-2018 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(kwargs['test'], 'rb') as f:
issue['filename'] = os.path.basename(kwargs['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
| # Copyright (c) 2017 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(issue['test'], 'rb') as f:
issue['filename'] = os.path.basename(issue['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
|
Fix mock needing config_file variable | from __future__ import absolute_import, unicode_literals
import argparse
import unittest
from nose.tools import ok_
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from streamparse.cli.run import main, subparser_hook
class RunTestCase(unittest.TestCase):
def test_subparser_hook(self):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
subparser_hook(subparsers)
subcommands = parser._optionals._actions[1].choices.keys()
ok_('run' in subcommands)
@patch('streamparse.cli.run.run_local_topology', autospec=True)
def test_main_args_passed(self, run_local_mock):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
subparser_hook(subparsers)
args = parser.parse_args('run -e my_env -n my_topo --ackers 1'.split())
main(args)
run_local_mock.assert_called_with(name='my_topo',
options={'topology.acker.executors': 1},
env_name='my_env',
time=0,
config_file=None)
if __name__ == '__main__':
unittest.main()
| from __future__ import absolute_import, unicode_literals
import argparse
import unittest
from nose.tools import ok_
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from streamparse.cli.run import main, subparser_hook
class RunTestCase(unittest.TestCase):
def test_subparser_hook(self):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
subparser_hook(subparsers)
subcommands = parser._optionals._actions[1].choices.keys()
ok_('run' in subcommands)
@patch('streamparse.cli.run.run_local_topology', autospec=True)
def test_main_args_passed(self, run_local_mock):
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
subparser_hook(subparsers)
args = parser.parse_args('run -e my_env -n my_topo --ackers 1'.split())
main(args)
run_local_mock.assert_called_with(name='my_topo',
options={'topology.acker.executors': 1},
env_name='my_env',
time=0)
if __name__ == '__main__':
unittest.main()
|
Add aiAttack details to swarmer | import {
child, avenger, protector, persecutor,
scorpion,
} from 'emoji';
export default {
/* The Good Guys */
child: {
name: `Child`,
emoji: child,
type: true,
maxHealth: 40,
abilities: {
move: {
range: 3,
},
},
},
avenger: {
name: `Avenger`,
emoji: avenger,
type: true,
maxHealth: 80,
abilities: {
move: {
range: 3,
},
attack: {
name: `Avenge`,
range: 1,
damage: 25,
}
},
},
protector: {
name: `Protector`,
emoji: protector,
type: true,
maxHealth: 100,
abilities: {
move: {
range: 2,
},
},
},
persecutor: {
name: `Persecutor`,
emoji: persecutor,
type: true,
maxHealth: 60,
abilities: {
move: {
range: 5,
},
},
},
/* The Bad Guys */
swarmer: {
name: `Swarmer`,
emoji: scorpion,
type: false,
maxHealth: 30,
abilities: {
swarm: {
range: 5,
},
aiAttack: {
range: 1,
damage: 15,
}
}
}
};
| import {
child, avenger, protector, persecutor,
scorpion,
} from 'emoji';
export default {
/* The Good Guys */
child: {
name: `Child`,
emoji: child,
type: true,
maxHealth: 40,
abilities: {
move: {
range: 3,
},
},
},
avenger: {
name: `Avenger`,
emoji: avenger,
type: true,
maxHealth: 80,
abilities: {
move: {
range: 3,
},
attack: {
name: `Avenge`,
range: 1,
damage: 25,
}
},
},
protector: {
name: `Protector`,
emoji: protector,
type: true,
maxHealth: 100,
abilities: {
move: {
range: 2,
},
},
},
persecutor: {
name: `Persecutor`,
emoji: persecutor,
type: true,
maxHealth: 60,
abilities: {
move: {
range: 5,
},
},
},
/* The Bad Guys */
swarmer: {
name: `Swarmer`,
emoji: scorpion,
type: false,
maxHealth: 30,
abilities: {
swarm: {
range: 5,
}
}
}
};
|
Rename BlankConfig to something that makes more sense | package ml.duncte123.skybot.config;
import com.google.gson.*;
import org.apache.commons.text.translate.UnicodeUnescaper;
import java.io.*;
public class ConfigLoader {
/**
* This will attempt to load the config and create it if it is not there
* @param file the file to load
* @return the loaded config
* @throws Exception if something goes wrong
*/
public static Config getConfig(final File file) throws Exception{
if (!file.exists()) {
file.createNewFile();
final FileWriter writer = new FileWriter(file);
writer.write("{}");
writer.close();
}
return new MainConfig(file);
}
public static class MainConfig extends Config {
private final File configFile;
MainConfig(final File file) throws Exception {
super(null, new JsonParser().parse(new FileReader(file)).getAsJsonObject());
this.configFile = file;
}
@Override
public File getConfigFile()
{
return this.configFile;
}
@Override
public void save() throws Exception {
final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
final String json = gson.toJson(this.config);
try {
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.configFile), "UTF-8"));
new UnicodeUnescaper().translate(json, writer);
writer.close();
}
catch (final IOException e) {
e.printStackTrace();
}
}
}
}
| package ml.duncte123.skybot.config;
import com.google.gson.*;
import org.apache.commons.text.translate.UnicodeUnescaper;
import java.io.*;
public class ConfigLoader {
/**
* This will attempt to load the config and create it if it is not there
* @param file the file to load
* @return the loaded config
* @throws Exception if something goes wrong
*/
public static Config getConfig(final File file) throws Exception{
if (!file.exists()) {
file.createNewFile();
final FileWriter writer = new FileWriter(file);
writer.write("{}");
writer.close();
}
return new BlankConfig(file);
}
public static class BlankConfig extends Config {
private final File configFile;
BlankConfig(final File file) throws Exception {
super(null, new JsonParser().parse(new FileReader(file)).getAsJsonObject());
this.configFile = file;
}
@Override
public File getConfigFile()
{
return this.configFile;
}
@Override
public void save() throws Exception {
final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
final String json = gson.toJson(this.config);
try {
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.configFile), "UTF-8"));
new UnicodeUnescaper().translate(json, writer);
writer.close();
}
catch (final IOException e) {
e.printStackTrace();
}
}
}
}
|
Replace Base64 with low quality placeholder
That should also fix MMV | <?php
/**
* Lazyload class
*/
class Lazyload {
public static function LinkerMakeExternalImage(&$url, &$alt, &$img) {
global $wgRequest;
if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
$url = preg_replace('/^(http|https):/', '', $url);
$img = '<span class="external-image" alt="' . htmlentities($alt) . '" data-url="' . htmlentities($url) . '"> </span>';
return false;
}
public static function ThumbnailBeforeProduceHTML($thumb, &$attribs, &$linkAttribs) {
global $wgRequest, $wgTitle;
if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
if (isset($wgTitle) && $wgTitle->getNamespace() === NS_FILE) return true;
$attribs['data-url'] = $attribs['src'];
$attribs['src'] = preg_replace('#/\d+px-#', '/10px-', $attribs['src']);
if (isset($attribs['srcset'])) {
$attribs['data-srcset'] = $attribs['srcset'];
unset($attribs['srcset']);
}
return true;
}
public static function BeforePageDisplay($out, $skin) {
$out->addModules( 'ext.lazyload' );
return true;
}
}
| <?php
/**
* Lazyload class
*/
class Lazyload {
public static function LinkerMakeExternalImage(&$url, &$alt, &$img) {
global $wgRequest;
if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
$url = preg_replace('/^(http|https):/', '', $url);
$img = '<span class="external-image" alt="' . htmlentities($alt) . '" data-url="' . htmlentities($url) . '"> </span>';
return false;
}
public static function ThumbnailBeforeProduceHTML($thumb, &$attribs, &$linkAttribs) {
global $wgRequest, $wgTitle;
if (defined('MW_API') && $wgRequest->getVal('action') === 'parse') return true;
if (isset($wgTitle) && $wgTitle->getNamespace() === NS_FILE) return true;
$attribs['data-url'] = $attribs['src'];
$attribs['src'] = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
if (isset($attribs['srcset'])) {
$attribs['data-srcset'] = $attribs['srcset'];
unset($attribs['srcset']);
}
return true;
}
public static function BeforePageDisplay($out, $skin) {
$out->addModules( 'ext.lazyload' );
return true;
}
}
|
Use class names in service provider. | <?php
namespace DvK\Laravel\Vat;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator as RequestValidator;
class VatServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
RequestValidator::extend('vat_number', function($attribute, $value, $parameters, $validator ) {
$vatValidator = new Validator();
$data = $validator->getData();
$country = isset( $data['country'] ) ? $data['country'] : '';
return $vatValidator->check( $value, $country );
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton( Validator::class, function (Container $app) {
return new Validator();
});
$this->app->singleton( Rates::class, function (Container $app) {
$defaultCacheDriver = $app['cache']->getDefaultDriver();
$cacheDriver = $app['cache']->driver( $defaultCacheDriver );
return new Rates( $cacheDriver );
});
}
/**
* Get the services provided by the provider.
*
* @return string[]
*/
public function provides()
{
return [
'DvK\Laravel\Vat\Validator',
'DvK\Laravel\Vat\Rates',
];
}
}
| <?php
namespace DvK\Laravel\Vat;
use Illuminate\Contracts\Container\Container;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator as RequestValidator;
class VatServiceProvider extends ServiceProvider
{
/**
* Boot the service provider.
*
* @return void
*/
public function boot()
{
RequestValidator::extend('vat_number', function($attribute, $value, $parameters, $validator ) {
$vatValidator = new Validator();
$data = $validator->getData();
$country = isset( $data['country'] ) ? $data['country'] : '';
return $vatValidator->check( $value, $country );
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('vat-validator', function (Container $app) {
return new Validator();
});
$this->app->singleton('vat-rates', function (Container $app) {
$defaultCacheDriver = $app['cache']->getDefaultDriver();
$cacheDriver = $app['cache']->driver( $defaultCacheDriver );
return new Rates( $cacheDriver );
});
}
/**
* Get the services provided by the provider.
*
* @return string[]
*/
public function provides()
{
return [
'vat-rates',
'vat-validator',
];
}
}
|
Add automatic regeneration for CLion | #!/usr/bin/env python3
"""This is a **proof-of-concept** CLion project generator."""
import functools
import json
import subprocess
import sys
subprocess.check_call(['cook', '--results'])
with open('results.json') as file:
content = json.load(file)
with open('CMakeLists.txt', 'w') as file:
w = functools.partial(print, file=file)
w('cmake_minimum_required(VERSION 2.8.8)')
w()
w('add_custom_target(COOK COMMAND ' + sys.executable + ' clion.py COMMAND cook '
'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})')
w()
outputs = {}
for primary, result in content.items():
for output in result['outputs']:
outputs[output] = primary
for primary, result in content.items():
if result.get('type') == 'cpp.object':
cpp = [file for file in result['inputs'] if file.endswith('.cpp')]
w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp)))
defines = ' '.join(name + '=' + str(val) for name, val
in result['define'].items())
if defines:
w('target_compile_definitions({} PRIVATE {})'
.format(primary, defines))
includes = result['include']
if includes:
w('target_include_directories({} PRIVATE {})'.format(
primary, ' '.join(includes)
))
w()
| #!/usr/bin/env python3
"""This is a **proof-of-concept** CLion project generator."""
import functools
import json
import subprocess
subprocess.check_call(['cook', '--results'])
with open('results.json') as file:
content = json.load(file)
with open('CMakeLists.txt', 'w') as file:
w = functools.partial(print, file=file)
w('cmake_minimum_required(VERSION 2.8.8)')
w()
w('add_custom_target(COOK COMMAND cook '
'WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})')
w()
outputs = {}
for primary, result in content.items():
for output in result['outputs']:
outputs[output] = primary
for primary, result in content.items():
if result.get('type') == 'cpp.object':
cpp = [file for file in result['inputs'] if file.endswith('.cpp')]
w('add_library({} OBJECT {})'.format(primary, ' '.join(cpp)))
defines = ' '.join(name + '=' + str(val) for name, val
in result['define'].items())
if defines:
w('target_compile_definitions({} PRIVATE {})'
.format(primary, defines))
includes = result['include']
if includes:
w('target_include_directories({} PRIVATE {})'.format(
primary, ' '.join(includes)
))
w()
|
Add tests for lines with both a count and percentage | #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%',
'ZMWs generating CCS (B) : 44 (47.31%)',
'Coefficient of correlation (A) : 28.78%',
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
},
{
'name': 'ZMWs generating CCS',
'annotation': 'B',
'count': 44,
'percentage': 47.31
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78,
'annotation': 'A'
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
| #!/usr/bin/env python3
import pytest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_PacBio_log, parse_line
PARSABLE_LINES = [
'',
'ZMWs input :',
'ZMWs input (A) :',
'ZMWs input : 93',
'ZMWs input (A) : 93',
'Coefficient of correlation : 28.78%'
]
PARSED_RESULTS = [
{},
{
'name':'ZMWs input'
},
{
'name':'ZMWs input',
'annotation':'A'
},
{
'name':'ZMWs input',
'count': 93
},
{
'name':'ZMWs input',
'annotation':'A',
'count': 93
},
{
'name': 'Coefficient of correlation',
'percentage': 28.78
}
]
MARK = zip(PARSABLE_LINES, PARSED_RESULTS)
@pytest.mark.parametrize(['line', 'data'], MARK)
def test_parsable_lines(line, data):
parsed_line = parse_line(line)
assert parsed_line == data
|
Convert directory output to the same as profile listing | @extends('components.content-area')
@section('content')
@include('components.page-title', ['title' => $page['title']])
<div class="content">
{!! $page['content']['main'] !!}
</div>
@forelse($profiles as $key => $profiles)
<h2>{{ $key }}</h2>
<div class="row flex flex-wrap -mx-4">
@foreach($profiles as $profile)
<div class="w-full sm:w-1/2 md:w-1/3 px-4 pb-6">
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}">
<div class="block bg-cover bg-center w-full pt-full lazy mb-1" data-src="{{ $profile['data']['Picture']['url'] ?? '/_resources/images/no-photo.svg' }}"></div>
<span class="font-bold">{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}</span>
</a>
@if(isset($profile['data']['Title']))
<span class="block text-sm">{{ $profile['data']['Title'] }}</span>
@endif
</div>
@endforeach
</div>
@empty
<p>No profiles found.</p>
@endforelse
@endsection
| @extends('components.content-area')
@section('content')
@include('components.page-title', ['title' => $page['title']])
<div class="content">
{!! $page['content']['main'] !!}
</div>
@forelse($profiles as $key => $profiles)
<h2>{{ $key }}</h2>
<div class="row flex flex-wrap -mx-4">
@foreach($profiles as $profile)
<div class="profile w-full sm:w-1/2 md:w-1/3 px-4 py-4">
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}" class="profile-img lazy " data-src="{{ $profile['data']['Picture']['url'] ?? '/_resources/images/no-photo.svg' }}">
<span class="visually-hidden">{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}</span>
</a>
<a href="/{{ ($site['subsite-folder'] !== null) ? $site['subsite-folder'] : '' }}profile/{{ $profile['data']['AccessID'] }}">{{ $profile['data']['First Name'] }} {{ $profile['data']['Last Name'] }}</a>
@if(isset($profile['data']['Title']))
<span>{{ $profile['data']['Title'] }}</span>
@endif
</div>
@endforeach
</div>
@empty
<p>No profiles found.</p>
@endforelse
@endsection
|
Remove commented out method call. | # -*- coding: utf-8 -*-
from .base_match import BaseMatchAdapter
from fuzzywuzzy import fuzz
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter selects a response to an
input statement by selecting the closest known matching
statement based on the Levenshtein Distance between the text
of each statement.
"""
def get(self, input_statement):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
statement_list = self.context.storage.get_response_statements()
if not statement_list:
if self.has_storage_context:
# Use a randomly picked statement
return 0, self.context.storage.get_random()
else:
raise self.EmptyDatasetException()
confidence = -1
closest_match = input_statement
# Find the closest matching known statement
for statement in statement_list:
ratio = fuzz.ratio(input_statement.text, statement.text)
if ratio > confidence:
confidence = ratio
closest_match = statement
# Convert the confidence integer to a percent
confidence /= 100.0
return confidence, closest_match
| # -*- coding: utf-8 -*-
from .base_match import BaseMatchAdapter
from fuzzywuzzy import fuzz
class ClosestMatchAdapter(BaseMatchAdapter):
"""
The ClosestMatchAdapter creates a response by
using fuzzywuzzy's process class to extract the most similar
response to the input. This adapter selects a response to an
input statement by selecting the closest known matching
statement based on the Levenshtein Distance between the text
of each statement.
"""
def get(self, input_statement):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
statement_list = self.context.storage.get_response_statements()
if not statement_list:
if self.has_storage_context:
# Use a randomly picked statement
return 0, self.context.storage.get_random()
else:
raise self.EmptyDatasetException()
confidence = -1
closest_match = input_statement
# Find the closest matching known statement
for statement in statement_list:
ratio = fuzz.ratio(input_statement.text, statement.text)
if ratio > confidence:
confidence = ratio
closest_match = statement
'''
closest_match, confidence = process.extractOne(
input_statement.text,
text_of_all_statements
)
'''
# Convert the confidence integer to a percent
confidence /= 100.0
return confidence, closest_match
|
Fix failing test for select | package seedu.address.logic.commands;
import seedu.address.commons.core.EventsCenter;
import seedu.address.commons.core.Messages;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.model.activity.ReadOnlyActivity;
import seedu.address.commons.core.UnmodifiableObservableList;
/**
* Selects a person identified using it's last displayed index from the address book.
*/
public class SelectCommand extends Command {
public final int targetIndex;
public static final String COMMAND_WORD = "select";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Selects the person identified by the index number used in the last person listing.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_SELECT_PERSON_SUCCESS = "Selected Task: %1$s";
public SelectCommand(int targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute() {
UnmodifiableObservableList<ReadOnlyActivity> lastShownList = model.getFilteredTaskList();
if (lastShownList.size() < targetIndex) {
indicateAttemptToExecuteIncorrectCommand();
return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
EventsCenter.getInstance().post(new JumpToListRequestEvent(targetIndex - 1));
return new CommandResult(String.format(MESSAGE_SELECT_PERSON_SUCCESS, targetIndex));
}
}
| package seedu.address.logic.commands;
import seedu.address.commons.core.EventsCenter;
import seedu.address.commons.core.Messages;
import seedu.address.commons.events.ui.JumpToListRequestEvent;
import seedu.address.model.activity.ReadOnlyActivity;
import seedu.address.commons.core.UnmodifiableObservableList;
/**
* Selects a person identified using it's last displayed index from the address book.
*/
public class SelectCommand extends Command {
public final int targetIndex;
public static final String COMMAND_WORD = "select";
public static final String MESSAGE_USAGE = COMMAND_WORD
+ ": Selects the person identified by the index number used in the last person listing.\n"
+ "Parameters: INDEX (must be a positive integer)\n"
+ "Example: " + COMMAND_WORD + " 1";
public static final String MESSAGE_SELECT_PERSON_SUCCESS = "Selected Person: %1$s";
public SelectCommand(int targetIndex) {
this.targetIndex = targetIndex;
}
@Override
public CommandResult execute() {
UnmodifiableObservableList<ReadOnlyActivity> lastShownList = model.getFilteredTaskList();
if (lastShownList.size() < targetIndex) {
indicateAttemptToExecuteIncorrectCommand();
return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
EventsCenter.getInstance().post(new JumpToListRequestEvent(targetIndex - 1));
return new CommandResult(String.format(MESSAGE_SELECT_PERSON_SUCCESS, targetIndex));
}
}
|
Add version to update url | const app = require('electron').app
const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL(`https://electron-api-demos.githubapp.com/updates?version=${app.getVersion()}`)
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
| const autoUpdater = require('electron').autoUpdater
const Menu = require('electron').Menu
var state = 'checking'
exports.initialize = function () {
autoUpdater.on('checking-for-update', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-available', function () {
state = 'checking'
exports.updateMenu()
})
autoUpdater.on('update-downloaded', function () {
state = 'installed'
exports.updateMenu()
})
autoUpdater.on('update-not-available', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.on('error', function () {
state = 'no-update'
exports.updateMenu()
})
autoUpdater.setFeedURL('https://electron-api-demos.githubapp.com/updates')
autoUpdater.checkForUpdates()
}
exports.updateMenu = function () {
var menu = Menu.getApplicationMenu()
if (!menu) return
menu.items.forEach(function (item) {
if (item.submenu) {
item.submenu.items.forEach(function (item) {
switch (item.key) {
case 'checkForUpdate':
item.visible = state === 'no-update'
break
case 'checkingForUpdate':
item.visible = state === 'checking'
break
case 'restartToUpdate':
item.visible = state === 'installed'
break
}
})
}
})
}
|
Fix from 'static::' to 'self::'. | <?php
namespace Imunew\Pipeline\Context;
/**
* Class Status
* @package Imunew\Pipeline
*/
class Status implements StatusInterface
{
/** @var string */
private static $INITIALIZED = 'initialized';
/** @var string */
private static $STARTED = 'started';
/** @var string */
private static $STOPPED = 'stopped';
/** @var string */
private $status;
/**
* Status constructor.
* @param string $status
*/
private function __construct($status)
{
$this->status = $status;
}
/**
* @return StatusInterface
*/
public static function initialize()
{
return new static(self::$INITIALIZED);
}
/**
* @return StatusInterface
*/
public static function start()
{
return new static(self::$STARTED);
}
/**
* @return StatusInterface
*/
public static function stop()
{
return new static(self::$STOPPED);
}
/**
* @return bool
*/
public function isInitialized()
{
return in_array($this->status, [self::$INITIALIZED]);
}
/**
* @return bool
*/
public function isStarted()
{
return in_array($this->status, [self::$STARTED]);
}
/**
* @return bool
*/
public function isStopped()
{
return in_array($this->status, [self::$STOPPED]);
}
}
| <?php
namespace Imunew\Pipeline\Context;
/**
* Class Status
* @package Imunew\Pipeline
*/
class Status implements StatusInterface
{
/** @var string */
private static $INITIALIZED = 'initialized';
/** @var string */
private static $STARTED = 'started';
/** @var string */
private static $STOPPED = 'stopped';
/** @var string */
private $status;
/**
* Status constructor.
* @param string $status
*/
private function __construct($status)
{
$this->status = $status;
}
/**
* @return StatusInterface
*/
public static function initialize()
{
return new static(static::$INITIALIZED);
}
/**
* @return StatusInterface
*/
public static function start()
{
return new static(static::$STARTED);
}
/**
* @return StatusInterface
*/
public static function stop()
{
return new static(static::$STOPPED);
}
/**
* @return bool
*/
public function isInitialized()
{
return in_array($this->status, [static::$INITIALIZED]);
}
/**
* @return bool
*/
public function isStarted()
{
return in_array($this->status, [static::$STARTED]);
}
/**
* @return bool
*/
public function isStopped()
{
return in_array($this->status, [static::$STOPPED]);
}
}
|
Add done result to replay | import json
from os import path
from tota.game import Drawer
class JsonReplayDrawer(Drawer):
def __init__(self, replay_dir):
self.replay_dir = replay_dir
def draw(self, game):
"""Draw the world with 'ascii'-art ."""
things_data = []
tick_data = {
't': game.world.t,
'things': things_data,
'effects': [{
'position': position,
'effect': effect,
}
for position, effect in game.world.effects.items()]
}
for thing in game.world.things.values():
thing_data = {
'id': id(thing),
'type': thing.__class__.__name__,
'position': thing.position,
}
if thing_data['type'] != 'Tree':
thing_data.update({
'life': thing.life,
'name': thing.name,
'team': thing.team,
'level': getattr(thing, 'level', None),
'xp': getattr(thing, 'xp', None),
'action': thing.last_action,
'target': thing.last_target,
'action_done': thing.last_action_done,
})
things_data.append(thing_data)
tick_path = path.join(self.replay_dir, '%08d.json' % game.world.t)
with open(tick_path, 'w') as tick_file:
json.dump(tick_data,
tick_file,
indent=2 if game.debug else None)
| import json
from os import path
from tota.game import Drawer
class JsonReplayDrawer(Drawer):
def __init__(self, replay_dir):
self.replay_dir = replay_dir
def draw(self, game):
"""Draw the world with 'ascii'-art ."""
things_data = []
tick_data = {
't': game.world.t,
'things': things_data,
'effects': [{
'position': position,
'effect': effect,
}
for position, effect in game.world.effects.items()]
}
for thing in game.world.things.values():
thing_data = {
'id': id(thing),
'type': thing.__class__.__name__,
'position': thing.position,
}
if thing_data['type'] != 'Tree':
thing_data.update({
'life': thing.life,
'name': thing.name,
'team': thing.team,
'level': getattr(thing, 'level', None),
'xp': getattr(thing, 'xp', None),
'action': thing.last_action,
'target': thing.last_target,
})
things_data.append(thing_data)
tick_path = path.join(self.replay_dir, '%08d.json' % game.world.t)
with open(tick_path, 'w') as tick_file:
json.dump(tick_data,
tick_file,
indent=2 if game.debug else None)
|
Set correct gen_description in rss importer. |
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url in urls:
for entry in parse(url).entries:
link = self.entry_to_link_dict(entry)
try:
Link.objects.get(link=link["link"])
except Link.DoesNotExist:
Link.objects.create(**link)
def entry_to_link_dict(self, entry):
link = {"title": entry.title, "user_id": 1, "gen_description": False}
try:
link["link"] = entry.summary.split('href="')[2].split('"')[0]
except IndexError:
link["link"] = entry.link
try:
publish_date = entry.published_parsed
except AttributeError:
pass
else:
publish_date = datetime.fromtimestamp(mktime(publish_date))
publish_date = make_aware(publish_date, get_default_timezone())
link["publish_date"] = publish_date
return link
|
from datetime import datetime
from time import mktime
from django.core.management.base import BaseCommand
from django.utils.timezone import get_default_timezone, make_aware
from feedparser import parse
from ...models import Link
class Command(BaseCommand):
def handle(self, *urls, **options):
for url in urls:
for entry in parse(url).entries:
link = self.entry_to_link_dict(entry)
try:
Link.objects.get(link=link["link"])
except Link.DoesNotExist:
Link.objects.create(**link)
def entry_to_link_dict(self, entry):
link = {"title": entry.title, "user_id": 1}
try:
link["link"] = entry.summary.split('href="')[2].split('"')[0]
except IndexError:
link["link"] = entry.link
try:
publish_date = entry.published_parsed
except AttributeError:
pass
else:
publish_date = datetime.fromtimestamp(mktime(publish_date))
publish_date = make_aware(publish_date, get_default_timezone())
link["publish_date"] = publish_date
return link
|
Optimize by using isdisjoint instead of finding intersection. | """
Derive a list of impossible differentials.
"""
import ast
import sys
def parse(line):
i, rounds, xss = ast.literal_eval(line)
yss = [set(xs) for xs in xss]
return (i, rounds, yss)
def main():
if len(sys.argv) != 3:
print("usage: ./find_ids.py [forward differentials file] [backward differentials file]", file=sys.stderr)
sys.exit(1)
ids = []
with open(sys.argv[1]) as f:
for i, forward_rounds, xss in map(parse, f):
if forward_rounds < 2:
continue
with open(sys.argv[2]) as g:
for j, backward_rounds, yss in map(parse, g):
if backward_rounds < 2:
continue
# truncate first round of backward differential
# by comparing last round of forward differential and second last
# round of backward differential
if xss[-1].isdisjoint(yss[-2]):
backward_rounds -= 1
print((i, forward_rounds, backward_rounds, j))
if __name__ == "__main__":
main()
| """
Derive a list of impossible differentials.
"""
import ast
import sys
def parse(line):
i, rounds, xss = ast.literal_eval(line)
yss = [set(xs) for xs in xss]
return (i, rounds, yss)
def main():
if len(sys.argv) != 3:
print("usage: ./find_ids.py [forward differentials file] [backward differentials file]", file=sys.stderr)
sys.exit(1)
ids = []
with open(sys.argv[1]) as f:
for i, forward_rounds, xss in map(parse, f):
with open(sys.argv[2]) as g:
for j, backward_rounds, yss in map(parse, g):
# truncate first round of backward differential
# by comparing last round of forward differential and second last
# round of backward differential
if xss[-1].intersection(yss[-2]) == set():
backward_rounds -= 1
rounds = forward_rounds + backward_rounds
# or vice versa
elif xss[-2].intersection(yss[-1]) == set():
forward_rounds -= 1
rounds = forward_rounds + backward_rounds
# if there is no contradiction, skip
else:
continue
if rounds >= 3:
print((i, forward_rounds, backward_rounds, j))
if __name__ == "__main__":
main()
|
chore(rollup): Mark strip-ansi as an external dependency | // @flow
import babel from 'rollup-plugin-babel';
// eslint-disable-next-line
export default function buildConfig(
// eslint-disable-next-line
entry /*: string*/,
// eslint-disable-next-line
dest /*: string*/
) /*: Object*/ {
return {
entry,
format: 'cjs',
plugins: [
babel({
babelrc: false,
exclude: 'node_modules/**',
presets: [
[
'env',
{
targets: {
node: '4.8',
},
modules: false,
exclude: ['transform-regenerator'],
},
],
],
plugins: [
'transform-decorators-legacy',
'transform-flow-strip-types',
'transform-class-properties',
'transform-object-rest-spread',
'transform-async-generator-functions',
'external-helpers',
],
}),
],
dest,
external: [
'lodash',
'string-humanize',
'retrieve-arguments',
'fs',
'crypto',
'babel-polyfill',
'yargs',
'zlib',
'decompress-zip',
'fs-extra',
'rimraf',
'strip-ansi',
],
};
}
| // @flow
import babel from 'rollup-plugin-babel';
// eslint-disable-next-line
export default function buildConfig(
// eslint-disable-next-line
entry /*: string*/,
// eslint-disable-next-line
dest /*: string*/
) /*: Object*/ {
return {
entry,
format: 'cjs',
plugins: [
babel({
babelrc: false,
exclude: 'node_modules/**',
presets: [
[
'env',
{
targets: {
node: '4.8',
},
modules: false,
exclude: ['transform-regenerator'],
},
],
],
plugins: [
'transform-decorators-legacy',
'transform-flow-strip-types',
'transform-class-properties',
'transform-object-rest-spread',
'transform-async-generator-functions',
'external-helpers',
],
}),
],
dest,
external: [
'lodash',
'string-humanize',
'retrieve-arguments',
'fs',
'crypto',
'babel-polyfill',
'yargs',
'zlib',
'decompress-zip',
'fs-extra',
'rimraf',
],
};
}
|
Test the volume rather than series. | import os
from nose.tools import (assert_equal, assert_in, assert_true)
from ...helpers.logging import logger
from qipipe.interfaces import GroupDicom
from ... import ROOT
from ...helpers.logging import logger
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', 'breast', 'BreastChemo3',
'Visit1')
class TestGroupDicom(object):
"""GroupDicom interface unit tests."""
def test_group_dicom(self):
logger(__name__).debug("Testing the GroupDicom interface on %s..."
% FIXTURE)
grouper = GroupDicom(tag='AcquisitionNumber', in_files=FIXTURE)
result = grouper.run()
grp_dict = result.outputs.groups
assert_true(not not grp_dict, "GroupDicom did not group the files")
for volume in [1, 14]:
assert_in(volume, grp_dict, "GroupDicom did not group the volume %d"
% volume)
assert_equal(len(grp_dict[volume]), 1, "Too many DICOM files were"
" grouped into volume %d: %d" %
(volume, len(grp_dict[volume])))
logger(__name__).debug("GroupDicom interface test completed")
if __name__ == "__main__":
import nose
nose.main(defaultTest=__name__)
| import os
from nose.tools import (assert_equal, assert_in, assert_true)
from ...helpers.logging import logger
from qipipe.interfaces import GroupDicom
from ... import ROOT
from ...helpers.logging import logger
# The test fixture.
FIXTURE = os.path.join(ROOT, 'fixtures', 'staging', 'breast', 'BreastChemo3',
'Visit1')
class TestGroupDicom(object):
"""GroupDicom interface unit tests."""
def test_group_dicom(self):
logger(__name__).debug("Testing the GroupDicom interface on %s..."
% FIXTURE)
grouper = GroupDicom(tag='SeriesNumber', in_files=FIXTURE)
result = grouper.run()
ser_dict = result.outputs.series_files_dict
assert_true(not not ser_dict, "GroupDicom did not group the files")
for series in [7, 33]:
assert_in(series, ser_dict, "GroupDicom did not group the"
" series %d" % series)
assert_equal(len(ser_dict[series]), 1, "Too many DICOM files were"
" grouped in series %d: %d" %
(series, len(ser_dict[series])))
logger(__name__).debug("GroupDicom interface test completed")
if __name__ == "__main__":
import nose
nose.main(defaultTest=__name__)
|
Add version, utf-8 and some comments. | # -*- coding: utf-8 -*-
__version__ = '0.1'
from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
"""Start the Django server."""
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
"""Stop Django server."""
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
| from robot.api import logger
import os
import signal
import subprocess
ROBOT_LIBRARY_DOC_FORMAT = 'reST'
class DjangoLibrary:
"""A library for testing Django with Robot Framework.
"""
django_pid = None
selenium_pid = None
# TEST CASE => New instance is created for every test case.
# TEST SUITE => New instance is created for every test suite.
# GLOBAL => Only one instance is created during the whole test execution.
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self, host="127.0.0.1", port=8000):
self.host = host
self.port = port
def start_django(self):
args = [
'python',
'mysite/manage.py',
'runserver',
'%s:%s' % (self.host, self.port),
'--nothreading',
'--noreload',
]
self.django_pid = subprocess.Popen(args).pid
logger.console(
"Django started (PID: %s)" % self.django_pid,
)
def stop_django(self):
os.kill(self.django_pid, signal.SIGKILL)
logger.console(
"Django stopped (PID: %s)" % self.django_pid,
)
|
Remove email from frontend config | <?php
return [
'title' => 'Веб студия «Палитра»',
'title_short' => 'Палитра',
'title_long' => 'Студия веб дизайна «Палитра»',
'phone' => '+3 8(099) 008 20 17',
'vk_link' => 'https://vk.com/id249896813',
'fb_link' => 'https://www.facebook.com/profile.php?id=100007822838492',
'tw_link' => 'https://twitter.com/',
'description' => 'Одним из важнейших условий успешного бизнеса является наличие места для регулярного размещения актуальной информации о компании. Вам необходим ресурс, где можно опубликовать подробные сведения о предоставляемых услугах, условиях заказа, контактах и реквизитах.',
'keywords' => 'заказать сайт под ключ',
];
| <?php
return [
'adminEmail' => '[email protected]',
'title' => 'Веб студия «Палитра»',
'title_short' => 'Палитра',
'title_long' => 'Студия веб дизайна «Палитра»',
'phone' => '+3 8(099) 008 20 17',
'vk_link' => 'https://vk.com/id249896813',
'fb_link' => 'https://www.facebook.com/profile.php?id=100007822838492',
'tw_link' => 'https://twitter.com/',
'description' => 'Одним из важнейших условий успешного бизнеса является наличие места для регулярного размещения актуальной информации о компании. Вам необходим ресурс, где можно опубликовать подробные сведения о предоставляемых услугах, условиях заказа, контактах и реквизитах.',
'keywords' => 'заказать сайт под ключ',
];
|
Build mat lib relative path | const path = require('path');
const webpack = require('webpack');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
'babylonjs-materials': path.resolve(__dirname, './src/legacy/legacy-grid.ts'),
},
output: {
path: path.resolve(__dirname, '../dist/preview release/materialsLibrary'),
filename: 'babylonjs.materials.min.js',
libraryTarget: 'umd',
library: {
root: ["MATERIALS"],
amd: "babylonjs-materials",
commonjs: "babylonjs-materials"
},
umdNamedDefine: true
},
resolve: {
extensions: ['.ts']
},
externals: [
function(_, request, callback) {
if (/^babylonjs.*$/i.test(request)) {
callback(null, {
root: "BABYLON",
commonjs: "babylonjs",
commonjs2: "babylonjs",
amd: "babylonjs"
});
}
else {
callback();
}
},
],
devtool: "souce-map",
module: {
rules: [{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'awesome-typescript-loader',
options: {
configFileName: path.resolve(__dirname, './tsconfig.json'),
declaration: false
}
}]
}]
},
mode: "production",
plugins: [
new HardSourceWebpackPlugin(),
new webpack.WatchIgnorePlugin([
/\.js$/,
/\.d\.ts$/,
/\.fx$/
])
],
} | const path = require('path');
const webpack = require('webpack');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
'babylonjs-materials': path.resolve(__dirname, './src/legacy/legacy.ts'),
},
output: {
path: path.resolve(__dirname, '../dist/preview release/materialsLibrary'),
filename: 'babylonjs.materials.min.js',
libraryTarget: 'umd',
library: {
root: ["MATERIALS"],
amd: "babylonjs-materials",
commonjs: "babylonjs-materials"
},
umdNamedDefine: true
},
resolve: {
extensions: ['.ts']
},
externals: [
{
babylonjs: {
root: "BABYLON",
commonjs: "babylonjs",
commonjs2: "babylonjs",
amd: "babylonjs"
}
},
/^babylonjs.*$/i,
],
devtool: "souce-map",
module: {
rules: [{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'awesome-typescript-loader',
options: {
configFileName: path.resolve(__dirname, './tsconfig.json'),
declaration: false
}
}]
}]
},
mode: "production",
plugins: [
new HardSourceWebpackPlugin(),
new webpack.WatchIgnorePlugin([
/\.js$/,
/\.d\.ts$/,
/\.fx$/
])
],
} |
Split mergeStream into its own function | 'use strict';
var fs = require('fs');
var split = require('split');
var argv = require('minimist')(process.argv.slice(2));
if (!argv.hasOwnProperty('file')) {
console.log('Usage: node index.js --file <path to line delimited GeoJSON FeatureCollections>');
} else {
mergeStream(argv.file, argv.output);
}
function mergeStream(inputFile, outputFile) {
if (!outputFile) {
outputFile = argv.file.split('.')[0] + '-merged.json';
}
var inputStream = fs.createReadStream(inputFile, {encoding: 'utf8'}).pipe(split());
var featureCollection = {
"type": "FeatureCollection",
"features": []
};
var start = '{"type": "FeatureCollection", "features": [';
fs.appendFileSync(outputFile, start, {encoding: 'utf8'});
var comma = "";
var line = 0;
inputStream.on('data', function (chunk) {
line = line + 1;
process.stderr.cursorTo(0);
process.stderr.write('Processing line: ' + String(line));
if (chunk) {
var features = JSON.parse(chunk).features;
features.forEach(function (feature) {
fs.appendFileSync(outputFile, comma + JSON.stringify(feature), {encoding: 'utf8'});
if (!comma) {
comma = ',';
}
});
}
});
inputStream.on('end', function () {
var end = ']}';
fs.appendFileSync(outputFile, end, {encoding: 'utf8'});
console.log('\ndone');
});
}
| 'use strict';
var fs = require('fs');
var split = require('split');
var argv = require('minimist')(process.argv.slice(2));
module.exports = function () {
if (!argv.hasOwnProperty('file')) {
console.log('Usage: node index.js --file <path to line delimeted GeoJSON FeatureCollections>');
} else {
var inputFile = argv.file;
var outputFile = argv.output || argv.file.split('.')[0] + '-merged.json';
var inputStream = fs.createReadStream(inputFile, {encoding: 'utf8'}).pipe(split());
var featureCollection = {
"type": "FeatureCollection",
"features": []
};
var start = '{"type": "FeatureCollection", "features": [';
fs.appendFileSync(outputFile, start, {encoding: 'utf8'});
var comma = "";
var line = 0;
inputStream.on('data', function (chunk) {
line = line + 1;
process.stderr.cursorTo(0);
process.stderr.write('Processing line: '+ String(line));
if (chunk) {
var features = JSON.parse(chunk).features;
features.forEach(function (feature) {
fs.appendFileSync(outputFile, comma + JSON.stringify(feature), {encoding: 'utf8'});
if (!comma) {
comma = ',';
}
});
}
});
inputStream.on('end', function() {
var end = ']}';
fs.appendFileSync(outputFile, end, {encoding: 'utf8'});
console.log('\ndone');
});
}
} |
Configure webpack to handle runway-compiler being outside this directory | var path = require('path');
var resolveLoader = {
root: [
path.resolve('node_modules'),
],
};
module.exports = [{
entry: "./web.js",
output: {
path: __dirname,
filename: "bundle.js"
},
devtool: 'eval-cheap-module-source-map',
module: {
loaders: [
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.model$/,
loader: "raw"
},
{
test: /\.(woff|woff2)$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
},
{
test: /\.ttf$/,
loader: "file-loader"
},
{
test: /\.eot$/,
loader: "file-loader"
},
{
test: /\.svg$/,
loader: "file-loader"
},
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['react'],
},
},
{
test: /\.json$/,
loader: "json-loader"
},
]
},
resolveLoader: resolveLoader,
}, {
entry: "./worker.js",
output: {
path: __dirname,
filename: "worker-bundle.js"
},
devtool: 'eval-cheap-module-source-map',
target: 'webworker',
module: {
loaders: [
{
test: /\.json$/,
loader: "json-loader"
},
],
},
resolveLoader: resolveLoader,
}];
| module.exports = [{
entry: "./web.js",
output: {
path: __dirname,
filename: "bundle.js"
},
devtool: 'eval-cheap-module-source-map',
module: {
loaders: [
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.model$/,
loader: "raw"
},
{
test: /\.(woff|woff2)$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
},
{
test: /\.ttf$/,
loader: "file-loader"
},
{
test: /\.eot$/,
loader: "file-loader"
},
{
test: /\.svg$/,
loader: "file-loader"
},
{
test: /\.jsx$/,
loader: 'babel-loader',
query: {
presets: ['react'],
},
},
{
test: /\.json$/,
loader: "json-loader"
},
]
}
}, {
entry: "./worker.js",
output: {
path: __dirname,
filename: "worker-bundle.js"
},
devtool: 'eval-cheap-module-source-map',
target: 'webworker',
module: {
loaders: [
{
test: /\.json$/,
loader: "json-loader"
},
],
},
}];
|
Fix wrong pattern for minecraft names | package org.monospark.spongematchers.base;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.monospark.spongematchers.Matcher;
public final class NameMatcher implements Matcher<String> {
public static final Map<String, String> REPLACEMENTS = createReplacements();
public static final Pattern NAME_REGEX = createRegex();
private static Map<String, String> createReplacements() {
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("*", ".*");
replacements.put("?", ".");
return replacements;
}
private static Pattern createRegex() {
StringBuilder toAppend = new StringBuilder();
for (Entry<String, String> entry : REPLACEMENTS.entrySet()) {
toAppend.append("|").append(entry.getKey());
}
return Pattern.compile("[a-zA-Z](?:\\w" + toAppend.toString() + ")+");
}
private Pattern regex;
public NameMatcher(String regex) {
if (!NAME_REGEX.matcher(regex).matches()) {
throw new IllegalArgumentException("Invalid name regex: " + regex);
}
this.regex = Pattern.compile(regex);
}
NameMatcher(Pattern regex) {
this.regex = regex;
}
@Override
public boolean matches(String o) {
return regex.matcher(o).matches();
}
}
| package org.monospark.spongematchers.base;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.monospark.spongematchers.Matcher;
public final class NameMatcher implements Matcher<String> {
public static final Map<String, String> REPLACEMENTS = createReplacements();
public static final Pattern NAME_REGEX = createRegex();
private static Map<String, String> createReplacements() {
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("*", ".*");
replacements.put("?", ".");
return replacements;
}
private static Pattern createRegex() {
StringBuilder toAppend = new StringBuilder();
for (Entry<String, String> entry : REPLACEMENTS.entrySet()) {
toAppend.append("|").append(entry.getKey());
}
return Pattern.compile("(?:\\w" + toAppend.toString() + ")");
}
private Pattern regex;
public NameMatcher(String regex) {
if (!NAME_REGEX.matcher(regex).matches()) {
throw new IllegalArgumentException("Invalid name regex: " + regex);
}
this.regex = Pattern.compile(regex);
}
NameMatcher(Pattern regex) {
this.regex = regex;
}
@Override
public boolean matches(String o) {
return regex.matcher(o).matches();
}
}
|
Fix: Remove reference to non-existent class | <?php
declare(strict_types=1);
/**
* Copyright (c) 2017 Andreas Möller.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @link https://github.com/localheinz/test-util
*/
namespace Localheinz\Test\Util\Test\Unit;
use Localheinz\Test\Util\Helper;
use Localheinz\Test\Util\Test\Fixture;
use PHPUnit\Framework;
final class ProjectCodeTest extends Framework\TestCase
{
use Helper;
public function testProductionClassesAreAbstractOrFinal()
{
$this->assertClassesAreAbstractOrFinal(__DIR__ . '/../../src');
}
public function testProductionClassesHaveTests()
{
$this->assertClassesHaveTests(
__DIR__ . '/../../src',
'Localheinz\\Test\\Util\\',
'Localheinz\\Test\\Util\\Test\\Unit\\'
);
}
public function testTestClassesAreAbstractOrFinal()
{
$this->assertClassesAreAbstractOrFinal(__DIR__ . '/..', [
Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\AlsoNeitherAbstractNorFinal::class,
Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\NeitherAbstractNorFinal::class,
Fixture\ClassIsAbstract\ConcreteClass::class,
Fixture\ClassIsFinal\NeitherAbstractNorFinalClass::class,
]);
}
}
| <?php
declare(strict_types=1);
/**
* Copyright (c) 2017 Andreas Möller.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* @link https://github.com/localheinz/test-util
*/
namespace Localheinz\Test\Util\Test\Unit;
use Localheinz\Test\Util\Helper;
use Localheinz\Test\Util\Test\Fixture;
use PHPUnit\Framework;
final class ProjectCodeTest extends Framework\TestCase
{
use Helper;
public function testProductionClassesAreAbstractOrFinal()
{
$this->assertClassesAreAbstractOrFinal(__DIR__ . '/../../src');
}
public function testProductionClassesHaveTests()
{
$this->assertClassesHaveTests(
__DIR__ . '/../../src',
'Localheinz\\Test\\Util\\',
'Localheinz\\Test\\Util\\Test\\Unit\\'
);
}
public function testTestClassesAreAbstractOrFinal()
{
$this->assertClassesAreAbstractOrFinal(__DIR__ . '/..', [
Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\AlsoNeitherAbstractNorFinal::class,
Fixture\ClassesAreAbstractOrFinal\NotAllAbstractOrFinal\NeitherAbstractNorFinal::class,
Fixture\ClassIsAbstract\ConcreteClass::class,
Fixture\ClassIsAbstractOrFinal\NeitherAbstractNorFinalClass::class,
Fixture\ClassIsFinal\NeitherAbstractNorFinalClass::class,
]);
}
}
|
Allow randomized size and position for enemies | /**
* enemy.js
*
* Manages creation and properties for our enemy object
*/
// Alias our enemy object
var enemy = game.objs.enemy;
/**
* Enemy object factory
*
* @returns {object}
*/
var createEnemy = function() {
var svg = document.getElementById('game-board');
var rect = document.createElementNS(SVG_SPEC, 'rect');
var gameBoard = game.objs.board;
var getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
var width = getRandomInt(10, 40);
var height = getRandomInt(10, 40);
var xPos = getRandomInt(100, gameBoard.width - width);
var yPos = getRandomInt(100, gameBoard.height - height);
var init = function() {
rect.setAttribute('x', xPos);
rect.setAttribute('y', yPos);
rect.setAttribute('width', width);
rect.setAttribute('height', height);
rect.id = 'enemy';
svg.appendChild(rect);
};
var destroy = function() {
var gameBoard = document.getElementById('game-board');
var enemy = document.getElementById('enemy');
if (enemy) {
gameBoard.removeChild(enemy);
}
game.destroy('enemy');
};
init();
return {
xPos: xPos,
yPos: yPos,
width: width,
height: height,
area: width * height,
destroy: destroy
};
};
// Set objects and methods
game.create.enemy = createEnemy;
game.objs.enemy = game.create.enemy(); | /**
* enemy.js
*
* Manages creation and properties for our enemy object
*/
// Alias our enemy object
var enemy = game.objs.enemy;
/**
* Enemy object factory
*
* @returns {object}
*/
var createEnemy = function() {
var svg = document.getElementById('game-board');
var rect = document.createElementNS(SVG_SPEC, 'rect');
var gameBoard = game.objs.board;
var xPos = 100;
var yPos = 100;
var width = 10;
var height = 10;
var init = function() {
rect.setAttribute('x', xPos);
rect.setAttribute('y', yPos);
rect.setAttribute('width', width);
rect.setAttribute('height', height);
rect.id = 'enemy';
svg.appendChild(rect);
};
var destroy = function() {
var gameBoard = document.getElementById('game-board');
var enemy = document.getElementById('enemy');
if (enemy) {
gameBoard.removeChild(enemy);
}
game.destroy('enemy');
};
init();
return {
xPos: xPos,
yPos: yPos,
width: width,
height: height,
area: width * height,
destroy: destroy
};
};
// Set objects and methods
game.create.enemy = createEnemy;
game.objs.enemy = game.create.enemy(); |
Add null check to format builder | package uk.co.drnaylor.minecraft.hammer.bukkit.text;
import org.bukkit.ChatColor;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerText;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextColours;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextFormats;
public final class HammerTextConverter {
private HammerTextConverter() { }
/**
* Constructs a message from the collection of {@link HammerText} messages.
*
* @param message The {@link HammerText} messages.
* @return The completed message.
*/
public static String constructMessage(HammerText message) {
StringBuilder sb = new StringBuilder();
for (HammerText.Element t : message.getElements()) {
if (sb.length() > 0) {
sb.append(ChatColor.RESET);
}
convertColour(t.colour, sb);
convertFormats(t.formats, sb);
sb.append(t.message);
}
return sb.toString();
}
private static void convertColour(HammerTextColours colour, StringBuilder sb) {
ChatColor c = HammerTextToCodeConverter.getCodeFromHammerText(colour);
if (c != null) {
sb.append(c);
}
}
private static void convertFormats(HammerTextFormats[] formats, StringBuilder sb) {
for (HammerTextFormats f : formats) {
if (f != null) {
sb.append(HammerTextToCodeConverter.getCodeFromHammerText(f));
}
}
}
}
| package uk.co.drnaylor.minecraft.hammer.bukkit.text;
import org.bukkit.ChatColor;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerText;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextColours;
import uk.co.drnaylor.minecraft.hammer.core.text.HammerTextFormats;
public final class HammerTextConverter {
private HammerTextConverter() { }
/**
* Constructs a message from the collection of {@link HammerText} messages.
*
* @param message The {@link HammerText} messages.
* @return The completed message.
*/
public static String constructMessage(HammerText message) {
StringBuilder sb = new StringBuilder();
for (HammerText.Element t : message.getElements()) {
if (sb.length() > 0) {
sb.append(ChatColor.RESET);
}
convertColour(t.colour, sb);
convertFormats(t.formats, sb);
sb.append(t.message);
}
return sb.toString();
}
private static void convertColour(HammerTextColours colour, StringBuilder sb) {
ChatColor c = HammerTextToCodeConverter.getCodeFromHammerText(colour);
if (c != null) {
sb.append(c);
}
}
private static void convertFormats(HammerTextFormats[] formats, StringBuilder sb) {
for (HammerTextFormats f : formats) {
sb.append(HammerTextToCodeConverter.getCodeFromHammerText(f));
}
}
}
|
Use hash location type for Github pages. | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'letnar-frontend',
environment: environment,
baseURL: '/',
locationType: 'auto',
adapterNamespace: 'api',
contentSecurityPolicy: {
'connect-src': "*",
'script-src': "'unsafe-eval' *",
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/ember-map-demo';
ENV.adapterNamespace = 'ember-map-demo/api';
ENV.locationType = 'hash';
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'letnar-frontend',
environment: environment,
baseURL: '/',
locationType: 'auto',
adapterNamespace: 'api',
contentSecurityPolicy: {
'connect-src': "*",
'script-src': "'unsafe-eval' *",
},
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = '/ember-map-demo';
ENV.adapterNamespace = 'ember-map-demo/api';
}
return ENV;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.