text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix bug in exception handling | from django.utils.translation import get_language
from django.db.models import Model
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
try:
from django.utils.translation import override
except ImportError:
from django.utils.translation import activate, deactivate
class override(object):
def __init__(self, language, deactivate=False):
self.language = language
self.deactivate = deactivate
self.old_language = get_language()
def __enter__(self):
activate(self.language)
def __exit__(self, exc_type, exc_value, traceback):
if self.deactivate:
deactivate()
else:
activate(self.old_language)
def name_in_language(obj, field):
try:
return getattr(obj.names.get(language_code=get_language()), field)
except ObjectDoesNotExist:
try:
return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE), field)
except ObjectDoesNotExist:
if '-' in settings.LANGUAGE_CODE:
return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE.split('-')[0]), field)
else:
raise | from django.utils.translation import get_language
from django.db.models import Model
from django.conf import settings
try:
from django.utils.translation import override
except ImportError:
from django.utils.translation import activate, deactivate
class override(object):
def __init__(self, language, deactivate=False):
self.language = language
self.deactivate = deactivate
self.old_language = get_language()
def __enter__(self):
activate(self.language)
def __exit__(self, exc_type, exc_value, traceback):
if self.deactivate:
deactivate()
else:
activate(self.old_language)
def name_in_language(obj, field):
try:
return getattr(obj.names.get(language_code=get_language()), field)
except Model.DoesNotExist:
try:
return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE), field)
except Model.DoesNotExist:
if '-' in settings.LANGUAGE_CODE:
return getattr(obj.names.get(language_code=settings.LANGUAGE_CODE.split('-')[0]), field)
else:
raise |
Make learn more link clickable. |
package com.battlelancer.seriesguide.ui;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.uwetrottmann.seriesguide.R;
/**
* Tells about trakt and how it integrates with SeriesGuide, allows to proceed
* to entering credentials step.
*/
public class ConnectTraktFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.connect_trakt_fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// connect button
getView().findViewById(R.id.buttonConnectTrakt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ConnectTraktCredentialsFragment f = ConnectTraktCredentialsFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.root_container, f);
ft.commit();
}
});
// discard button
getView().findViewById(R.id.buttonDiscard).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
// make learn more link clickable
((TextView) getView().findViewById(R.id.textViewAbout))
.setMovementMethod(LinkMovementMethod.getInstance());
}
}
|
package com.battlelancer.seriesguide.ui;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import com.uwetrottmann.seriesguide.R;
/**
* Tells about trakt and how it integrates with SeriesGuide, allows to proceed
* to entering credentials step.
*/
public class ConnectTraktFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.connect_trakt_fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// connect button
getView().findViewById(R.id.buttonConnectTrakt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ConnectTraktCredentialsFragment f = ConnectTraktCredentialsFragment.newInstance();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.root_container, f);
ft.commit();
}
});
// discard button
getView().findViewById(R.id.buttonDiscard).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
}
|
Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint | from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.ModelSerializer):
x = serializers.SerializerMethodField('get_time')
y = serializers.SerializerMethodField('get_value')
class Meta:
fields = ['x', 'y']
def get_time(self, obj):
return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC
def get_value(self, obj):
return obj.value
class MeasurementGraphSeriesSerializer(GraphSeriesSerializer):
alarm = serializers.SerializerMethodField('get_alarm')
def __init__(self, *args, **kwargs):
self.alarm_dict = kwargs.pop('alarm_dict', None)
super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs)
if not self.alarm_dict:
self.fields.pop('alarm')
def get_alarm(self, obj):
if obj.id in self.alarm_dict:
alarm = self.alarm_dict[obj.id]
serializer = SimpleAlarmSerializer(alarm)
return serializer.data
return None
class Meta(GraphSeriesSerializer.Meta):
model = Measurement
fields = GraphSeriesSerializer.Meta.fields + ['alarm']
class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer):
class Meta(GraphSeriesSerializer.Meta):
model = ThresholdValue
class SimpleAlarmSerializer(serializers.ModelSerializer):
class Meta:
model = Alarm
fields = ['is_treated']
| from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.ModelSerializer):
x = serializers.SerializerMethodField('get_time')
y = serializers.SerializerMethodField('get_value')
class Meta:
fields = ['x', 'y']
def get_time(self, obj):
return int(timegm(obj.time.utctimetuple())) * 1000 # Milliseconds since epoch, UTC
def get_value(self, obj):
return obj.value
class MeasurementGraphSeriesSerializer(GraphSeriesSerializer):
alarm = serializers.SerializerMethodField('get_alarm')
def __init__(self, *args, **kwargs):
self.alarm_dict = kwargs.pop('alarm_dict', None)
super(MeasurementGraphSeriesSerializer, self).__init__(*args, **kwargs)
if not self.alarm_dict:
self.fields.pop('alarm')
def get_alarm(self, obj):
if obj.id in self.alarm_dict:
alarm = self.alarm_dict[obj.id]
serializer = SimpleAlarmSerializer(alarm)
return serializer.data
return None
class Meta(GraphSeriesSerializer.Meta):
model = Measurement
fields = GraphSeriesSerializer.Meta.fields + ['alarm']
class ThresholdValueGraphSeriesSerializer(GraphSeriesSerializer):
class Meta(GraphSeriesSerializer.Meta):
model = ThresholdValue
class SimpleAlarmSerializer(serializers.ModelSerializer):
class Meta:
model = Alarm
fields = ('id', 'time_created', 'is_treated', 'treated_text')
|
Use a single database for all air quality measurements | # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "indoor_air_quality")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
}
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
| # coding=utf-8
from local_settings import *
from utils import SensorConsumerBase
import redis
import datetime
import sys
class Bathroom(SensorConsumerBase):
def __init__(self):
SensorConsumerBase.__init__(self, "bathroom")
def run(self):
self.subscribe("bathroom-pubsub", self.pubsub_callback)
def pubsub_callback(self, data):
if "action" in data:
# if data["action"] == "user_dismissed":
return
influx_data = {
"measurement": "bathroom",
"timestamp": data["utctimestamp"].isoformat() + "Z",
"fields": {
"distance_reading": data["data"]["distance_reading"],
"bathroom_temperature": round(data["data"]["bathroom_temperature"], 1),
"bathroom_humidity": round(data["data"]["bathroom_humidity"], 1),
"corridor_temperature": round(data["data"]["corridor_temperature"], 1),
"corridor_humidity": round(data["data"]["corridor_humidity"], 1)
}
}
self.insert_into_influx([influx_data])
def main():
item = Bathroom()
item.run()
return 0
if __name__ == '__main__':
sys.exit(main())
|
Change scale range to normalization with source and target min max | import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = None
for root, directories, files in os.walk(image_region_path):
for file in files:
if not file.endswith(".png"):
continue
image = skimage.io.imread(f"{root}/{file}")
image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2)
if result_image is None:
result_image = image
else:
height, width, rgba = image.shape
for i in range(height):
for ii in range(width):
if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]):
result_image[i, ii, 3] = 0
skimage.io.imsave(output_file_path, result_image)
def normalize(n, source_min, source_max, target_min=0, target_max=1):
return ((n - source_min) * (target_max - target_min) / (source_max - source_min)) + target_min
| import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = None
for root, directories, files in os.walk(image_region_path):
for file in files:
if not file.endswith(".png"):
continue
image = skimage.io.imread(f"{root}/{file}")
image = np.concatenate((image, np.full((image.shape[0], image.shape[1], 1), 255, dtype="uint8")), axis=2)
if result_image is None:
result_image = image
else:
height, width, rgba = image.shape
for i in range(height):
for ii in range(width):
if not np.array_equal(image[i, ii, :2], result_image[i, ii, :2]):
result_image[i, ii, 3] = 0
skimage.io.imsave(output_file_path, result_image)
def scale_range(n, minimum, maximum):
n += -(np.min(n))
n /= np.max(n) / (maximum - minimum)
n += minimum
return n
|
Use Schema for updating the OnlineUser-Entry to use the doc validation
Unfortunately, the `update` method of our schema class does not support the `upsert`-option. So we check if the entry already exists and perform an insert or an update depending on the findOne result. | import { Meteor } from 'meteor/meteor';
import { OnlineUsersSchema } from './onlineusers.schema';
import moment from 'moment/moment';
if (Meteor.isServer) {
Meteor.publish('onlineUsersForRoute', function (route) {
return OnlineUsersSchema.find({activeRoute: route});
});
}
const checkRouteParamAndAuthorization = (route, userId) => {
check(route, String);
if (!userId) {
throw new Meteor.Error('not-authorized');
}
};
Meteor.methods({
'onlineUsers.enterRoute'(route) {
const userId = Meteor.userId();
checkRouteParamAndAuthorization(route, userId);
const doc = {
userId: userId,
activeRoute:route,
updatedAt: new Date()
};
const selector = { userId: userId, activeRoute:route };
const existingDoc = OnlineUsersSchema.findOne(selector);
if (existingDoc) {
OnlineUsersSchema.update(selector, doc);
} else {
OnlineUsersSchema.insert(doc);
}
// remove outdated entries
const aMinAgo = moment().add(-1,'minutes').toDate();
OnlineUsersSchema.remove({updatedAt: {"$lt" : aMinAgo}});
},
'onlineUsers.leaveRoute'(route) {
const userId = Meteor.userId();
checkRouteParamAndAuthorization(route, userId);
OnlineUsersSchema.remove({userId: userId, activeRoute:route});
}
}); | import { Meteor } from 'meteor/meteor';
import { OnlineUsersSchema } from './onlineusers.schema';
import moment from 'moment/moment';
if (Meteor.isServer) {
Meteor.publish('onlineUsersForRoute', function (route) {
return OnlineUsersSchema.find({activeRoute: route});
});
}
const checkRouteParamAndAuthorization = (route, userId) => {
check(route, String);
if (!userId) {
throw new Meteor.Error('not-authorized');
}
};
Meteor.methods({
'onlineUsers.enterRoute'(route) {
const userId = Meteor.userId();
checkRouteParamAndAuthorization(route, userId);
OnlineUsersSchema.getCollection().update({
userId: userId,
activeRoute:route
}, {
userId: userId,
activeRoute:route,
updatedAt: new Date()
}, {
upsert: true
});
// remove outdated entries
const aMinAgo = moment().add(-1,'minutes').toDate();
OnlineUsersSchema.remove({updatedAt: {"$lt" : aMinAgo}});
},
'onlineUsers.leaveRoute'(route) {
const userId = Meteor.userId();
checkRouteParamAndAuthorization(route, userId);
OnlineUsersSchema.remove({userId: userId, activeRoute:route});
}
}); |
Add missing spaces, re-indent HTML |
<?php echo $head; ?>
<div class="pure-g">
<h2><?php echo _('Facebook login successful!') ?></h2>
<div class="pure-u-1 pure-u-md-1-3">
<p> <?php
echo _('The last step.');
echo ' ';
echo _('You can add a message to your check-in.');
echo ' ';
?>
</p>
</div>
<div class="pure-u-1 pure-u-md-2-3">
<form class="pure-form">
<fieldset>
<legend><?php echo _('Check In'); ?></legend>
<input type="textarea" placeholder="" name="message" id="text_fb_message">
<?php echo $suggested_message; ?>
</input>
<button class="pure-button" id="button_clear_fb_message">
<?php echo _('Clear message'); ?>
</button>
<button type="submit" class="pure-button pure-button-primary" action="<?php echo $post_action; ?>">
<?php echo _('Check in to') . $place_name; ?>
</button>
</fieldset>
</form>
</div>
</div>
<div class="pure-g">
<div class="pure-u-1">
<p> <?php echo_('If you do not want to check in, you can still use the access code!') ; ?> <p>
<a href="<?php echo $retry_url; ?>" class="pure-button"><?php echo _('Back to login'); ?></a>
</div>
</div>
<?php echo $foot; ?>
|
<?php echo $head; ?>
<div class="pure-g">
<h2><?php echo _('Facebook login successful!') ?></h2>
<div class="pure-u-1 pure-u-md-1-3">
<p> <?php
echo _('The last step.');
echo _('You can add a message to your check-in.');
?>
</p>
</div>
<div class="pure-u-1 pure-u-md-2-3">
<form class="pure-form">
<fieldset>
<legend><?php echo _('Check In'); ?></legend>
<input type="textarea" placeholder="" name="message" id="text_fb_message">
<?php echo $suggested_message; ?>
</input>
<button class="pure-button" id="button_clear_fb_message">
<?php echo _('Clear message'); ?>
</button>
<button type="submit" class="pure-button pure-button-primary" action="<?php echo $post_action; ?>">
<?php echo _('Check in to') . $place_name; ?>
</button>
</fieldset>
</form>
</div>
</div>
<div class="pure-g">
<div class="pure-u-1">
<p> <?php echo_('If you do not want to check in, you can still use the access code!') ; ?> <p>
<a href="<?php echo $retry_url; ?>" class="pure-button"><?php echo _('Back to login'); ?></a>
</div>
</div>
<?php echo $foot; ?>
|
Use of @component for buttons in form | @component('core::admin._buttons-form', ['model' => $model])
@endcomponent
{!! BootForm::hidden('id') !!}
<div class="row">
@if ($model->id)
<div class="col-sm-6 container-menulinks">
<p>
<a href="{{ route('admin::create-menulink', $model->id) }}">
<i class="fa fa-fw fa-plus-circle"></i>@lang('menus::global.New menulink')
</a>
</p>
<div ng-app="typicms" ng-cloak ng-controller="ListController">
<div class="btn-toolbar">
@include('core::admin._lang-switcher-for-list')
</div>
<!-- Nested node template -->
<div ui-tree="treeOptions">
<ul ui-tree-nodes="" data-max-depth="3" ng-model="models" id="tree-root">
<li ng-repeat="model in models" ui-tree-node ng-include="'/views/partials/listItemMenulink.html'"></li>
</ul>
</div>
</div>
</div>
@endif
<div class="col-sm-6">
{!! BootForm::text(__('Name'), 'name') !!}
{!! BootForm::text(__('Class'), 'class') !!}
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
</div>
</div>
| @include('core::admin._buttons-form')
{!! BootForm::hidden('id') !!}
<div class="row">
@if ($model->id)
<div class="col-sm-6 container-menulinks">
<p>
<a href="{{ route('admin::create-menulink', $model->id) }}">
<i class="fa fa-fw fa-plus-circle"></i>@lang('menus::global.New menulink')
</a>
</p>
<div ng-app="typicms" ng-cloak ng-controller="ListController">
<div class="btn-toolbar">
@include('core::admin._lang-switcher-for-list')
</div>
<!-- Nested node template -->
<div ui-tree="treeOptions">
<ul ui-tree-nodes="" data-max-depth="3" ng-model="models" id="tree-root">
<li ng-repeat="model in models" ui-tree-node ng-include="'/views/partials/listItemMenulink.html'"></li>
</ul>
</div>
</div>
</div>
@endif
<div class="col-sm-6">
{!! BootForm::text(__('Name'), 'name') !!}
{!! BootForm::text(__('Class'), 'class') !!}
{!! TranslatableBootForm::hidden('status')->value(0) !!}
{!! TranslatableBootForm::checkbox(__('Published'), 'status') !!}
</div>
</div>
|
Revert - Fix route parameters for a row action | <?php
/*
* This file is part of the DataGridBundle.
*
* (c) Stanislav Turza <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sorien\DataGridBundle\Grid\Column;
use Sorien\DataGridBundle\Grid\Action\RowAction;
class ActionsColumn extends Column
{
private $rowActions;
public function __construct($column, $title, array $rowActions = array())
{
$this->rowActions = $rowActions;
parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false));
}
public function getRouteParameters($row, $action)
{
$actionParameters = $action->getRouteParameters();
if(!empty($actionParameters)){
$routeParameters = array();
foreach ($actionParameters as $name => $parameter) {
if(is_numeric($name)){
$routeParameters[$parameter] = $row->getField($parameter);
} else {
$routeParameters[$name] = $parameter;
}
}
return $routeParameters;
}
return array_merge(
array($row->getPrimaryField() => $row->getPrimaryFieldValue()),
$action->getRouteParameters()
);
}
public function getRowActions()
{
return $this->rowActions;
}
public function setRowActions(array $rowActions) {
$this->rowActions = $rowActions;
}
public function getType()
{
return 'actions';
}
}
| <?php
/*
* This file is part of the DataGridBundle.
*
* (c) Stanislav Turza <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sorien\DataGridBundle\Grid\Column;
use Sorien\DataGridBundle\Grid\Action\RowAction;
class ActionsColumn extends Column
{
private $rowActions;
public function __construct($column, $title, array $rowActions = array())
{
$this->rowActions = $rowActions;
parent::__construct(array('id' => $column, 'title' => $title, 'sortable' => false, 'source' => false));
}
public function getRouteParameters($row, $action)
{
$actionParameters = $action->getRouteParameters();
if(!empty($actionParameters)){
$routeParameters = array();
foreach ($actionParameters as $name => $parameter) {
if(is_numeric($name)){
$routeParameters[$parameter] = $row->getField($parameter);
} else {
$routeParameters[$name] = $parameter;
}
}
}
return array_merge(
array($row->getPrimaryField() => $row->getPrimaryFieldValue()),
$routeParameters
);
}
public function getRowActions()
{
return $this->rowActions;
}
public function setRowActions(array $rowActions) {
$this->rowActions = $rowActions;
}
public function getType()
{
return 'actions';
}
}
|
Read the files again upon deletion | <?php
namespace Kibo\Phast\Cache\File;
use Kibo\Phast\Common\ObjectifiedFunctions;
class DiskCleanup extends ProbabilisticExecutor {
/**
* @var integer
*/
private $maxSize;
/**
* @var float
*/
private $portionToFree;
public function __construct(array $config, ObjectifiedFunctions $functions = null) {
$this->maxSize = $config['diskCleanup']['maxSize'];
$this->probability = $config['diskCleanup']['probability'];
$this->portionToFree = $config['diskCleanup']['portionToFree'];
parent::__construct($config, $functions);
}
protected function execute() {
$usedSpace= $this->calculateUsedSpace();
$neededSpace = round($this->portionToFree * $this->maxSize);
$bytesToDelete = $usedSpace - $this->maxSize + $neededSpace;
$deletedBytes = 0;
/** @var \SplFileInfo $file */
foreach ($this->getCacheFiles($this->cacheRoot) as $file) {
if ($deletedBytes >= $bytesToDelete) {
break;
}
$deletedBytes += $file->getSize();
@unlink($file->getRealPath());
}
}
private function calculateUsedSpace() {
$size = 0;
$files = [];
/** @var \SplFileInfo $file */
foreach ($this->getCacheFiles($this->cacheRoot) as $file) {
$size += $file->getSize();
$files[] = $file;
}
return $size;
}
}
| <?php
namespace Kibo\Phast\Cache\File;
use Kibo\Phast\Common\ObjectifiedFunctions;
class DiskCleanup extends ProbabilisticExecutor {
/**
* @var integer
*/
private $maxSize;
/**
* @var float
*/
private $portionToFree;
public function __construct(array $config, ObjectifiedFunctions $functions = null) {
$this->maxSize = $config['diskCleanup']['maxSize'];
$this->probability = $config['diskCleanup']['probability'];
$this->portionToFree = $config['diskCleanup']['portionToFree'];
parent::__construct($config, $functions);
}
protected function execute() {
list ($usedSpace, $files) = $this->calculateUsedSpace();
$neededSpace = round($this->portionToFree * $this->maxSize);
$bytesToDelete = $usedSpace - $this->maxSize + $neededSpace;
$deletedBytes = 0;
/** @var \SplFileInfo $file */
foreach ($files as $file) {
if ($deletedBytes >= $bytesToDelete) {
break;
}
$deletedBytes += $file->getSize();
@unlink($file->getRealPath());
}
}
private function calculateUsedSpace() {
$size = 0;
$files = [];
/** @var \SplFileInfo $file */
foreach ($this->getCacheFiles($this->cacheRoot) as $file) {
$size += $file->getSize();
$files[] = $file;
}
return [$size, $files];
}
}
|
Use Window instead of JFrame to find top-level parent. | /*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglass.state;
import java.awt.Component;
import java.awt.Window;
import javax.swing.JComponent;
import javax.swing.JInternalFrame;
/**
*/
public class ToolBarWindowIsActiveState extends State {
public ToolBarWindowIsActiveState() {
super("WindowIsActive");
}
protected boolean isInState(JComponent c) {
Component parent = c;
while (parent.getParent() != null) {
if (parent instanceof JInternalFrame || parent instanceof Window) {
break;
}
parent = parent.getParent();
}
if (parent instanceof JInternalFrame) {
return ((JInternalFrame) parent).isSelected();
} else if (parent instanceof Window) {
return ((Window) parent).isFocused();
}
// Default to true.
return true;
}
}
| /*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglass.state;
import java.awt.Component;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
/**
*/
public class ToolBarWindowIsActiveState extends State {
public ToolBarWindowIsActiveState() {
super("WindowIsActive");
}
protected boolean isInState(JComponent c) {
Component parent = c;
while (parent.getParent() != null) {
if (parent instanceof JInternalFrame || parent instanceof JFrame) {
break;
}
parent = parent.getParent();
}
if (parent instanceof JInternalFrame) {
return ((JInternalFrame) parent).isSelected();
} else if (parent instanceof JFrame) {
return ((JFrame) parent).isActive();
}
// Default to true.
return true;
}
}
|
Create lcov report so that it can be uploaded to Codeclimate | const path = require('path');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
preprocessors: { 'src/testception-spec.js': ['webpack'] },
files: ['src/testception-spec.js'],
webpack: {
mode: 'none',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: { esModules: true }
},
include: path.resolve('src/')
}
]
}
},
reporters: ['progress', 'coverage-istanbul'],
coverageIstanbulReporter: {
dir: 'coverage',
subdir: '.',
reports: ['html', 'text-summary', 'lcov'],
thresholds: {
each: {
statements: 100,
branches: 100,
functions: 100,
lines: 100
}
}
},
port: 8080,
runnerPort: 9100,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['jsdom'],
captureTimeout: 5000,
singleRun: true
});
};
| const path = require('path');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
preprocessors: { 'src/testception-spec.js': ['webpack'] },
files: ['src/testception-spec.js'],
webpack: {
mode: 'none',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: { esModules: true }
},
include: path.resolve('src/')
}
]
}
},
reporters: ['progress', 'coverage-istanbul'],
coverageIstanbulReporter: {
dir: 'coverage',
subdir: '.',
reports: ['html', 'text-summary'],
thresholds: {
each: {
statements: 100,
branches: 100,
functions: 100,
lines: 100
}
}
},
port: 8080,
runnerPort: 9100,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['jsdom'],
captureTimeout: 5000,
singleRun: true
});
};
|
Return http status code 301 when api version is wrong | # -*- coding: utf-8 -*-
from functools import wraps, partial
from flask import request
from flask_api import status
from flask.wrappers import Response
from app.config import API_ACCEPT_HEADER, API_VERSION
def API(method=None):
if method is None:
return partial(API)
@wraps(method)
def decorated(*args, **kwargs):
_return = method(*args, **kwargs)
if isinstance(_return, Response):
return _return
if request.url.find('v' + str(API_VERSION)) > 0:
if request.headers['Accept'] == API_ACCEPT_HEADER:
ret, code = _return
else:
ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE)
else:
ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY)
return serialize(ret, code)
def serialize(ret, code):
_return = {'code': code}
if not status.is_success(code):
_return['status'] = 'fail'
if ret is not None:
if isinstance(ret, dict):
_return.update(ret)
else:
_return['message'] = ret
else:
_return['status'] = 'success'
if ret is not None:
if isinstance(ret, dict):
_return.update(ret)
else:
_return['data'] = ret
return _return, code
return decorated
| # -*- coding: utf-8 -*-
from functools import wraps, partial
from flask import request
from flask_api import status
from flask.wrappers import Response
from app.config import API_ACCEPT_HEADER
def API(method=None):
if method is None:
return partial(API)
@wraps(method)
def decorated(*args, **kwargs):
_return = method(*args, **kwargs)
if isinstance(_return, Response):
return _return
if request.headers['Accept'] == API_ACCEPT_HEADER:
ret, code = _return
else:
ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE)
return serialize(ret, code)
def serialize(ret, code):
_return = {'code': code}
if not status.is_success(code):
_return['status'] = 'fail'
if ret is not None:
if isinstance(ret, dict):
_return.update(ret)
else:
_return['message'] = ret
else:
_return['status'] = 'success'
if ret is not None:
if isinstance(ret, dict):
_return.update(ret)
else:
_return['data'] = ret
return _return, code
return decorated
|
Remove user-content- link prefix from the generated html |
var fs = require('fs'),
path = require('path'),
hogan = require('hogan.js'),
Client = require('github');
var html = fs.readFileSync('base.html', 'utf8');
template = hogan.compile(html);
var client = new Client({
version: '3.0.0'
});
var dpath = path.resolve(__dirname, '../markdown/'),
files = [
'about', 'install',
'config', 'settings', 'custom',
'one-to-many', 'many-to-many', 'many-to-one', 'one-to-one',
'ckeditor', 'tinymce', 'multiple',
'views', 'events', 'embedding',
'themes',
'shell', 'nginx', 'apache'
];
var data = '';
(function loop (index, cb) {
if (index == files.length) return cb();
var text = fs.readFileSync(path.join(dpath ,files[index]+'.md'), 'utf8');
client.markdown.render({
text: text,
mode: 'markdown'
}, function (err, res) {
data += '<div class="file">'+res.data;
if (index < files.length-1) data += '<p><br /></p><hr />';
data += '</div>';
loop(++index, cb);
});
}(0, function () {
var content = template.render({}, {content: data.replace(/user-content-/g,'')});
fs.writeFileSync(path.resolve(__dirname, '../index.html'), content, 'utf8');
}));
|
var fs = require('fs'),
path = require('path'),
hogan = require('hogan.js'),
Client = require('github');
var html = fs.readFileSync('base.html', 'utf8');
template = hogan.compile(html);
var client = new Client({
version: '3.0.0'
});
var dpath = path.resolve(__dirname, '../markdown/'),
files = [
'about', 'install',
'config', 'settings', 'custom',
'one-to-many', 'many-to-many', 'many-to-one', 'one-to-one',
'ckeditor', 'tinymce', 'multiple',
'views', 'events', 'embedding',
'themes',
'shell', 'nginx', 'apache'
];
var data = '';
(function loop (index, cb) {
if (index == files.length) return cb();
var text = fs.readFileSync(path.join(dpath ,files[index]+'.md'), 'utf8');
client.markdown.render({
text: text,
mode: 'markdown'
}, function (err, res) {
data += '<div class="file">'+res.data;
if (index < files.length-1) data += '<p><br /></p><hr />';
data += '</div>';
loop(++index, cb);
});
}(0, function () {
var content = template.render({}, {content: data});
fs.writeFileSync(path.resolve(__dirname, '../index.html'), content, 'utf8');
}));
|
Fix accidental logic error in argument checking | /* @flow */
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import type { ValidationContext } from '../index';
import { GraphQLError } from '../../error';
import { print } from '../../language/printer';
import { isValidLiteralValue } from '../../utilities/isValidLiteralValue';
export function badValueMessage(
argName: any,
type: any,
value: any,
verboseErrors?: [any]
): string {
var message = verboseErrors ? '\n' + verboseErrors.join('\n') : '';
return (
`Argument "${argName}" has invalid value ${value}.${message}`
);
}
/**
* Argument values of correct type
*
* A GraphQL document is only valid if all field argument literal values are
* of the type expected by their position.
*/
export function ArgumentsOfCorrectType(context: ValidationContext): any {
return {
Argument(argAST) {
var argDef = context.getArgument();
if (argDef) {
var errors = isValidLiteralValue(argDef.type, argAST.value);
if (errors.length) {
return new GraphQLError(
badValueMessage(
argAST.name.value,
argDef.type,
print(argAST.value),
errors
),
[ argAST.value ]
);
}
}
}
};
}
| /* @flow */
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import type { ValidationContext } from '../index';
import { GraphQLError } from '../../error';
import { print } from '../../language/printer';
import { isValidLiteralValue } from '../../utilities/isValidLiteralValue';
export function badValueMessage(
argName: any,
type: any,
value: any,
verboseErrors?: [any]
): string {
var message = verboseErrors ? '\n' + verboseErrors.join('\n') : '';
return (
`Argument "${argName}" has invalid value ${value}.${message}`
);
}
/**
* Argument values of correct type
*
* A GraphQL document is only valid if all field argument literal values are
* of the type expected by their position.
*/
export function ArgumentsOfCorrectType(context: ValidationContext): any {
return {
Argument(argAST) {
var argDef = context.getArgument();
if (argDef) {
var errors = isValidLiteralValue(argDef.type, argAST.value);
}
if (errors.length) {
return new GraphQLError(
badValueMessage(
argAST.name.value,
argDef.type,
print(argAST.value),
errors
),
[ argAST.value ]
);
}
}
};
}
|
Test modified according to refactorings | package org.jlib.core.collection;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.ForwardingMap;
import org.junit.Test;
public class CachingMapTest {
@Test
public void performance() {
final Map<String, String> hashMap = new HashMap<>();
hashMap.put("ja", "nein");
hashMap.put("gut", "schlecht");
hashMap.put("München", "Berlin");
final Map<String, String> forwardingMap = new ForwardingMap<String, String>() {
@Override
protected Map<String, String> delegate() {
return hashMap;
}
};
final Map<String, String> cacheMap = new CachingMap<>(hashMap);
for (int i = 0; i < 20; i++) {
System.out.println("HashMap: " + measure(hashMap));
System.out.println("DelegatingMap: " + measure(forwardingMap));
System.out.println("CacheMap: " + measure(cacheMap));
}
}
private long measure(final Map<String, String> map) {
final int MAX = 100;
final String MUC = "ja";
long start = System.nanoTime();
for (int i = 0; i < MAX; i++)
if (map.containsKey(MUC))
map.get(MUC);
long end = System.nanoTime();
return end - start;
}
}
| package org.jlib.core.collection;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class CachingMapTest {
@Test
public void performance() {
final Map<String, String> hashMap = new HashMap<>();
hashMap.put("ja", "nein");
hashMap.put("gut", "schlecht");
hashMap.put("München", "Berlin");
final Map<String, String> delegatingMap = new DelegatingMap<String, String>(hashMap) {
// intentilonally empty
};
final Map<String, String> cacheMap = new CachingMap<>(hashMap);
for (int i = 0; i < 20; i++) {
System.out.println("HashMap: " + measure(hashMap));
System.out.println("DelegatingMap: " + measure(delegatingMap));
System.out.println("CacheMap: " + measure(cacheMap));
}
}
private long measure(final Map<String, String> map) {
final int MAX = 100;
final String MUC = "ja";
long start = System.nanoTime();
for (int i = 0; i < MAX; i++)
if (map.containsKey(MUC))
map.get(MUC);
long end = System.nanoTime();
return end - start;
}
}
|
Update test suite. Works great :rainbows: | describe('Landing page', function() {
it('should have the correct title', function(done, server, client) {
var title = client.evalSync(function() {
var titleText = $('title').text();
emit('return', titleText);
});
title.should.equal('NEBUL4');
done();
});
});
describe('Gameplay', function() {
it('up arrow should move ship forwards', function(done, server, client) {
var position = client.evalSync(function() {
var initial = 0, after = 0;
App.container.on('playerLoaded', function() {
initial = App.player.position.z;
App.pushKey('up');
});
App.container.on('playerChanged', function() {
after = App.player.position.z;
emit('return', { initial: initial, after: after });
});
});
position.initial.should.be.exactly(0);
position.after.should.be.exactly(0.1);
done();
});
it('konami code should work', function(done, server, client) {
var codeDidTrigger = client.evalSync(function() {
App.container.on('playerLoaded', function() {
App.pushKeys('up up down down left right left right b a', 1);
});
App.container.on('konami', function() {
emit('return', true);
});
});
codeDidTrigger.should.equal(true);
done();
});
});
| describe('Landing page', function() {
it('should have the correct title', function(done, server, client) {
var title = client.evalSync(function() {
var titleText = $('title').text();
emit('return', titleText);
});
title.should.equal('NEBUL4');
done();
});
});
describe('Gameplay', function() {
it('up arrow should move ship forwards', function(done, server, client) {
var position = client.evalSync(function() {
var initial = 0, after = 0;
App.container.on('shipLoaded', function() {
initial = App.player.ship.position.z;
App.pushKey('up');
});
App.container.on('shipChanged', function() {
after = App.player.ship.position.z;
emit('return', { initial: initial, after: after });
});
});
position.initial.should.be.exactly(0);
position.after.should.be.exactly(0.1);
done();
});
it('konami code should work', function(done, server, client) {
var codeDidTrigger = client.evalSync(function() {
App.container.on('shipLoaded', function() {
App.pushKeys('up up down down left right left right b a', 1);
});
App.container.on('konami', function() {
emit('return', true);
});
});
codeDidTrigger.should.equal(true);
done();
});
});
|
Update TrampolinedParser a little for my purposes. | from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incoming data.
@param receiver: Responsible for logic operation on the parsed data.
Typically, the logic operation will be invoked inside the grammar,
e.g., rule = expr1 expr2 (-> receiver.doSomeStuff())
@param bindings: The namespace that can be accessed inside the grammar.
"""
self.grammar = grammar
self.bindings = dict(bindings)
self.bindings['receiver'] = self.receiver = receiver
self._setupInterp()
def _setupInterp(self):
"""
Resets the parser. The parser will begin parsing with the rule named
'initial'.
"""
self._interp = TrampolinedGrammarInterpreter(
grammar=self.grammar, ruleName=self.receiver.currentRule,
callback=None, globals=self.bindings)
def receive(self, data):
"""
Receive the incoming data and begin parsing. The parser will parse the
data incrementally according to the 'initial' rule in the grammar.
@param data: The raw data received.
"""
while data:
status = self._interp.receive(data)
if status is _feed_me:
return
data = ''.join(self._interp.input.data[self._interp.input.position:])
self._setupInterp()
| from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incoming data.
@param receiver: Responsible for logic operation on the parsed data.
Typically, the logic operation will be invoked inside the grammar,
e.g., rule = expr1 expr2 (-> receiver.doSomeStuff())
@param bindings: The namespace that can be accessed inside the grammar.
"""
self.grammar = grammar
self.bindings = dict(bindings)
self.bindings['receiver'] = self.receiver = receiver
self._setupInterp()
def _setupInterp(self):
"""
Resets the parser. The parser will begin parsing with the rule named
'initial'.
"""
self._interp = TrampolinedGrammarInterpreter(
grammar=self.grammar, ruleName='initial', callback=None,
globals=self.bindings)
def receive(self, data):
"""
Receive the incoming data and begin parsing. The parser will parse the
data incrementally according to the 'initial' rule in the grammar.
@param data: The raw data received.
"""
while data:
try:
status = self._interp.receive(data)
except Exception as e:
# maybe we should raise it?
raise e
else:
if status is _feed_me:
return
data = ''.join(self._interp.input.data[self._interp.input.position:])
self._setupInterp() |
Introduce additional empty array check. | <?php
class BinaryGap
{
private $number;
/**
* BinaryGap constructor.
* @param $number
*/
public function __construct($number)
{
$this->number = $number;
}
/**
* @return mixed
*/
public function getNumber() {
return $this->number;
}
private function convertToBinary($number) {
return decbin($number);
}
/**
* Find longest sequence of zeros in binary representation of an integer.
*/
public function calculateBinaryGap() {
$binaryNumber = $this->convertToBinary($this->getNumber());
$binaryNumberArray = str_split($binaryNumber);
$binaryCount = array();
$counter = 0;
foreach($binaryNumberArray as $index => $binNum) {
if($binNum == "0")
$counter++;
else if($binNum == "1") {
if($counter > 0)
$binaryCount[] = $counter;
$counter = 0;
}
}
if(!empty($binaryCount))
return max($binaryCount);
else
return 0;
}
}
$binaryGap = new BinaryGap(1011);
echo "The largest binary gap is " . $binaryGap->calculateBinaryGap() . "\n"; | <?php
class BinaryGap
{
private $number;
/**
* BinaryGap constructor.
* @param $number
*/
public function __construct($number)
{
$this->number = $number;
}
/**
* @return mixed
*/
public function getNumber() {
return $this->number;
}
private function convertToBinary($number) {
return decbin($number);
}
/**
* Find longest sequence of zeros in binary representation of an integer.
*/
public function calculateBinaryGap() {
$binaryNumber = $this->convertToBinary($this->getNumber());
$binaryNumberArray = str_split($binaryNumber);
$binaryCount = array();
$counter = 0;
foreach($binaryNumberArray as $index => $binNum) {
if($binNum == "0")
$counter++;
else if($binNum == "1") {
if($counter > 0)
$binaryCount[] = $counter;
$counter = 0;
}
}
return max($binaryCount);
}
}
$binaryGap = new BinaryGap(209);
echo "The largest binary gap is " . $binaryGap->calculateBinaryGap() . "\n"; |
Add test for default values. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import knot
class TestContainer(unittest.TestCase):
def test_wrapper_looks_like_service(self):
c = knot.Container()
@c.service('service')
def service(container):
"""Docstring."""
pass
self.assertEqual(c['service'].__name__, 'service')
self.assertEqual(c['service'].__doc__, 'Docstring.')
def test_returns_if_value(self):
c = knot.Container({'value': 'foobar'})
self.assertEqual(c('value'), 'foobar')
def test_calls_if_service(self):
c = knot.Container()
@c.service('service')
def service(container):
return 'foobar'
self.assertEqual(c('service'), 'foobar')
def test_returns_default_with_unknown_key(self):
c = knot.Container()
self.assertEqual(c('service', 'foobar'), 'foobar')
self.assertEqual(c('service', lambda c: 'foobar'), 'foobar')
def test_shares_service(self):
c = knot.Container()
@c.service('service', True)
def service(container):
return {}
dict1 = c('service')
dict2 = c('service')
assert isinstance(dict1, dict)
assert isinstance(dict2, dict)
assert dict1 is dict2
if __name__ == '__main__':
unittest.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import knot
class TestContainer(unittest.TestCase):
def test_wrapper_looks_like_service(self):
c = knot.Container()
@c.service('service')
def service(container):
"""Docstring."""
pass
self.assertEqual(c['service'].__name__, 'service')
self.assertEqual(c['service'].__doc__, 'Docstring.')
def test_returns_if_value(self):
c = knot.Container({'value': 'foobar'})
self.assertEqual(c('value'), 'foobar')
def test_calls_if_service(self):
c = knot.Container()
@c.service('service')
def service(container):
return 'foobar'
self.assertEqual(c('service'), 'foobar')
def test_shares_service(self):
c = knot.Container()
@c.service('service', True)
def service(container):
return {}
dict1 = c('service')
dict2 = c('service')
assert isinstance(dict1, dict)
assert isinstance(dict2, dict)
assert dict1 is dict2
if __name__ == '__main__':
unittest.main()
|
Add support for Python 2.6 | import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
self.checksLogger.debug('Output of {0}: {1}'.format(pluginCommand, out))
if err:
self.checksLogger.error(
'Error executing {0}: {1}'.format(pluginCommand, err)
)
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
| import subprocess
nagiosPluginsCommandLines = [
"/usr/lib64/nagios/plugins/check_sensors",
"/usr/lib64/nagios/plugins/check_mailq -w 10 -c 20 -M postfix",
]
class NagiosWrapper:
def __init__(self, agentConfig, checksLogger, rawConfig):
self.agentConfig = agentConfig
self.checksLogger = checksLogger
self.rawConfig = rawConfig
def run(self):
data = {}
for pluginCommandLine in nagiosPluginsCommandLines:
# subprocess needs a list containing the command and
# its parameters
pluginCommandLineList = pluginCommandLine.split(" ")
# the check command to retrieve it's name
pluginCommand = pluginCommandLineList[0]
p = subprocess.Popen(
pluginCommandLineList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = p.communicate()
self.checksLogger.debug('Output of {}: {}'.format(pluginCommand, out))
if err:
self.checksLogger.error('Error executing {}: {}'.format(
pluginCommand, err))
# the check command name = return value:
# 0 - OK
# 1 - WARNING
# 2 - CRITICAL
# 3 - UNKNOWN
data[pluginCommand.split("/")[-1]] = p.returncode
# add performance data if it exists
perfData = out.split("|")
if len(perfData) > 1:
data[perfData[1].split(";")[0].split("=")[0]] = perfData[
1].split(";")[0].split("=")[1]
return data
|
Fix the Operating System classifier, it was invalid | from setuptools import setup, find_packages
from suponoff import __version__ as version
if __name__ == '__main__':
with open("README.rst") as f:
long_description = f.read()
setup(
name="suponoff",
version=version,
author="Gambit Research",
author_email="[email protected]",
description="An alternative Supervisor web interface.",
long_description=long_description,
license="BSD",
url="https://github.com/GambitResearch/suponoff",
zip_safe=False,
include_package_data=True,
packages=find_packages(),
scripts=[
'suponoff-monhelper.py'
],
install_requires=[
"Django >= 1.7", # just because I only tested with Django 1.7...
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
("Topic :: Software Development :: Libraries :: "
"Application Frameworks"),
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Systems Administration",
])
| from setuptools import setup, find_packages
from suponoff import __version__ as version
if __name__ == '__main__':
with open("README.rst") as f:
long_description = f.read()
setup(
name="suponoff",
version=version,
author="Gambit Research",
author_email="[email protected]",
description="An alternative Supervisor web interface.",
long_description=long_description,
license="BSD",
url="https://github.com/GambitResearch/suponoff",
zip_safe=False,
include_package_data=True,
packages=find_packages(),
scripts=[
'suponoff-monhelper.py'
],
install_requires=[
"Django >= 1.7", # just because I only tested with Django 1.7...
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
("Topic :: Software Development :: Libraries :: "
"Application Frameworks"),
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Systems Administration",
])
|
Add ability to define band create function for geotiff images
This commit makes defining bands for custom geotiffs more flexible by
allowing passing custom functions for defining bands for different
datasources or other variables - subsequent commits for MODIS take
advantage of this | import os
from rf.models import Image
from rf.utils.io import Visibility
from .io import get_geotiff_size_bytes, get_geotiff_resolution
from .create_bands import create_geotiff_bands
def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None,
visibility=Visibility.PRIVATE, imageMetadata={}, scene=None,
owner=None, band_create_function=create_geotiff_bands):
"""Create an Image object from a GeoTIFF.
Args:
orgnizationId (str): UUID of organization that this image belongs to
tif_path (str): Local path to tif file
sourceuri (str): remote source of image
visibility (str): accessibility level for object
imageMetadata (dict): Optional dict of metadata about the image
scene (Scene): Optional Scene object holding this image
owner (str): Optional owner of an image
band_create_function (function): function to aid in creating bands for a geotiff
"""
filename = filename if filename else os.path.basename(tif_path)
return Image(
organizationId,
get_geotiff_size_bytes(tif_path),
visibility,
filename,
sourceuri,
band_create_function(tif_path),
imageMetadata,
# TIFFs can have a different resolution in the X and Y directions, that is, pixels can be
# rectangular with respect to the ground. The RF API doesn't currently support this, so just
# select the X resolution.
get_geotiff_resolution(tif_path)[0],
[],
scene=scene,
owner=owner
)
| import os
from rf.models import Image
from rf.utils.io import Visibility
from .io import get_geotiff_size_bytes, get_geotiff_resolution
from .create_bands import create_geotiff_bands
def create_geotiff_image(organizationId, tif_path, sourceuri, filename=None,
visibility=Visibility.PRIVATE, imageMetadata={}, scene=None,
owner=None):
"""Create an Image object from a GeoTIFF.
Args:
orgnizationId (str): UUID of organization that this image belongs to
tif_path (str): Local path to tif file
sourceuri (str): remote source of image
visibility (str): accessibility level for object
imageMetadata (dict): Optional dict of metadata about the image
scene (Scene): Optional Scene object holding this image
owner (str): Optional owner of an image
"""
filename = filename if filename else os.path.basename(tif_path)
return Image(
organizationId,
get_geotiff_size_bytes(tif_path),
visibility,
filename,
sourceuri,
create_geotiff_bands(tif_path),
imageMetadata,
# TIFFs can have a different resolution in the X and Y directions, that is, pixels can be
# rectangular with respect to the ground. The RF API doesn't currently support this, so just
# select the X resolution.
get_geotiff_resolution(tif_path)[0],
[],
scene=scene,
owner=owner
)
|
Add support for html emails and extra headers | from django.core.mail import (
EmailMessage, EmailMultiAlternatives, get_connection
)
from django.conf import settings
try:
from froide.bounce.utils import make_bounce_address
except ImportError:
make_bounce_address = None
HANDLE_BOUNCES = settings.FROIDE_CONFIG['bounce_enabled']
def get_mail_connection(**kwargs):
return get_connection(
backend=settings.EMAIL_BACKEND,
**kwargs
)
def send_mail(subject, body, user_email,
from_email=None,
html=None,
attachments=None, fail_silently=False,
bounce_check=True, headers=None,
auto_bounce=True, **kwargs):
if not user_email:
return
if bounce_check:
# TODO: Check if this email should be sent
pass
if from_email is None:
from_email = settings.DEFAULT_FROM_EMAIL
backend_kwargs = {}
if HANDLE_BOUNCES and auto_bounce and make_bounce_address:
backend_kwargs['return_path'] = make_bounce_address(user_email)
connection = get_mail_connection(**backend_kwargs)
if html is None:
email_klass = EmailMessage
else:
email_klass = EmailMultiAlternatives
email = email_klass(subject, body, from_email, [user_email],
connection=connection, headers=headers)
if html is not None:
email.attach_alternative(
html,
"text/html"
)
if attachments is not None:
for name, data, mime_type in attachments:
email.attach(name, data, mime_type)
return email.send(fail_silently=fail_silently)
| from django.core.mail import EmailMessage, get_connection
from django.conf import settings
try:
from froide.bounce.utils import make_bounce_address
except ImportError:
make_bounce_address = None
HANDLE_BOUNCES = settings.FROIDE_CONFIG['bounce_enabled']
def get_mail_connection(**kwargs):
return get_connection(
backend=settings.EMAIL_BACKEND,
**kwargs
)
def send_mail(subject, body, user_email,
from_email=None,
attachments=None, fail_silently=False,
bounce_check=True,
auto_bounce=True, **kwargs):
if not user_email:
return
if bounce_check:
# TODO: Check if this email should be sent
pass
if from_email is None:
from_email = settings.DEFAULT_FROM_EMAIL
backend_kwargs = {}
if HANDLE_BOUNCES and auto_bounce and make_bounce_address:
backend_kwargs['return_path'] = make_bounce_address(user_email)
connection = get_mail_connection(**backend_kwargs)
email = EmailMessage(subject, body, from_email, [user_email],
connection=connection)
if attachments is not None:
for name, data, mime_type in attachments:
email.attach(name, data, mime_type)
return email.send(fail_silently=fail_silently)
|
Update task controller to update its content after task edition | /*
eslint no-shadow: ["error", { "allow": ["$scope"] }]
*/
/*
eslint no-underscore-dangle: ["error", { "allow": ["_id",] }]
*/
angular.module('MainApp')
.controller('TaskControl', ($scope, $mdDialog, db) => {
$scope.current = undefined;
$scope.isShown = true;
$scope.do = false;
$scope.delete = false;
$scope.markAsDone = db.markAsDone;
$scope.remove = db.remove;
function DialogController($scope, task) {
$scope.task = task;
$scope.cancel = function cancel() {
$mdDialog.cancel();
};
$scope.update = function update(newTask) {
if (newTask) {
$mdDialog.hide(newTask);
}
};
}
$scope.edit = (ev, cur) => {
$mdDialog.show({
controller: DialogController,
locals: {
task: cur.text,
},
templateUrl: 'app/components/tasks/templates/editTaskDialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
})
.then((task) => {
db.edit(cur._id, task);
db.find('open', (tasks) => {
$scope.tasks = tasks;
});
});
};
$scope.$on('Update tasks', () => {
db.find('open', (tasks) => {
$scope.tasks = tasks;
$scope.$apply();
});
});
db.find('open', (tasks) => {
$scope.tasks = tasks;
});
});
| /*
eslint no-shadow: ["error", { "allow": ["$scope"] }]
*/
/*
eslint no-underscore-dangle: ["error", { "allow": ["_id",] }]
*/
angular.module('MainApp')
.controller('TaskControl', ($scope, $mdDialog, db) => {
$scope.current = undefined;
$scope.isShown = true;
$scope.do = false;
$scope.delete = false;
$scope.markAsDone = db.markAsDone;
$scope.remove = db.remove;
function DialogController($scope, task) {
$scope.task = task;
$scope.cancel = function cancel() {
$mdDialog.cancel();
};
$scope.update = function update(newTask) {
if (newTask) {
$mdDialog.hide(newTask);
}
};
}
$scope.edit = (ev, cur) => {
$mdDialog.show({
controller: DialogController,
locals: {
task: cur.text,
},
templateUrl: 'app/components/tasks/templates/editTaskDialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
})
.then((task) => {
db.edit(cur._id, task);
});
};
db.find('open', (tasks) => {
$scope.tasks = tasks;
});
});
|
Load ratings in reviews for customer users | <?php
/**
* Customers may only see approved reviews and any they posted themselves
*
* @author Daniel Deady <[email protected]>
* @license MIT
*/
class Clockworkgeek_Extrarestful_Model_Api2_Review_Rest_Customer_V1
extends Clockworkgeek_Extrarestful_Model_Api2_Review
{
/**
* Hides ID and Status for customers other than the calling one
*
* @see Clockworkgeek_Extrarestful_Model_Api2_Review::_retrieveCollection()
*/
protected function _loadCollection(Varien_Data_Collection_Db $reviews)
{
parent::_loadCollection($reviews);
/** @var $review Mage_Review_Model_Review */
foreach ($reviews as $review) {
if ($review->getCustomerId() != $this->getApiUser()->getUserId()) {
$review->unsCustomerId()->unsStatus();
}
}
}
/**
* Customers do not get to see pending or rejected reviews.
*
* @see Clockworkgeek_Extrarestful_Model_Api2_Review::_getReviews()
*/
protected function _getCollection()
{
$reviews = parent::_getCollection();
$reviews->addActiveCustomer($this->getApiUser()->getUserId());
return $reviews;
}
protected function _saveModel($data)
{
$data['customer_id'] = $this->getApiUser()->getUserId();
return parent::_saveModel($data);
}
}
| <?php
/**
* Customers may only see approved reviews and any they posted themselves
*
* @author Daniel Deady <[email protected]>
* @license MIT
*/
class Clockworkgeek_Extrarestful_Model_Api2_Review_Rest_Customer_V1
extends Clockworkgeek_Extrarestful_Model_Api2_Review
{
/**
* Hides ID and Status for customers other than the calling one
*
* @see Clockworkgeek_Extrarestful_Model_Api2_Review::_retrieveCollection()
*/
protected function _loadCollection(Varien_Data_Collection_Db $reviews)
{
/** @var $review Mage_Review_Model_Review */
foreach ($reviews as $review) {
if ($review->getCustomerId() != $this->getApiUser()->getUserId()) {
$review->unsCustomerId()->unsStatus();
}
}
}
/**
* Customers do not get to see pending or rejected reviews.
*
* @see Clockworkgeek_Extrarestful_Model_Api2_Review::_getReviews()
*/
protected function _getCollection()
{
$reviews = parent::_getCollection();
$reviews->addActiveCustomer($this->getApiUser()->getUserId());
return $reviews;
}
protected function _saveModel($data)
{
$data['customer_id'] = $this->getApiUser()->getUserId();
return parent::_saveModel($data);
}
}
|
Revert "update to remove client type hinting"
This reverts commit a73a6e688d7bcaa17b6c3ba2688291dfa878ea5d. | <?php
namespace hceudevs\RateLimitBundle\Service\Storage;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;
class Redis implements StorageInterface
{
/**
* @var \Predis\Client
*/
protected $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function getRateInfo($key)
{
$info = $this->client->hgetall($key);
$rateLimitInfo = new RateLimitInfo();
$rateLimitInfo->setLimit($info['limit']);
$rateLimitInfo->setCalls($info['calls']);
$rateLimitInfo->setResetTimestamp($info['reset']);
return $rateLimitInfo;
}
public function limitRate($key)
{
if (! $this->client->hexists($key, 'limit')) {
return false;
}
$this->client->hincrby($key, 'calls', 1);
return $this->getRateInfo($key);
}
public function createRate($key, $limit, $period)
{
$this->client->hset($key, 'limit', $limit);
$this->client->hset($key, 'calls', 1);
$this->client->hset($key, 'reset', time() + $period);
$this->client->expire($key, $period);
return $this->getRateInfo($key);
}
public function resetRate($key)
{
$this->client->hdel($key);
return true;
}
}
| <?php
namespace hceudevs\RateLimitBundle\Service\Storage;
use Noxlogic\RateLimitBundle\Service\RateLimitInfo;
use Predis\Client;
class Redis implements StorageInterface
{
/**
* @var \Predis\Client
*/
protected $client;
public function __construct($client)
{
$this->client = $client;
}
public function getRateInfo($key)
{
$info = $this->client->hgetall($key);
$rateLimitInfo = new RateLimitInfo();
$rateLimitInfo->setLimit($info['limit']);
$rateLimitInfo->setCalls($info['calls']);
$rateLimitInfo->setResetTimestamp($info['reset']);
return $rateLimitInfo;
}
public function limitRate($key)
{
if (! $this->client->hexists($key, 'limit')) {
return false;
}
$this->client->hincrby($key, 'calls', 1);
return $this->getRateInfo($key);
}
public function createRate($key, $limit, $period)
{
$this->client->hset($key, 'limit', $limit);
$this->client->hset($key, 'calls', 1);
$this->client->hset($key, 'reset', time() + $period);
$this->client->expire($key, $period);
return $this->getRateInfo($key);
}
public function resetRate($key)
{
$this->client->hdel($key);
return true;
}
}
|
Add a subclass for the dot graph | """
Python in Astronomy 2016 is the second iteration of the Python in Astronomy
conference series.
This is the docstring for the pyastro module, this gets included as the
description for the module.
"""
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
class PyAstro16(PyAstro):
"""
The 2016 edition of the python in astronomy conference.
"""
__doc__ += PyAstro.__doc__
| """
Python in Astronomy 2016 is the second iteration of the Python in Astronomy
conference series.
This is the docstring for the pyastro module, this gets included as the
description for the module.
"""
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.ndarray`
Array one.
b : `numpy.ndarray`
Array two
Returns
-------
result : `numpy.ndarray`
``a`` multiplied by ``b``
"""
return np.multipy(a, b)
class PyAstro(object):
"""
This is a class docstring, here you must describe the parameters for the
creation of the class, which is normally the signature of the ``__init__``
method.
Parameters
----------
awesomeness_level : `int`
How awesome is pyastro16??!
day : `int`
Day of the conference. Defaults to 1.
Attributes
----------
awesomeness_level: `int`
How awesome is this class attributes?! You can document attributes that
are not properties here.
"""
def __init__(self, awesomeness_level, day=1):
"""
This docstring is not used, because it is for a hidden method.
"""
self.awesomeness_level = awesomeness_level
self._day = day
@property
def day(self):
"""
Day of the conference.
Properties are automatically documented as attributes
"""
return self._day
|
Use Docker config pointing at the correct interface/subnect for networking. | from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
deploy_docker(config={
# Make Docker use the Vagrant provided interface which has it's own /24
'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
})
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
| from pyinfra import inventory, state
from pyinfra_docker import deploy_docker
from pyinfra_etcd import deploy_etcd
from pyinfra_kubernetes import deploy_kubernetes_master, deploy_kubernetes_node
SUDO = True
FAIL_PERCENT = 0
def get_etcd_nodes():
return [
'http://{0}:2379'.format(
etcd_node.fact.network_devices[etcd_node.data.etcd_interface]
['ipv4']['address'],
)
for etcd_node in inventory.get_group('etcd_nodes')
]
# Install/configure etcd cluster
with state.limit('etcd_nodes'):
deploy_etcd()
# Install/configure the masters (apiserver, controller, scheduler)
with state.limit('kubernetes_masters'):
deploy_kubernetes_master(etcd_nodes=get_etcd_nodes())
# Install/configure the nodes
with state.limit('kubernetes_nodes'):
# Install Docker
deploy_docker()
# Install Kubernetes node components (kubelet, kube-proxy)
first_master = inventory.get_group('kubernetes_masters')[0]
deploy_kubernetes_node(
master_address='http://{0}'.format((
first_master
.fact.network_devices[first_master.data.network_interface]
['ipv4']['address']
)),
)
# deploy_docker(config={
# # Make Docker use the Vagrant provided interface which has it's own /24
# 'bip': '{{ host.fact.network_devices[host.data.network_interface].ipv4.address }}',
# })
|
Change to semantic version number | from setuptools import setup, find_packages
setup(
name = "django-ajax-utilities",
version = '1.2.0',
url = 'https://github.com/citylive/django-ajax-utilities',
license = 'BSD',
description = "Pagination, xhr and tabbing utilities for the Django framework.",
long_description = open('README','r').read(),
author = 'Jonathan Slenders, City Live nv',
packages = find_packages('src'),
package_data = {'django_ajax': [
'static/*.js', 'static/*/*.js', 'static/*/*/*.js',
'static/*.css', 'static/*/*.css', 'static/*/*/*.css',
'static/*.png', 'static/*/*.png', 'static/*/*/*.png', 'static/*/*/*/*.png',
'static/*.gif', 'static/*/*.gif', 'static/*/*/*.gif', 'static/*/*/*/*.gif',
'templates/*.html', 'templates/*/*.html', 'templates/*/*/*.html'
],},
zip_safe=False, # Don't create egg files, Django cannot find templates in egg files.
include_package_data=True,
package_dir = {'': 'src'},
classifiers = [
'Intended Audience :: Developers',
'Programming Language :: Python',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Framework :: Django',
],
)
| from setuptools import setup, find_packages
setup(
name = "django-ajax-utilities",
url = 'https://github.com/citylive/django-ajax-utilities',
license = 'BSD',
description = "Pagination, xhr and tabbing utilities for the Django framework.",
long_description = open('README','r').read(),
author = 'Jonathan Slenders, City Live nv',
packages = find_packages('src'),
package_data = {'django_ajax': [
'static/*.js', 'static/*/*.js', 'static/*/*/*.js',
'static/*.css', 'static/*/*.css', 'static/*/*/*.css',
'static/*.png', 'static/*/*.png', 'static/*/*/*.png', 'static/*/*/*/*.png',
'static/*.gif', 'static/*/*.gif', 'static/*/*/*.gif', 'static/*/*/*/*.gif',
'templates/*.html', 'templates/*/*.html', 'templates/*/*/*.html'
],},
zip_safe=False, # Don't create egg files, Django cannot find templates in egg files.
include_package_data=True,
package_dir = {'': 'src'},
classifiers = [
'Intended Audience :: Developers',
'Programming Language :: Python',
'Operating System :: OS Independent',
'Environment :: Web Environment',
'Framework :: Django',
],
)
|
Refactor out function to call digest only when safe | ngGridDirectives.directive('ngViewport', [function() {
return function($scope, elm) {
var isMouseWheelActive;
var prevScollLeft;
var prevScollTop = 0;
var ensureDigest = function() {
if (!$scope.$root.$$phase) {
$scope.$digest();
}
};
elm.bind('scroll', function(evt) {
var scrollLeft = evt.target.scrollLeft,
scrollTop = evt.target.scrollTop;
if ($scope.$headerContainer) {
$scope.$headerContainer.scrollLeft(scrollLeft);
}
$scope.adjustScrollLeft(scrollLeft);
$scope.adjustScrollTop(scrollTop);
ensureDigest();
prevScollLeft = scrollLeft;
prevScollTop = scrollTop;
isMouseWheelActive = false;
return true;
});
elm.bind("mousewheel DOMMouseScroll", function() {
isMouseWheelActive = true;
if (elm.focus) { elm.focus(); }
return true;
});
if (!$scope.enableCellSelection) {
$scope.domAccessProvider.selectionHandlers($scope, elm);
}
};
}]); | ngGridDirectives.directive('ngViewport', [function() {
return function($scope, elm) {
var isMouseWheelActive;
var prevScollLeft;
var prevScollTop = 0;
elm.bind('scroll', function(evt) {
var scrollLeft = evt.target.scrollLeft,
scrollTop = evt.target.scrollTop;
if ($scope.$headerContainer) {
$scope.$headerContainer.scrollLeft(scrollLeft);
}
$scope.adjustScrollLeft(scrollLeft);
$scope.adjustScrollTop(scrollTop);
if (!$scope.$root.$$phase) {
$scope.$digest();
}
prevScollLeft = scrollLeft;
prevScollTop = scrollTop;
isMouseWheelActive = false;
return true;
});
elm.bind("mousewheel DOMMouseScroll", function() {
isMouseWheelActive = true;
if (elm.focus) { elm.focus(); }
return true;
});
if (!$scope.enableCellSelection) {
$scope.domAccessProvider.selectionHandlers($scope, elm);
}
};
}]); |
Check getRootNode method exists for older Symfony versions | <?php
namespace AshleyDawson\SimplePaginationBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Class Configuration
*
* @package AshleyDawson\SimplePaginationBundle\DependencyInjection
* @author Ashley Dawson <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
const ROOT_NODE_NAME = '';
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ashley_dawson_simple_pagination');
$rootNode = \method_exists($treeBuilder, 'getRootNode')
? $treeBuilder->getRootNode()
: $treeBuilder->root('ashley_dawson_simple_pagination');
$rootNode
->children()
->arrayNode('defaults')
->addDefaultsIfNotSet()
->children()
->integerNode('items_per_page')->defaultValue(10)->min(1)->isRequired()->end()
->integerNode('pages_in_range')->defaultValue(5)->min(1)->isRequired()->end()
->scalarNode('template')->defaultValue('AshleyDawsonSimplePaginationBundle:Pagination:default.html.twig')->end()
->end()
->end()
;
return $treeBuilder;
}
}
| <?php
namespace AshleyDawson\SimplePaginationBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Class Configuration
*
* @package AshleyDawson\SimplePaginationBundle\DependencyInjection
* @author Ashley Dawson <[email protected]>
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('ashley_dawson_simple_pagination');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->arrayNode('defaults')
->addDefaultsIfNotSet()
->children()
->integerNode('items_per_page')->defaultValue(10)->min(1)->isRequired()->end()
->integerNode('pages_in_range')->defaultValue(5)->min(1)->isRequired()->end()
->scalarNode('template')->defaultValue('AshleyDawsonSimplePaginationBundle:Pagination:default.html.twig')->end()
->end()
->end()
;
return $treeBuilder;
}
}
|
Add `:=` as a relevance booster for Go | /*
Language: Go
Author: Stephan Kountso aka StepLg <[email protected]>
Contributors: Evgeny Stepanischev <[email protected]>
Description: Google go language (golang). For info about language see http://golang.org/
Category: system
*/
function(hljs) {
var GO_KEYWORDS = {
keyword:
'break default func interface select case map struct chan else goto package switch ' +
'const fallthrough if range type continue for import return var go defer ' +
'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' +
'uint16 uint32 uint64 int uint uintptr rune',
literal:
'true false iota nil',
built_in:
'append cap close complex copy imag len make new panic print println real recover delete'
};
return {
aliases: ['golang'],
keywords: GO_KEYWORDS,
illegal: '</',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
{
className: 'string',
begin: '\'', end: '[^\\\\]\''
},
{
className: 'string',
begin: '`', end: '`'
},
{
className: 'number',
begin: hljs.C_NUMBER_RE + '[dflsi]?',
relevance: 0
},
hljs.C_NUMBER_MODE,
{
begin: /:=/ // relevance booster
}
]
};
}
| /*
Language: Go
Author: Stephan Kountso aka StepLg <[email protected]>
Contributors: Evgeny Stepanischev <[email protected]>
Description: Google go language (golang). For info about language see http://golang.org/
Category: system
*/
function(hljs) {
var GO_KEYWORDS = {
keyword:
'break default func interface select case map struct chan else goto package switch ' +
'const fallthrough if range type continue for import return var go defer ' +
'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' +
'uint16 uint32 uint64 int uint uintptr rune',
literal:
'true false iota nil',
built_in:
'append cap close complex copy imag len make new panic print println real recover delete'
};
return {
aliases: ['golang'],
keywords: GO_KEYWORDS,
illegal: '</',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
{
className: 'string',
begin: '\'', end: '[^\\\\]\''
},
{
className: 'string',
begin: '`', end: '`'
},
{
className: 'number',
begin: hljs.C_NUMBER_RE + '[dflsi]?',
relevance: 0
},
hljs.C_NUMBER_MODE
]
};
}
|
Improve invalid request exception message. | <?php
namespace League\Glide\Requests;
use Symfony\Component\HttpFoundation\Request;
class RequestFactory
{
/**
* Create a request instance.
* @param max $args The request object or path/params combination.
* @param array $defaultManipulations The default image manipulations.
* @return Request The request object.
*/
public static function create($args, $defaultManipulations = [])
{
if (isset($args[0]) and $args[0] instanceof Request) {
$request = $args[0];
}
if (isset($args[0]) and is_string($args[0])) {
$params = [];
if (isset($args[1]) and is_array($args[1])) {
$params = $args[1];
}
$request = new Request($params, [], [], [], [], array_merge($_SERVER, ['REQUEST_URI' => $args[0]]));
}
if (!isset($request)) {
throw new InvalidArgumentException('Not a valid path/params combination or Request object.');
}
foreach ($defaultManipulations as $key => $value) {
if (!$request->get($key)) {
$request->query->set($key, $value);
}
}
return $request;
}
}
| <?php
namespace League\Glide\Requests;
use Symfony\Component\HttpFoundation\Request;
class RequestFactory
{
/**
* Create a request instance.
* @param max $args The request object or path/params combination.
* @param array $defaultManipulations The default image manipulations.
* @return Request The request object.
*/
public static function create($args, $defaultManipulations = [])
{
if (isset($args[0]) and $args[0] instanceof Request) {
$request = $args[0];
}
if (isset($args[0]) and is_string($args[0])) {
$params = [];
if (isset($args[1]) and is_array($args[1])) {
$params = $args[1];
}
$request = new Request($params, [], [], [], [], array_merge($_SERVER, ['REQUEST_URI' => $args[0]]));
}
if (!isset($request)) {
throw new InvalidArgumentException('Not a valid path or Request object.');
}
foreach ($defaultManipulations as $key => $value) {
if (!$request->get($key)) {
$request->query->set($key, $value);
}
}
return $request;
}
}
|
Make FontMetrics available to inline script as $fontMetrics
Since the FontMetrics class is no longer designed to be used statically a user must instantiate their own copy or reuse the one instantiated by dompdf. While not overly difficult to instantiate
(see load_font.php) there will be less friction and easier migration for the end user if we provide access to the instance used by dompdf. | <?php
/**
* @package dompdf
* @link http://dompdf.github.com/
* @author Benj Carson <[email protected]>
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
namespace Dompdf;
use Dompdf\Frame;
/**
* Executes inline PHP code during the rendering process
*
* @package dompdf
*/
class PhpEvaluator
{
/**
* @var Canvas
*/
protected $_canvas;
function __construct(Canvas $canvas)
{
$this->_canvas = $canvas;
}
function evaluate($code, $vars = array())
{
if (!$this->_canvas->get_dompdf()->get_option("enable_php")) {
return;
}
// Set up some variables for the inline code
$pdf = $this->_canvas;
$fontMetrics = $pdf->get_dompdf()->getFontMetrics();
$PAGE_NUM = $pdf->get_page_number();
$PAGE_COUNT = $pdf->get_page_count();
// Override those variables if passed in
foreach ($vars as $k => $v) {
$$k = $v;
}
//$code = html_entity_decode($code); // @todo uncomment this when tested
eval($code);
}
function render(Frame $frame)
{
$this->evaluate($frame->get_node()->nodeValue);
}
}
| <?php
/**
* @package dompdf
* @link http://dompdf.github.com/
* @author Benj Carson <[email protected]>
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
namespace Dompdf;
use Dompdf\Frame;
/**
* Executes inline PHP code during the rendering process
*
* @package dompdf
*/
class PhpEvaluator
{
/**
* @var Canvas
*/
protected $_canvas;
function __construct(Canvas $canvas)
{
$this->_canvas = $canvas;
}
function evaluate($code, $vars = array())
{
if (!$this->_canvas->get_dompdf()->get_option("enable_php")) {
return;
}
// Set up some variables for the inline code
$pdf = $this->_canvas;
$PAGE_NUM = $pdf->get_page_number();
$PAGE_COUNT = $pdf->get_page_count();
// Override those variables if passed in
foreach ($vars as $k => $v) {
$$k = $v;
}
//$code = html_entity_decode($code); // @todo uncomment this when tested
eval($code);
}
function render(Frame $frame)
{
$this->evaluate($frame->get_node()->nodeValue);
}
}
|
Make the default rules as string | <?php
namespace GeniusTS\Preferences\Models;
use Illuminate\Contracts\View\View;
/**
* Class Element
*
* @package GeniusTS\Preferences
* @property string $name
* @property string $namespace
* @property string $rules
* @property View $view
*/
class Element
{
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $namespace;
/**
* @var string
*/
protected $rules;
/**
* Element constructor.
*
* @param string $name
* @param string $rules
*/
public function __construct($name, $rules = '')
{
$this->name = $name;
if (is_string($rules))
{
$this->rules = $rules;
}
}
/**
* Set the name space of element
*
* @param string $namespace
*
* @return $this
*/
public function setNamespace($namespace)
{
$this->namespace = $namespace;
return $this;
}
/**
* @param string $property
*
* @return null
*/
public function __get($property)
{
if (property_exists($this, $property))
{
return $this->{$property};
}
return null;
}
} | <?php
namespace GeniusTS\Preferences\Models;
use Illuminate\Contracts\View\View;
/**
* Class Element
*
* @package GeniusTS\Preferences
* @property string $name
* @property string $namespace
* @property string $rules
* @property View $view
*/
class Element
{
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $namespace;
/**
* @var string
*/
protected $rules;
/**
* Element constructor.
*
* @param string $name
* @param null $rules
*/
public function __construct($name, $rules = null)
{
$this->name = $name;
if (is_string($rules))
{
$this->rules = $rules;
}
}
/**
* Set the name space of element
*
* @param string $namespace
*
* @return $this
*/
public function setNamespace($namespace)
{
$this->namespace = $namespace;
return $this;
}
/**
* @param string $property
*
* @return null
*/
public function __get($property)
{
if (property_exists($this, $property))
{
return $this->{$property};
}
return null;
}
} |
Switch to head requests rather than get requests. | #!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.head(link, headers=headers, allow_redirects=True)
return r.status_code
except (SSLError, InvalidSchema, ConnectionError):
return 409
def is_valid_link(status_code):
if status_code == 200:
return True
else:
return False
def process_links(links):
bad_links = 0
try:
for link in links:
status_code = get_link_status_code(link['href'])
if not is_valid_link(status_code):
print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href'])
bad_links += 1
except KeyboardInterrupt:
pass
linkrot = int(bad_links/len(links)*100)
print '\n%s%% linkrot\n' % linkrot
def process_bookmarks_file(filename):
with open(filename) as f:
bookmarks = json.load(f)
process_links(bookmarks)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'Usage: pinboard_linkrot.py <bookmarks.json>'
exit(1)
process_bookmarks_file(sys.argv[1])
| #!/usr/bin/env python
from __future__ import division
import requests
import json
import sys
from requests.exceptions import SSLError, InvalidSchema, ConnectionError
def get_link_status_code(link):
headers = {'User-agent':'Mozilla/5.0'}
try:
r = requests.get(link, headers = headers)
return r.status_code
except (SSLError, InvalidSchema, ConnectionError):
return 409
def is_valid_link(status_code):
if status_code == 200:
return True
else:
return False
def process_links(links):
bad_links = 0
try:
for link in links:
status_code = get_link_status_code(link['href'])
if not is_valid_link(status_code):
print 'Invalid link (%s): %s [%s]' % (status_code, link['description'], link['href'])
bad_links += 1
except KeyboardInterrupt:
pass
linkrot = int(bad_links/len(links)*100)
print '\n%s%% linkrot\n' % linkrot
def process_bookmarks_file(filename):
with open(filename) as f:
bookmarks = json.load(f)
process_links(bookmarks)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'Usage: pinboard_linkrot.py <bookmarks.json>'
exit(1)
process_bookmarks_file(sys.argv[1])
|
Add test for required registration. | # -*- coding: utf-8 -*-
import unittest
from flask import Flask
from flask.ext.knot import Knot, get_container
def create_app():
app = Flask(__name__)
app.config['TESTING'] = True
return app
class TestKnot(unittest.TestCase):
def test_acts_like_container(self):
app = create_app()
dic = Knot(app)
def foo(c):
return 'bar'
dic.add_factory(foo)
self.assertEqual(dic.provide('foo'), 'bar')
def test_does_use_app_config_on_initialization(self):
app = create_app()
app.config['foo'] = 'bar'
dic = Knot(app)
self.assertEqual(dic['foo'], 'bar')
def test_does_not_use_app_config_after_initialization(self):
app = create_app()
app.config['foo'] = 'bar'
dic = Knot()
dic.init_app(app)
self.assertRaises(KeyError, lambda: dic['foo'])
def test_container_is_shared(self):
app1 = create_app()
app2 = create_app()
dic = Knot()
dic.init_app(app1)
dic.init_app(app2)
dic1 = get_container(app1)
dic2 = get_container(app2)
assert dic1 is dic2
def test_registration_is_required(self):
app = create_app()
self.assertRaises(RuntimeError, lambda: get_container(app))
if __name__ == '__main__':
unittest.main()
| # -*- coding: utf-8 -*-
import unittest
from flask import Flask
from flask.ext.knot import Knot, get_container
def create_app():
app = Flask(__name__)
app.config['TESTING'] = True
return app
class TestKnot(unittest.TestCase):
def test_acts_like_container(self):
app = create_app()
dic = Knot(app)
def foo(c):
return 'bar'
dic.add_factory(foo)
self.assertEqual(dic.provide('foo'), 'bar')
def test_does_use_app_config_on_initialization(self):
app = create_app()
app.config['foo'] = 'bar'
dic = Knot(app)
self.assertEqual(dic['foo'], 'bar')
def test_does_not_use_app_config_after_initialization(self):
app = create_app()
app.config['foo'] = 'bar'
dic = Knot()
dic.init_app(app)
self.assertRaises(KeyError, lambda: dic['foo'])
def test_container_is_shared(self):
app1 = create_app()
app2 = create_app()
dic = Knot()
dic.init_app(app1)
dic.init_app(app2)
dic1 = get_container(app1)
dic2 = get_container(app2)
assert dic1 is dic2
if __name__ == '__main__':
unittest.main()
|
Add test to ensure write_xyz does not directly take in compound | import numpy as np
import pytest
import mbuild as mb
from mbuild.formats.xyz import write_xyz
from mbuild.utils.io import get_fn
from mbuild.tests.base_test import BaseTest
from mbuild.exceptions import MBuildError
class TestXYZ(BaseTest):
def test_load_no_top(self, ethane):
ethane.save(filename='ethane.xyz')
ethane_in = mb.load('ethane.xyz')
assert len(ethane_in.children) == 8
assert ethane_in.n_bonds == 0
assert set([child.name for child in ethane_in.children]) == {'C', 'H'}
def test_wrong_n_atoms(self):
with pytest.raises(MBuildError):
mb.load(get_fn('too_few_atoms.xyz'))
with pytest.raises(MBuildError):
mb.load(get_fn('too_many_atoms.xyz'))
def test_bad_input(self, ethane):
with pytest.raises(ValueError):
assert isinstance(ethane, mb.Compound)
write_xyz(ethane, 'compound.xyz')
def test_save(self, ethane):
ethane.save(filename='ethane.xyz')
ethane_in = mb.load('ethane.xyz')
assert len(ethane_in.children) == 8
assert set([child.name for child in ethane_in.children]) == {'C', 'H'}
def test_coordinates(self, ethane):
ethane.save(filename='ethane.xyz')
ethane_in = mb.load('ethane.xyz')
assert np.allclose(ethane.xyz, ethane_in.xyz)
| import numpy as np
import pytest
import mbuild as mb
from mbuild.utils.io import get_fn
from mbuild.tests.base_test import BaseTest
from mbuild.exceptions import MBuildError
class TestXYZ(BaseTest):
def test_load_no_top(self, ethane):
ethane.save(filename='ethane.xyz')
ethane_in = mb.load('ethane.xyz')
assert len(ethane_in.children) == 8
assert ethane_in.n_bonds == 0
assert set([child.name for child in ethane_in.children]) == {'C', 'H'}
def test_wrong_n_atoms(self):
with pytest.raises(MBuildError):
mb.load(get_fn('too_few_atoms.xyz'))
with pytest.raises(MBuildError):
mb.load(get_fn('too_many_atoms.xyz'))
def test_save(self, ethane):
ethane.save(filename='ethane.xyz')
ethane_in = mb.load('ethane.xyz')
assert len(ethane_in.children) == 8
assert set([child.name for child in ethane_in.children]) == {'C', 'H'}
def test_coordinates(self, ethane):
ethane.save(filename='ethane.xyz')
ethane_in = mb.load('ethane.xyz')
assert np.allclose(ethane.xyz, ethane_in.xyz)
|
Update for compatibility with pesto==14
Ignore-this: 7a596766eb3deedefb2c9ba36ce5ecfc
darcs-hash:20100419210717-8e352-6286dc43ea83998229ccdcd619ff1f4990ff82ee.gz | from setuptools import setup, find_packages
import sys, os
def read(*path):
"""
Read and return content from ``path``
"""
f = open(
os.path.join(
os.path.dirname(__file__),
*path
),
'r'
)
try:
return f.read().decode('UTF-8')
finally:
f.close()
setup(
name='flea',
version='2',
description="Test WSGI applications using lxml",
long_description=read('README'),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Topic :: Internet :: WWW/HTTP :: WSGI',
'Topic :: Software Development :: Testing',
],
keywords='',
author='Oliver Cope',
author_email='[email protected]',
url='',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'pesto ==12, ==13, ==14',
'lxml',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import sys, os
def read(*path):
"""
Read and return content from ``path``
"""
f = open(
os.path.join(
os.path.dirname(__file__),
*path
),
'r'
)
try:
return f.read().decode('UTF-8')
finally:
f.close()
setup(
name='flea',
version='2',
description="Test WSGI applications using lxml",
long_description=read('README'),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Topic :: Internet :: WWW/HTTP :: WSGI',
'Topic :: Software Development :: Testing',
],
keywords='',
author='Oliver Cope',
author_email='[email protected]',
url='',
license='BSD',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=False,
install_requires=[
'pesto ==12, ==13',
'lxml',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Switch from scanner to tokenizer. | import verify
import tokenizer
class Tree:
def __init__(self, elements):
self._elements = elements
def count(self):
return len(self._elements)
def elements(self):
result = []
for element in self._elements:
if element.__class__ == Tree:
result += [element.elements()]
else:
result += [element]
return result
def to_string(self):
# return ' '.join( list comprehension blah blah blah
with_parentheses = verify.sexp_to_string(self._elements)
return with_parentheses[1:(len(with_parentheses)-1)]
def read_expression(tokenizer1):
while True:
token = tokenizer1.next_token()
if token == None:
return None
if token.isspace() or token.startswith("#"):
continue
if token == '(':
result = []
while True:
subsexp = read_expression(tokenizer1)
if subsexp == ')':
break
elif subsexp == None:
raise SyntaxError('eof inside sexp')
result.append(subsexp)
return result
else:
return token
def parse(stream):
tokenizer1 = tokenizer.Tokenizer(stream)
tokens = []
while True:
expression = read_expression(tokenizer1)
if expression == None:
break
tokens += [expression]
return Tree(tokens)
| import verify
class Tree:
def __init__(self, elements):
self._elements = elements
def count(self):
return len(self._elements)
def elements(self):
result = []
for element in self._elements:
if element.__class__ == Tree:
result += [element.elements()]
else:
result += [element]
return result
def to_string(self):
# return ' '.join( list comprehension blah blah blah
with_parentheses = verify.sexp_to_string(self._elements)
return with_parentheses[1:(len(with_parentheses)-1)]
def read_expression(scanner):
while True:
tok = scanner.get_tok()
if tok == None:
return None
if tok == '(':
result = []
while 1:
subsexp = read_expression(scanner)
if subsexp == ')':
break
elif subsexp == None:
raise SyntaxError('eof inside sexp')
result.append(subsexp)
return result
else:
return tok
def parse(stream):
scanner = verify.Scanner(stream)
tokens = []
while True:
expression = read_expression(scanner)
if expression == None:
break
tokens += [expression]
return Tree(tokens)
|
Remove redundant and incorrect test | <?php
namespace Mockery\Generator\StringManipulation\Pass;
use Mockery as m;
use Mockery\Generator\StringManipulation\Pass\ClassNamePass;
use Mockery\Generator\MockConfiguration;
class ClassNamePassTest extends \PHPUnit_Framework_TestCase
{
const CODE = "namespace Mockery; class Mock {}";
public function setup()
{
$this->pass = new ClassNamePass();
}
/**
* @test
*/
public function shouldRemoveNamespaceDefinition()
{
$config = new MockConfiguration;
$code = $this->pass->apply(static::CODE, $config);
$this->assertNotContains('namespace Mockery;', $code);
}
/**
* @test
*/
public function shouldReplaceNamespaceIfClassNameIsNamespaced()
{
$config = new MockConfiguration();
$config->setName("Dave\Dave");
$code = $this->pass->apply(static::CODE, $config);
$this->assertNotContains('namespace Mockery;', $code);
$this->assertContains('namespace Dave;', $code);
}
/**
* @test
*/
public function shouldReplaceClassNameWithSpecifiedName()
{
$config = new MockConfiguration();
$config->setName("Dave");
$code = $this->pass->apply(static::CODE, $config);
$this->assertContains('class Dave', $code);
}
}
| <?php
namespace Mockery\Generator\StringManipulation\Pass;
use Mockery as m;
use Mockery\Generator\StringManipulation\Pass\ClassNamePass;
use Mockery\Generator\MockConfiguration;
class ClassNamePassTest extends \PHPUnit_Framework_TestCase
{
const CODE = "namespace Mockery; class Mock {}";
public function setup()
{
$this->pass = new ClassNamePass();
}
/**
* @test
*/
public function shouldRemoveNamespaceDefinition()
{
$config = new MockConfiguration;
$code = $this->pass->apply(static::CODE, $config);
$this->assertNotContains('namespace Mockery;', $code);
}
/**
* @test
*/
public function shouldReplaceNamespaceIfClassNameIsNamespaced()
{
$config = new MockConfiguration();
$config->setName("Dave\Dave");
$code = $this->pass->apply(static::CODE, $config);
$this->assertNotContains('namespace Mockery;', $code);
$this->assertContains('namespace Dave;', $code);
}
/**
* @test
*/
public function shouldReplaceClassNameWithSpecifiedName()
{
$config = new MockConfiguration();
$config->setName("Dave");
$code = $this->pass->apply(static::CODE, $config);
$this->assertContains('class Dave', $code);
}
/**
* @test
*/
public function shouldReplaceClassNameWithGeneratedNameIfNotSpecified()
{
$config = m::mock("Mockery\Generator\MockConfiguration", array(
"generateName" => "Dave",
))->shouldIgnoreMissing();
$code = $this->pass->apply(static::CODE, $config);
$this->assertContains('class Dave', $code);
}
}
|
Exclude user field from form | from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"user",
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
"report_url",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
exclude = [
'status',
]
| from django.forms import ModelForm, widgets
from .models import Fellow, Event, Expense, Blog
class FellowForm(ModelForm):
class Meta:
model = Fellow
exclude = [
"home_lon",
"home_lat",
"inauguration_year",
"funding_notes",
"mentor",
]
class EventForm(ModelForm):
class Meta:
model = Event
exclude = [
"status",
"budget_approve",
"report_url",
]
# We don't want to expose fellows' data
# so we will request the email
# and match on the database.
labels = {
'fellow': 'Fellow',
'url': "Event's homepage url",
'name': "Event's name",
}
class ExpenseForm(ModelForm):
class Meta:
model = Expense
exclude = [
'id',
'status',
]
class BlogForm(ModelForm):
class Meta:
model = Blog
exclude = [
'status',
]
|
Add skip argument to `bulk:all` | <?php
namespace App\Console\Commands\Bulk;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class BulkAll extends BaseCommand
{
protected $signature = 'bulk:all {skip?}';
protected $description = "Reset database and import everything";
public function handle()
{
$shouldSkipTo = $this->argument('skip') ?? false;
// Import all bulkable resources from compliant data services
foreach (config('resources.inbound') as $source => $endpoints) {
foreach ($endpoints as $endpoint => $resource) {
dump("$source >> $endpoint");
if ($shouldSkipTo && $source !== $shouldSkipTo) {
dump("Skipping...");
continue;
}
$this->call('bulk:import', [
'source' => $source,
'endpoint' => $endpoint,
]);
$shouldSkipTo = false;
}
}
/*
// TODO: Use bulking for import:images
// TODO: Use upserts for import:analytics
// Import non-standard data
$this->call('import:mobile');
$this->call('import:sites', ['--yes' => 'default']);
$this->call('import:ulan');
$this->call('import:analytics');
// EventOccurrence is not included in import:web to avoid duplication
$this->call('import:web-full', ['--yes' => 'default', 'endpoint' => 'event-occurrences']);
*/
}
}
| <?php
namespace App\Console\Commands\Bulk;
use Aic\Hub\Foundation\AbstractCommand as BaseCommand;
class BulkAll extends BaseCommand
{
protected $signature = 'bulk:all';
protected $description = "Reset database and import everything";
public function handle()
{
// Import all bulkable resources from compliant data services
foreach (config('resources.inbound') as $source => $endpoints) {
foreach ($endpoints as $endpoint => $resource) {
dump("$source >> $endpoint");
$this->call('bulk:import', [
'source' => $source,
'endpoint' => $endpoint,
]);
}
}
/*
// TODO: Use bulking for import:images
// TODO: Use upserts for import:analytics
// Import non-standard data
$this->call('import:mobile');
$this->call('import:sites', ['--yes' => 'default']);
$this->call('import:ulan');
$this->call('import:analytics');
// EventOccurrence is not included in import:web to avoid duplication
$this->call('import:web-full', ['--yes' => 'default', 'endpoint' => 'event-occurrences']);
*/
}
}
|
conan: Copy find modules to root of module path | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class IWYUCTargetCmakeConan(ConanFile):
name = "iwyu-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/iwyu-target-cmake"
license = "MIT"
def source(self):
zip_name = "iwyu-target-cmake.zip"
download("https://github.com/polysquare/"
"iwyu-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="Find*.cmake",
dst="",
src="iwyu-target-cmake-" + VERSION,
keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/iwyu-target-cmake",
src="iwyu-target-cmake-" + VERSION,
keep_path=True)
| from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class IWYUCTargetCmakeConan(ConanFile):
name = "iwyu-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspillaz/cmake-include-guard",
"tooling-find-pkg-util/master@smspillaz/tooling-find-pkg-util",
"tooling-cmake-util/master@smspillaz/tooling-cmake-util",
"cmake-unit/master@smspillaz/cmake-unit")
url = "http://github.com/polysquare/iwyu-target-cmake"
license = "MIT"
def source(self):
zip_name = "iwyu-target-cmake.zip"
download("https://github.com/polysquare/"
"iwyu-target-cmake/archive/{version}.zip"
"".format(version="v" + VERSION),
zip_name)
unzip(zip_name)
os.unlink(zip_name)
def package(self):
self.copy(pattern="*.cmake",
dst="cmake/iwyu-target-cmake",
src="iwyu-target-cmake-" + VERSION,
keep_path=True)
|
Fix create account validation, Dashboard filters | <ul>
<?php foreach($pager->getResults() as $flight): ?>
<li>
<?php if($flight->getDrafted() && $flight->getStatus() == "new"): ?>
<?php if($flight->getTripNumber()): ?>
<span><?php echo $flight->getTripNumber() ?>(Drafted)</span>
<?php else: ?>
<span>Drafted</span>
<span><?php echo $flight->getId() ?></span>
<?php endif ?>
<a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit</a>
<?php elseif($flight->getDrafted() && $flight->getStatus() == "assess"): ?>
<span><?php echo $flight->getTripNumber() ?>(Drafted)</span>
<a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit</a>
<?php else: ?>
<span><?php echo $flight->getTripNumber() ?></span>
<span><?php echo $flight->getRiskFactorSum() ?></span>
<span><?php echo date('Y-m-d', strtotime($flight->getCreatedAt())) ?></span>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
<div class="pager">
<?php include_partial('dashboard/pager', array('pager' => $pager, 'account' => $account)); ?>
</div> | <ul>
<?php foreach($pager->getResults() as $flight): ?>
<li>
<?php if($flight->getDrafted() && $flight->getStatus() == "new"): ?>
<span>Drafted</span>
<span><?php echo $flight->getId() ?></span>
<a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit</a>
<?php elseif($flight->getDrafted() && $flight->getStatus() == "assess"): ?>
<span><?php echo $flight->getTripNumber() ?>(Drafted)</span>
<a href="<?php echo url_for("@edit_flight?account_id={$account->getId()}&id={$flight->getId()}") ?>">Edit</a>
<?php else: ?>
<span><?php echo $flight->getTripNumber() ?></span>
<span><?php echo $flight->getRiskFactorSum() ?></span>
<span><?php echo date('Y-m-d', strtotime($flight->getCreatedAt())) ?></span>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>
<div class="pager">
<?php include_partial('dashboard/pager', array('pager' => $pager, 'account' => $account)); ?>
</div> |
Add nullable validation rule to software version field | <?php
namespace RadDB\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateMachineRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'modality' => 'required|integer',
'description' => 'required|string|max:60',
'manufacturer' => 'required|integer',
'model' => 'required|string|max:50',
'serialNumber' => 'required|string|max:20',
'softwareVersion' => 'string|max:50|nullable',
'vendSiteID' => 'string|nullable|max:25',
'manufDate' => 'date_format:Y-m-d|nullable',
'installDate' => 'date_format:Y-m-d|nullable',
'location' => 'required|integer',
'room' => 'required|string|max:20',
'status' => 'required|in:Active,Inactive,Removed|max:50',
'notes' => 'string|nullable|max:65535',
];
}
}
| <?php
namespace RadDB\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateMachineRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'modality' => 'required|integer',
'description' => 'required|string|max:60',
'manufacturer' => 'required|integer',
'model' => 'required|string|max:50',
'serialNumber' => 'required|string|max:20',
'softwareVersion' => 'string|max:50',
'vendSiteID' => 'string|nullable|max:25',
'manufDate' => 'date_format:Y-m-d|nullable',
'installDate' => 'date_format:Y-m-d|nullable',
'location' => 'required|integer',
'room' => 'required|string|max:20',
'status' => 'required|in:Active,Inactive,Removed|max:50',
'notes' => 'string|nullable|max:65535',
];
}
}
|
Implement Twittter; fix aggregate scores | <?php
namespace Metrics\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Metrics\Http\Requests;
use Metrics\Http\Controllers\Controller;
use Metrics\Idol\Idol;
class IdolController extends Controller
{
private $idol;
public function __construct(Idol $idol)
{
$this->idol = $idol;
}
public function analyseKeyword(){
$keyword = Input::get('keyword');
$max_results = (Input::has('max_results')) ? Input::get('max_results') : 20;
$idol = $this->idol;
try {
if (Input::has('min_date') || Input::has('max_date')) {
$min_date = (Input::has('min_date')) ? Input::get('min_date') . 'e' : null;
$max_date = (Input::has('max_date')) ? Input::get('max_date') . 'e' : null;
$response = $idol->queryTextIndexByKeyword($keyword, $min_date, $max_date, $max_results);
} else {
$response = $idol->queryTextIndexWithTicker($keyword, $max_results);
}
} catch (\Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
return response()->json($response, 200);
}
}
| <?php
namespace Metrics\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Metrics\Http\Requests;
use Metrics\Http\Controllers\Controller;
use Metrics\Idol\Idol;
class IdolController extends Controller
{
private $idol;
public function __construct(Idol $idol)
{
$this->idol = $idol;
}
public function analyseKeyword(){
$keyword = Input::get('keyword');
$max_results = (Input::has('max_results')) ? Input::get('max_results') : 20;
$idol = $this->idol;
try {
if (Input::has('min_date') || Input::has('max_date')) {
$min_date = (Input::has('min_date')) ? Input::get('min_date') . 'e' : null;
$max_date = (Input::has('max_date')) ? Input::get('max_date') . 'e' : null;
$response = $idol->queryTextIndexByKeyword($keyword, $min_date, $max_date, $max_results);
} else {
$response = $idol->queryTwitterWithKeyword($keyword, $max_results);
}
} catch (\Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
return response()->json($response, 200);
}
}
|
Add comments to every method. | function InputManager() {
this.km;
this.notify;
this.newGame;
this.quitGame;
this.pauseGame;
}
/* Store the game-related keycodes to listen for */
InputManager.prototype.setKeyMap = function(keyMap) {
this.km = keyMap;
}
/* Defines the comm pipeline to take when a relavent event is captured */
InputManager.prototype.register = function(event, callback) {
switch(event) {
case 'action': this.notify = callback; break;
case 'newgame': this.newGame = callback; break;
case 'quitgame': this.quitGame = callback; break;
case 'pausegame': this.pauseGame = callback; break;
}
}
/* Register the event filter with the browser */
InputManager.prototype.listen = function() {
document.addEventListener('keydown', this.keyHandler.bind(this));
}
/* The filter to use to get only game-related events */
InputManager.prototype.keyHandler = function(e) {
switch(e.keyCode) {
case this.km.LEFT:
case this.km.RIGHT:
case this.km.DOWN:
case this.km.DROP:
case this.km.RTURN:
case this.km.LTURN:
this.notify(e.keyCode);
break;
case this.km.NEW:
this.newGame();
break;
case this.km.QUIT:
this.quitGame();
break;
case this.km.PAUSE:
this.pauseGame();
break;
}
}
| function InputManager() {
this.km;
this.notify;
this.newGame;
this.quitGame;
this.pauseGame;
}
InputManager.prototype.setKeyMap = function(keyMap) {
this.km = keyMap;
}
InputManager.prototype.register = function(event, callback) {
switch(event) {
case 'action': this.notify = callback; break;
case 'newgame': this.newGame = callback; break;
case 'quitgame': this.quitGame = callback; break;
case 'pausegame': this.pauseGame = callback; break;
}
}
InputManager.prototype.listen = function() {
document.addEventListener('keydown', this.keyHandler.bind(this));
}
InputManager.prototype.keyHandler = function(e) {
switch(e.keyCode) {
case this.km.LEFT:
case this.km.RIGHT:
case this.km.DOWN:
case this.km.DROP:
case this.km.RTURN:
case this.km.LTURN:
this.notify(e.keyCode);
break;
case this.km.NEW:
this.newGame();
break;
case this.km.QUIT:
this.quitGame();
break;
case this.km.PAUSE:
this.pauseGame();
break;
}
}
|
Add exit code to exception | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool;
use \Symfony\Component\Process\Process;
abstract class Exiftool
{
/**
* Execute a command and return the output
*
* @param string $command
* @return string
* @throws \Exception
*/
protected static function executeCommand($command)
{
$process = new Process($command);
$process->run();
if ( ! $process->isSuccessful()) {
throw new Exception\RuntimeException(sprintf('Command %s failed : %s, exitcode %s', $command, $process->getErrorOutput(), $process->getExitCode()));
}
return $process->getOutput();
}
/**
*
* @return string
*/
protected static function getBinary()
{
$dev = __DIR__ . '/../../vendor/phpexiftool/exiftool/exiftool';
$packaged = __DIR__ . '/../../../../phpexiftool/exiftool/exiftool';
foreach (array($packaged, $dev) as $location) {
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$location .= '.exe';
}
if (is_executable($location)) {
return realpath($location);
}
}
}
}
| <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool;
use \Symfony\Component\Process\Process;
abstract class Exiftool
{
/**
* Execute a command and return the output
*
* @param string $command
* @return string
* @throws \Exception
*/
protected static function executeCommand($command)
{
$process = new Process($command);
$process->run();
if ( ! $process->isSuccessful()) {
throw new Exception\RuntimeException(sprintf('Command %s failed : %s', $command, $process->getErrorOutput()));
}
return $process->getOutput();
}
/**
*
* @return string
*/
protected static function getBinary()
{
$dev = __DIR__ . '/../../vendor/phpexiftool/exiftool/exiftool';
$packaged = __DIR__ . '/../../../../phpexiftool/exiftool/exiftool';
foreach (array($packaged, $dev) as $location) {
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$location .= '.exe';
}
if (is_executable($location)) {
return realpath($location);
}
}
}
}
|
Add `strict` mode to consider warnings as errors
This is a first approach to fix issue #38. It would be good improve
output to make it more uniform with `mocha` errors, but at least it
does the job :-) | var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var globAll = require('glob-all');
var replaceAll = require("replaceall");
var cli = new CLIEngine({});
function test(p, opts) {
it('should have no errors in ' + p, function () {
var format, warn;
if (opts && opts.timeout) {
this.timeout(opts.timeout);
}
if (opts && opts.formatter) {
format = opts.formatter;
}
if (opts && opts.hasOwnProperty('alwaysWarn')) {
warn = opts.alwaysWarn;
} else { // Show warnings by default
warn = true;
}
var report = cli.executeOnFiles([p]);
var formatter = cli.getFormatter(format);
if (report) {
if (report.errorCount > 0 || opts.strict && report.warningCount > 0) {
throw new Error(
chalk.red('Code did not pass lint rules') +
// remove process.cwd() to convert absolute to relative paths
replaceAll(process.cwd() + '/', '', formatter(report.results))
);
} else if (
warn &&
report.warningCount > 0
) {
console.log(formatter(report.results));
}
}
});
}
module.exports = function (patterns, options) {
describe('eslint', function () {
globAll.sync(patterns).forEach(function (file) {
test(file, options);
});
});
};
| var CLIEngine = require('eslint').CLIEngine;
var chalk = require('chalk');
var globAll = require('glob-all');
var replaceAll = require("replaceall");
var cli = new CLIEngine({});
function test(p, opts) {
it('should have no errors in ' + p, function () {
var format, warn;
if (opts && opts.timeout) {
this.timeout(opts.timeout);
}
if (opts && opts.formatter) {
format = opts.formatter;
}
if (opts && opts.hasOwnProperty('alwaysWarn')) {
warn = opts.alwaysWarn;
} else { // Show warnings by default
warn = true;
}
var report = cli.executeOnFiles([p]);
var formatter = cli.getFormatter(format);
if (
report &&
report.errorCount > 0
) {
throw new Error(
chalk.red('Code did not pass lint rules') +
// remove process.cwd() to convert absolute to relative paths
replaceAll(process.cwd() + '/', '', formatter(report.results))
);
} else if (
warn &&
report &&
report.warningCount > 0
) {
console.log(formatter(report.results));
}
});
}
module.exports = function (patterns, options) {
describe('eslint', function () {
globAll.sync(patterns).forEach(function (file) {
test(file, options);
});
});
};
|
Fix bug with 'all' argument | from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
assert 'all' not in args.resources or len(args.resources) == 1
if 'all' in args.resources:
args.resources = [name.replace('Resource', '') for name in names_registered()]
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
| from copy import copy
import argparse
from preparation.resources.Resource import names_registered, resource_by_name
from hb_res.storage import get_storage, ExplanationStorage
def generate_asset(resource, out_storage: ExplanationStorage):
out_storage.clear()
for explanation in resource:
r = copy(explanation)
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is not None:
out_storage.add_entry(r)
def rebuild_trunk(trunk: str):
resource = resource_by_name(trunk + 'Resource')()
with get_storage(trunk) as out_storage:
print("Starting {} generation".format(trunk))
generate_asset(resource, out_storage)
print("Finished {} generation".format(trunk))
def make_argparser():
parser = argparse.ArgumentParser(description='Rebuild some asset')
names = [name.replace('Resource', '') for name in names_registered()]
parser.add_argument('resources',
metavar='RESOURCE',
nargs='+',
choices=names + ['all'],
help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names)))
return parser
def main(args=None):
if not isinstance(args, argparse.Namespace):
parser = make_argparser()
args = parser.parse_args(args)
assert all not in args.resources or len(args.resources) == 1
for name in args.resources:
rebuild_trunk(name)
if __name__ == '__main__':
main()
|
Add Max priority for queue declare | <?php
namespace VladimirYuldashev\LaravelQueueRabbitMQ\Console;
use Exception;
use Illuminate\Console\Command;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector;
class QueueDeclareCommand extends Command
{
protected $signature = 'rabbitmq:queue-declare
{name : The name of the queue to declare}
{connection=rabbitmq : The name of the queue connection to use}
{--durable=1}
{--max-priority=4}
{--auto-delete=0}';
protected $description = 'Declare queue';
/**
* @param RabbitMQConnector $connector
* @throws Exception
*/
public function handle(RabbitMQConnector $connector): void
{
$config = $this->laravel['config']->get('queue.connections.'.$this->argument('connection'));
$queue = $connector->connect($config);
if ($queue->isQueueExists($this->argument('name'))) {
$this->warn('Queue already exists.');
return;
}
$maxPriority = (int) $this->option('max-priority');
$arguments = [
'x-max-priority' => $maxPriority
];
$queue->declareQueue(
$this->argument('name'),
(bool) $this->option('durable'),
(bool) $this->option('auto-delete'),
$arguments
);
$this->info('Queue declared successfully.');
}
}
| <?php
namespace VladimirYuldashev\LaravelQueueRabbitMQ\Console;
use Exception;
use Illuminate\Console\Command;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Connectors\RabbitMQConnector;
class QueueDeclareCommand extends Command
{
protected $signature = 'rabbitmq:queue-declare
{name : The name of the queue to declare}
{connection=rabbitmq : The name of the queue connection to use}
{--durable=1}
{--auto-delete=0}';
protected $description = 'Declare queue';
/**
* @param RabbitMQConnector $connector
* @throws Exception
*/
public function handle(RabbitMQConnector $connector): void
{
$config = $this->laravel['config']->get('queue.connections.'.$this->argument('connection'));
$queue = $connector->connect($config);
if ($queue->isQueueExists($this->argument('name'))) {
$this->warn('Queue already exists.');
return;
}
$queue->declareQueue(
$this->argument('name'),
(bool) $this->option('durable'),
(bool) $this->option('auto-delete')
);
$this->info('Queue declared successfully.');
}
}
|
Fix latent bug in proxied XMLRPC that broke adding 5.8.x rUS (RBL-7945) | #
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
import urllib
from conary.repository import transport
class ProxiedTransport(transport.Transport):
"""
Transport class for contacting rUS through a proxy
"""
def __init__(self, *args, **kw):
# Override transport.XMLOpener with our own that does the right thing
# with the selector.
transport.XMLOpener = ProxiedXMLOpener
return transport.Transport.__init__(self, *args, **kw)
def parse_response(self, *args, **kw):
resp = transport.Transport.parse_response(self, *args, **kw)
# The request method on transport.Transport expects this return
# result.
return [[resp,]]
def request(self, *args, **kw):
resp = transport.Transport.request(self, *args, **kw)
# Return just the value.
return resp[0][1]
class ProxiedXMLOpener(transport.XMLOpener):
def createConnection(self, *args, **kw):
h, urlstr, selector, headers = transport.URLOpener.createConnection(self, *args, **kw)
# transport.URLOpener.createConnection leaves selector as the full
# protocol, host, path string. That does not always work with proxy,
# so parse out just the path.
proto, rest = urllib.splittype(selector)
host, rest = urllib.splithost(rest)
return h, urlstr, rest, headers
| #
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
import urllib
from conary.repository import transport
class ProxiedTransport(transport.Transport):
"""
Transport class for contacting rUS through a proxy
"""
def __init__(self, *args, **kw):
# Override transport.XMLOpener with our own that does the right thing
# with the selector.
transport.XMLOpener = ProxiedXMLOpener
return transport.Transport.__init__(self, *args, **kw)
def parse_response(self, *args, **kw):
resp = transport.Transport.parse_response(self, *args, **kw)
# The request method on transport.Transport expects this return
# result.
return [[resp,]]
def request(self, *args, **kw):
resp = transport.Transport.request(self, *args, **kw)
# Return just the value.
return resp[0][1][0]
class ProxiedXMLOpener(transport.XMLOpener):
def createConnection(self, *args, **kw):
h, urlstr, selector, headers = transport.URLOpener.createConnection(self, *args, **kw)
# transport.URLOpener.createConnection leaves selector as the full
# protocol, host, path string. That does not always work with proxy,
# so parse out just the path.
proto, rest = urllib.splittype(selector)
host, rest = urllib.splithost(rest)
return h, urlstr, rest, headers
|
Fix dependency reference to autoprefixer. | var autoprefixer = require('autoprefixer');
var postcss = require('postcss');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
// setting from = input filename works unless there is a directory,
// then autoprefixer adds the directory onto the source filename twice.
// setting to to anything else causes an un-necessary extra file to be
// added to the map, but its better than it failing
processOptions.from = sourceMap.getOutputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = postcss([autoprefixer(options)]).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
| var autoprefixer = require('autoprefixer-core');
var postcss = require('postcss');
module.exports = function(less) {
function AutoprefixProcessor(options) {
this.options = options || {};
};
AutoprefixProcessor.prototype = {
process: function (css, extra) {
var options = this.options;
var sourceMap = extra.sourceMap;
var sourceMapInline, processOptions = {};
if (sourceMap) {
processOptions.map = {};
processOptions.to = sourceMap.getOutputFilename();
// setting from = input filename works unless there is a directory,
// then autoprefixer adds the directory onto the source filename twice.
// setting to to anything else causes an un-necessary extra file to be
// added to the map, but its better than it failing
processOptions.from = sourceMap.getOutputFilename();
sourceMapInline = sourceMap.isInline();
if (sourceMapInline) {
processOptions.map.inline = true;
} else {
processOptions.map.prev = sourceMap.getExternalSourceMap();
processOptions.map.annotation = sourceMap.getSourceMapURL();
}
}
var processed = postcss([autoprefixer(options)]).process(css, processOptions);
if (sourceMap && !sourceMapInline) {
sourceMap.setExternalSourceMap(processed.map);
}
return processed.css;
}
};
return AutoprefixProcessor;
};
|
Add length validation to string form field | <?php
namespace Kunstmaan\FormBundle\Entity\FormSubmissionFieldTypes;
use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
use Kunstmaan\FormBundle\Form\StringFormSubmissionType;
use Symfony\Component\Validator\Constraints as Assert;
/**
* The StringFormSubmissionField can be used to store string values to a FormSubmission
*
* @ORM\Entity
* @ORM\Table(name="kuma_string_form_submission_fields")
*/
class StringFormSubmissionField extends FormSubmissionField
{
/**
* @ORM\Column(name="sfsf_value", type="string")
* @Assert\Length(max=255)
*/
protected $value;
/**
* Returns the default form type for this FormSubmissionField
*
* @return string
*/
public function getDefaultAdminType()
{
return StringFormSubmissionType::class;
}
/**
* Return a string representation of this FormSubmissionField
*
* @return string
*/
public function __toString()
{
$value = $this->getValue();
return !empty($value) ? $value : '';
}
/**
* Returns the current value of this field
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Sets the current value of this field
*
* @param string $value
*
* @return StringFormSubmissionField
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
}
| <?php
namespace Kunstmaan\FormBundle\Entity\FormSubmissionFieldTypes;
use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
use Kunstmaan\FormBundle\Form\StringFormSubmissionType;
/**
* The StringFormSubmissionField can be used to store string values to a FormSubmission
*
* @ORM\Entity
* @ORM\Table(name="kuma_string_form_submission_fields")
*/
class StringFormSubmissionField extends FormSubmissionField
{
/**
* @ORM\Column(name="sfsf_value", type="string")
*/
protected $value;
/**
* Returns the default form type for this FormSubmissionField
*
* @return string
*/
public function getDefaultAdminType()
{
return StringFormSubmissionType::class;
}
/**
* Return a string representation of this FormSubmissionField
*
* @return string
*/
public function __toString()
{
$value = $this->getValue();
return !empty($value) ? $value : '';
}
/**
* Returns the current value of this field
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Sets the current value of this field
*
* @param string $value
*
* @return StringFormSubmissionField
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
}
|
chore(tests): Fix false positive test result | import { moduleFor, test } from 'ember-qunit';
moduleFor('service:client', 'Unit | Service | Client', {
// Specify the other units that are required for this test.
//needs: ['service:server']
});
// Replace this with your real tests.
test('it exists', function(assert) {
assert.expect(3);
let name = 'Foo';
let age = 5;
let windowEvents = {};
var client = this.subject({
answers: {
'my-name-is': name,
'my-age-is': age
},
window: {
parent: {
postMessage: function(payload) {
function respond(id, answer) {
let query = {
id: id,
type: 'messenger-server-inbound',
response: answer
};
windowEvents['message']({
data: JSON.stringify(query),
origin: null,
source: null
});
}
let question = JSON.parse(payload);
respond(question.id, client.answers[question.name]);
}
},
addEventListener: function(event, callback) {
windowEvents[event] = callback;
}
}
});
assert.ok(client);
client.fetch('parent:my-name-is').then(function(returnedName) {
assert.equal(returnedName, name, 'Name should be Foo');
});
client.fetch('parent:my-age-is').then(function(returnedAge) {
assert.equal(returnedAge, age, 'Age should be 5');
});
});
| import { moduleFor, test } from 'ember-qunit';
moduleFor('service:client', 'Unit | Service | Client', {
// Specify the other units that are required for this test.
//needs: ['service:server']
});
// Replace this with your real tests.
test('it exists', function(assert) {
assert.expect(3);
let name = 'Foo';
let age = 5;
let windowEvents = {};
var client = this.subject({
answers: {
'my-name-is': name,
'my-age-is': age
},
window: {
postMessage: function(payload) {
function respond(id, answer) {
let query = {
id: id,
type: 'messenger-server-inbound',
response: answer
};
windowEvents['message']({
data: JSON.stringify(query),
origin: null,
source: null
});
}
let question = JSON.parse(payload);
respond(question.id, client.answers[question.name]);
},
addEventListener: function(event, callback) {
windowEvents[event] = callback;
},
//Fake parent window postMessage
parent: {
postMessage: function(payload) {
assert.ok(payload);
}
}
}
});
assert.ok(client);
client.fetch('parent:my-name-is').then(function(returnedName) {
assert.equal(returnedName, name, 'Name should be Foo');
});
client.fetch('parent:my-age-is').then(function(returnedAge) {
assert.equal(returnedAge, age, 'Age should be 5');
});
});
|
Fix bug in Element to allow subclassing |
class Button(object):
"""Button object, used for creating button messages"""
def __init__(self, type=None, title="", payload=""):
# Type: request param key
valid_types = {
'web_url': 'url',
'postback': 'payload'
}
assert type in valid_types, "Type %s is not a Button type" \
% (type,)
self.title = title
self.type = type
self.typekey = valid_types[type]
self.payload = payload
def to_json(self):
request_payload = {}
request_payload[self.typekey] = self.payload
request_payload['title'] = self.title
request_payload['type'] = self.type
return request_payload
class Element(object):
"""Elements are features of Templates"""
def __init__(self, title="", subtitle="", image_url="", buttons=None):
self.title = title
self.image_url = image_url
self.subtitle = subtitle
self.buttons = buttons
def to_json(self):
if self.buttons:
buttons = [button.to_json() for button in self.buttons]
payload = {
'title': self.title,
'image_url': self.image_url,
'subtitle': self.subtitle,
'buttons': buttons
}
return payload
|
class Button(object):
"""Button object, used for creating button messages"""
def __init__(self, type=None, title="", payload=""):
# Type: request param key
valid_types = {
'web_url': 'url',
'postback': 'payload'
}
assert type in valid_types, "Type %s is not a Button type" \
% (type,)
self.title = title
self.type = type
self.typekey = valid_types[type]
self.payload = payload
def to_json(self):
request_payload = {}
request_payload[self.typekey] = self.payload
request_payload['title'] = self.title
request_payload['type'] = self.type
return request_payload
class Element():
"""Elements are features of Templates"""
def __init__(self, title="", subtitle="", image_url="", buttons=None):
self.title = title
self.image_url = image_url
self.subtitle = subtitle
self.buttons = buttons
def to_json(self):
if self.buttons:
buttons = [button.to_json() for button in self.buttons]
payload = {
'title': self.title,
'image_url': self.image_url,
'subtitle': self.subtitle,
'buttons': buttons
}
return payload
|
Increase test timeout again for Travis | 'use strict';
var assert = require('assert');
var path = require('path');
var execFileSync = require('child_process').execFileSync;
var root = path.resolve(__dirname, '..');
var hook = path.relative(root, 'bin/commit-msg');
var validFile = path.relative(root,
path.resolve(__dirname, 'resources/COMMIT_EDITMSG'));
var invalidFile = path.relative(root,
path.resolve(__dirname, 'resources/COMMIT_EDITMSG-invalid'));
describe('commig-msg', function() {
this.timeout(5000); // allow enough time
describe('valid', function() {
it('should exit with status 0', function() {
assert.doesNotThrow(
function() {
execFileSync('node', [hook, validFile], {
cwd: root,
encoding: 'utf8',
stdio: [null]
});
}
);
});
});
describe('invalid', function() {
it('should exit with error status 9', function() {
assert.throws(
function() {
execFileSync('node', [hook, invalidFile], {
cwd: root,
encoding: 'utf8',
stdio: [null]
});
},
function(e) {
return e.status === 9;
}
);
});
});
});
| 'use strict';
var assert = require('assert');
var path = require('path');
var execFileSync = require('child_process').execFileSync;
var root = path.resolve(__dirname, '..');
var hook = path.relative(root, 'bin/commit-msg');
var validFile = path.relative(root,
path.resolve(__dirname, 'resources/COMMIT_EDITMSG'));
var invalidFile = path.relative(root,
path.resolve(__dirname, 'resources/COMMIT_EDITMSG-invalid'));
describe('commig-msg', function() {
describe('valid', function() {
it('should exit with status 0', function() {
assert.doesNotThrow(
function() {
execFileSync('node', [hook, validFile], {
cwd: root,
encoding: 'utf8',
stdio: [null]
});
}
);
});
});
describe('invalid', function() {
it('should exit with error status 9', function() {
assert.throws(
function() {
execFileSync('node', [hook, invalidFile], {
cwd: root,
encoding: 'utf8',
stdio: [null]
});
},
function(e) {
return e.status === 9;
}
);
});
});
});
|
Make sure we remember to which the user was merged | from django.db.models.functions import Lower
from django.db.models import Count
from bluebottle.members.models import Member
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
from bluebottle.activities.models import Activity, Contributor
from bluebottle.initiatives.models import Initiative
for client in Client.objects.all():
with LocalTenant(client):
duplicate = Member.objects.annotate(
lower=Lower('email')
).values('lower').annotate(count=Count('lower')).filter(count__gt=1)
for result in duplicate:
first = Member.objects.filter(email__iexact=result['lower']).order_by('date_joined').first()
for duplicate in Member.objects.filter(
email__iexact=result['lower']
).exclude(pk=first.pk).order_by('date_joined'):
for activity in Activity.objects.filter(owner=duplicate):
activity.owner = first
activity.execute_triggers(send_messages=False)
activity.save()
for contributor in Contributor.objects.filter(user=duplicate):
contributor.user = first
contributor.execute_triggers(send_messages=False)
contributor.save()
for initiative in Initiative.objects.filter(owner=duplicate):
initiative.owner = first
initiative.execute_triggers(send_messages=False)
initiative.save()
duplicate.anonymize()
duplicate.email = 'merged-{}@example.com'.format(first.pk)
duplicate.save()
| from django.db.models.functions import Lower
from django.db.models import Count
from bluebottle.members.models import Member
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant
from bluebottle.activities.models import Activity, Contributor
from bluebottle.initiatives.models import Initiative
for client in Client.objects.all():
with LocalTenant(client):
duplicate = Member.objects.annotate(
lower=Lower('email')
).values('lower').annotate(count=Count('lower')).filter(count__gt=1)
for result in duplicate:
first = Member.objects.filter(email__iexact=result['lower']).order_by('date_joined').first()
for duplicate in Member.objects.filter(
email__iexact=result['lower']
).exclude(pk=first.pk).order_by('date_joined'):
for activity in Activity.objects.filter(owner=duplicate):
activity.owner = first
activity.execute_triggers(send_messages=False)
activity.save()
for contributor in Contributor.objects.filter(user=duplicate):
contributor.user = first
contributor.execute_triggers(send_messages=False)
contributor.save()
for initiative in Initiative.objects.filter(owner=duplicate):
initiative.owner = first
initiative.execute_triggers(send_messages=False)
initiative.save()
duplicate.anonymize()
|
Revert "hide worker and coordinator"
This reverts commit d2fc4b1fb37d8b687d7a5561be74a1e04fa0d57c. | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
name = 'Mikko Korpela'
# I might be just a little bit too much afraid of those bots..
address = name.lower().replace(' ', '.')+chr(64)+'gmail.com'
setup(name='robotframework-pabot',
version='1.2.0',
description='Parallel test runner for Robot Framework',
long_description='A parallel executor for Robot Framework tests.'
' With Pabot you can split one execution into multiple and save test execution time.',
author=name,
author_email=address,
url='https://pabot.org',
download_url='https://pypi.python.org/pypi/robotframework-pabot',
packages=find_packages(),
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Testing',
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Framework :: Robot Framework'
],
entry_points = {'console_scripts': [
'pabot=pabot.pabot:main',
'pabotcoordinator=pabot.coordinatorwrapper:main',
'pabotworker=pabot.workerwrapper:main']},
license='Apache License, Version 2.0',
install_requires=[
'robotframework',
'websockets>=8.1;python_version>="3.6"',
'robotremoteserver>=1.1',
'typing;python_version<"3.5"'])
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
name = 'Mikko Korpela'
# I might be just a little bit too much afraid of those bots..
address = name.lower().replace(' ', '.')+chr(64)+'gmail.com'
setup(name='robotframework-pabot',
version='1.2.0',
description='Parallel test runner for Robot Framework',
long_description='A parallel executor for Robot Framework tests.'
' With Pabot you can split one execution into multiple and save test execution time.',
author=name,
author_email=address,
url='https://pabot.org',
download_url='https://pypi.python.org/pypi/robotframework-pabot',
packages=find_packages(),
classifiers=[
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Testing',
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Framework :: Robot Framework'
],
entry_points = {'console_scripts': [
'pabot=pabot.pabot:main']},
license='Apache License, Version 2.0',
install_requires=[
'robotframework',
'websockets>=8.1;python_version>="3.6"',
'robotremoteserver>=1.1',
'typing;python_version<"3.5"'])
|
Remove `Profiler` functions from demo | <?php
namespace Demo\Application\Adapter;
use Colonel\Configuration;
use Twig_Loader_Filesystem;
use Twig_Environment;
class TwigAdapter
{
private $twig;
private $loader;
public function __construct(
Configuration $configuration
) {
$this->configuration = $configuration;
$this->initialise();
}
public function initialise()
{
$this->loader = new Twig_Loader_Filesystem;
$this->setPaths(
$this->configuration['kernel']['root'],
$this->configuration['twig']['paths']
);
$this->twig = new Twig_Environment(
$this->loader,
$this->configuration['twig']['options']
);
$this->twig->addFunction(new \Twig_SimpleFunction('dump', function() {
echo '<pre>';
var_dump(func_get_args());
echo '</pre>';
}));
}
public function render($view, array $parameters = [])
{
$view = $this->twig->render($view, $parameters);
return $view;
}
private function setPaths($projectRoot, array $paths = [])
{
foreach ($paths as $namespace => $path) {
$this->loader->addPath(
sprintf('%s/%s', $projectRoot, $path),
$namespace
);
}
}
} | <?php
namespace Demo\Application\Adapter;
use Colonel\Configuration;
use Colonel\Profiler;
use Twig_Loader_Filesystem;
use Twig_Environment;
class TwigAdapter
{
private $twig;
private $loader;
public function __construct(
Configuration $configuration
) {
$this->configuration = $configuration;
$this->initialise();
}
public function initialise()
{
$this->loader = new Twig_Loader_Filesystem;
$this->setPaths(
$this->configuration['kernel']['root'],
$this->configuration['twig']['paths']
);
$this->twig = new Twig_Environment(
$this->loader,
$this->configuration['twig']['options']
);
$this->twig->addFunction(new \Twig_SimpleFunction('dump', function() {
echo '<pre>';
var_dump(func_get_args());
echo '</pre>';
}));
}
public function render($view, array $parameters = [])
{
$view = $this->twig->render($view, $parameters);
return $view;
}
private function setPaths($projectRoot, array $paths = [])
{
foreach ($paths as $namespace => $path) {
$this->loader->addPath(
sprintf('%s/%s', $projectRoot, $path),
$namespace
);
}
}
} |
Modify public contribute form definition | <?php
/**
* ProTalk
*
* Copyright (c) 2012-2013, ProTalk
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Protalk\MediaBundle\Form\Media;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ContributeMedia extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text');
$builder->add('email', 'email');
$builder->add('hostUrl', 'url', array('label' => 'Where can we find it?'));
$builder->add('title', 'text');
$builder->add('tags', 'text', array('required' => false));
$builder->add(
'recaptcha',
'ewz_recaptcha',
array(
'attr' => array(
'options' => array(
'theme' => 'clean'
)
)
)
);
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Protalk\MediaBundle\Entity\Contribution',
);
}
public function getName()
{
return 'contribution';
}
}
| <?php
/**
* ProTalk
*
* Copyright (c) 2012-2013, ProTalk
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Protalk\MediaBundle\Form\Media;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ContributeMedia extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', 'text');
$builder->add('email', 'email');
$builder->add('hostUrl', 'url');
$builder->add('hostName', 'text');
$builder->add('title', 'text');
$builder->add('slidesUrl', 'url', array('required' => false));
$builder->add('speaker', 'text', array('required' => false));
$builder->add('tags', 'text', array('required' => false));
$builder->add('description', 'textarea', array('required' => false));
$builder->add(
'category',
'entity',
array('class' => 'ProtalkMediaBundle:Category',
'property' => 'name',
'empty_value' => 'Choose a category'
)
);
$builder->add(
'recaptcha',
'ewz_recaptcha',
array(
'attr' => array(
'options' => array(
'theme' => 'clean'
)
)
)
);
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Protalk\MediaBundle\Entity\Contribution',
);
}
public function getName()
{
return 'contribution';
}
}
|
Set table engine to MyISAM explicitly (for fulltext support) | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('discussion_id')->unsigned();
$table->integer('number')->unsigned()->nullable();
$table->dateTime('time');
$table->integer('user_id')->unsigned()->nullable();
$table->string('type', 100)->nullable();
$table->text('content')->nullable();
$table->text('content_html')->nullable();
$table->dateTime('edit_time')->nullable();
$table->integer('edit_user_id')->unsigned()->nullable();
$table->dateTime('hide_time')->nullable();
$table->integer('hide_user_id')->unsigned()->nullable();
$table->unique(['discussion_id', 'number']);
$table->engine = 'MyISAM';
});
DB::statement('ALTER TABLE posts ADD FULLTEXT content (content)');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use DB;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('discussion_id')->unsigned();
$table->integer('number')->unsigned()->nullable();
$table->dateTime('time');
$table->integer('user_id')->unsigned()->nullable();
$table->string('type', 100)->nullable();
$table->text('content')->nullable();
$table->text('content_html')->nullable();
$table->dateTime('edit_time')->nullable();
$table->integer('edit_user_id')->unsigned()->nullable();
$table->dateTime('hide_time')->nullable();
$table->integer('hide_user_id')->unsigned()->nullable();
$table->unique(['discussion_id', 'number']);
});
DB::statement('ALTER TABLE posts ADD FULLTEXT content (content)');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('posts');
}
}
|
Fix login success status code | (function () {
'use strict';
var jsonfile = require('jsonfile');
var path = require('path');
var authcontroller = require('./../src/authcontroller');
authcontroller.authorize()
.then(function (response) {
var config;
var configFilePath = path.join(__dirname, './../cli-config.json');
switch (response.statusCode) {
case 201:
config = jsonfile.readFileSync(configFilePath);
config.credentials.appsngen = response.body;
config.credentials.appsngen.received = Date.now();
jsonfile.writeFileSync(configFilePath, config, {
spaces: 4
});
console.log('Authorization completed successfully.');
break;
case 401:
console.log('Invalid username or password.');
process.exit(1);
break;
default:
console.log(response.body.message);
console.log('Unexpected response: ' + response.statusCode);
process.exit(1);
}
})
.catch(function(error) {
console.error(error);
process.exit(1);
});
})(); | (function () {
'use strict';
var jsonfile = require('jsonfile');
var path = require('path');
var authcontroller = require('./../src/authcontroller');
authcontroller.authorize()
.then(function (response) {
var config;
var configFilePath = path.join(__dirname, './../cli-config.json');
switch (response.statusCode) {
case 200:
config = jsonfile.readFileSync(configFilePath);
config.credentials.appsngen = response.body;
config.credentials.appsngen.received = Date.now();
jsonfile.writeFileSync(configFilePath, config, {
spaces: 4
});
console.log('Authorization completed successfully.');
break;
case 401:
console.log('Invalid username or password.');
process.exit(1);
break;
default:
console.log(response.body.message);
console.log('Unexpected response: ' + response.statusCode);
process.exit(1);
}
})
.catch(function(error) {
console.error(error);
process.exit(1);
});
})(); |
Change delimiter for repository regex
'#' is the default delimiter for route regexes in
`Symfony\Component\Routing\RouteCompiler`, so use this. | <?php
namespace Gitlist\Util;
use Silex\Application;
class Routing
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function getRepositoryRegex()
{
static $regex = null;
if ($regex === null) {
$app = $this->app;
$quoted_paths = array_map(
function ($repo) use ($app) {
return preg_quote($app['util.routing']->getRelativePath($repo['path']), '#');
},
$this->app['git']->getRepositories($this->app['git.repos'])
);
$regex = '/' . implode('|', $quoted_paths) . '/';
}
return $regex;
}
/**
* Strips the base path from a full repository path
*
* @param string $repo_path Full path to the repository
* @return string Relative path to the repository from git.repositories
*/
public function getRelativePath($repo_path)
{
if (strpos($repo_path, $this->app['git.repos']) === 0) {
$relative_path = substr($repo_path, strlen($this->app['git.repos']));
return ltrim($relative_path, '/');
} else {
throw new \InvalidArgumentException(
sprintf("Path '%s' does not match configured repository directory", $repo_path)
);
}
}
}
| <?php
namespace Gitlist\Util;
use Silex\Application;
class Routing
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function getRepositoryRegex()
{
static $regex = null;
if ($regex === null) {
$app = $this->app;
$quoted_paths = array_map(
function ($repo) use ($app) {
return preg_quote($app['util.routing']->getRelativePath($repo['path']), '/');
},
$this->app['git']->getRepositories($this->app['git.repos'])
);
$regex = '/' . implode('|', $quoted_paths) . '/';
}
return $regex;
}
/**
* Strips the base path from a full repository path
*
* @param string $repo_path Full path to the repository
* @return string Relative path to the repository from git.repositories
*/
public function getRelativePath($repo_path)
{
if (strpos($repo_path, $this->app['git.repos']) === 0) {
$relative_path = substr($repo_path, strlen($this->app['git.repos']));
return ltrim($relative_path, '/');
} else {
throw new \InvalidArgumentException(
sprintf("Path '%s' does not match configured repository directory", $repo_path)
);
}
}
}
|
Add failsafe to HTTP request | <?php namespace Laito;
/**
* Http class
*
* @package default
* @author Mangolabs
*/
class Http extends Core
{
/**
* @var array Fixed parameters array
*/
private $params = [];
/**
* Sets fixed parameters to be sent in all calls
*
* @param array $params Parameters
* @return object Http instance
*/
public function setupParams ($params = []) {
if (is_array($params)) {
$this->params = array_merge($this->params, $params);
}
return $this;
}
/**
* Makes an HTTP call
*
* @param string $url URL to request
* @param string $method HTTP method
* @param array $params Parameters
* @return object Http instance
*/
public function call ($url, $method = 'GET', $params = []) {
// Set call parameters
$params = array_merge($this->params, is_array($params)? $params : []);
// Setup parameters
$content = '';
$queryString = http_build_query($params);
if ($method === 'GET') {
$url = $url . '?' . $queryString;
} else {
$content = $queryString;
}
// Make call
$result = @file_get_contents($url, false, stream_context_create([
'http' => [
'method' => $method,
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $content
]
]));
// Return result
return $result;
}
} | <?php namespace Laito;
/**
* Http class
*
* @package default
* @author Mangolabs
*/
class Http extends Core
{
/**
* @var array Fixed parameters array
*/
private $params = [];
/**
* Sets fixed parameters to be sent in all calls
*
* @param array $params Parameters
* @return object Http instance
*/
public function setupParams ($params = []) {
if (is_array($params)) {
$this->params = array_merge($this->params, $params);
}
return $this;
}
/**
* Makes an HTTP call
*
* @param string $url URL to request
* @param string $method HTTP method
* @param array $params Parameters
* @return object Http instance
*/
public function call ($url, $method = 'GET', $params = []) {
// Set call parameters
$params = array_merge($this->params, is_array($params)? $params : []);
// Setup parameters
$content = '';
$queryString = http_build_query($params);
if ($method === 'GET') {
$url = $url . '?' . $queryString;
} else {
$content = $queryString;
}
// Make call
$result = file_get_contents($url, false, stream_context_create([
'http' => [
'method' => $method,
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $content
]
]));
// Return result
return $result;
}
} |
Mark payment cancelled if id is presented | <?php
namespace Czende\GoPayPlugin\Action;
use Czende\GoPayPlugin\GoPayWrapper;
use Payum\Core\Action\ActionInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Request\GetStatusInterface;
/**
* @author Jan Czernin <[email protected]>
*/
final class StatusAction implements ActionInterface {
/**
* Execute request based on status.
* @param mixed $request
* @throws Payum\Core\Exception\RequestNotSupportedException if the action doesn't support the request.
*/
public function execute($request) {
/** @var $request GetStatusInterface */
RequestNotSupportedException::assertSupports($this, $request);
$model = ArrayObject::ensureArrayObject($request->getModel());
$status = $model['status'];
if ($status === null || $status === GoPayWrapper::CREATED) {
if (isset($model['external_payment_id'])) {
$request->markCanceled();
} else {
$request->markNew();
}
return;
}
if ($status === GoPayWrapper::PAID) {
$request->markCaptured();
return;
}
if ($status === GoPayWrapper::CANCELED) {
$request->markCanceled();
return;
}
$request->markUnknown();
}
/**
* @param mixed $request
* @return boolean
*/
public function supports($request) {
return
$request instanceof GetStatusInterface &&
$request->getModel() instanceof \ArrayAccess;
}
}
| <?php
namespace Czende\GoPayPlugin\Action;
use Czende\GoPayPlugin\GoPayWrapper;
use Payum\Core\Action\ActionInterface;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Request\GetStatusInterface;
/**
* @author Jan Czernin <[email protected]>
*/
final class StatusAction implements ActionInterface {
/**
* Execute request based on status.
* @param mixed $request
* @throws Payum\Core\Exception\RequestNotSupportedException if the action doesn't support the request.
*/
public function execute($request) {
/** @var $request GetStatusInterface */
RequestNotSupportedException::assertSupports($this, $request);
$model = ArrayObject::ensureArrayObject($request->getModel());
$status = $model['status'];
if ($status === null || $status === GoPayWrapper::CREATED) {
$request->markNew();
return;
}
if ($status === GoPayWrapper::PAID) {
$request->markCaptured();
return;
}
if ($status === GoPayWrapper::CANCELED) {
$request->markCanceled();
return;
}
$request->markUnknown();
}
/**
* @param mixed $request
* @return boolean
*/
public function supports($request) {
return
$request instanceof GetStatusInterface &&
$request->getModel() instanceof \ArrayAccess;
}
}
|
Fix webdriver user creation bug | from apps.webdriver_testing.webdriver_base import WebdriverTestCase
from apps.webdriver_testing import data_helpers
from apps.webdriver_testing.data_factories import UserFactory
class WebdriverTestCaseSubtitlesUpload(WebdriverTestCase):
"""TestSuite for uploading subtitles via the api.
"""
def setUp(self):
WebdriverTestCase.setUp(self)
self.user = UserFactory.create(username = 'user')
data_helpers.create_user_api_key(self, self.user)
def api_create_user(self, **kwargs):
"""Create a user via the api.
Creating Users:
POST /api2/partners/users/
"""
create_url = 'users/'
create_data = {'username': None,
'email': None,
'password': 'password',
'first_name': None,
'last_name': None,
'create_login_token': None
}
create_data.update(kwargs)
status, response = data_helpers.post_api_request(self,
create_url,
create_data)
print status
return response
def test_create(self):
new_user = {'username': 'newuser',
'email': '[email protected]',
'first_name': 'New',
'last_name': 'User_1',
}
user_data = self.api_create_user(**new_user)
print user_data['username']
| from apps.webdriver_testing.webdriver_base import WebdriverTestCase
from apps.webdriver_testing import data_helpers
from apps.webdriver_testing.data_factories import UserFactory
class WebdriverTestCaseSubtitlesUpload(WebdriverTestCase):
"""TestSuite for uploading subtitles via the api.
"""
def setUp(self):
WebdriverTestCase.setUp(self)
self.user = UserFactory.create(username = 'user')
data_helpers.create_user_api_key(self, self.user)
def api_create_user(self, **kwargs):
"""Create a user via the api.
Creating Users:
POST /api2/partners/users/
"""
create_url = 'users'
create_data = {'username': None,
'email': None,
'password': 'password',
'first_name': None,
'last_name': None,
'create_login_token': None
}
create_data.update(kwargs)
status, response = data_helpers.post_api_request(self,
create_url,
create_data)
print status
return response
def test_create(self):
new_user = {'username': 'newuser',
'email': '[email protected]',
'first_name': 'New',
'last_name': 'User_1',
}
user_data = self.api_create_user(**new_user)
users = user_data['objects']
print '#######'
for x in users:
print x['username']
|
Rewrite OL+ legend to be non-drupaly. | var OpenLayersPlusLegend = function(opts) {
var self = this;
this.map = $(opts[0]).data('map');
this.setLegend = function(layer) {
// The layer param may vary based on the context from which we are called.
layer = layer.object ? layer.object : layer;
if ('legend' in layer) {
var legend_content = layer.legend || 'your mother';
var legends = $('div.openlayers-legends', self.map.div);
if (layer.visibility && !('legendDiv' in layer)) {
layer.legendDiv = $("<div class='openlayers-legend'></div>").append(legend_content);
legends.append(layer.legendDiv);
}
else if (!layer.visibility && ('legendDiv' in layer)) {
layer.legendDiv.remove();
delete layer.legendDiv;
}
}
};
this.map.layers.forEach(function (layer) {
if (!$('div.openlayers-legends', self.map.div).size()) {
$(self.map.div).append("<div class='openlayers-legends'></div>");
}
layer.events.register('visibilitychanged', layer, self.setLegend);
self.setLegend(layer);
});
};
| var OpenLayersPlusLegend = {};
OpenLayersPlusLegend = {};
OpenLayersPlusLegend.attach = function(context) {
var data = $(context).data('openlayers');
if (data && data.map.behaviors.openlayers_plus_behavior_legend) {
var layer, i;
for (i in data.openlayers.layers) {
layer = data.openlayers.layers[i];
if (data.map.behaviors.openlayers_plus_behavior_legend[layer.drupalID]) {
if (!$('div.openlayers-legends', context).size()) {
$(context).append("<div class='openlayers-legends'></div>");
}
layer.events.register('visibilitychanged', layer, OpenLayersPlusLegend.setLegend);
// Trigger the setLegend() method at attach time. We don't know whether
// our behavior is being called after the map has already been drawn.
OpenLayersPlusLegend.setLegend(layer);
}
}
}
};
OpenLayersPlusLegend.setLegend = function(layer) {
// The layer param may vary based on the context from which we are called.
layer = layer.object ? layer.object : layer;
var name = layer.drupalID;
var map = $(layer.map.div);
var data = map.data('openlayers');
var legend = data.map.behaviors.openlayers_plus_behavior_legend[name];
var legends = $('div.openlayers-legends', map);
if (layer.visibility && $('#openlayers-legend-'+ name, legends).size() === 0) {
legends.append(legend);
}
else if (!layer.visibility) {
$('#openlayers-legend-'+name, legends).remove();
}
};
|
Revert default webdriver to Firefox
Chrome doesn't yet work, anyway... :-( | from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Firefox"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
| from threading import RLock, local
from multiprocessing.pool import ThreadPool
from os import environ as ENV
import logging.config
from flask import Flask, request
from selenium import webdriver
logging.basicConfig()
app = Flask(__name__)
Driver = getattr(webdriver, ENV.get("WEBDRIVER", "Chrome"))
class RetryFailed(Exception):
pass
class Engine():
def __init__(self):
self.driver = Driver()
self.lock = RLock()
def render(self, url, retry=0):
if retry > 3:
raise RetryFailed()
with self.lock:
try:
self.driver.get(url)
return self.driver.get_screenshot_as_png()
except:
self.driver = Driver()
return self.render(url, retry + 1)
thread_local = local()
def thread_init():
thread_local.engine = Engine()
pool = ThreadPool(int(ENV.get("SCREENSHOT_WORKERS", 4)),
thread_init)
def render(url):
return thread_local.engine.render(url)
@app.route('/')
def screenshot():
url = request.args.get('url')
logging.info("Got request for url: %s", url)
return pool.apply(render, (url,)), 200, {
'Content-Type': 'image/png',
}
if __name__ == '__main__':
app.run(debug=True)
|
Add more explicit jumpToFrame during frontend load | (function() {
'use strict';
angular.module('nin').directive('demo', function($interval, demo) {
return {
restrict: 'E',
template: '<div class=demo-container></div>',
link: function(scope, element) {
demo.setContainer(element[0].children[0]);
setTimeout(function() {
demo.resize();
});
scope.$watch('fullscreen', function (toFullscreen){
if (toFullscreen) {
// go to fullscreen
element[0].children[0].classList.add('fullscreen');
} else {
// exit fullscreen
element[0].children[0].classList.remove('fullscreen');
}
demo.resize();
});
scope.$watch('mute', function (toMute) {
if (toMute) {
demo.music.setVolume(0);
} else {
demo.music.setVolume(scope.volume);
}
});
scope.$watch('volume', function(volume) {
if (scope.mute) return;
demo.music.setVolume(volume);
});
$interval(function() {
scope.$parent.$parent.currentFrame = demo.getCurrentFrame();
scope.$parent.$parent.duration = demo.music.getDuration() * 60;
}, 1000 / 60);
setTimeout(function(){
demo.start();
demo.music.pause();
demo.jumpToFrame(0);
}, 0);
}
};
});
})();
| (function() {
'use strict';
angular.module('nin').directive('demo', function($interval, demo) {
return {
restrict: 'E',
template: '<div class=demo-container></div>',
link: function(scope, element) {
demo.setContainer(element[0].children[0]);
setTimeout(function() {
demo.resize();
});
scope.$watch('fullscreen', function (toFullscreen){
if (toFullscreen) {
// go to fullscreen
element[0].children[0].classList.add('fullscreen');
} else {
// exit fullscreen
element[0].children[0].classList.remove('fullscreen');
}
demo.resize();
});
scope.$watch('mute', function (toMute) {
if (toMute) {
demo.music.setVolume(0);
} else {
demo.music.setVolume(scope.volume);
}
});
scope.$watch('volume', function(volume) {
if (scope.mute) return;
demo.music.setVolume(volume);
});
$interval(function() {
scope.$parent.$parent.currentFrame = demo.getCurrentFrame();
scope.$parent.$parent.duration = demo.music.getDuration() * 60;
}, 1000 / 60);
setTimeout(function(){
demo.start();
demo.music.pause();
}, 0);
}
};
});
})();
|
Remove false comment about ajax_start and ajax_stop | import {Locale} from 'Framework/Locale'
import {Flash} from 'Framework/Flash'
const locale = new Locale()
export class Ajax {
initAjax () {
/* set some defaults for AJAX-request */
$.ajaxSetup(
{
cache: false,
type: 'POST',
dataType: 'json',
timeout: 5000
}
)
/* 403 means we aren't authenticated anymore, so reload the page */
$(document).ajaxError((event, XMLHttpRequest, ajaxOptions) => {
if (XMLHttpRequest.status === 403) {
window.location.reload()
}
if (ajaxOptions !== null) {
let textStatus = locale.err('GeneralError')
if (XMLHttpRequest.responseText !== null) {
let json = $.parseJSON(XMLHttpRequest.responseText)
if (json.message !== null) {
textStatus = json.message
} else {
textStatus = XMLHttpRequest.responseText
}
}
new Flash().add(textStatus, 'danger')
}
return false
})
$(document).ajaxStart(() => {
$.event.trigger('ajax_start')
})
$(document).ajaxStop(() => {
$.event.trigger('ajax_stop')
})
}
}
| import {Locale} from 'Framework/Locale'
import {Flash} from 'Framework/Flash'
const locale = new Locale()
export class Ajax {
initAjax () {
/* set some defaults for AJAX-request */
$.ajaxSetup(
{
cache: false,
type: 'POST',
dataType: 'json',
timeout: 5000
}
)
/* 403 means we aren't authenticated anymore, so reload the page */
$(document).ajaxError((event, XMLHttpRequest, ajaxOptions) => {
if (XMLHttpRequest.status === 403) {
window.location.reload()
}
if (ajaxOptions !== null) {
let textStatus = locale.err('GeneralError')
if (XMLHttpRequest.responseText !== null) {
let json = $.parseJSON(XMLHttpRequest.responseText)
if (json.message !== null) {
textStatus = json.message
} else {
textStatus = XMLHttpRequest.responseText
}
}
new Flash().add(textStatus, 'danger')
}
return false
})
/* show spinners */
$(document).ajaxStart(() => {
$.event.trigger('ajax_start')
})
$(document).ajaxStop(() => {
$.event.trigger('ajax_stop')
})
}
}
|
Add method for getting random neighbor | package maze;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* @author Nick Hirakawa
*/
public class Cell {
private int x;
private int y;
private boolean visited;
private List<Cell> neighbors;
private Random random;
public Cell(int x, int y){
this.x = x;
this.y = y;
this.setVisited(false);
this.neighbors = new LinkedList<Cell>();
random = new Random();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void addNeighbor(Cell cell){
if(!this.neighbors.contains(cell)){
this.neighbors.add(cell);
}
}
public List<Cell> getNeighbors(){
return this.neighbors;
}
public Cell getRandomNeighbor(){
return this.neighbors.get(random.nextInt(neighbors.size()));
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
@Override
public int hashCode(){
int result = 17;
result = 37 * result + this.x;
result = 37 * result + this.y;
return result;
}
@Override
public boolean equals(Object other){
Cell cell = (Cell)other;
return cell.x == this.x && cell.y == this.y;
}
@Override
public String toString(){
return "(" + x + "," + y + ")";
}
} | package maze;
import java.util.LinkedList;
import java.util.List;
/**
* @author Nick Hirakawa
*/
public class Cell {
private int x;
private int y;
private boolean visited;
private List<Cell> neighbors;
public Cell(int x, int y){
this.x = x;
this.y = y;
this.setVisited(false);
this.neighbors = new LinkedList<Cell>();
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void addNeighbor(Cell cell){
if(!this.neighbors.contains(cell)){
this.neighbors.add(cell);
}
}
public List<Cell> getNeighbors(){
return this.neighbors;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
@Override
public int hashCode(){
int result = 17;
result = 37 * result + this.x;
result = 37 * result + this.y;
return result;
}
@Override
public boolean equals(Object other){
Cell cell = (Cell)other;
return cell.x == this.x && cell.y == this.y;
}
@Override
public String toString(){
return "(" + x + "," + y + ")";
}
} |
Print statement was breaking python 3 builds | import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
| import nose
from nose.tools import raises
import dpath.path
import dpath.exceptions
import dpath.options
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_invalid_keyname():
tdict = {
"I/contain/the/separator": 0
}
for x in dpath.path.paths(tdict):
pass
@raises(dpath.exceptions.InvalidKeyName)
def test_path_paths_empty_key_disallowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
for x in dpath.path.paths(tdict):
pass
def test_path_paths_empty_key_allowed():
tdict = {
"Empty": {
"": {
"Key": ""
}
}
}
parts=[]
dpath.options.ALLOW_EMPTY_STRING_KEYS=True
for x in dpath.path.paths(tdict, dirs=False, leaves=True):
path = x
for x in path[:-1]:
parts.append(x[0])
dpath.options.ALLOW_EMPTY_STRING_KEYS=False
print "/".join(parts)
assert("/".join(parts) == "Empty//Key")
def test_path_paths_int_keys():
dpath.path.validate([
['I', dict],
['am', dict],
['path', dict],
[0, dict],
['of', dict],
[2, int]
])
|
Fix unit tests failing if sqlite is not present | <?php
namespace Exporter\Test\Source;
use Exporter\Source\PDOStatementSourceIterator;
class PDOStatementSourceIteratorTest extends \PHPUnit_Framework_TestCase
{
protected $dbh;
public function setUp()
{
if (!in_array('sqlite', \PDO::getAvailableDrivers())) {
$this->markTestSkipped('the sqlite extension is not available');
}
if (is_file('foo.db')) {
unlink('foo.db');
}
$this->dbh = new \PDO('sqlite:foo.db');
$this->dbh->exec('CREATE TABLE `user` (`id` int(11), `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL )');
$data = array(
array(1, 'john', '[email protected]'),
array(2, 'john 2', '[email protected]'),
array(3, 'john 3', '[email protected]'),
);
foreach ($data as $user) {
$query = $this->dbh->prepare('INSERT INTO user (id, username, email) VALUES(?, ?, ?)');
$query->execute($user);
}
}
public function tearDown()
{
unlink('foo.db');
}
public function testHandler()
{
$stm = $this->dbh->prepare('SELECT id, username, email FROM user');
$stm->execute();
$iterator = new PDOStatementSourceIterator($stm);
$data = array();
foreach ($iterator as $user) {
$data[] = $user;
}
$this->assertEquals(3, count($data));
}
}
| <?php
namespace Exporter\Test\Source;
use Exporter\Source\PDOStatementSourceIterator;
class PDOStatementSourceIteratorTest extends \PHPUnit_Framework_TestCase
{
protected $dbh;
public function setUp()
{
if (is_file('foo.db')) {
unlink('foo.db');
}
$this->dbh = new \PDO('sqlite:foo.db');
$this->dbh->exec('CREATE TABLE `user` (`id` int(11), `username` varchar(255) NOT NULL, `email` varchar(255) NOT NULL )');
$data = array(
array(1, 'john', '[email protected]'),
array(2, 'john 2', '[email protected]'),
array(3, 'john 3', '[email protected]'),
);
foreach ($data as $user) {
$query = $this->dbh->prepare('INSERT INTO user (id, username, email) VALUES(?, ?, ?)');
$query->execute($user);
}
}
public function tearDown()
{
unlink('foo.db');
}
public function testHandler()
{
$stm = $this->dbh->prepare('SELECT id, username, email FROM user');
$stm->execute();
$iterator = new PDOStatementSourceIterator($stm);
$data = array();
foreach ($iterator as $user) {
$data[] = $user;
}
$this->assertEquals(3, count($data));
}
}
|
Increase tool priority, to keep space between cherrypy builtin tools like `json_out`. | import cherrypy
from mako.lookup import TemplateLookup
class Tool(cherrypy.Tool):
_lookups = {}
def __init__(self):
cherrypy.Tool.__init__(self, 'before_handler',
self.callable,
priority=40)
def callable(self,
filename=None,
directories=None,
module_directory=None,
collection_size=-1):
if filename is None or directories is None:
return
# Find the appropriate template lookup.
key = (tuple(directories), module_directory)
try:
lookup = self._lookups[key]
except KeyError:
lookup = TemplateLookup(directories=directories,
module_directory=module_directory,
collection_size=collection_size,
input_encoding='utf8')
self._lookups[key] = lookup
cherrypy.request.lookup = lookup
# Replace the current handler.
cherrypy.request.template = template = lookup.get_template(filename)
inner_handler = cherrypy.serving.request.handler
def wrapper(*args, **kwargs):
context = inner_handler(*args, **kwargs)
response = template.render(**context)
return response
cherrypy.serving.request.handler = wrapper
| import cherrypy
from mako.lookup import TemplateLookup
class Tool(cherrypy.Tool):
_lookups = {}
def __init__(self):
cherrypy.Tool.__init__(self, 'before_handler',
self.callable,
priority=20)
def callable(self,
filename=None,
directories=None,
module_directory=None,
collection_size=-1):
if filename is None or directories is None:
return
# Find the appropriate template lookup.
key = (tuple(directories), module_directory)
try:
lookup = self._lookups[key]
except KeyError:
lookup = TemplateLookup(directories=directories,
module_directory=module_directory,
collection_size=collection_size,
input_encoding='utf8')
self._lookups[key] = lookup
cherrypy.request.lookup = lookup
# Replace the current handler.
cherrypy.request.template = template = lookup.get_template(filename)
inner_handler = cherrypy.serving.request.handler
def wrapper(*args, **kwargs):
context = inner_handler(*args, **kwargs)
response = template.render(**context)
return response
cherrypy.serving.request.handler = wrapper
|
Make fetch URL less specific | /* global fetch document */
import React from 'react';
import TotalWidget from './TotalWidget';
import NextTripWidget from './NextTripWidget';
import TripTable from './TripTable';
import Map from './Map';
import './scss/overview.scss';
class Overview extends React.Component {
constructor() {
super();
this.loading = true;
this.state = {
trips: []
};
}
componentDidMount() {
this.getData();
}
getData() {
fetch(`${document.location.protocol}//${document.location.hostname}:4444/trips`)
.then((response) => {
return response.json();
})
.then((trips) => {
this.loading = false;
this.setState({ trips });
});
}
render() {
return (
<div className="container">
{ this.loading ? <span>Loading..</span> :
<section>
<div className="row">
<NextTripWidget
color="light"
nextTrip={this.state.trips.next}
/>
<TotalWidget
color="medium"
totals={this.state.trips.total}
/>
</div>
<Map
countries={this.state.trips.allCountries}
selector="visitedMap"
/>
<TripTable
trips={this.state.trips.visited}
/>
<h1>Wishlist</h1>
<Map
countries={this.state.trips.wishlist}
selector="wishlistMap"
/>
</section>
}
</div>
);
}
}
export default Overview;
| /* global fetch */
import React from 'react';
import TotalWidget from './TotalWidget';
import NextTripWidget from './NextTripWidget';
import TripTable from './TripTable';
import Map from './Map';
import './scss/overview.scss';
class Overview extends React.Component {
constructor() {
super();
this.loading = true;
this.state = {
trips: []
};
}
componentDidMount() {
this.getData();
}
getData() {
fetch('http://localhost:4444/trips')
.then((response) => {
return response.json();
})
.then((trips) => {
this.loading = false;
this.setState({ trips });
});
}
render() {
return (
<div className="container">
{ this.loading ? <span>Loading..</span> :
<section>
<div className="row">
<NextTripWidget
color="light"
nextTrip={this.state.trips.next}
/>
<TotalWidget
color="medium"
totals={this.state.trips.total}
/>
</div>
<Map
countries={this.state.trips.allCountries}
selector="visitedMap"
/>
<TripTable
trips={this.state.trips.visited}
/>
<h1>Wishlist</h1>
<Map
countries={this.state.trips.wishlist}
selector="wishlistMap"
/>
</section>
}
</div>
);
}
}
export default Overview;
|
Set curl ssl verify to false. | <?php
namespace Yusef\Channels;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;
/**
* Class FirebaseChannel
* @package Yusef\Channels
*/
class FirebaseChannel
{
/**
* @const The API URL for Firebase
*/
const API_URI = 'https://fcm.googleapis.com/fcm/send';
/**
* @var Client
*/
private $client;
/**
* @param Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* @param mixed $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
/** @var FcmMessage $message */
$message = $notification->toFcm($notifiable);
if (is_null($message->getTo())) {
if (!$to = $notifiable->routeNotificationFor('fcm')) {
return;
}
$message->to($to);
}
$this->client->request('post', self::API_URI, [
'verify' => false,
'headers' => [
'Authorization' => 'key=' . $this->getApiKey(),
'Content-Type' => 'application/json',
],
'body' => $message->formatData(),
]);
}
/**
* @return string
*/
private function getApiKey()
{
return config('services.fcm.key');
}
}
| <?php
namespace Yusef\Channels;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;
/**
* Class FirebaseChannel
* @package Yusef\Channels
*/
class FirebaseChannel
{
/**
* @const The API URL for Firebase
*/
const API_URI = 'https://fcm.googleapis.com/fcm/send';
/**
* @var Client
*/
private $client;
/**
* @param Client $client
*/
public function __construct(Client $client)
{
$this->client = $client;
}
/**
* @param mixed $notifiable
* @param Notification $notification
*/
public function send($notifiable, Notification $notification)
{
/** @var FcmMessage $message */
$message = $notification->toFcm($notifiable);
if (is_null($message->getTo())) {
if (!$to = $notifiable->routeNotificationFor('fcm')) {
return;
}
$message->to($to);
}
$response = $this->client->post(self::API_URI, [
'headers' => [
'Authorization' => 'key=' . $this->getApiKey(),
'Content-Type' => 'application/json',
],
'body' => $message->formatData(),
]);
// dd(json_decode($data)->data, $response->getBody()->getContents());
}
/**
* @return string
*/
private function getApiKey()
{
return config('services.fcm.key');
}
}
|
Include the version number in the plugin spec. | /*global Uint8Array*/
var exifParser = require('exif-parser'),
fs = require('fs');
module.exports = {
name: 'unexpected-exif',
version: require('../package.json').version,
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
expect.addAssertion(['string', 'Buffer'], 'to have (exif|EXIF) data satisfying', function (expect, subject, value) {
var title,
subjectUrl;
if (typeof subject === 'string') {
var matchDataUrl = subject.match(/^data:[^;]*;base64,(.*)$/);
if (matchDataUrl) {
subject = new Buffer(matchDataUrl[1], 'base64');
} else {
title = subject;
subjectUrl = subject;
subject = fs.readFileSync(subject);
}
} else if (subject instanceof Uint8Array) {
subject = new Buffer(subject);
}
this.subjectOutput = function () {
this.image(subjectUrl || subject, { width: 10, height: 5, link: true, title: title });
};
return expect(exifParser.create(subject).parse(), 'to satisfy', value);
});
}
};
| /*global Uint8Array*/
var exifParser = require('exif-parser'),
fs = require('fs');
module.exports = {
name: 'unexpected-exif',
installInto: function (expect) {
expect.installPlugin(require('magicpen-media'));
expect.addAssertion(['string', 'Buffer'], 'to have (exif|EXIF) data satisfying', function (expect, subject, value) {
var title,
subjectUrl;
if (typeof subject === 'string') {
var matchDataUrl = subject.match(/^data:[^;]*;base64,(.*)$/);
if (matchDataUrl) {
subject = new Buffer(matchDataUrl[1], 'base64');
} else {
title = subject;
subjectUrl = subject;
subject = fs.readFileSync(subject);
}
} else if (subject instanceof Uint8Array) {
subject = new Buffer(subject);
}
this.subjectOutput = function () {
this.image(subjectUrl || subject, { width: 10, height: 5, link: true, title: title });
};
return expect(exifParser.create(subject).parse(), 'to satisfy', value);
});
}
};
|
Allow ls to pass arguments | from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
if len(args.strip()) > 0:
for g in self.explorer.list_groups(args):
print(g+"/")
for ds in self.explorer.list_datasets(args):
print(ds)
else:
for g in self.explorer.list_groups():
print(g+"/")
for ds in self.explorer.list_datasets():
print(ds)
def do_cd(self, args, opts=None):
if len(args) == 0:
args = '/'
self.explorer.change_dir(args)
def do_load(self, args, opts=None):
print("Loading "+ args)
self.explorer = h5_wrapper.H5Explorer(args)
def do_pwd(self, args, opts=None):
print(self.explorer.working_dir)
def do_pushd(self, args, opts=None):
self.explorer.push_dir(args)
def do_popd(self, args, opts=None):
self.explorer.pop_dir()
self.do_pwd(None)
def precmd(self, line):
if not line.startswith('load') and (line.endswith('.h5') or line.endswith('.hdf5')):
line = 'load ' + line
return line
def do_exit(self, args):
return True
def do_clear(self, args):
os.system('clear')
if __name__ == '__main__':
c = CmdApp()
c.cmdloop()
| from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
for g in self.explorer.list_groups():
print(g+"/")
for ds in self.explorer.list_datasets():
print(ds)
def do_cd(self, args, opts=None):
if len(args) == 0:
args = '/'
self.explorer.change_dir(args)
def do_load(self, args, opts=None):
print("Loading "+ args)
self.explorer = h5_wrapper.H5Explorer(args)
def do_pwd(self, args, opts=None):
print(self.explorer.working_dir)
def do_pushd(self, args, opts=None):
self.explorer.push_dir(args)
def do_popd(self, args, opts=None):
self.explorer.pop_dir()
self.do_pwd(None)
def precmd(self, line):
if not line.startswith('load') and (line.endswith('.h5') or line.endswith('.hdf5')):
line = 'load ' + line
return line
def do_exit(self, args):
return True
def do_clear(self, args):
os.system('clear')
if __name__ == '__main__':
c = CmdApp()
c.cmdloop()
|
Put that editor in a div, editors love divs.
2011-12 Called, they want their meme back. | @section('content')
<div class="container">
<div class="row">
<!-- Dummy Add post box -->
<div class="box">
<div class="col-lg-12 text-center">
<form>
<h2><span id="post-title" contenteditable="true">Test</span><br><small id="post-date">{{ \Carbon\Carbon::now() }}</small></h2>
<div class="editor">
<textarea name="post-content" class="js-st-instance"></textarea>
</div>
<button type="submit" class="btn btn-default btn-lg">Add Post</button>
<hr>
</form>
</div>
</div>
@foreach($posts as $post)
<div class="box">
<div class="col-lg-12 text-center">
<img class="img-responsive img-border img-full" src="img/slide-3.jpg">
<h2>{{ $post->getTitle() }}<br><small>{{ $post->getPublishDate() }}</small></h2>
<p>{{ Str::words($post->getContent(), 100) }}</p>
<a href="#" class="btn btn-default btn-lg">Read More</a>
<hr>
</div>
</div>
@endforeach
</div>
</div>
@endsection | @section('content')
<div class="container">
<div class="row">
<!-- Dummy Add post box -->
<div class="box">
<div class="col-lg-12 text-center">
<form>
<h2><span id="post-title" contenteditable="true">Test</span><br><small id="post-date">{{ \Carbon\Carbon::now() }}</small></h2>
<textarea name="post-content" class="js-st-instance"></textarea>
<button type="submit" class="btn btn-default btn-lg">Add Post</button>
<hr>
</form>
</div>
</div>
@foreach($posts as $post)
<div class="box">
<div class="col-lg-12 text-center">
<img class="img-responsive img-border img-full" src="img/slide-3.jpg">
<h2>{{ $post->getTitle() }}<br><small>{{ $post->getPublishDate() }}</small></h2>
<p>{{ Str::words($post->getContent(), 100) }}</p>
<a href="#" class="btn btn-default btn-lg">Read More</a>
<hr>
</div>
</div>
@endforeach
</div>
</div>
@endsection |
Fix a test that should've been fixed long ago with the others | package forklift.integration;
import forklift.Forklift;
import forklift.connectors.ConnectorException;
import forklift.consumer.Consumer;
import forklift.exception.StartupException;
import forklift.producers.ForkliftProducerI;
import forklift.producers.ProducerException;
import org.junit.Test;
public class ConsumerActionTests extends BaseIntegrationTest {
/**
* Test subscribing to a topic, unsubscribing, then resubscribing to the topic.
*/
@Test
public void topicTurnoverTest() throws StartupException, ConnectorException, InterruptedException, ProducerException {
Forklift forklift = serviceManager.newManagedForkliftInstance();
ForkliftProducerI producer = forklift.getConnector().getQueueProducer("forklift-string-topic");
sentMessageIds.add(producer.send("message1"));
final Consumer c1 = new Consumer(StringConsumer.class, forklift);
// Shutdown the consumer after all the messages have been processed.
c1.setOutOfMessages((listener) -> {
timeouts++;
if (sentMessageIds.equals(consumedMessageIds) || timeouts > maxTimeouts) {
listener.shutdown();
}
});
// Start the consumer.
c1.listen();
sentMessageIds.add(producer.send("message2"));
final Consumer c2 = new Consumer(StringConsumer.class, forklift);
// Shutdown the consumer after all the messages have been processed.
timeouts = 0;
c2.setOutOfMessages((listener) -> {
timeouts++;
if (sentMessageIds.equals(consumedMessageIds) || timeouts > maxTimeouts) {
listener.shutdown();
}
});
// Start the consumer.
c2.listen();
messageAsserts();
}
}
| package forklift.integration;
import forklift.Forklift;
import forklift.connectors.ConnectorException;
import forklift.consumer.Consumer;
import forklift.exception.StartupException;
import forklift.producers.ForkliftProducerI;
import forklift.producers.ProducerException;
import org.junit.Test;
public class ConsumerActionTests extends BaseIntegrationTest {
/**
* Test subscribing to a topic, unsubscribing, then resubscribing to the topic.
*/
@Test
public void topicTurnoverTest() throws StartupException, ConnectorException, InterruptedException, ProducerException {
Forklift forklift = serviceManager.newManagedForkliftInstance();
ForkliftProducerI producer = forklift.getConnector().getQueueProducer("forklift-string-topic");
sentMessageIds.add(producer.send("message1"));
final Consumer c1 = new Consumer(StringConsumer.class, forklift);
// Shutdown the consumer after all the messages have been processed.
c1.setOutOfMessages((listener) -> {
listener.shutdown();
});
// Start the consumer.
c1.listen();
Thread.sleep(3000);
sentMessageIds.add(producer.send("message2"));
final Consumer c2 = new Consumer(StringConsumer.class, forklift);
// Shutdown the consumer after all the messages have been processed.
c2.setOutOfMessages((listener) -> {
listener.shutdown();
});
// Start the consumer.
c2.listen();
messageAsserts();
}
}
|
Replace tabs with spaces to match style | function scrobble (artist, title, duration) {
chrome.runtime.sendMessage({type: 'validate', artist: artist, track: title}, function (response) {
if (response !== false) {
chrome.runtime.sendMessage({
type: 'nowPlaying',
artist: response.artist,
track: response.track,
duration: duration
});
} else
chrome.runtime.sendMessage({type: 'nowPlaying'}); // unidentified music
});
}
$(function () {
$(window).unload(function () {
// reset the background scrobbler song data
chrome.runtime.sendMessage({type: 'reset'});
return true;
});
window.addEventListener('message', function(event) {
if (event.source != window)
return;
if (event.data && event.data.artist && event.data.title && event.data.duration)
scrobble(event.data.artist, event.data.title, event.data.duration);
}, false);
var injectScript = document.createElement('script');
injectScript.type = 'text/javascript';
injectScript.src = chrome.extension.getURL('connectors/vk-dom-inject.js');
(document.head || document.documentElement).appendChild(injectScript);
});
/**
* Listen for requests from scrobbler.js
*/
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
switch(request.type) {
// background calls this to see if the script is already injected
case 'ping':
sendResponse(true);
break;
}
}
);
| function scrobble (artist, title, duration) {
chrome.runtime.sendMessage({type: 'validate', artist: artist, track: title}, function (response) {
if (response !== false) {
chrome.runtime.sendMessage({
type: 'nowPlaying',
artist: response.artist,
track: response.track,
duration: duration
});
} else
chrome.runtime.sendMessage({type: 'nowPlaying'}); // unidentified music
});
}
$(function () {
$(window).unload(function () {
// reset the background scrobbler song data
chrome.runtime.sendMessage({type: 'reset'});
return true;
});
window.addEventListener('message', function(event) {
if (event.source != window)
return;
if (event.data && event.data.artist && event.data.title && event.data.duration)
scrobble(event.data.artist, event.data.title, event.data.duration);
}, false);
var injectScript = document.createElement('script');
injectScript.type = 'text/javascript';
injectScript.src = chrome.extension.getURL('connectors/vk-dom-inject.js');
(document.head || document.documentElement).appendChild(injectScript);
});
/**
* Listen for requests from scrobbler.js
*/
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
switch(request.type) {
// background calls this to see if the script is already injected
case 'ping':
sendResponse(true);
break;
}
}
);
|
BUGFIX: Remove pre-PHP7 code and avoid __toString deprecation warning | <?php
namespace Neos\Flow\Reflection;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
/**
* Extended version of the ReflectionParameter
*
* @Flow\Proxy(false)
*/
class ParameterReflection extends \ReflectionParameter
{
/**
* @var string
*/
protected $parameterClassName;
/**
* Returns the declaring class
*
* @return ClassReflection The declaring class
*/
public function getDeclaringClass()
{
return new ClassReflection(parent::getDeclaringClass()->getName());
}
/**
* Returns the parameter class
*
* @return ClassReflection The parameter class
*/
public function getClass()
{
try {
$class = parent::getClass();
} catch (\Exception $exception) {
return null;
}
return is_object($class) ? new ClassReflection($class->getName()) : null;
}
/**
* @return string The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise
*/
public function getBuiltinType()
{
$type = $this->getType();
if ($type === null || !$type->isBuiltin()) {
return null;
}
return $type instanceof \ReflectionNamedType ? $type->getName() : (string)$type;
}
}
| <?php
namespace Neos\Flow\Reflection;
/*
* This file is part of the Neos.Flow package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
/**
* Extended version of the ReflectionParameter
*
* @Flow\Proxy(false)
*/
class ParameterReflection extends \ReflectionParameter
{
/**
* @var string
*/
protected $parameterClassName;
/**
* Returns the declaring class
*
* @return ClassReflection The declaring class
*/
public function getDeclaringClass()
{
return new ClassReflection(parent::getDeclaringClass()->getName());
}
/**
* Returns the parameter class
*
* @return ClassReflection The parameter class
*/
public function getClass()
{
try {
$class = parent::getClass();
} catch (\Exception $exception) {
return null;
}
return is_object($class) ? new ClassReflection($class->getName()) : null;
}
/**
* @return string The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise
*/
public function getBuiltinType()
{
if (!is_callable([$this, 'getType'])) {
return null;
}
$type = $this->getType();
if ($type === null || !$type->isBuiltin()) {
return null;
}
return (string)$type;
}
}
|
Fix path to .sql files | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom managers for working with CAL-ACCESS processed data models.
"""
from __future__ import unicode_literals
import os
from django.db import models, connection
class ProcessedDataManager(models.Manager):
"""
Utilities for loading raw CAL-ACCESS data into processed data models.
"""
def load_raw_data(self):
with connection.cursor() as c:
c.execute(self.raw_data_load_query)
@property
def raw_data_load_query_path(self):
return os.path.join(
os.path.dirname(__file__),
'sql',
'load_%s_model.sql' % self.model._meta.model_name,
)
@property
def has_raw_data_load_query(self):
if os.path.exists(self.raw_data_load_query_path):
return True
else:
return False
@property
def raw_data_load_query(self):
sql = ''
if self.has_raw_data_load_query:
with open(self.raw_data_load_query_path) as f:
sql = f.read()
return sql
@property
def db_table(self):
"""
Return the model's database table name as a string.
"""
return self._meta.db_table
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Custom managers for working with CAL-ACCESS processed data models.
"""
from __future__ import unicode_literals
import os
from django.db import models, connection
class ProcessedDataManager(models.Manager):
"""
Utilities for loading raw CAL-ACCESS data into processed data models.
"""
def load_raw_data(self):
with connection.cursor() as c:
c.execute(self.raw_data_load_query)
@property
def raw_data_load_query_path(self):
return os.path.join(
'calaccess_processed',
'sql',
'load_%s_model.sql' % self.model._meta.model_name,
)
@property
def has_raw_data_load_query(self):
if os.path.exists(self.raw_data_load_query_path):
return True
else:
return False
@property
def raw_data_load_query(self):
sql = ''
if self.has_raw_data_load_query:
with open(self.raw_data_load_query_path) as f:
sql = f.read()
return sql
@property
def db_table(self):
"""
Return the model's database table name as a string.
"""
return self._meta.db_table
|
Fix bug: trying to call .replace on NoneType | import re
import xml.etree.ElementTree as ET
from os import path
from tmc.exercise_tests.basetest import BaseTest, TestResult
class CheckTest(BaseTest):
def __init__(self):
super().__init__("Check")
def applies_to(self, exercise):
return path.isfile(path.join(exercise.path(), "Makefile"))
def test(self, exercise):
_, _, err = self.run(["make", "clean", "all", "run-test"], exercise)
ret = []
testpath = path.join(exercise.path(), "test", "tmc_test_results.xml")
if not path.isfile(testpath):
return [TestResult(success=False, message=err)]
xmlsrc = ""
with open(testpath) as fp:
xmlsrc = fp.read()
xmlsrc = re.sub(r"&(\s)", r"&\1", xmlsrc)
ns = "{http://check.sourceforge.net/ns}"
root = ET.fromstring(xmlsrc)
for test in root.iter(ns + "test"):
success = True
name = test.find(ns + "description").text
message = None
if test.get("result") == "failure":
success = False
message = test.find(ns + "message").text
message = message.replace(r"&", "&")))
ret.append(TestResult(success=success, name=name, message=message))
return ret
| import re
import xml.etree.ElementTree as ET
from os import path
from tmc.exercise_tests.basetest import BaseTest, TestResult
class CheckTest(BaseTest):
def __init__(self):
super().__init__("Check")
def applies_to(self, exercise):
return path.isfile(path.join(exercise.path(), "Makefile"))
def test(self, exercise):
_, _, err = self.run(["make", "clean", "all", "run-test"], exercise)
ret = []
testpath = path.join(exercise.path(), "test", "tmc_test_results.xml")
if not path.isfile(testpath):
return [TestResult(success=False, message=err)]
xmlsrc = ""
with open(testpath) as fp:
xmlsrc = fp.read()
xmlsrc = re.sub(r"&(\s)", r"&\1", xmlsrc)
ns = "{http://check.sourceforge.net/ns}"
root = ET.fromstring(xmlsrc)
for test in root.iter(ns + "test"):
success = True
name = test.find(ns + "description").text
message = None
if test.get("result") == "failure":
success = False
message = test.find(ns + "message").text
ret.append(TestResult(success=success,
name=name,
message=message.replace(r"&", "&")))
return ret
|
Replace route template with XML style closing tags | // @ngInject
module.exports = function($stateProvider, $urlRouterProvider, $provide) {
$stateProvider
.state('root', {
abstract: true,
url: '',
template: '<dm-layout />',
})
.state('root.mail', {
abstract: true,
url: '',
views: {
header: {template: '<dm-header />'},
'': {template: '<dm-mailbox-layout />'},
},
resolve: {
'User': resolveUser,
},
})
.state('root.mail.inbox', {
url: '/inbox/:label?',
views: {
pageHeader: {template: '<dm-mailbox-header />'},
'': {template: '<dm-mailbox />'},
},
params: {
label: { value: 'inbox', squash: '' },
},
})
.state('root.mail.compose', {
url: '/compose',
views: {
pageHeader: {template: 'Compose Header'},
'': {template: '<dm-compose />'},
},
});
$urlRouterProvider
.otherwise('/inbox/');
// @ngInject
function resolveUser(API) {
return API.getUser().then(function(user) {
$provide.value('User', user.data);
return user.data;
});
}
}
| // @ngInject
module.exports = function($stateProvider, $urlRouterProvider, $provide) {
$stateProvider
.state('root', {
abstract: true,
url: '',
template: '<dm-layout></dm-layout>',
})
.state('root.mail', {
abstract: true,
url: '',
views: {
header: {template: '<dm-header></dm-header>'},
'': {template: '<dm-mailbox-layout></dm-mailbox-layout>'},
},
resolve: {
'User': resolveUser,
},
})
.state('root.mail.inbox', {
url: '/inbox/:label?',
views: {
pageHeader: {template: '<dm-mailbox-header></dm-mailbox-heder>'},
'': {template: '<dm-mailbox></dm-mailbox>'},
},
params: {
label: { value: 'inbox', squash: '' },
},
})
.state('root.mail.compose', {
url: '/compose',
views: {
pageHeader: {template: 'Compose Header'},
'': {template: '<dm-compose />'},
},
});
$urlRouterProvider
.otherwise('/inbox/');
// @ngInject
function resolveUser(API) {
return API.getUser().then(function(user) {
$provide.value('User', user.data);
return user.data;
});
}
}
|
Fix bug in GoogleTokenVerifier causing it never to work.
Apparently, I was horribly misusing constants. Comprehensive tests would have uncovered this. I'm not convinced that I'm doing the right thing by injecting services inside the verification function, and this particular section (the verification function and how best to make that customizable) could really use a second pair of eyes.
It would help to know a pattern for configuring functions that use services inside providers. | 'use strict';
/**
* A module to include instead of `angularOauth` for a service preconfigured
* for Google OAuth authentication.
*
* Guide: https://developers.google.com/accounts/docs/OAuth2UserAgent
*/
angular.module('googleOauth', ['angularOauth']).
constant('GoogleTokenVerifier', function(config, accessToken, deferred) {
var $injector = angular.injector(['ng']);
return $injector.invoke(['$http', '$rootScope', function($http, $rootScope) {
var verificationEndpoint = 'https://www.googleapis.com/oauth2/v1/tokeninfo';
$rootScope.$apply(function() {
$http({method: 'GET', url: verificationEndpoint, params: {access_token: accessToken}}).
success(function(data) {
if (data.audience == config.clientId) {
deferred.resolve(data);
} else {
deferred.reject({name: 'invalid_audience'});
}
}).
error(function(data, status, headers, config) {
deferred.reject({
name: 'error_response',
data: data,
status: status,
headers: headers,
config: config
});
});
});
return deferred;
}]);
}).
config(function(TokenProvider, GoogleTokenVerifier) {
TokenProvider.extendConfig({
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
scopes: ["https://www.googleapis.com/auth/userinfo.email"],
verifyFunc: GoogleTokenVerifier
});
});
| 'use strict';
/**
* A module to include instead of `angularOauth` for a service preconfigured
* for Google OAuth authentication.
*
* Guide: https://developers.google.com/accounts/docs/OAuth2UserAgent
*/
angular.module('googleOauth', ['angularOauth']).
constant('GoogleTokenVerifier', function($http) {
return function(config, accessToken, deferred) {
var verificationEndpoint = 'https://www.googleapis.com/oauth2/v1/tokeninfo';
$http.get(verificationEndpoint, {params: {access_token: accessToken}}).
success(function(data) {
if (data.audience == config.clientId) {
deferred.resolve(data);
} else {
deferred.reject({name: 'invalid_audience'});
}
}).
error(function(data, status, headers, config) {
deferred.reject({
name: 'error_response',
data: data,
status: status,
headers: headers,
config: config
});
});
}
}).
config(function(TokenProvider, GoogleTokenVerifier) {
TokenProvider.extendConfig({
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
tokenVerifierEndpoint: 'https://www.googleapis.com/oauth2/v1/tokeninfo',
scopes: ["https://www.googleapis.com/auth/userinfo.email"],
verifyFunc: GoogleTokenVerifier
});
});
|
Clean up OK alarm links | /** @typedef {import('./index').EventBridgeCloudWatchAlarmsEvent} EventBridgeCloudWatchAlarmsEvent */
const urls = require('./urls');
module.exports = {
/**
* @param {EventBridgeCloudWatchAlarmsEvent} event
* @param {AWS.CloudWatch.DescribeAlarmsOutput} desc
* @param {AWS.CloudWatch.DescribeAlarmHistoryOutput} history
* @returns {String[]}
*/
detailLines(event, desc, history) {
if (
event.detail?.previousState?.reasonData &&
event.detail?.state?.reasonData
) {
const stateData = JSON.parse(event.detail.state.reasonData);
const previousData = JSON.parse(event.detail.previousState.reasonData);
if (stateData?.startDate && previousData?.startDate) {
const okTime = Date.parse(stateData.startDate);
const alarmTime = Date.parse(previousData.startDate);
const dif = okTime - alarmTime;
const difSec = dif / 1000;
let duration = difSec;
let durationUnit = 'seconds';
if (difSec >= 3600) {
duration = Math.round(difSec / 3600);
durationUnit = 'hours';
} else if (difSec >= 60) {
duration = Math.round(difSec / 60);
durationUnit = 'minutes';
}
const url = urls.metricsConsole(event, desc, history);
return [
`*Alarm duration:* ${duration} ${durationUnit} | View in: <${url}|CloudWatch Metrics>`,
];
}
}
return [];
},
};
| /** @typedef {import('./index').EventBridgeCloudWatchAlarmsEvent} EventBridgeCloudWatchAlarmsEvent */
const urls = require('./urls');
module.exports = {
/**
* @param {EventBridgeCloudWatchAlarmsEvent} event
* @param {AWS.CloudWatch.DescribeAlarmsOutput} desc
* @param {AWS.CloudWatch.DescribeAlarmHistoryOutput} history
* @returns {String[]}
*/
detailLines(event, desc, history) {
if (
event.detail?.previousState?.reasonData &&
event.detail?.state?.reasonData
) {
const stateData = JSON.parse(event.detail.state.reasonData);
const previousData = JSON.parse(event.detail.previousState.reasonData);
if (stateData?.startDate && previousData?.startDate) {
const okTime = Date.parse(stateData.startDate);
const alarmTime = Date.parse(previousData.startDate);
const dif = okTime - alarmTime;
const difSec = dif / 1000;
let duration = difSec;
let durationUnit = 'seconds';
if (difSec >= 3600) {
duration = Math.round(difSec / 3600);
durationUnit = 'hours';
} else if (difSec >= 60) {
duration = Math.round(difSec / 60);
durationUnit = 'minutes';
}
const url = urls.metricsConsole(event, desc, history);
return [`*Alarm duration:* <${url}|${duration} ${durationUnit}>`];
}
}
return [];
},
};
|
Fix create action for key value pair | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'reactor': "http://%s:9102" % st2host,
'datastore': "http://%s:9103" % st2host
}
try:
client = Client(st2_endpoints)
except Exception as e:
return e
if action == 'get':
kvp = client.keys.get_by_name(key)
if not kvp:
raise Exception('Key error with %s.' % key)
return kvp.value
else:
instance = client.keys.get_by_name(key) or KeyValuePair()
instance.id = key
instance.name = key
instance.value = value
kvp = client.keys.update(instance) if action in ['create', 'update'] else None
if action == 'delete':
return kvp
else:
return kvp.serialize()
| from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'reactor': "http://%s:9102" % st2host,
'datastore': "http://%s:9103" % st2host
}
try:
client = Client(st2_endpoints)
except Exception as e:
return e
if action == 'get':
kvp = client.keys.get_by_name(key)
if not kvp:
raise Exception('Key error with %s.' % key)
return kvp.value
else:
instance = KeyValuePair()
instance.id = client.keys.get_by_name(key).name
instance.name = key
instance.value = value
try:
kvstore = getattr(client.keys, action)
kvp = kvstore(instance)
except Exception as e:
raise
if action == 'delete':
return kvp
else:
return kvp.serialize()
|
Make sure we don't have a import namespace clash with DRF
For python 2.7 you need to add from __future__ import absolute_import | from __future__ import absolute_import
import logging
from django.contrib.auth import authenticate
from rest_framework import exceptions
from rest_framework.authentication import (
BaseAuthentication, get_authorization_header
)
logger = logging.getLogger(__name__)
class AdfsAccessTokenAuthentication(BaseAuthentication):
"""
ADFS access Token authentication
"""
www_authenticate_realm = 'api'
def authenticate(self, request):
"""
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return None
if len(auth) == 1:
msg = 'Invalid authorization header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid authorization header. Access token should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
# Authenticate the user
# The AdfsBackend authentication backend will notice the "access_token" parameter
# and skip the request for an access token using the authorization code
user = authenticate(access_token=auth[1])
if user is None:
raise exceptions.AuthenticationFailed('Invalid access token.')
if not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
return user, auth[1]
def authenticate_header(self, request):
return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
| import logging
from django.contrib.auth import authenticate
from rest_framework import exceptions
from rest_framework.authentication import (
BaseAuthentication, get_authorization_header
)
logger = logging.getLogger(__name__)
class AdfsAccessTokenAuthentication(BaseAuthentication):
"""
ADFS access Token authentication
"""
www_authenticate_realm = 'api'
def authenticate(self, request):
"""
Returns a `User` if a correct access token has been supplied
in the Authorization header. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return None
if len(auth) == 1:
msg = 'Invalid authorization header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid authorization header. Access token should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
# Authenticate the user
# The AdfsBackend authentication backend will notice the "access_token" parameter
# and skip the request for an access token using the authorization code
user = authenticate(access_token=auth[1])
if user is None:
raise exceptions.AuthenticationFailed('Invalid access token.')
if not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
return user, auth[1]
def authenticate_header(self, request):
return 'Bearer realm="%s" token_type="JWT"' % self.www_authenticate_realm
|
Write a correct postal address | const request = require('supertest');
const app = require('../app');
describe('name to point', function () {
it('should return JSON object with geolocation',
function (done) {
request(app)
.get('/point?name=OldCity&lat=53.66&lon=23.83')
.expect(200)
.expect({
lat: '53.70177645',
lon: '23.8347894179425',
display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район,' +
' Гродно, Гродненская область, 230005, Беларусь',
})
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
it('should respond with Not Found in case of failed name resolution',
function (done) {
request(app)
.get('/point?name=NONAME&lat=53.66&lon=23.83')
.expect(404)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
});
| const request = require('supertest');
const app = require('../app');
describe('name to point', function () {
it('should return JSON object with geolocation',
function (done) {
request(app)
.get('/point?name=OldCity&lat=53.66&lon=23.83')
.expect(200)
.expect({
lat: '53.70177645',
lon: '23.8347894179425',
display_name: 'OldCity, 17, улица Дубко, Девятовка, Ленинский район,' +
' Гродно, Гродненская область, 230012, Беларусь',
})
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
it('should respond with Not Found in case of failed name resolution',
function (done) {
request(app)
.get('/point?name=NONAME&lat=53.66&lon=23.83')
.expect(404)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
});
|
Fix social links at the bottom of posts | import React from 'react'
import Helmet from 'react-helmet'
import { graphql } from 'gatsby'
import Layout from '../components/Layout'
import PostTemplateDetails from '../components/PostTemplateDetails'
class PostTemplate extends React.Component {
render() {
const { title, subtitle } = this.props.data.site.siteMetadata
const post = this.props.data.markdownRemark
const { title: postTitle, description: postDescription } = post.frontmatter
const description = postDescription !== null ? postDescription : subtitle
return (
<Layout>
<div>
<Helmet>
<title>{`${postTitle} - ${title}`}</title>
<meta name="description" content={description} />
</Helmet>
<PostTemplateDetails {...this.props} />
</div>
</Layout>
)
}
}
export default PostTemplate
export const pageQuery = graphql`
query PostBySlug($slug: String!) {
site {
siteMetadata {
title
subtitle
copyright
author {
name
email
twitter
github
linkedin
}
url
}
}
markdownRemark(fields: { slug: { eq: $slug } }) {
id
html
excerpt
fields {
tagSlugs
}
frontmatter {
title
tags
date
}
}
}
`
| import React from 'react'
import Helmet from 'react-helmet'
import { graphql } from 'gatsby'
import Layout from '../components/Layout'
import PostTemplateDetails from '../components/PostTemplateDetails'
class PostTemplate extends React.Component {
render() {
const { title, subtitle } = this.props.data.site.siteMetadata
const post = this.props.data.markdownRemark
const { title: postTitle, description: postDescription } = post.frontmatter
const description = postDescription !== null ? postDescription : subtitle
return (
<Layout>
<div>
<Helmet>
<title>{`${postTitle} - ${title}`}</title>
<meta name="description" content={description} />
</Helmet>
<PostTemplateDetails {...this.props} />
</div>
</Layout>
)
}
}
export default PostTemplate
export const pageQuery = graphql`
query PostBySlug($slug: String!) {
site {
siteMetadata {
title
subtitle
copyright
author {
name
twitter
}
url
}
}
markdownRemark(fields: { slug: { eq: $slug } }) {
id
html
excerpt
fields {
tagSlugs
}
frontmatter {
title
tags
date
}
}
}
`
|
Print messages for prepare upload. | import sys
import olrcdb
import os
# Globals
COUNT = 0
class FileParser(object):
'''Object used to parse through a directory for all it's files. Collects
the paths of all the files and stores a record of these in a new table in
the database.
The Schema of the database is:
NewTable(path, uploaded=false)
'''
def __init__(self, directory, table_name):
self.directory = directory
self.table_name = table_name
def prepare_upload(connect, directory, table_name):
'''Given a database connection, directory and table_name,
-Create the table in the database
-populate the table with (path, uploaded=false)
where each path is a file in the given directory.'''
global COUNT
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# Add file name to the list.
if os.path.isfile(file_path):
connect.insert_path(file_path, table_name)
COUNT += 1
sys.stdout.flush()
sys.stdout.write("\r{0} parsed. \n".format(COUNT))
else:
prepare_upload(connect, file_path, table_name)
if __name__ == "__main__":
# Check for proper parameters
if len(sys.argv) != 3:
sys.stderr.write(
'Usage: python prepareupload.py path-to-drive table-name\n'
)
sys.exit(1)
connect = olrcdb.DatabaseConnection()
connect.create_table(sys.argv[2])
prepare_upload(connect, sys.argv[1], sys.argv[2])
| import sys
import olrcdb
import os
# Globals
COUNT = 0
class FileParser(object):
'''Object used to parse through a directory for all it's files. Collects
the paths of all the files and stores a record of these in a new table in
the database.
The Schema of the database is:
NewTable(path, uploaded=false)
'''
def __init__(self, directory, table_name):
self.directory = directory
self.table_name = table_name
def prepare_upload(connect, directory, table_name):
'''Given a database connection, directory and table_name,
-Create the table in the database
-populate the table with (path, uploaded=false)
where each path is a file in the given directory.'''
global COUNT
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
# Add file name to the list.
if os.path.isfile(file_path):
connect.insert_path(file_path, table_name)
COUNT += 1
else:
prepare_upload(connect, file_path, table_name)
if __name__ == "__main__":
# Check for proper parameters
if len(sys.argv) != 3:
sys.stderr.write(
'Usage: python prepareupload.py path-to-drive table-name\n'
)
sys.exit(1)
connect = olrcdb.DatabaseConnection()
connect.create_table(sys.argv[2])
prepare_upload(connect, sys.argv[1], sys.argv[2])
|
Fix to_bool to accept 0. |
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False' or val == '0':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
__all__ = ('to_bool', 'ConfigPropertyList')
from kivy.properties import ConfigParserProperty
from re import compile, split
to_list_pat = compile('(?:, *)?\\n?')
def to_bool(val):
'''
Takes anything and converts it to a bool type.
'''
if val == 'False':
return False
return not not val
def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
**kwargs):
''' Accepts either a list of a string. Nothing else.
'''
def to_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = split(to_list_pat, val.strip(' []()'))
for i, v in enumerate(vals):
vals[i] = val_type(v)
return vals
def to_2d_list(val):
if isinstance(val, list):
vals = list(val)
else:
vals = [split(to_list_pat, line.strip(' []()'))
for line in val.strip(' []()').splitlines()]
for i, line in enumerate(vals):
for j, v in enumerate(line):
vals[i][j] = val_type(v)
return vals
if not isinstance(val, list):
val = [[val]] if inner_list else [val]
v_type = to_2d_list if inner_list else to_list
return ConfigParserProperty(val, section, key, config, val_type=v_type,
**kwargs)
|
Delete Minutes: Popup dialog shows concerning minutes date. |
import { MeetingSeries } from '/imports/meetingseries'
Template.minutesList.helpers({
buttonBackground: function () {
return (this.isFinalized) ? "default" : "info";
},
addMinutesPath: function () {
let ms = new MeetingSeries(this.meetingSeriesId);
return (ms.addNewMinutesAllowed()) ? "/minutesadd/" + this.meetingSeriesId : "";
},
addMinutesNotAllowed: function () {
let ms = new MeetingSeries(this.meetingSeriesId);
return !ms.addNewMinutesAllowed();
},
isDeleteNotAllowed: function () {
return (this.isFinalized || this.isUnfinalized);
}
});
Template.minutesList.events({
"click #deleteMinutes": function (evt) {
let disabled = evt.currentTarget.getAttribute('disabled');
if (disabled) return;
console.log("Remove Meeting Minute " + this._id + " from Series: " + this.meetingSeries_id);
let dialogContent = "Do you really want to delete this meeting minute dated on <strong>" + this.date + "</strong>?";
confirmationDialog(
/* callback called if user wants to continue */
() => {
let ms = new MeetingSeries(this.meetingSeries_id);
ms.removeMinutesWithId(this._id);
},
/* Dialog content */
dialogContent
);
}
}); |
import { MeetingSeries } from '/imports/meetingseries'
Template.minutesList.helpers({
buttonBackground: function () {
return (this.isFinalized) ? "default" : "info";
},
addMinutesPath: function () {
let ms = new MeetingSeries(this.meetingSeriesId);
return (ms.addNewMinutesAllowed()) ? "/minutesadd/" + this.meetingSeriesId : "";
},
addMinutesNotAllowed: function () {
let ms = new MeetingSeries(this.meetingSeriesId);
return !ms.addNewMinutesAllowed();
},
isDeleteNotAllowed: function () {
return (this.isFinalized || this.isUnfinalized);
}
});
Template.minutesList.events({
"click #deleteMinutes": function (evt) {
let disabled = evt.currentTarget.getAttribute('disabled');
if (disabled) return;
console.log("Remove Meeting Minute " + this._id + " from Series: " + this.meetingSeries_id);
confirmationDialog(
/* callback called if user wants to continue */
() => {
let ms = new MeetingSeries(this.meetingSeries_id);
ms.removeMinutesWithId(this._id);
},
/* Dialog content */
"Do you really want to delete this meeting minute?"
);
}
}); |
Remove suppress() as it's no longer required | # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if handler is not None else lambda x: x
super().__init__(stdout=sys.stdout, stderr=sys.stderr)
def _handle_data(self, data, stream):
data = self._data_handler(self._decode(data))
if data and stream:
stream.write(data)
def _handle_stdout(self, data):
self._handle_data(data, self._stdout)
def _handle_stderr(self, data):
self._handle_data(data, self._stderr)
@contextlib.contextmanager
def forward(handler=None):
global _fwd
if _fwd is None and is_kernel() and fcntl:
with Forwarder(handler=handler):
yield
else:
yield
def start_forwarding(handler=None):
global _fwd
if fcntl:
if _fwd is None:
_fwd = Forwarder(handler=handler)
_fwd.__enter__()
def stop_forwarding(handler=None):
global _fwd
if fcntl:
if _fwd is not None:
_fwd.__exit__(None, None, None)
_fwd = None
| # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if handler is not None else lambda x: x
super().__init__(stdout=sys.stdout, stderr=sys.stderr)
def _handle_data(self, data, stream):
data = self._data_handler(self._decode(data))
if data and stream:
stream.write(data)
def _handle_stdout(self, data):
self._handle_data(data, self._stdout)
def _handle_stderr(self, data):
self._handle_data(data, self._stderr)
@contextlib.contextmanager
def suppress():
if fcntl:
with Forwarder(handler=lambda _: None):
yield
else:
yield
@contextlib.contextmanager
def forward(handler=None):
global _fwd
if _fwd is None and is_kernel() and fcntl:
with Forwarder(handler=handler):
yield
else:
yield
def start_forwarding(handler=None):
global _fwd
if fcntl:
if _fwd is None:
_fwd = Forwarder(handler=handler)
_fwd.__enter__()
def stop_forwarding(handler=None):
global _fwd
if fcntl:
if _fwd is not None:
_fwd.__exit__(None, None, None)
_fwd = None
|
Use charCode instead of keyCode | ;(function(){
var G = dijkstra.hexGrid(2);
var view = new dijkstra.GraphView(G, document.getElementById('graph'), {
placement: function(position){ return {
'x': 100 * position.x,
'y': 100 * position.y
}},
radius: 20,
between: 0.3,
vertex: {
events : {
mouseenter: function(event){
var id = this.getAttribute('data-vertex');
var v = G.findVertex(id);
algorithm.setPathFrom(v);
}
}
}
});
var algorithm = new dijkstra.ShortestPath(G);
algorithm.setSource(G.vertices[0]);
algorithm.setTarget(G.vertices[G.vertices.length - 1]);
algorithm.setPathFrom(G.vertices[G.vertices.length - 1]);
view.visualize(algorithm);
function loop(){
view.update();
requestAnimationFrame(loop);
};
loop();
document.body.addEventListener('keypress', function(event){
if (event.charCode == 32) {
algorithm.step();
}
});
window.G = G;
})();
| ;(function(){
var G = dijkstra.hexGrid(2);
var view = new dijkstra.GraphView(G, document.getElementById('graph'), {
placement: function(position){ return {
'x': 100 * position.x,
'y': 100 * position.y
}},
radius: 20,
between: 0.3,
vertex: {
events : {
mouseenter: function(event){
var id = this.getAttribute('data-vertex');
var v = G.findVertex(id);
algorithm.setPathFrom(v);
}
}
}
});
var algorithm = new dijkstra.ShortestPath(G);
algorithm.setSource(G.vertices[0]);
algorithm.setTarget(G.vertices[G.vertices.length - 1]);
algorithm.setPathFrom(G.vertices[G.vertices.length - 1]);
view.visualize(algorithm);
function loop(){
view.update();
requestAnimationFrame(loop);
};
loop();
document.body.addEventListener('keypress', function(event){
if (event.keyCode == 32) {
algorithm.step();
}
});
window.G = G;
})();
|
Convert Non-strict to strict equality checking
Convert non-strict equality checking, using `==`, to the strict version, using `===`. | var SolidityUtils = {
getCharacterOffsetToLineAndColumnMapping: function(source) {
var mapping = [];
source = source.split("");
var line = 0;
var column = 0;
source.forEach(function(character) {
if (character === "\n") {
line += 1;
column = -1;
mapping.push({
line: line,
column: 0
});
} else {
mapping.push({
line: line,
column: column
});
}
column += 1;
});
return mapping;
},
getHumanReadableSourceMap: function(sourceMap) {
var map = sourceMap.split(';');
var last = {};
return map.map(function(current) {
var ret = {
start: last.start,
length: last.length,
file: last.file,
jump: last.jump
};
current = current.split(':');
if (current[0] && current[0] !== '-1' && current[0].length) {
ret.start = parseInt(current[0]);
}
if (current[1] && current[1] !== '-1' && current[1].length) {
ret.length = parseInt(current[1]);
}
if (current[2] /*&& current[2] !== '-1'*/ && current[2].length) {
ret.file = parseInt(current[2]);
}
if (current[3] && current[3].length) {
ret.jump = current[3];
}
last = ret;
return ret;
});
}
};
module.exports = SolidityUtils;
| var SolidityUtils = {
getCharacterOffsetToLineAndColumnMapping: function(source) {
var mapping = [];
source = source.split("");
var line = 0;
var column = 0;
source.forEach(function(character) {
if (character == "\n") {
line += 1;
column = -1;
mapping.push({
line: line,
column: 0
});
} else {
mapping.push({
line: line,
column: column
});
}
column += 1;
});
return mapping;
},
getHumanReadableSourceMap: function(sourceMap) {
var map = sourceMap.split(';');
var last = {};
return map.map(function(current) {
var ret = {
start: last.start,
length: last.length,
file: last.file,
jump: last.jump
};
current = current.split(':');
if (current[0] && current[0] !== '-1' && current[0].length) {
ret.start = parseInt(current[0]);
}
if (current[1] && current[1] !== '-1' && current[1].length) {
ret.length = parseInt(current[1]);
}
if (current[2] /*&& current[2] !== '-1'*/ && current[2].length) {
ret.file = parseInt(current[2]);
}
if (current[3] && current[3].length) {
ret.jump = current[3];
}
last = ret;
return ret;
});
}
};
module.exports = SolidityUtils;
|
Subsets and Splits