text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Fix admin page permitted user logic | <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/
public function indexAction()
{
// if user is not logged in, redirect to login page
$securityContext = $this->container->get('security.authorization_checker');
if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('fos_user_security_login');
}
// Load the data for the current user into an object
$user = $this->getUser();
// continue only if user has Admin access, else redirect to Home
if ($user->getEmail() !== '[email protected]') {
return $this->redirectToRoute('home');
}
// Get an instance of the Entity Manager
$em = $this->getDoctrine()->getManager();
$tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
->findOneById(12);
$dataUpdatesManager = $this->get('app.data_updates.manager');
$dataUpdatesManager->setEntityManager($em);
$dataUpdatesManager->updateTeamsByTournament($tournament);
// $dataUpdatesManager->updateFixtures();
return $this->redirectToRoute('home');
}
}
| <?php
namespace Devlabs\SportifyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Devlabs\SportifyBundle\Entity\Tournament;
class AdminController extends Controller
{
/**
* @Route("/admin", name="admin_index")
*/
public function indexAction()
{
// if user is not logged in, redirect to login page
$securityContext = $this->container->get('security.authorization_checker');
if (!$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
return $this->redirectToRoute('fos_user_security_login');
}
// Load the data for the current user into an object
$user = $this->getUser();
if (!($user->getEmail() !== '[email protected]')) {
return $this->redirectToRoute('home');
}
// Get an instance of the Entity Manager
$em = $this->getDoctrine()->getManager();
$tournament = $em->getRepository('DevlabsSportifyBundle:Tournament')
->findOneById(12);
$dataUpdatesManager = $this->get('app.data_updates.manager');
$dataUpdatesManager->setEntityManager($em);
$dataUpdatesManager->updateTeamsByTournament($tournament);
// $dataUpdatesManager->updateFixtures();
return $this->redirectToRoute('home');
}
}
|
Replace double quotes with single quotes | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.model.course.SectionTermData', {
extend: 'Ext.data.Model',
requires: [
'SlateAdmin.proxy.Records',
'Ext.data.identifier.Negative'
],
// model config
idProperty: 'ID',
identifier: 'negative',
fields: [
{
name: 'ID',
type: 'int',
allowNull: true
},
{
name: 'Class',
type: 'string',
defaultValue: 'Slate\\Courses\\SectionTermData'
},
{
name: 'Created',
type: 'date',
dateFormat: 'timestamp',
allowNull: true
},
{
name: 'CreatorID',
type: 'int',
allowNull: true
},
{
name: 'RevisionID',
type: 'int',
allowNull: true
},
{
name: 'Modified',
type: 'date',
dateFormat: 'timestamp',
allowNull: true
},
{
name: 'ModifierID',
type: 'int',
allowNull: true
},
{
name: 'SectionID',
type: 'int'
},
{
name: 'TermID',
type: 'int'
},
{
name: 'TermReportNotes',
type: 'string',
allowNull: true
},
{
name: 'InterimReportNotes',
type: 'string',
allowNull: true
}
],
proxy: {
type: 'slaterecords',
url: '/section-data'
}
}); | /*jslint browser: true, undef: true *//*global Ext*/
Ext.define('SlateAdmin.model.course.SectionTermData', {
extend: 'Ext.data.Model',
requires: [
'SlateAdmin.proxy.Records',
'Ext.data.identifier.Negative'
],
// model config
idProperty: 'ID',
identifier: 'negative',
fields: [
{
name: "ID",
type: "int",
allowNull: true
},
{
name: "Class",
type: "string",
defaultValue: "Slate\\Courses\\SectionTermData"
},
{
name: "Created",
type: "date",
dateFormat: "timestamp",
allowNull: true
},
{
name: "CreatorID",
type: "int",
allowNull: true
},
{
name: "RevisionID",
type: "int",
allowNull: true
},
{
name: "Modified",
type: "date",
dateFormat: "timestamp",
allowNull: true
},
{
name: "ModifierID",
type: "int",
allowNull: true
},
{
name: "SectionID",
type: "int"
},
{
name: "TermID",
type: "int"
},
{
name: "TermReportNotes",
type: "string",
allowNull: true
},
{
name: "InterimReportNotes",
type: "string",
allowNull: true
}
],
proxy: {
type: 'slaterecords',
url: '/section-data'
}
}); |
Use anchorscroll to hopefully make sure modals appear within view on mobile. | /**
* Copyright 2015 Ian Davies
*
* 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.
*/
define([], function() {
return ['$compile', '$location', '$anchorScroll', function($compile, $location, $anchorScroll) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var rawClone = element.clone();
scope.modals = scope.modals || {};
scope.modals[attrs.isaacModal] = {
show: function() {
$("#isaacModal").empty().append($compile(rawClone)(scope));
$("#isaacModal").foundation("reveal", "open");
var windowHeight = $(window).height(),
modalHeight = $("#isaacModal").height(),
modalPosition = (33/100*windowHeight) - (modalHeight/2);
$("#isaacModal").css("top", modalPosition > 0 ? modalPosition+'px' : 0);
// make sure the top of the modal is in view.
$location.hash('isaacModal');
$anchorScroll();
},
hide: function() {
$("#isaacModal").foundation("reveal", "close");
},
}
}
}
}];
}); | /**
* Copyright 2015 Ian Davies
*
* 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.
*/
define([], function() {
return ['$compile', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var rawClone = element.clone();
scope.modals = scope.modals || {};
scope.modals[attrs.isaacModal] = {
show: function() {
$("#isaacModal").empty().append($compile(rawClone)(scope));
$("#isaacModal").foundation("reveal", "open");
var windowHeight = $(window).height(),
modalHeight = $("#isaacModal").height(),
modalPosition = (33/100*windowHeight) - (modalHeight/2);
$("#isaacModal").css("top", modalPosition > 0 ? modalPosition+'px' : 0);
},
hide: function() {
$("#isaacModal").foundation("reveal", "close");
},
}
}
}
}];
}); |
chore(ipc): Add extra debug and read DoForcePingTimeout in the
constructor
Signed-off-by: Francisco Miguel Biete <[email protected]>
<[email protected]> | <?php
class PingTrackingRedis extends InterProcessRedis {
const TTL = 3600;
private $key;
public function __construct() {
parent::__construct();
$this->key = "ZP-PING|" . Request::GetDeviceID() . '|' . Request::GetAuthUser() . '|' . Request::GetAuthDomain();
$this->DoForcePingTimeout();
}
/**
* Checks if there are newer ping requests for the same device & user so
* the current process could be terminated
*
* @access public
* @return boolean true if the current process is obsolete
*/
public function DoForcePingTimeout() {
while (true) {
self::$redis->watch($this->key);
$savedtime = self::$redis->get($this->key);
if ($savedtime === false || $savedtime < $_SERVER['REQUEST_TIME']) {
$res = self::$redis->multi()->setex($this->key,self::TTL, $_SERVER['REQUEST_TIME'])->exec();
if ($res === false) {
ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout(): set just failed, retrying");
ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout() key: ".$this->key);
ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout() reqtime: ".$_SERVER['REQUEST_TIME']);
ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout() last: ".self::$redis->getLastError());
continue;
}
else {
return false;
}
}
if ($savedtime === $_SERVER['REQUEST_TIME']) {
self::$redis->unwatch();
return false;
}
if ($savedtime > $_SERVER['REQUEST_TIME']) {
self::$redis->unwatch();
return true;
}
}
}
}
| <?php
class PingTrackingRedis extends InterProcessRedis {
const TTL = 3600;
private $key;
public function __construct() {
parent::__construct();
$this->key = "ZP-PING|" . Request::GetDeviceID() . '|' . Request::GetAuthUser() . '|' . Request::GetAuthDomain();
}
/**
* Checks if there are newer ping requests for the same device & user so
* the current process could be terminated
*
* @access public
* @return boolean true if the current process is obsolete
*/
public function DoForcePingTimeout() {
while (true) {
self::$redis->watch($this->key);
$savedtime = self::$redis->get($this->key);
if ($savedtime === false || $savedtime < $_SERVER['REQUEST_TIME']) {
$res = self::$redis->multi()->setex($this->key,self::TTL, $_SERVER['REQUEST_TIME'])->exec();
if ($res === false) {
ZLog::Write(LOGLEVEL_DEBUG, "DoForcePingTimeout(): set just failed, retrying");
continue;
}
else {
return false;
}
}
if ($savedtime === $_SERVER['REQUEST_TIME']) {
self::$redis->unwatch();
return false;
}
if ($savedtime > $_SERVER['REQUEST_TIME']) {
self::$redis->unwatch();
return true;
}
}
}
}
|
Replace array access to slims's container with a call to 'get'. | <?php
/**
* PHP version 7.0
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace Ewallet\Slim\Providers;
use Pimple\{Container, ServiceProviderInterface};
use Slim\App;
use Slim\Http\{Request, Response};
class EwalletControllerProvider implements ServiceProviderInterface
{
/** @var App */
private $app;
/**
* @param App $app
*/
public function __construct(App $app)
{
$this->app = $app;
}
/**
* @param Container $container
*/
public function register(Container $container)
{
$router = $this->app->getContainer()->get('router');
$this->app->get(
'/',
function (Request $request, Response $response) use ($router) {
return $response->withRedirect($request->getUri()->withPath(
$router->pathFor('transfer_form')
));
}
)->setName('ewallet_home');
$this->app->get(
'/transfer-form',
'ewallet.transfer_form_controller:enterTransferInformation'
)->setName('transfer_form');
$this->app->post(
'/transfer-funds',
'ewallet.transfer_funds_controller:transfer'
)->setName('transfer_funds');
}
}
| <?php
/**
* PHP version 7.0
*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
namespace Ewallet\Slim\Providers;
use Pimple\{Container, ServiceProviderInterface};
use Slim\App;
use Slim\Http\{Request, Response};
class EwalletControllerProvider implements ServiceProviderInterface
{
/** @var App */
private $app;
/**
* @param App $app
*/
public function __construct(App $app)
{
$this->app = $app;
}
/**
* @param Container $container
*/
public function register(Container $container)
{
$router = $this->app->getContainer()['router'];
$this->app->get(
'/',
function (Request $request, Response $response) use ($router) {
return $response->withRedirect($request->getUri()->withPath(
$router->pathFor('transfer_form')
));
}
)->setName('ewallet_home');
$this->app->get(
'/transfer-form',
'ewallet.transfer_form_controller:enterTransferInformation'
)->setName('transfer_form');
$this->app->post(
'/transfer-funds',
'ewallet.transfer_funds_controller:transfer'
)->setName('transfer_funds');
}
}
|
Set default state property values to `null` | /* eslint-disable */
// export default function detailReducer(state = {}, action) {
/* istanbul ignore next */
window.reducers = window.reducers || {};
window.reducers.detailReducer = (state = {}, action) => {
switch (action.type) {
case 'FETCH_DETAIL':
return {
...state,
dataSelection: null,
detail: {
endpoint: action.payload,
reload: Boolean(state.detail && state.detail.endpoint === action.payload),
isLoading: true,
isFullscreen: action.payload && action.payload.includes('catalogus/api')
},
layerSelection: {
...state.layerSelection,
isEnabled: false
},
map: {
...state.map,
isFullscreen: false,
isLoading: true
},
page: {
...state.page,
name: null,
type: null
},
search: null,
straatbeeld: null
};
case 'SHOW_DETAIL':
return {
...state,
detail: {
...state.detail,
display: action.payload.display,
geometry: action.payload.geometry,
isFullscreen: action.payload.isFullscreen,
isLoading: false,
reload: false
},
map: {
...state.map,
isLoading: false
}
};
default:
return state;
}
};
| /* eslint-disable */
// export default function detailReducer(state = {}, action) {
/* istanbul ignore next */
window.reducers = window.reducers || {};
window.reducers.detailReducer = (state = {}, action) => {
switch (action.type) {
case 'FETCH_DETAIL':
return {
...state,
dataSelection: null,
detail: {
endpoint: action.payload,
reload: Boolean(state.detail && state.detail.endpoint === action.payload),
isLoading: true,
isFullscreen: action.payload && action.payload.includes('catalogus/api')
},
layerSelection: {
...state.layerSelection,
isEnabled: false
},
map: {
...state.map,
isFullscreen: false,
isLoading: true
},
page: {
...state.page,
name: '',
type: ''
},
search: null,
straatbeeld: null
};
case 'SHOW_DETAIL':
return {
...state,
detail: {
...state.detail,
display: action.payload.display,
geometry: action.payload.geometry,
isFullscreen: action.payload.isFullscreen,
isLoading: false,
reload: false
},
map: {
...state.map,
isLoading: false
}
};
default:
return state;
}
};
|
Remove self.debug as LoggerMixin was removed from new versions of rapidsms. | import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
logger.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
| import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
self.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
Add setDateTime(DateTime) and setPriority(Priority) methods | package tars.testutil;
import tars.model.task.*;
import tars.model.tag.UniqueTagList;
/**
* A mutable task object. For testing only.
*/
public class TestTask implements ReadOnlyTask {
private Name name;
private UniqueTagList tags;
private DateTime dateTime;
private Status status;
private Priority priority;
public TestTask() {
tags = new UniqueTagList();
}
public void setName(Name name) {
this.name = name;
}
public void setDateTime(DateTime dateTime) {
this.dateTime = dateTime;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
@Override
public Name getName() {
return name;
}
@Override
public DateTime getDateTime() {
return dateTime;
}
@Override
public Status getStatus() {
return status;
}
@Override
public Priority getPriority() {
return priority;
}
@Override
public UniqueTagList getTags() {
return tags;
}
@Override
public String toString() {
return getAsText();
}
public String getAddCommand() {
StringBuilder sb = new StringBuilder();
sb.append("add " + this.getName().taskName + " ");
sb.append("-dt " + this.getDateTime().toString() + " ");
sb.append("-p " + this.getPriority().toString() + " ");
this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " "));
return sb.toString();
}
}
| package tars.testutil;
import tars.model.task.*;
import tars.model.tag.UniqueTagList;
/**
* A mutable task object. For testing only.
*/
public class TestTask implements ReadOnlyTask {
private Name name;
private UniqueTagList tags;
private DateTime dateTime;
private Status status;
private Priority priority;
public TestTask() {
tags = new UniqueTagList();
}
public void setName(Name name) {
this.name = name;
}
@Override
public Name getName() {
return name;
}
@Override
public DateTime getDateTime() {
return dateTime;
}
@Override
public Status getStatus() {
return status;
}
@Override
public Priority getPriority() {
return priority;
}
@Override
public UniqueTagList getTags() {
return tags;
}
@Override
public String toString() {
return getAsText();
}
public String getAddCommand() {
StringBuilder sb = new StringBuilder();
sb.append("add " + this.getName().taskName + " ");
sb.append("-dt " + this.getDateTime().toString() + " ");
sb.append("-p " + this.getPriority().toString() + " ");
this.getTags().getInternalList().stream().forEach(s -> sb.append("t/" + s.tagName + " "));
return sb.toString();
}
}
|
Remove dependency on unicodecsv module | # I started here: https://www.django-rest-framework.org/api-guide/renderers/#example
import csv
import io
import logging
from rest_framework import renderers
logger = logging.getLogger(__name__)
class SimpleCSVRenderer(renderers.BaseRenderer):
"""Renders simple 1-level-deep data as csv"""
media_type = "text/plain" # should we use text/csv instead?
format = "csv"
def render(self, data, media_type=None, renderer_context={}):
if "results" not in data:
logger.warning(f"no results in data: {str(data)}")
# Is this the right thing to do?
detail = data.get("detail", "unexpected error")
return detail
table_data = self.to_table(data["results"])
csv_buffer = io.StringIO()
writer = csv.writer(csv_buffer)
for row in table_data:
writer.writerow(row)
return csv_buffer.getvalue().encode("utf-8")
def to_table(self, data, fields=None):
"""Generator to stream the data as a series of rows"""
if data:
if fields is None:
fields = data[0].keys()
yield fields
for item in data:
row = [item.get(key, None) for key in fields]
yield row
| # I started here: https://www.django-rest-framework.org/api-guide/renderers/#example
from rest_framework import renderers
import unicodecsv as csv
import io
import logging
logger = logging.getLogger(__name__)
class SimpleCSVRenderer(renderers.BaseRenderer):
"""Renders simple 1-level-deep data as csv"""
media_type = "text/plain" # should we use text/csv instead?
format = "csv"
def render(self, data, media_type=None, renderer_context={}):
if "results" not in data:
logger.warning(f"no results in data: {str(data)}")
# Is this the right thing to do?
detail = data.get("detail", "unexpected error")
return detail
table_data = self.to_table(data["results"])
csv_buffer = io.BytesIO()
writer = csv.writer(csv_buffer)
for row in table_data:
writer.writerow(row)
return csv_buffer.getvalue()
def to_table(self, data, fields=None):
"""Generator to stream the data as a series of rows"""
if data:
if fields is None:
fields = data[0].keys()
yield fields
for item in data:
row = [item.get(key, None) for key in fields]
yield row
|
Change timeout type, increase to 2s | <?php
namespace App;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;
class Node extends Model
{
function online()
{
try {
$client = new Client(['exceptions' => false]);
$res = $client->request('GET', $this->url.'/ping',
['timeout' => 2,
'headers' => ['X-AllCall-Key' => $this->key]
]);
if ($res->getStatusCode() == 200)
return true;
}
catch (Exception $e) {
return false;
}
}
function status()
{
try {
$client = new Client(['exceptions' => false]);
$res = $client->request('GET', $this->url.'/status',
['timeout' => 2,
'headers' => ['X-AllCall-Key' => $this->key]
]);
if ($res->getStatusCode() == 200)
return json_decode($res->getBody())->response;
if ($res->getStatusCode() == 401)
return "Invalid Key";
else
return false;
}
catch (Exception $e) {
return false;
}
}
}
| <?php
namespace App;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;
class Node extends Model
{
function online()
{
try {
$client = new Client(['exceptions' => false]);
$res = $client->request('GET', $this->url.'/ping',
['connect_timeout' => 1,
'headers' => ['X-AllCall-Key' => $this->key]
]);
if ($res->getStatusCode() == 200)
return true;
}
catch (Exception $e) {
return false;
}
}
function status()
{
try {
$client = new Client(['exceptions' => false]);
$res = $client->request('GET', $this->url.'/status',
['connect_timeout' => 1,
'headers' => ['X-AllCall-Key' => $this->key]
]);
if ($res->getStatusCode() == 200)
return json_decode($res->getBody())->response;
if ($res->getStatusCode() == 401)
return "Invalid Key";
else
return false;
}
catch (Exception $e) {
return false;
}
}
}
|
Update onEvents schema to allow array of signal/scale listeners. | export default {
"defs": {
"listener": {
"oneOf": [
{"$ref": "#/refs/signal"},
{
"type": "object",
"properties": {
"scale": {"type": "string"}
},
"required": ["scale"]
},
{"$ref": "#/defs/stream"}
]
},
"onEvents": {
"type": "array",
"items": {
"allOf": [
{
"type": "object",
"properties": {
"events": {
"oneOf": [
{"$ref": "#/refs/selector"},
{"$ref": "#/defs/listener"},
{
"type": "array",
"minItems": 1,
"items": {"$ref": "#/defs/listener"}
}
]
},
"force": {"type": "boolean"}
},
"required": ["events"]
},
{
"oneOf": [
{
"type": "object",
"properties": {
"encode": {"type": "string"}
},
"required": ["encode"]
},
{
"type": "object",
"properties": {
"update": {
"oneOf": [
{"$ref": "#/refs/exprString"},
{"$ref": "#/refs/expr"},
{"$ref": "#/refs/signal"},
{
"type": "object",
"properties": {"value": {}},
"required": ["value"]
}
]
}
},
"required": ["update"]
}
]
}
]
}
}
}
};
| export default {
"defs": {
"onEvents": {
"type": "array",
"items": {
"allOf": [
{
"type": "object",
"properties": {
"events": {
"oneOf": [
{"$ref": "#/refs/selector"},
{"$ref": "#/refs/signal"},
{
"type": "object",
"properties": {
"scale": {"type": "string"}
},
"required": ["scale"]
},
{"$ref": "#/defs/stream"},
{
"type": "array",
"minItems": 1,
"items": {"$ref": "#/defs/stream"}
}
]
},
"force": {"type": "boolean"}
},
"required": ["events"]
},
{
"oneOf": [
{
"type": "object",
"properties": {
"encode": {"type": "string"}
},
"required": ["encode"]
},
{
"type": "object",
"properties": {
"update": {
"oneOf": [
{"$ref": "#/refs/exprString"},
{"$ref": "#/refs/expr"},
{"$ref": "#/refs/signal"},
{
"type": "object",
"properties": {"value": {}},
"required": ["value"]
}
]
}
},
"required": ["update"]
}
]
}
]
}
}
}
};
|
Fix checking of limit parameter | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
try:
intParam = int(param)
except ValueError:
return [False, param]
if str(intParam) != param:
return [False, param]
return [(intParam > 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl") | from twisted.words.protocols import irc
from txircd.modbase import Mode
class LimitMode(Mode):
def checkSet(self, user, target, param):
intParam = int(param)
if str(intParam) != param:
return [False, param]
return [(intParam >= 0), param]
def checkPermission(self, user, cmd, data):
if cmd != "JOIN":
return data
targetChannels = data["targetchan"]
keys = data["keys"]
removeChannels = []
for channel in targetChannels:
if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]):
user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
removeChannels.append(channel)
for channel in removeChannels:
index = targetChannels.index(channel)
targetChannels.pop(index)
keys.pop(index)
data["targetchan"] = targetChannels
data["keys"] = keys
return data
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
return {
"modes": {
"cpl": LimitMode()
},
"common": True
}
def cleanup(self):
self.ircd.removeMode("cpl") |
Rename „lint“ mode to „validate“ | const minimist = require('minimist');
// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
boolean: ["dev", "debug", "d", "v", "validate", "help", "version"],
string: ["init"],
});
const cwd = process.cwd();
module.exports = {
runnerPath: `${cwd}/kabafile.js`,
modulePath: `${cwd}/node_modules/kaba`,
app: getAppEnvironment(argv),
verbose: argv.v,
arguments: argv._,
init: argv.init || null,
version: argv.version,
help: argv.help,
};
/**
*
* @param {{dev: boolean, debug: boolean, d: boolean, v: boolean, validate: boolean}} argv
*
* @return {KabaAppEnvironment}
*/
function getAppEnvironment (argv)
{
const env = {
debug: false,
lint: false,
watch: false,
verbose: false,
mode: "compile",
cliVersion: null,
};
if (argv.d || argv.dev)
{
env.debug = true;
env.lint = true;
env.watch = true;
}
if (argv.debug)
{
env.debug = true;
}
if (argv.v)
{
env.verbose = true;
}
if (argv.validate)
{
env.lint = true;
env.mode = "validate";
}
if (argv.debug)
{
env.debug = true;
}
return env;
}
| const minimist = require('minimist');
// prepare CLI arguments
const argv = minimist(process.argv.slice(2), {
boolean: ["dev", "debug", "d", "v", "lint", "help", "version"],
string: ["init"],
});
const cwd = process.cwd();
module.exports = {
runnerPath: `${cwd}/kabafile.js`,
modulePath: `${cwd}/node_modules/kaba`,
app: getAppEnvironment(argv),
verbose: argv.v,
arguments: argv._,
init: argv.init || null,
version: argv.version,
help: argv.help,
};
/**
*
* @param {{dev: boolean, debug: boolean, d: boolean, v: boolean, lint: boolean}} argv
*
* @return {KabaAppEnvironment}
*/
function getAppEnvironment (argv)
{
const env = {
debug: false,
lint: false,
watch: false,
verbose: false,
mode: "compile",
cliVersion: null,
};
if (argv.d || argv.dev)
{
env.debug = true;
env.lint = true;
env.watch = true;
}
if (argv.debug)
{
env.debug = true;
}
if (argv.v)
{
env.verbose = true;
}
if (argv.lint)
{
env.lint = true;
env.mode = "lint";
}
if (argv.debug)
{
env.debug = true;
}
return env;
}
|
Use style loader instead of raw loader for css and get rid of html-raw loader | const path = require('path');
var webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {
'main': './main.ts'
},
module: {
loaders: [
{test: /\.ts$/, exclude: /node_modules/, loader: 'ts-loader'},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: 'url-loader'}
]
},
output: {
path: './dist',
filename: 'bundle.js'
},
plugins: [
new CopyWebpackPlugin(
[
{
from: './index.html',
to: 'index.html'
}
]
),
new webpack.ProvidePlugin(
{
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}
)
],
resolve: {
extensions: ['.ts', '.js']
}
};
| const path = require('path');
var webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {
'main': './main.ts'
},
module: {
loaders: [
{test: /\.css$/, loader: 'raw-loader'},
{test: /\.html$/, loader: 'raw-loader'},
{test: /\.ts$/, loader: 'ts-loader'},
{test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/, loader: 'url-loader'}
]
},
output: {
path: './dist',
filename: 'bundle.js'
},
plugins: [
new CopyWebpackPlugin(
[
{
from: './index.html',
to: 'index.html'
}
]
),
new webpack.ProvidePlugin(
{
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}
)
],
resolve: {
extensions: ['.ts', '.js']
}
};
|
Fix typo in dependency-injected property name. | <?php
namespace Northstar\Http\Controllers;
use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
/**
* Amazon Web Services API wrapper.
* @var AWS
*/
protected $aws;
public function __construct(AWS $aws)
{
$this->aws = $aws;
$this->middleware('key:user');
$this->middleware('auth');
}
/**
* Store a new avatar for a user.
* POST /users/:id/avatar
*
* @param Request $request
* @param $id - User ID
* @return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
if ($request->file('photo')) {
$file = $request->file('photo');
} else {
$file = $request->photo;
}
$this->validate($request, [
'photo' => 'required',
]);
$filename = $this->aws->storeImage('avatars', $id, $file);
// Save filename to User model
$user = User::where('_id', $id)->first();
$user->photo = $filename;
$user->save();
// Respond to user with success and photo URL
return $this->respond($user);
}
}
| <?php
namespace Northstar\Http\Controllers;
use Northstar\Services\AWS;
use Northstar\Models\User;
use Illuminate\Http\Request;
class AvatarController extends Controller
{
/**
* Amazon Web Services API wrapper.
* @var AWS
*/
protected $phoenix;
public function __construct(AWS $aws)
{
$this->aws = $aws;
$this->middleware('key:user');
$this->middleware('auth');
}
/**
* Store a new avatar for a user.
* POST /users/:id/avatar
*
* @param Request $request
* @param $id - User ID
* @return \Illuminate\Http\Response
*/
public function store(Request $request, $id)
{
if ($request->file('photo')) {
$file = $request->file('photo');
} else {
$file = $request->photo;
}
$this->validate($request, [
'photo' => 'required',
]);
$filename = $this->aws->storeImage('avatars', $id, $file);
// Save filename to User model
$user = User::where('_id', $id)->first();
$user->photo = $filename;
$user->save();
// Respond to user with success and photo URL
return $this->respond($user);
}
}
|
Add now navigates to Lists page | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewList } from '../actions';
class ListEdit extends Component {
constructor(props) {
super(props);
this.state = {listName: ''};
}
saveClickHandler(e) {
e.preventDefault();
console.log("saveClickHandler", this);
this.props.addNewList(this.state.listName);
this.props.history.push('/');
}
cancelClickHandler(e) {
e.preventDefault();
console.log("cancelClickHandler");
}
render() {
//console.log('edit List', props);
let screenTitle = this.props.params.listId ? "Edit List" : "Add new List";
return (
<div>
<h3>{screenTitle}</h3>
<input type="text"
placeholder="Name of List"
onChange={event => this.setState({listName: event.target.value})}
/>
<div className="footer">
<a onClick={this.cancelClickHandler.bind(this)} href="#">Cancel</a>
<a onClick={this.saveClickHandler.bind(this)} href="#">Save</a>
</div>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
"use strict";
return bindActionCreators({addNewList}, dispatch);
}
export default connect(null, mapDispatchToProps)(ListEdit); | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addNewList } from '../actions';
class ListEdit extends Component {
constructor(props) {
super(props);
this.state = {listName: ''};
}
saveClickHandler(e) {
e.preventDefault();
console.log("saveClickHandler", this);
this.props.addNewList(this.state.listName);
}
cancelClickHandler(e) {
e.preventDefault();
console.log("cancelClickHandler");
}
render() {
//console.log('edit List', props);
let screenTitle = this.props.params.listId ? "Edit List" : "Add new List";
return (
<div>
<h3>{screenTitle}</h3>
<input type="text"
placeholder="Name of List"
onChange={event => this.setState({listName: event.target.value})}
/>
<div className="footer">
<a onClick={this.cancelClickHandler.bind(this)} href="#">Cancel</a>
<a onClick={this.saveClickHandler.bind(this)} href="#">Save</a>
</div>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
"use strict";
return bindActionCreators({addNewList}, dispatch);
}
export default connect(null, mapDispatchToProps)(ListEdit); |
Return user after oauth login | <?php
namespace Facilis\Users\OAuth2;
use League\OAuth2\Client\Exception\IDPException;
use League\OAuth2\Client\Provider\ProviderInterface;
use Nette\Object;
class LoginService extends Object
{
/**
* @var IStateStorage
*/
private $stateStorage;
function __construct(IStateStorage $stateStorage)
{
$this->stateStorage = $stateStorage;
}
public function login(ProviderInterface $provider, $code, $state, IOAuthAccountManager $manager)
{
if ($code === null) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$this->stateStorage->storeState($provider->state);
header('Location: ' . $authUrl);
// Check given state against previously stored one to mitigate CSRF attack
} elseif ($state === null || ($state !== $this->stateStorage->loadState())) {
$this->stateStorage->storeState(null);
throw new InvalidStateException();
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $code
]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$userDetails = $provider->getUserDetails($token);
return $manager->persistOAuthAccount(get_class($provider), $token, $userDetails);
} catch (IDPException $e) {
throw new AuthenticationException;
}
}
}
} | <?php
namespace Facilis\Users\OAuth2;
use League\OAuth2\Client\Exception\IDPException;
use League\OAuth2\Client\Provider\ProviderInterface;
use Nette\Object;
class LoginService extends Object
{
/**
* @var IStateStorage
*/
private $stateStorage;
function __construct(IStateStorage $stateStorage)
{
$this->stateStorage = $stateStorage;
}
public function login(ProviderInterface $provider, $code, $state, IOAuthAccountManager $manager)
{
if ($code === null) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$this->stateStorage->storeState($provider->state);
header('Location: ' . $authUrl);
// Check given state against previously stored one to mitigate CSRF attack
} elseif ($state === null || ($state !== $this->stateStorage->loadState())) {
$this->stateStorage->storeState(null);
throw new InvalidStateException();
} else {
// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
'code' => $code
]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$userDetails = $provider->getUserDetails($token);
$manager->persistOAuthAccount(get_class($provider), $token, $userDetails);
} catch (IDPException $e) {
throw new AuthenticationException;
}
}
}
} |
Upgrade nose to 1.3.1 for Travis | #!/usr/bin/env python2
import os
from setuptools import setup, find_packages
from plugins import __version__
repo_directory = os.path.dirname(__file__)
try:
long_description = open(os.path.join(repo_directory, 'README.rst')).read()
except:
long_description = None
setup(
name='gds-nagios-plugins',
version=__version__,
packages=find_packages(exclude=['test*']),
author='Tom Booth',
author_email='[email protected]',
maintainer='Government Digital Service',
url='https://github.com/alphagov/nagios-plugins',
description='nagios-plugins: a set of useful nagios plugins',
long_description=long_description,
license='MIT',
keywords='',
setup_requires=['setuptools-pep8'],
install_requires=[
"nagioscheck==0.1.6"
],
tests_require=[
"nose==1.3.1",
"freezegun==0.1.11"
],
test_suite='nose.collector',
entry_points={
'console_scripts': [
'check_apt_security_updates='
'plugins.command.check_apt_security_updates:main',
'check_reboot_required=plugins.command.check_reboot_required:main',
'check_elasticsearch=plugins.command.check_elasticsearch:main'
]
}
)
| #!/usr/bin/env python2
import os
from setuptools import setup, find_packages
from plugins import __version__
repo_directory = os.path.dirname(__file__)
try:
long_description = open(os.path.join(repo_directory, 'README.rst')).read()
except:
long_description = None
setup(
name='gds-nagios-plugins',
version=__version__,
packages=find_packages(exclude=['test*']),
author='Tom Booth',
author_email='[email protected]',
maintainer='Government Digital Service',
url='https://github.com/alphagov/nagios-plugins',
description='nagios-plugins: a set of useful nagios plugins',
long_description=long_description,
license='MIT',
keywords='',
setup_requires=['setuptools-pep8'],
install_requires=[
"nagioscheck==0.1.6"
],
tests_require=[
"nose==1.3.0",
"freezegun==0.1.11"
],
test_suite='nose.collector',
entry_points={
'console_scripts': [
'check_apt_security_updates='
'plugins.command.check_apt_security_updates:main',
'check_reboot_required=plugins.command.check_reboot_required:main',
'check_elasticsearch=plugins.command.check_elasticsearch:main'
]
}
)
|
Fix "bin/cm migration add" again | <?php
class CM_Migration_Manager implements CM_Service_ManagerAwareInterface {
use CM_Service_ManagerAwareTrait;
/** @var string[] */
private $_modules;
/**
* @param CM_Service_Manager $serviceManager
* @param string[] $modules
*/
public function __construct(CM_Service_Manager $serviceManager, array $modules) {
$this->setServiceManager($serviceManager);
$this->_modules = $modules;
}
/**
* @return CM_Migration_Loader
*/
public function getLoader() {
return new CM_Migration_Loader($this->getServiceManager(), $this->_getMigrationPaths());
}
/**
* @return array
*/
protected function _getMigrationPaths() {
$paths = [
self::getMigrationPathByModule(),
];
foreach ($this->_modules as $moduleName) {
$paths[] = self::getMigrationPathByModule($moduleName);
}
return $paths;
}
/**
* @param string|null $moduleName
* @return string
*/
public static function getMigrationPathByModule($moduleName = null) {
$modulePath = null !== $moduleName ? CM_Util::getModulePath((string) $moduleName) : DIR_ROOT;
return join(DIRECTORY_SEPARATOR, [$modulePath, 'resources', 'migration']);
}
}
| <?php
class CM_Migration_Manager implements CM_Service_ManagerAwareInterface {
use CM_Service_ManagerAwareTrait;
/** @var string[] */
private $_modules;
/**
* @param CM_Service_Manager $serviceManager
* @param string[] $modules
*/
public function __construct(CM_Service_Manager $serviceManager, array $modules) {
$this->setServiceManager($serviceManager);
$this->_modules = $modules;
}
/**
* @return CM_Migration_Loader
*/
public function getLoader() {
return new CM_Migration_Loader($this->getServiceManager(), $this->_getMigrationPaths());
}
/**
* @return array
*/
protected function _getMigrationPaths() {
$paths = [
$this->_getMigrationPathByModule(),
];
foreach ($this->_modules as $moduleName) {
$paths[] = self::getMigrationPathByModule($moduleName);
}
return $paths;
}
/**
* @param string|null $moduleName
* @return string
*/
public static function getMigrationPathByModule($moduleName = null) {
$modulePath = null !== $moduleName ? CM_Util::getModulePath((string) $moduleName) : DIR_ROOT;
return join(DIRECTORY_SEPARATOR, [$modulePath, 'resources', 'migration']);
}
}
|
Allow PHP response to send MultipleHeaders safely
- Detect MultipleHeaderDescription
- when found, pass boolean false as second argument to header() | <?php
namespace Zend\Http\PhpEnvironment;
use Zend\Http\Header\MultipleHeaderDescription,
Zend\Http\Response as HttpResponse,
Zend\Stdlib\Parameters;
class Response extends HttpResponse
{
protected $headersSent = false;
protected $contentSent = false;
public function __construct()
{
}
public function headersSent()
{
return $this->headersSent;
}
public function contentSent()
{
return $this->contentSent;
}
public function sendHeaders()
{
if ($this->headersSent()) {
return;
}
$version = $this->getVersion();
$code = $this->getStatusCode();
$message = $this->getReasonPhrase();
$status = sprintf('HTTP/%s %d %s', $version, $code, $message);
header($status);
foreach ($this->headers() as $header) {
if ($header instanceof MultipleHeaderDescription) {
header($header->toString(), false);
continue;
}
header($header->toString());
}
$this->headersSent = true;
return $this;
}
public function sendContent()
{
if ($this->contentSent()) {
return;
}
echo $this->getContent();
$this->contentSent = true;
return $this;
}
public function send()
{
$this->sendHeaders()
->sendContent();
return $this;
}
}
| <?php
namespace Zend\Http\PhpEnvironment;
use Zend\Http\Response as HttpResponse,
Zend\Stdlib\Parameters;
class Response extends HttpResponse
{
protected $headersSent = false;
protected $contentSent = false;
public function __construct()
{
}
public function headersSent()
{
return $this->headersSent;
}
public function contentSent()
{
return $this->contentSent;
}
public function sendHeaders()
{
if ($this->headersSent()) {
return;
}
$version = $this->getVersion();
$code = $this->getStatusCode();
$message = $this->getReasonPhrase();
$status = sprintf('HTTP/%s %d %s', $version, $code, $message);
header($status);
foreach ($this->headers() as $header) {
header($header->toString());
}
$this->headersSent = true;
return $this;
}
public function sendContent()
{
if ($this->contentSent()) {
return;
}
echo $this->getContent();
$this->contentSent = true;
return $this;
}
public function send()
{
$this->sendHeaders()
->sendContent();
return $this;
}
}
|
Fix the gift certificate module so that an invalid code won't throw an exception. | """
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
valid_gc = False
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
valid_gc = gc.valid
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not valid_gc:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
| """
GiftCertificate processor
"""
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__init__('giftcertificate', settings)
def capture_payment(self, testing=False, order=None, amount=NOTSET):
"""
Process the transaction and return a ProcessorResponse
"""
if not order:
order = self.order
if amount==NOTSET:
amount = order.balance
payment = None
if self.order.paid_in_full:
success = True
reason_code = "0"
response_text = _("No balance to pay")
else:
try:
gc = GiftCertificate.objects.from_order(self.order)
except GiftCertificate.DoesNotExist:
success = False
reason_code="1"
response_text = _("No such Gift Certificate")
if not gc.valid:
success = False
reason_code="2"
response_text = _("Bad Gift Certificate")
else:
gc.apply_to_order(self.order)
payment = gc.orderpayment
reason_code = "0"
response_text = _("Success")
success = True
if not self.order.paid_in_full:
response_text = _("%s balance remains after gift certificate was applied") % moneyfmt(self.order.balance)
return ProcessorResult(self.key, success, response_text, payment=payment)
|
Add guard for orphaned references | <?php
namespace TeiEditionBundle\Entity;
/**
*
*
*/
trait ArticleReferencesTrait
{
/* Currently simple sort by article title */
protected function sortArticleReferences($articleReferences)
{
usort($articleReferences, function ($a, $b) {
return strcmp(mb_strtolower($a->getArticle()->getName(), 'UTF-8'),
mb_strtolower($b->getArticle()->getName(), 'UTF-8'));
});
return $articleReferences;
}
public function getArticleReferences($lang = null, $ignoreArticles = null)
{
if (is_null($this->articleReferences)) {
return [];
}
if (is_null($lang)) {
return $this->articleReferences->toArray();
}
$langCode3 = \TeiEditionBundle\Utils\Iso639::code1to3($lang);
$ignoreArticleIds = [];
if (!is_null($ignoreArticles)) {
foreach ($ignoreArticles as $article) {
$ignoreArticleIds[] = $article->getId();
}
}
return $this->sortArticleReferences($this->articleReferences->filter(
function ($entity) use ($langCode3, $ignoreArticleIds) {
if (is_null($entity->getArticle())) {
// orphaned references, should only happen on manual delete
return false;
}
if (in_array($entity->getArticle()->getId(), $ignoreArticleIds)) {
return false;
}
return 1 == $entity->getArticle()->getStatus()
&& $entity->getArticle()->getLanguage() == $langCode3;
}
)->toArray());
}
}
| <?php
namespace TeiEditionBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
*
*/
trait ArticleReferencesTrait
{
/* Currently simple sort by article title */
protected function sortArticleReferences($articleReferences)
{
usort($articleReferences, function ($a, $b) {
return strcmp(mb_strtolower($a->getArticle()->getName(), 'UTF-8'),
mb_strtolower($b->getArticle()->getName(), 'UTF-8'));
});
return $articleReferences;
}
public function getArticleReferences($lang = null, $ignoreArticles = null)
{
if (is_null($this->articleReferences)) {
return [];
}
if (is_null($lang)) {
return $this->articleReferences->toArray();
}
$langCode3 = \TeiEditionBundle\Utils\Iso639::code1to3($lang);
$ignoreArticleIds = [];
if (!is_null($ignoreArticles)) {
foreach ($ignoreArticles as $article) {
$ignoreArticleIds[] = $article->getId();
}
}
return $this->sortArticleReferences($this->articleReferences->filter(
function ($entity) use ($langCode3, $ignoreArticleIds) {
if (in_array($entity->getArticle()->getId(), $ignoreArticleIds)) {
return false;
}
return 1 == $entity->getArticle()->getStatus()
&& $entity->getArticle()->getLanguage() == $langCode3;
}
)->toArray());
}
}
|
Call parent with last set to True
This way we get __parent__.site set to a valid site, or it raises an
error.
We may want to change this in the future... | import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=True)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
| import logging
log = logging.getLogger(__name__)
from uuid import UUID
from pyramid.compat import string_types
from .... import models as m
class Entries(object):
"""Entries
Traversal object for a site ID
"""
__name__ = None
__parent__ = None
def __init__(self):
self.__name__ = 'entries'
log.debug("Entries!")
def __getitem__(self, key):
"""Check to see if we can traverse this ..."""
next_ctx = None
if next_ctx is None:
raise KeyError
else:
next_ctx.__parent__ = self
return next_ctx
def finalise(self, last=True):
"""Attempts to find all entries for a certain site
:last: If this is the last context in the tree.
:returns: None
"""
if self.__parent__ is not None:
# Finalise the parent first
self.__parent__.finalise(last=False)
# Get the entries variable from the parent
self.site = self.__parent__.site
self.site = self.site.first()
if not self.site:
raise ValueError('Unable to get validate site ID')
self.entries = m.DBSession.query(m.Entry).filter(m.Entry.site == self.site)
else:
# We need a parent ...
raise ValueError
|
Adjust --dump-config color theme for better readability
Add jinja highlighting to --dump-config | from argparse import SUPPRESS
import yaml
from loguru import logger
from rich.syntax import Syntax
from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console
logger = logger.bind(name='dump_config')
class OutputDumpConfig:
"""
Dumps task config in STDOUT in yaml at exit or abort event.
"""
@plugin.priority(plugin.PRIORITY_LAST)
def on_task_start(self, task, config):
if task.options.dump_config:
console.rule(f'config from task: {task.name}')
syntax = Syntax(yaml.safe_dump(task.config).strip(), 'yaml+jinja', theme='native')
console(syntax)
console.rule()
task.abort(silent=True)
if task.options.dump_config_python:
console(task.config)
task.abort(silent=True)
@event('plugin.register')
def register_plugin():
plugin.register(OutputDumpConfig, 'dump_config', debug=True, builtin=True, api_ver=2)
@event('options.register')
def register_parser_arguments():
exec_parser = options.get_parser('execute')
exec_parser.add_argument(
'--dump-config',
action='store_true',
dest='dump_config',
default=False,
help='display the config of each feed after template merging/config generation occurs',
)
exec_parser.add_argument(
'--dump-config-python',
action='store_true',
dest='dump_config_python',
default=False,
help=SUPPRESS,
)
| from argparse import SUPPRESS
from loguru import logger
from rich.syntax import Syntax
from flexget import options, plugin
from flexget.event import event
from flexget.terminal import console
logger = logger.bind(name='dump_config')
class OutputDumpConfig:
"""
Dumps task config in STDOUT in yaml at exit or abort event.
"""
@plugin.priority(plugin.PRIORITY_LAST)
def on_task_start(self, task, config):
if task.options.dump_config:
import yaml
console.rule(f'config from task: {task.name}')
syntax = Syntax(yaml.safe_dump(task.config).strip(), 'yaml')
console(syntax)
console.rule()
task.abort(silent=True)
if task.options.dump_config_python:
console(task.config)
task.abort(silent=True)
@event('plugin.register')
def register_plugin():
plugin.register(OutputDumpConfig, 'dump_config', debug=True, builtin=True, api_ver=2)
@event('options.register')
def register_parser_arguments():
exec_parser = options.get_parser('execute')
exec_parser.add_argument(
'--dump-config',
action='store_true',
dest='dump_config',
default=False,
help='display the config of each feed after template merging/config generation occurs',
)
exec_parser.add_argument(
'--dump-config-python',
action='store_true',
dest='dump_config_python',
default=False,
help=SUPPRESS,
)
|
Fix typo in DataStore test | 'use strict';
var test = require('tape');
var DataStore = require('../../lib/data-store/data-store');
test('----- DataStore', function(t) {
t.plan(3);
t.test('Registers/Retrieves modules', function(st){
st.plan(1);
var name = 'test:module';
var tag = 'HEAD';
var definition = {a: 1};
DataStore.registerModule(name, tag, definition);
var retrievedModule = DataStore.getModule(name, tag);
st.ok(retrievedModule.a === definition.a, 'registers and retrieves modules');
});
t.test('Saves/Retrieves executed components', function(st){
st.plan(1);
var component = {};
DataStore.saveExecutedComponent('body', component);
var retrievedComponent = DataStore.getExecutedComponent('body');
st.ok(component === retrievedComponent, 'saved & retrieved component are equal');
});
t.test('Registers components', function(st) {
st.plan(2);
var component = {};
var uid = 'uid';
DataStore.registerComponent(uid, component);
var retrievedComponent = DataStore.getComponent(uid);
st.ok(component === retrievedComponent, 'saved & retrieved component are equal');
var component2 = {};
try {
DataStore.registerComponent(uid, component2);
}
catch (e) {
st.pass('Does not save component w/ already registered UID');
}
});
});
| 'use strict';
var test = require('tape');
var DataStore = require('../../lib/data-store/data-store');
test('----- DataStore', function(t) {
t.plan(3);
t.test('Saves/Retrieves modules', function(st){
st.plan(1);
var name = 'test:module';
var tag = 'HEAD';
var definition = {a: 1};
var retrievedModule = DataStore.getModule(name, tag);
st.ok(retrievedModule.a === definition.a, 'saves and retrieves modules');
});
t.test('Saves/Retrieves executed components', function(st){
st.plan(1);
var component = {};
DataStore.saveExecutedComponent('body', component);
var retrievedComponent = DataStore.getExecutedComponent('body');
st.ok(component === retrievedComponent, 'saved & retrieved component are equal');
});
t.test('Registers components', function(st) {
st.plan(2);
var component = {};
var uid = 'uid';
DataStore.registerComponent(uid, component);
var retrievedComponent = DataStore.getComponent(uid);
st.ok(component === retrievedComponent, 'saved & retrieved component are equal');
var component2 = {};
try {
DataStore.registerComponent(uid, component2);
}
catch (e) {
st.pass('Does not save component w/ already registered UID');
}
});
});
|
Fix a bug when the list name was not visible | import _ from 'lodash'
import {
COMPANY_LISTS__LISTS_LOADED,
COMPANY_LISTS__SELECT,
COMPANY_LISTS__COMPANIES_LOADED,
COMPANY_LISTS__FILTER,
COMPANY_LISTS__ORDER,
} from '../../actions'
import { RECENT } from './Filters'
const initialState = {
orderBy: RECENT,
}
export default (
state = initialState,
{ type, id, result, payload, query, orderBy }
) => {
switch (type) {
case COMPANY_LISTS__LISTS_LOADED:
return {
...state,
lists: _.mapValues(result, (name) => ({ name })),
selectedId: Object.keys(result)[0],
}
case COMPANY_LISTS__COMPANIES_LOADED:
return {
...state,
lists: {
...state.lists,
[payload]: {
...state.lists[payload],
companies: result,
},
},
}
case COMPANY_LISTS__SELECT:
return {
...state,
selectedId: id,
query: '',
}
case COMPANY_LISTS__FILTER:
return { ...state, query }
case COMPANY_LISTS__ORDER:
return { ...state, orderBy }
default:
return state
}
}
| import _ from 'lodash'
import {
COMPANY_LISTS__LISTS_LOADED,
COMPANY_LISTS__SELECT,
COMPANY_LISTS__COMPANIES_LOADED,
COMPANY_LISTS__FILTER,
COMPANY_LISTS__ORDER,
} from '../../actions'
import { RECENT } from './Filters'
const initialState = {
orderBy: RECENT,
}
export default (
state = initialState,
{ type, id, result, payload, query, orderBy }
) => {
switch (type) {
case COMPANY_LISTS__LISTS_LOADED:
return {
...state,
lists: _.mapValues(result, (title) => ({ title })),
selectedId: Object.keys(result)[0],
}
case COMPANY_LISTS__COMPANIES_LOADED:
return {
...state,
lists: {
...state.lists,
[payload]: {
...state.lists[payload],
companies: result,
},
},
}
case COMPANY_LISTS__SELECT:
return {
...state,
selectedId: id,
query: '',
}
case COMPANY_LISTS__FILTER:
return { ...state, query }
case COMPANY_LISTS__ORDER:
return { ...state, orderBy }
default:
return state
}
}
|
Convert to base 64 using standard library | // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Base64;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
public class LogReader {
long earliestLogThreshold;
long latestLogThreshold;
protected JSONObject readLogs(String logDirectory, long earliestLogThreshold, long latestLogThreshold) throws IOException, JSONException {
this.earliestLogThreshold = earliestLogThreshold;
this.latestLogThreshold = latestLogThreshold;
JSONObject json = new JSONObject();
File root = new File(logDirectory);
traverse_folder(root, json, "");
return json;
}
private void traverse_folder(File root, JSONObject json, String filename) throws IOException, JSONException {
File[] files = root.listFiles();
for(File child : files) {
long logTime = Files.readAttributes(child.toPath(), BasicFileAttributes.class).creationTime().toMillis();
if(child.isFile() && earliestLogThreshold < logTime && logTime < latestLogThreshold) {
json.put(filename + child.getName(), Base64.getEncoder().encodeToString(Files.readAllBytes(child.toPath())));
}
else if (!child.isFile()){
traverse_folder(child, json, filename + child.getName() + "-");
}
}
}
}
| // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler;
import org.json.JSONException;
import org.json.JSONObject;
import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
public class LogReader {
long earliestLogThreshold;
long latestLogThreshold;
protected JSONObject readLogs(String logDirectory, long earliestLogThreshold, long latestLogThreshold) throws IOException, JSONException {
this.earliestLogThreshold = earliestLogThreshold;
this.latestLogThreshold = latestLogThreshold;
JSONObject json = new JSONObject();
File root = new File(logDirectory);
traverse_folder(root, json, "");
return json;
}
private void traverse_folder(File root, JSONObject json, String filename) throws IOException, JSONException {
File[] files = root.listFiles();
for(File child : files) {
long logTime = Files.readAttributes(child.toPath(), BasicFileAttributes.class).creationTime().toMillis();
if(child.isFile() && earliestLogThreshold < logTime && logTime < latestLogThreshold) {
json.put(filename + child.getName(), DatatypeConverter.printBase64Binary(Files.readAllBytes(child.toPath())));
}
else if (!child.isFile()){
traverse_folder(child, json, filename + child.getName() + "-");
}
}
}
}
|
Clean up input tables class and instance declarations | from utils import write_csv_rows, read_csv_rows
class input_table:
def __init__(self, filename, name, headers, content=[]):
self.filename = filename
self.name = name
self.headers = headers
self.content = content
connect_filename = 'connectivity.csv'
connect_name = ['Connectivity Table']
connect_headers = ['x1','y1','x2','y2','E','A']
connect_tbl = input_table(connect_filename,
connect_name,
connect_headers)
force_filename = 'forces.csv'
force_name = ['Force Table']
force_headers = ['x','y','Fx','Fy']
force_tbl = input_table(force_filename,
force_name,
force_headers)
bc_filename = 'boundary_conditions.csv'
bc_name = ['Boundary Conditions']
bc_headers = ['x','y','Constrained Dimension','Displacement']
bc_tbl = input_table(bc_filename,
bc_name,
bc_headers)
sim_filename = 'simulation_parameters.csv'
sim_name = ['Simulation Parameters']
sim_headers = ['Numerical Soln Multiplier','Degrees of Freedom']
sim_content = ['1e9']
sim_tbl = input_table(sim_filename,
sim_name,
sim_headers,
sim_content)
input_files = [connect_tbl,force_tbl,bc_tbl,sim_tbl]
for i in range(0,len(input_files)):
tbl_list = [input_files[i].name,
input_files[i].headers,
input_files[i].content]
write_csv_rows(input_files[i].filename,tbl_list)
print(input_files[i].name[0] + ' written to ' +\
input_files[i].filename)
| from utils import write_csv_rows, read_csv_rows
class input_table:
def __init__(self, filename, content):
self.filename = filename
self.content = content
connect_tbl=input_table('connectivity.csv',
[['Connectivity Table'],
['x1','y1','x2','y2','E','A']])
force_tbl=input_table('forces.csv',
[['Force Table'],
['x','y','Fx','Fy']])
bc_tbl=input_table('boundary_conditions.csv',
[['Boundary Conditions'],
['x','y','Constrained Dimension','Displacement']])
sim_tbl=input_table('simulation_parameters.csv',
[['Simulation Parameters'],
['Numerical Soln Multiplier','Degrees of Freedom'],
['1e9']])
input_files=[connect_tbl,force_tbl,bc_tbl,sim_tbl]
for i in range(0,len(input_files)):
write_csv_rows(input_files[i].filename,input_files[i].content)
print(input_files[i].content[0][0] + ' written to ' + input_files[i].filename)
|
feature: Allow use of snap-opt-* attrs for opts | angular.module('snap')
.directive('snapContent', ['SnapConstructor', 'snapRemote', function (SnapConstructor, snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = angular.extend({}, snapRemote.globalOptions);
// Get `snapOpt*` attrs, for now there is no *binding* going on here.
// We're just providing a more declarative way to set initial values.
angular.forEach(attrs, function(val, attr) {
if(attr.indexOf('snapOpt') === 0) {
attr = attr.substring(7);
if(attr.length) {
attr = attr[0].toLowerCase() + attr.substring(1);
snapOptions[attr] = scope.$eval(val);
}
}
});
// Always force the snap element to be the one this directive is
// attached to.
snapOptions.element = element[0];
var snapId = attrs.snapId;
if(!!snapId) {
snapId = scope.$eval(attrs.snapId);
}
// override snap options if some provided in snap-options attribute
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
angular.extend(snapOptions, scope.$eval(attrs.snapOptions));
}
snapRemote.register(new SnapConstructor(snapOptions), snapId);
// watch snapOptions for updates
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
scope.$watch(attrs.snapOptions, function(newSnapOptions) {
snapRemote.getSnapper(snapId).then(function(snapper) {
snapper.settings(newSnapOptions);
});
}, true);
}
scope.$on('$destroy', function() {
snapRemote.unregister(snapId);
});
}
};
}]);
| angular.module('snap')
.directive('snapContent', ['SnapConstructor', 'snapRemote', function (SnapConstructor, snapRemote) {
'use strict';
return {
restrict: 'AE',
link: function postLink(scope, element, attrs) {
element.addClass('snap-content');
var snapOptions = {
element: element[0]
};
angular.extend(snapOptions, snapRemote.globalOptions);
var snapId = attrs.snapId;
if(!!snapId) {
snapId = scope.$eval(attrs.snapId);
}
// override snap options if some provided in snap-options attribute
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
angular.extend(snapOptions, scope.$eval(attrs.snapOptions));
}
snapRemote.register(new SnapConstructor(snapOptions), snapId);
// watch snapOptions for updates
if(angular.isDefined(attrs.snapOptions) && attrs.snapOptions) {
scope.$watch(attrs.snapOptions, function(newSnapOptions) {
snapRemote.getSnapper(snapId).then(function(snapper) {
snapper.settings(newSnapOptions);
});
}, true);
}
scope.$on('$destroy', function() {
snapRemote.unregister(snapId);
});
}
};
}]);
|
Add current pot and cards to client table representation | //J-
package com.whippy.poker.common.beans;
import java.util.List;
public class ClientTable {
private ClientSeat[] seats;
private int id;
private TableState state;
private int dealerPosition;
private int currentPot;
private List<Card> currentCards;
public ClientTable(ClientSeat[] seats, int id, TableState state, int dealerPosition, int currentPot, List<Card> currentCards) {
this.seats = seats;
this.id = id;
this.state = state;
this.dealerPosition = dealerPosition;
this.setCurrentPot(currentPot);
this.currentCards = currentCards;
}
public void setSeats(ClientSeat[] seats) {
this.seats = seats;
}
public void setId(int id) {
this.id = id;
}
public void setState(TableState state) {
this.state = state;
}
public void setDealerPosition(int dealerPosition) {
this.dealerPosition = dealerPosition;
}
public ClientTable(){
}
public ClientSeat[] getSeats() {
return seats;
}
public int getId() {
return id;
}
public TableState getState() {
return state;
}
public int getDealerPosition() {
return dealerPosition;
}
public int getCurrentPot() {
return currentPot;
}
public void setCurrentPot(int currentPot) {
this.currentPot = currentPot;
}
public List<Card> getCurrentCards() {
return currentCards;
}
public void setCurrentCards(List<Card> currentCards) {
this.currentCards = currentCards;
}
}
//J+
| //J-
package com.whippy.poker.common.beans;
public class ClientTable {
private ClientSeat[] seats;
private int id;
private TableState state;
private int dealerPosition;
private int currentPot;
public ClientTable(ClientSeat[] seats, int id, TableState state, int dealerPosition, int currentPot) {
this.seats = seats;
this.id = id;
this.state = state;
this.dealerPosition = dealerPosition;
this.currentPot = currentPot;
}
public void setSeats(ClientSeat[] seats) {
this.seats = seats;
}
public void setId(int id) {
this.id = id;
}
public void setState(TableState state) {
this.state = state;
}
public void setDealerPosition(int dealerPosition) {
this.dealerPosition = dealerPosition;
}
public ClientTable(){
}
public ClientSeat[] getSeats() {
return seats;
}
public int getId() {
return id;
}
public TableState getState() {
return state;
}
public int getDealerPosition() {
return dealerPosition;
}
}
//J+
|
Fix query for chat messages | /* @flow */
import React, { Component, PropTypes } from 'react';
import Connect from '../../../modules/store/Connect';
import ChatMessages from '../views/ChatMessages';
import type { SubscriptionRange } from '../../../modules/store/ConnectTypes';
export default class ChatMessagesContainer extends Component<void, any, SubscriptionRange> {
state: SubscriptionRange = {
start: Infinity,
before: 20,
after: 0,
};
_loadMore: Function = (count: number) => {
this.setState({
before: count + 20,
});
};
render() {
const {
start,
before,
after
} = this.state;
return (
<Connect
mapSubscriptionToProps={{
user: {
key: {
type: 'state',
path: 'user'
},
},
texts: {
key: {
slice: {
type: 'text',
filter: {
parent_cts: [ this.props.thread ]
},
order: 'createTime'
},
range: {
start,
before,
after
}
},
}
}}
passProps={{ ...this.props, loadMore: this._loadMore }}
component={ChatMessages}
/>
);
}
}
ChatMessagesContainer.propTypes = {
thread: PropTypes.string.isRequired
};
| /* @flow */
import React, { Component, PropTypes } from 'react';
import Connect from '../../../modules/store/Connect';
import ChatMessages from '../views/ChatMessages';
import type { SubscriptionRange } from '../../../modules/store/ConnectTypes';
export default class ChatMessagesContainer extends Component<void, any, SubscriptionRange> {
state: SubscriptionRange = {
start: Infinity,
before: 20,
after: 0,
};
_loadMore: Function = (count: number) => {
this.setState({
before: count + 20,
});
};
render() {
const {
start,
before,
after
} = this.state;
return (
<Connect
mapSubscriptionToProps={{
user: {
key: {
type: 'state',
path: 'user'
},
},
texts: {
key: {
slice: {
type: 'text',
filter: {
thread: this.props.thread
},
order: 'createTime'
},
range: {
start,
before,
after
}
},
}
}}
passProps={{ ...this.props, loadMore: this._loadMore }}
component={ChatMessages}
/>
);
}
}
ChatMessagesContainer.propTypes = {
thread: PropTypes.string.isRequired
};
|
[Core] Implement twig function for variants prices map | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Provider;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Product\Model\ProductOptionValueInterface;
/**
* @author Mateusz Zalewski <[email protected]>
*/
final class ProductVariantsPricesProvider implements ProductVariantsPricesProviderInterface
{
/**
* {@inheritdoc}
*/
public function provideVariantsPrices(ProductInterface $product)
{
$variantsPrices = [];
/** @var ProductVariantInterface $variant */
foreach ($product->getVariants() as $variant) {
$variantsPrices[] = $this->constructOptionsMap($variant);
}
return $variantsPrices;
}
/**
* @param ProductVariantInterface $variant
*
* @return array
*/
private function constructOptionsMap(ProductVariantInterface $variant)
{
$optionMap = [];
/** @var ProductOptionValueInterface $option */
foreach ($variant->getOptions() as $option) {
$optionMap[$option->getOption()->getCode()] = $option->getValue();
}
$optionMap['value'] = $variant->getPrice();
return $optionMap;
}
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Core\Provider;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Product\Model\OptionValueInterface;
/**
* @author Mateusz Zalewski <[email protected]>
*/
final class ProductVariantsPricesProvider implements ProductVariantsPricesProviderInterface
{
/**
* {@inheritdoc}
*/
public function provideVariantsPrices(ProductInterface $product)
{
$variantsPrices = [];
/** @var ProductVariantInterface $variant */
foreach ($product->getVariants() as $variant) {
$variantsPrices[] = $this->constructOptionsMap($variant);
}
return $variantsPrices;
}
/**
* @param ProductVariantInterface $variant
*
* @return array
*/
private function constructOptionsMap(ProductVariantInterface $variant)
{
$optionMap = [];
/** @var OptionValueInterface $option */
foreach ($variant->getOptions() as $option) {
$optionMap[$option->getOption()->getCode()] = $option->getValue();
}
$optionMap['value'] = $variant->getPrice();
return $optionMap;
}
}
|
Remove php 5.4 array tags | <?php
namespace Payum\Core\Tests\Mocks\Model;
use Payum\Core\Exception\LogicException;
class Propel2ModelQuery
{
const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";
protected $filters = array();
protected $modelReflection;
public function __construct()
{
$this->modelReflection = new \ReflectionClass(static::MODEL_CLASS);
}
public function filterBy($column, $value)
{
if (!$this->modelReflection->hasProperty($column)) {
throw new LogicException(sprintf(
"The model doesn't have the column '%s'",
$column
));
}
$this->filters[] = array($column, $value);
return $this;
}
public function findOne()
{
$model = new Propel2Model();
$this->applyFilters($model);
return $model;
}
public function findPk($id)
{
$model = new Propel2Model();
$model->setId($id);
return $model;
}
protected function applyFilters(Propel2Model $model)
{
foreach ($this->filters as $filter) {
$propriety = new \ReflectionProperty(static::MODEL_CLASS, $filter[0]);
$propriety->setAccessible(true);
$propriety->setValue($model, $filter[1]);
}
}
}
| <?php
namespace Payum\Core\Tests\Mocks\Model;
use Payum\Core\Exception\LogicException;
class Propel2ModelQuery
{
const MODEL_CLASS = "Payum\\Core\\Tests\\Mocks\\Model\\Propel2Model";
protected $filters = array();
protected $modelReflection;
public function __construct()
{
$this->modelReflection = new \ReflectionClass(static::MODEL_CLASS);
}
public function filterBy($column, $value)
{
if (!$this->modelReflection->hasProperty($column)) {
throw new LogicException(sprintf(
"The model doesn't have the column '%s'",
$column
));
}
$this->filters[] = [$column, $value];
return $this;
}
public function findOne()
{
$model = new Propel2Model();
$this->applyFilters($model);
return $model;
}
public function findPk($id)
{
$model = new Propel2Model();
$model->setId($id);
return $model;
}
protected function applyFilters(Propel2Model $model)
{
foreach ($this->filters as $filter) {
$propriety = new \ReflectionProperty(static::MODEL_CLASS, $filter[0]);
$propriety->setAccessible(true);
$propriety->setValue($model, $filter[1]);
}
}
}
|
Fix return code when running unittests. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test runner for sqlparse."""
import optparse
import os
import sys
import unittest
test_mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if test_mod not in sys.path:
sys.path.insert(1, test_mod)
parser = optparse.OptionParser()
parser.add_option('-P', '--profile',
help='Create hotshot profile.',
action='store_true', default=False)
def main(args):
"""Create a TestSuite and run it."""
loader = unittest.TestLoader()
suite = unittest.TestSuite()
fnames = [os.path.split(f)[-1] for f in args]
for fname in os.listdir(os.path.dirname(__file__)):
if (not fname.startswith('test_') or not fname.endswith('.py')
or (fnames and fname not in fnames)):
continue
modname = os.path.splitext(fname)[0]
mod = __import__(os.path.splitext(fname)[0])
suite.addTests(loader.loadTestsFromModule(mod))
return unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
opts, args = parser.parse_args()
if opts.profile:
import hotshot
prof = hotshot.Profile("sqlparse.prof")
prof.runcall(main, args)
prof.close()
else:
result = main(args)
if not result.wasSuccessful():
return_code = 1
else:
return_code = 0
sys.exit(return_code)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test runner for sqlparse."""
import optparse
import os
import sys
import unittest
test_mod = os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))
if test_mod not in sys.path:
sys.path.insert(1, test_mod)
parser = optparse.OptionParser()
parser.add_option('-P', '--profile',
help='Create hotshot profile.',
action='store_true', default=False)
def main(args):
"""Create a TestSuite and run it."""
loader = unittest.TestLoader()
suite = unittest.TestSuite()
fnames = [os.path.split(f)[-1] for f in args]
for fname in os.listdir(os.path.dirname(__file__)):
if (not fname.startswith('test_') or not fname.endswith('.py')
or (fnames and fname not in fnames)):
continue
modname = os.path.splitext(fname)[0]
mod = __import__(os.path.splitext(fname)[0])
suite.addTests(loader.loadTestsFromModule(mod))
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
opts, args = parser.parse_args()
if opts.profile:
import hotshot
prof = hotshot.Profile("sqlparse.prof")
prof.runcall(main, args)
prof.close()
else:
main(args)
|
Change display of returned time | var Reader = (function () {
/*
* Gets an DOM element and anaylzes it's textual reading content.
* Returns the estimated time to read in seconds.
*/
function calculateTimeToRead(element) {
var content = jQuery(element).text(),
sentences = content.split('. '),
i,
time = 0;
for (i = 0; i < sentences.length; i++) {
// Each sentence assumed to be read in 7 seconds. Basic calc.
time += 7;
}
return time;
}
var self = {
/*
* Estimates time to read the text inside given DOM elements selector.
* Returns time in minutes.
*/
estimate: function estimate(selector) {
var elements = jQuery(selector),
i,
totalTime = 0;
for (i = 0; i < elements.length; i++) {
var currentEl = elements[i],
time = calculateTimeToRead(currentEl);
totalTime += time;
}
// Turn into minutes
totalTime /= 60;
return totalTime > 1 ? totalTime : Math.round(totalTime);
}
};
return self;
})(); | var Reader = (function () {
/*
* Gets an DOM element and anaylzes it's textual reading content.
* Returns the estimated time to read in seconds.
*/
function calculateTimeToRead(element) {
var content = jQuery(element).text(),
sentences = content.split('. '),
i,
time = 0;
for (i = 0; i < sentences.length; i++) {
// Each sentence assumed to be read in 7 seconds. Basic calc.
time += 7;
}
return time;
}
var self = {
/*
* Estimates time to read the text inside given DOM elements selector.
* Returns time in minutes.
*/
estimate: function estimate(selector) {
var elements = jQuery(selector),
i,
totalTime = 0;
for (i = 0; i < elements.length; i++) {
var currentEl = elements[i],
time = calculateTimeToRead(currentEl);
totalTime += time;
}
return totalTime / 60;
}
};
return self;
})(); |
Add utf decode for reading data | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import threading
import websocket
from polyaxon_client.logger import logger
from polyaxon_client.workers.socket_worker import SocketWorker
class SocketTransportMixin(object):
"""Socket operations transport."""
def socket(self, url, message_handler, headers=None):
webs = websocket.WebSocketApp(
url,
on_message=lambda ws, message: self._on_message(message_handler, message),
on_error=self._on_error,
on_close=self._on_close,
header=self._get_headers(headers)
)
return webs
def stream(self, url, message_handler, headers=None):
webs = self.socket(url=url, message_handler=message_handler, headers=headers)
webs.run_forever(ping_interval=30, ping_timeout=10)
def _on_message(self, message_handler, message):
if message_handler and message:
message_handler(json.loads(message).decode('utf-8'))
@staticmethod
def _on_error(ws, error):
if isinstance(error, (KeyboardInterrupt, SystemExit)):
logger.info('Quitting... The session will be running in the background.')
else:
logger.debug('Termination cause: %s', error)
logger.debug('Session disconnected.')
@staticmethod
def _on_close(ws):
logger.info('Session ended')
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import websocket
from polyaxon_client.logger import logger
class SocketTransportMixin(object):
"""Socket operations transport."""
def socket(self, url, message_handler, headers=None):
webs = websocket.WebSocketApp(
url,
on_message=lambda ws, message: self._on_message(message_handler, message),
on_error=self._on_error,
on_close=self._on_close,
header=self._get_headers(headers)
)
return webs
def stream(self, url, message_handler, headers=None):
webs = self.socket(url=url, message_handler=message_handler, headers=headers)
webs.run_forever(ping_interval=30, ping_timeout=10)
def _on_message(self, message_handler, message):
if message_handler and message:
message_handler(json.loads(message))
@staticmethod
def _on_error(ws, error):
if isinstance(error, (KeyboardInterrupt, SystemExit)):
logger.info('Quitting... The session will be running in the background.')
else:
logger.debug('Termination cause: %s', error)
logger.debug('Session disconnected.')
@staticmethod
def _on_close(ws):
logger.info('Session ended')
|
Change "Unread messages." to "Jump to first unread message."
Also get rid of the "up" arrow so as not to indiciate direction. This is important because in future the RM will not be based on what has been paginated into the client (but instead RM will be handled server-side) and thus we cannot assert any kind of direction on it relative to the events in the viewport. | /*
Copyright 2016 OpenMarket Ltd
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.
*/
'use strict';
var React = require('react');
var sdk = require('../../../index');
module.exports = React.createClass({
displayName: 'TopUnreadMessagesBar',
propTypes: {
onScrollUpClick: React.PropTypes.func,
onCloseClick: React.PropTypes.func,
},
render: function() {
return (
<div className="mx_TopUnreadMessagesBar">
<div className="mx_TopUnreadMessagesBar_scrollUp"
onClick={this.props.onScrollUpClick}>
Jump to first unread message. <span style={{ textDecoration: 'underline' }} onClick={this.props.onCloseClick}>Mark all read</span>
</div>
<img className="mx_TopUnreadMessagesBar_close"
src="img/cancel.svg" width="18" height="18"
alt="Close" title="Close"
onClick={this.props.onCloseClick} />
</div>
);
},
});
| /*
Copyright 2016 OpenMarket Ltd
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.
*/
'use strict';
var React = require('react');
var sdk = require('../../../index');
module.exports = React.createClass({
displayName: 'TopUnreadMessagesBar',
propTypes: {
onScrollUpClick: React.PropTypes.func,
onCloseClick: React.PropTypes.func,
},
render: function() {
return (
<div className="mx_TopUnreadMessagesBar">
<div className="mx_TopUnreadMessagesBar_scrollUp"
onClick={this.props.onScrollUpClick}>
<img src="img/scrollup.svg" width="24" height="24"
alt="Scroll to unread messages"
title="Scroll to unread messages"/>
Unread messages. <span style={{ textDecoration: 'underline' }} onClick={this.props.onCloseClick}>Mark all read</span>
</div>
<img className="mx_TopUnreadMessagesBar_close"
src="img/cancel.svg" width="18" height="18"
alt="Close" title="Close"
onClick={this.props.onCloseClick} />
</div>
);
},
});
|
Extend mocking to run validation | from django.conf import settings
from mock import Mock, patch
from unittest2 import TestCase
settings.configure()
# Need to import this after configure()
from django.db.models import ForeignKey
class TestPreference(object):
_meta = Mock(fields=[ForeignKey('user', name='user')])
objects = Mock()
def __init__(self, name, value, user=None):
self.name = name
self.value = value
self.user = user
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return '<{name}:{value}:{user}>'.format(**self.__dict__)
def __cmp__(self, other):
return cmp(self.name, other.name)
class TestUser(object):
@property
def preferences(self):
return Mock(all=Mock(return_value=self._preferences))
@preferences.setter
def preferences(self, value):
self._preferences = [
TestPreference(k, v) for k, v in value.iteritems()]
class SerializerTestCase(TestCase):
def patch_from_native(self):
def from_native(self, data, files):
self._errors = {}
if data:
self.perform_validation(data)
return TestPreference(data['name'], data['value'],
data.get('user'))
patcher = patch(
'madprops.serializers.ModelSerializer.from_native',
new=from_native)
self.patched_from_native = patcher.start()
self.addCleanup(patcher.stop)
# get_fields inspects the model's _meta, deeply
patcher = patch(
'madprops.serializers.ModelSerializer.get_fields',
new=lambda self: {})
self.patched_get_fields = patcher.start()
self.addCleanup(patcher.stop)
| from django.conf import settings
from mock import Mock, patch
from unittest2 import TestCase
settings.configure()
# Need to import this after configure()
from django.db.models import ForeignKey
class TestPreference(object):
_meta = Mock(fields=[ForeignKey('user', name='user')])
objects = Mock()
def __init__(self, name, value, user=None):
self.name = name
self.value = value
self.user = user
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return '<{name}:{value}:{user}>'.format(**self.__dict__)
def __cmp__(self, other):
return cmp(self.name, other.name)
class TestUser(object):
@property
def preferences(self):
return Mock(all=Mock(return_value=self._preferences))
@preferences.setter
def preferences(self, value):
self._preferences = [
TestPreference(k, v) for k, v in value.iteritems()]
class SerializerTestCase(TestCase):
def patch_from_native(self):
patcher = patch(
'madprops.serializers.ModelSerializer.from_native',
new=lambda self, data, files: TestPreference(
data['name'], data['value'], data.get('user'))
)
self.patched_from_native = patcher.start()
self.addCleanup(patcher.stop)
|
Use secure url for cloudinary | var path = require('path'),
config;
config = {
production: {
url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/',
mail: {},
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
pool: { min: 0, max: 5 }
},
server: {
host: '0.0.0.0',
port: process.env.PORT
},
storage: {
active: 'ghost-cloudinary-store',
'ghost-cloudinary-store': {
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true
}
},
paths:{
contentPath: path.join(__dirname, '/content/')
}
},
development: {
url: 'http://localhost:2368',
mail: {},
fileStorage: true,
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
host: '0.0.0.0',
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
}
};
module.exports = config;
| var path = require('path'),
config;
config = {
production: {
url: process.env.BASE_URL || 'http://blog.ertrzyiks.pl/',
mail: {},
database: {
client: 'postgres',
connection: process.env.DATABASE_URL,
pool: { min: 0, max: 5 }
},
server: {
host: '0.0.0.0',
port: process.env.PORT
},
storage: {
active: 'ghost-cloudinary-store',
'ghost-cloudinary-store': {
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
}
},
paths:{
contentPath: path.join(__dirname, '/content/')
}
},
development: {
url: 'http://localhost:2368',
mail: {},
fileStorage: true,
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-dev.db')
},
debug: false
},
server: {
host: '0.0.0.0',
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '/content/')
}
}
};
module.exports = config;
|
Fix plural form of todo when there are no todos | import React from 'react';
import TodoItem from './TodoItem';
export default class extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onAddTodo}>Add Todo</button>
<ul>
<For each="item" of={this.props.todos}>
<TodoItem
key={item.id}
id={item.id}
value={item.value}
completed={item.completed}
onEdit={this.props.onEditTodo}
onDelete={this.props.onDeleteTodo}
onSubmit={this.props.onAddTodo}
/>
</For>
</ul>
<span>
{this.props.todos.length}{' '}
todo{this.props.todos.length === 1 ? '' : 's'}
</span>
<style jsx>{`
ul {
list-style: none;
padding-left: 0;
}
`}</style>
</div>
);
}
}
| import React from 'react';
import TodoItem from './TodoItem';
export default class extends React.Component {
render() {
return (
<div>
<button onClick={this.props.onAddTodo}>Add Todo</button>
<ul>
<For each="item" of={this.props.todos}>
<TodoItem
key={item.id}
id={item.id}
value={item.value}
completed={item.completed}
onEdit={this.props.onEditTodo}
onDelete={this.props.onDeleteTodo}
onSubmit={this.props.onAddTodo}
/>
</For>
</ul>
<span>
{this.props.todos.length}{' '}
todo{this.props.todos.length > 1 ? 's' : ''}
</span>
<style jsx>{`
ul {
list-style: none;
padding-left: 0;
}
`}</style>
</div>
);
}
}
|
Handle None axis_labels in ToBytes. | """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
axis_labels = (stream.axis_labels
if stream.axis_labels is not None
else {})
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
| """Commonly-used default transformers."""
from fuel.transformers import ScaleAndShift, Cast, SourcewiseTransformer
from fuel.transformers.image import ImagesFromBytes
def uint8_pixels_to_floatX(which_sources):
return (
(ScaleAndShift, [1 / 255.0, 0], {'which_sources': which_sources}),
(Cast, ['floatX'], {'which_sources': which_sources}))
class ToBytes(SourcewiseTransformer):
"""Transform a stream of ndarray examples to bytes.
Notes
-----
Used for retrieving variable-length byte data stored as, e.g. a uint8
ragged array.
"""
def __init__(self, stream, **kwargs):
kwargs.setdefault('produces_examples', stream.produces_examples)
axis_labels = stream.axis_labels
for source in kwargs.get('which_sources', stream.sources):
axis_labels[source] = (('batch', 'bytes')
if 'batch' in axis_labels.get(source, ())
else ('bytes',))
kwargs.setdefault('axis_labels', axis_labels)
super(ToBytes, self).__init__(stream, **kwargs)
def transform_source_example(self, example, _):
return example.tostring()
def transform_source_batch(self, batch, _):
return [example.tostring() for example in batch]
def rgb_images_from_encoded_bytes(which_sources):
return ((ToBytes, [], {'which_sources': ('encoded_images',)}),
(ImagesFromBytes, [], {'which_sources': ('encoded_images',)}))
|
Fix OpenFlow packets getting stuffed with \0 bytes. | package eu.netide.lib.netip;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Class representing a message of type OPENFLOW.
* Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
*/
public class OpenFlowMessage extends Message {
private OFMessage ofMessage;
/**
* Instantiates a new Open flow message.
*/
public OpenFlowMessage() {
super(new MessageHeader(), new byte[0]);
header.setMessageType(MessageType.OPENFLOW);
}
/**
* Gets of message.
*
* @return the of message
*/
public OFMessage getOfMessage() {
return ofMessage;
}
/**
* Sets of message.
*
* @param ofMessage the of message
*/
public void setOfMessage(OFMessage ofMessage) {
this.ofMessage = ofMessage;
}
@Override
public byte[] getPayload() {
ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
ofMessage.writeTo(dcb);
this.payload = new byte[dcb.readableBytes()];
dcb.readBytes(this.payload, 0, this.payload.length);
return this.payload;
}
@Override
public String toString() {
return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
}
}
| package eu.netide.lib.netip;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Class representing a message of type OPENFLOW.
* Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
*/
public class OpenFlowMessage extends Message {
private OFMessage ofMessage;
/**
* Instantiates a new Open flow message.
*/
public OpenFlowMessage() {
super(new MessageHeader(), new byte[0]);
header.setMessageType(MessageType.OPENFLOW);
}
/**
* Gets of message.
*
* @return the of message
*/
public OFMessage getOfMessage() {
return ofMessage;
}
/**
* Sets of message.
*
* @param ofMessage the of message
*/
public void setOfMessage(OFMessage ofMessage) {
this.ofMessage = ofMessage;
}
@Override
public byte[] getPayload() {
ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
ofMessage.writeTo(dcb);
this.payload = dcb.array();
return this.payload;
}
@Override
public String toString() {
return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
}
}
|
Update phpdoc constructor parameter can't be null | <?php
namespace SumoCoders\FrameworkMultiUserBundle\Security;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordResetTokenException;
use SumoCoders\FrameworkMultiUserBundle\User\UserInterface;
class PasswordResetToken
{
/**
* @var string
*/
private $token;
/**
* PasswordResetToken constructor.
*
* @param string $token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
* @param UserInterface $user
* @param $token
*
* @throws InvalidPasswordResetTokenException
*
* @return bool
*/
public static function validateToken(UserInterface $user, PasswordResetToken $token)
{
if ($user->getPasswordResetToken()->equals($token)) {
return true;
}
throw new InvalidPasswordResetTokenException('The given token is not valid.');
}
/**
* Generates a PasswordToken
*
* @return PasswordResetToken
*/
public static function generate()
{
$token = time() . base64_encode(random_bytes(10));
return new self($token);
}
/**
* Check if a token is equal to a different token.
*
* @param PasswordResetToken $token
*
* @return bool
*/
public function equals(PasswordResetToken $token)
{
return $token->token === $this->token;
}
}
| <?php
namespace SumoCoders\FrameworkMultiUserBundle\Security;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordResetTokenException;
use SumoCoders\FrameworkMultiUserBundle\User\UserInterface;
class PasswordResetToken
{
/**
* @var string
*/
private $token;
/**
* PasswordResetToken constructor.
*
* @param string|null $token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
* @param UserInterface $user
* @param $token
*
* @throws InvalidPasswordResetTokenException
*
* @return bool
*/
public static function validateToken(UserInterface $user, PasswordResetToken $token)
{
if ($user->getPasswordResetToken()->equals($token)) {
return true;
}
throw new InvalidPasswordResetTokenException('The given token is not valid.');
}
/**
* Generates a PasswordToken
*
* @return PasswordResetToken
*/
public static function generate()
{
$token = time() . base64_encode(random_bytes(10));
return new self($token);
}
/**
* Check if a token is equal to a different token.
*
* @param PasswordResetToken $token
*
* @return bool
*/
public function equals(PasswordResetToken $token)
{
return $token->token === $this->token;
}
}
|
Add some detail text to assertion. | import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version, "A valid version string is required"
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog)
self.parser.add_argument(
'--version', action='version', version=self.version, help="Print version and exit.")
self.parser.add_argument(
'--quiet', action="store_true", help="Suppress logging output.")
self.parser.add_argument(
'--debug', action="store_true", help="Enable debug logging output.")
self.parser.add_argument(
'--host', metavar='<fqhn>', help="Optional fully qualified host name to connect to.")
self.parser.add_argument(
'--config-file', metavar='<file>', help="Optional path to a configuration file.")
self.parser.add_argument(
'--credential-file', metavar='<file>', help="Optional path to a credential file.")
def remove_options(self, options):
for option in options:
for action in self.parser._actions:
if vars(action)['option_strings'][0] == option:
self.parser._handle_conflict_resolve(None, [(option, action)])
break
def parse_cli(self):
args = self.parser.parse_args()
init_logging(level=logging.ERROR if args.quiet else (logging.DEBUG if args.debug else logging.INFO))
return args
| import argparse
import logging
from . import init_logging
class BaseCLI(object):
def __init__(self, description, epilog, version=None):
assert version
self.version = version
self.parser = argparse.ArgumentParser(description=description, epilog=epilog)
self.parser.add_argument(
'--version', action='version', version=self.version, help="Print version and exit.")
self.parser.add_argument(
'--quiet', action="store_true", help="Suppress logging output.")
self.parser.add_argument(
'--debug', action="store_true", help="Enable debug logging output.")
self.parser.add_argument(
'--host', metavar='<fqhn>', help="Optional fully qualified host name to connect to.")
self.parser.add_argument(
'--config-file', metavar='<file>', help="Optional path to a configuration file.")
self.parser.add_argument(
'--credential-file', metavar='<file>', help="Optional path to a credential file.")
def remove_options(self, options):
for option in options:
for action in self.parser._actions:
if vars(action)['option_strings'][0] == option:
self.parser._handle_conflict_resolve(None, [(option, action)])
break
def parse_cli(self):
args = self.parser.parse_args()
init_logging(level=logging.ERROR if args.quiet else (logging.DEBUG if args.debug else logging.INFO))
return args
|
Add error callback to geoloc | class HomeCtrl {
constructor(AppConstants, NetworkRequests, $localStorage, $timeout) {
'ngInject';
this._NetworkRequests = NetworkRequests;
this._storage = $localStorage;
this.appName = AppConstants.appName;
// Detect recommended browsers
let isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
let isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
let isFirefox = /Firefox/.test(navigator.userAgent);
// If no recommended browser used, open modal
if(!isChrome && !isSafari && !isFirefox) {
$('#noSupportModal').modal({
backdrop: 'static',
keyboard: false
});
}
// Get position and closest nodes if no mainnet node in local storage
if (navigator.geolocation && !this._storage.selectedMainnetNode) {
// Get position
navigator.geolocation.getCurrentPosition((res) => {
// Get the closest nodes
this._NetworkRequests.getNearestNodes(res.coords).then((res) => {
// Pick a random node in the array
let node = res.data[Math.floor(Math.random()*res.data.length)];
// Set the node in local storage
this._storage.selectedMainnetNode = 'http://'+node.ip+':7778';
}, (err) => {
// If error it will use default node
console.log(err)
});
}, (err) => {
// If error it will use default node
console.log(err)
});
}
}
}
export default HomeCtrl; | class HomeCtrl {
constructor(AppConstants, NetworkRequests, $localStorage) {
'ngInject';
this._NetworkRequests = NetworkRequests;
this._storage = $localStorage;
this.appName = AppConstants.appName;
// Detect recommended browsers
let isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
let isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
let isFirefox = /Firefox/.test(navigator.userAgent);
// If no recommended browser used, open modal
if(!isChrome && !isSafari && !isFirefox) {
$('#noSupportModal').modal({
backdrop: 'static',
keyboard: false
});
}
// Get position and closest nodes if no mainnet node in local storage
if (navigator.geolocation && !this._storage.selectedMainnetNode) {
// Get position
navigator.geolocation.getCurrentPosition((res) => {
// Get the closest nodes
this._NetworkRequests.getNearestNodes(res.coords).then((res) => {
// Pick a random node in the array
let node = res.data[Math.floor(Math.random()*res.data.length)];
// Set the node in local storage
this._storage.selectedMainnetNode = 'http://'+node.ip+':7778';
}, (err) => {
// If error it will use default node
console.log(err)
});
});
}
}
}
export default HomeCtrl;
|
Remove specific SASS cache directory | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
style: 'expanded',
sourcemap: 'auto'
},
files: {
'assets/css/boostrap.css': 'assets/sass/boostrap.scss'
},
}
},
cssmin: {
target: {
files: [{
expand: true,
cwd: 'assets/css',
src: ['*.css', '!*.min.css'],
dest: 'assets/css',
ext: '.min.css'
}]
}
},
watch: {
css: {
files: 'assets/sass/**/*.scss',
tasks: ['sass', 'cssmin']
}
}
});
// Load the plugins.
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-watch');
// Tasks.
grunt.registerTask('default', ['sass', 'cssmin', 'watch']);
grunt.registerTask('build', ['sass', 'cssmin']);
grunt.registerTask('watcher', ['watch']);
}; | module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
sass: {
dist: {
options: {
style: 'expanded',
sourcemap: 'auto',
cacheLocation: 'sass/.sass-cache'
},
files: {
'assets/css/boostrap.css': 'assets/sass/boostrap.scss'
},
}
},
cssmin: {
target: {
files: [{
expand: true,
cwd: 'assets/css',
src: ['*.css', '!*.min.css'],
dest: 'assets/css',
ext: '.min.css'
}]
}
},
watch: {
css: {
files: 'assets/sass/**/*.scss',
tasks: ['sass', 'cssmin']
}
}
});
// Load the plugins.
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-watch');
// Tasks.
grunt.registerTask('default', ['sass', 'cssmin', 'watch']);
grunt.registerTask('build', ['sass', 'cssmin']);
grunt.registerTask('watcher', ['watch']);
}; |
Handle error responses as well
Does require including $q to do the promise rejection. | (function() {
'use strict';
var handle_phpdebugbar_response = function(response) {
if (phpdebugbar && phpdebugbar.ajaxHandler) {
// We have a debugbar and an ajaxHandler
// Dig through response to look for the
// debugbar id.
var headers = response && response.headers && response.headers();
if (!headers) {
return;
}
// Not very elegant, but this is how the debugbar.js defines the header.
var headerName = phpdebugbar.ajaxHandler.headerName + '-id';
var debugBarID = headers[headerName];
if (debugBarID) {
// A debugBarID was found! Now we just pass the
// id to the debugbar to load the data
phpdebugbar.loadDataSet(debugBarID, ('ajax'));
}
}
};
angular.module('ng-phpdebugbar', [])
.factory('phpDebugBarInterceptor', function($q) {
return {
'request': function(config) {
// This is the header that debugbar looks for that triggers
// the debugbarid to be returned in the response headers.
config.headers['X-Requested-With'] = 'XMLHttpRequest';
return config;
},
'response': function(response) {
handle_phpdebugbar_response(response);
return response;
},
'responseError': function(rejection) {
handle_phpdebugbar_response(response);
return $q.reject(rejection);
},
};
})
.config(['$httpProvider',
function($httpProvider) {
// Adds our debug interceptor to all $http requests
$httpProvider.interceptors.push('phpDebugBarInterceptor');
}
]);
})();
| (function() {
'use strict';
var getDebugBarID = function(response) {
var headers = response && response.headers && response.headers();
if (!headers) {
// Something terrible happened. Bail.
return;
}
// Not very elegant, but this is how the debugbar.js defines the header.
var headerName = phpdebugbar.ajaxHandler.headerName + '-id';
return headers[headerName];
};
angular.module('ng-phpdebugbar', [])
.factory('phpDebugBarInterceptor', function() {
return {
'request': function(config) {
// This is the header that debugbar looks for that triggers
// the debugbarid to be returned in the response headers.
config.headers['X-Requested-With'] = 'XMLHttpRequest';
return config;
},
'response': function(response) {
if (phpdebugbar && phpdebugbar.ajaxHandler) {
// We have a debugbar and an ajaxHandler
// Dig through response to look for the
// debugbar id.
var debugBarID = getDebugBarID(response);
if (debugBarID) {
// A debugBarID was found! Now we just pass the
// id to the debugbar to load the data
phpdebugbar.loadDataSet(debugBarID, ('ajax'));
}
}
return response;
}
};
})
.config(['$httpProvider',
function($httpProvider) {
// Adds our debug interceptor to all $http requests
$httpProvider.interceptors.push('phpDebugBarInterceptor');
}
]);
})(); |
Disable REST Upload by default | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
if context.config.UPLOAD_ENABLED:
# TODO Old handler to upload images
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
| #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]
import tornado.web
import tornado.ioloop
from thumbor.handlers.healthcheck import HealthcheckHandler
from thumbor.handlers.upload import UploadHandler
from thumbor.handlers.images import ImagesHandler
from thumbor.handlers.image import ImageHandler
from thumbor.url import Url
from thumbor.handlers.imaging import ImagingHandler
class ThumborServiceApp(tornado.web.Application):
def __init__(self, context):
self.context = context
handlers = [
(r'/healthcheck', HealthcheckHandler),
]
# TODO Old handler to upload images
if context.config.UPLOAD_ENABLED:
handlers.append(
(r'/upload', UploadHandler, { 'context': context })
)
# Handler to upload images (POST).
handlers.append(
(r'/image', ImagesHandler, { 'context': context })
)
# Handler to retrieve or modify existing images (GET, PUT, DELETE)
handlers.append(
(r'/image/(.*)', ImageHandler, { 'context': context })
)
# Imaging handler (GET)
handlers.append(
(Url.regex(), ImagingHandler, { 'context': context })
)
super(ThumborServiceApp, self).__init__(handlers)
|
Use \Page instead of Concrete\Core\Page\Page
Former-commit-id: 5f27527c65b9ed3815ca1a37eef8d3e6dccee225
Former-commit-id: 5b239b1afa020bcaebcb90fa58cc461a91098c82 | <?php
namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty;
use Core;
use UserInfo;
use Page;
class UserCorePageProperty extends CorePageProperty
{
public function __construct()
{
$this->setCorePagePropertyHandle('user');
$this->setPageTypeComposerControlName(tc('PageTypeComposerControlName', 'User'));
$this->setPageTypeComposerControlIconSRC(ASSETS_URL . '/attributes/text/icon.png');
}
public function publishToPage(Page $c, $data, $controls)
{
if (Core::make('helper/validation/numbers')->integer($data['user'])) {
$this->addPageTypeComposerControlRequestValue('uID', $data['user']);
}
parent::publishToPage($c, $data, $controls);
}
public function validate()
{
$uID = $this->getPageTypeComposerControlDraftValue();
$ux = UserInfo::getByID($uID);
$e = Core::make('helper/validation/error');
if (!is_object($ux)) {
$control = $this->getPageTypeComposerFormLayoutSetControlObject();
$e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlLabel()));
return $e;
}
}
public function getPageTypeComposerControlDraftValue()
{
if (is_object($this->page)) {
$c = $this->page;
return $c->getCollectionUserID();
}
}
}
| <?php
namespace Concrete\Core\Page\Type\Composer\Control\CorePageProperty;
use Core;
use UserInfo;
use Concrete\Core\Page\Page;
class UserCorePageProperty extends CorePageProperty
{
public function __construct()
{
$this->setCorePagePropertyHandle('user');
$this->setPageTypeComposerControlName(tc('PageTypeComposerControlName', 'User'));
$this->setPageTypeComposerControlIconSRC(ASSETS_URL . '/attributes/text/icon.png');
}
public function publishToPage(Page $c, $data, $controls)
{
if (Core::make('helper/validation/numbers')->integer($data['user'])) {
$this->addPageTypeComposerControlRequestValue('uID', $data['user']);
}
parent::publishToPage($c, $data, $controls);
}
public function validate()
{
$uID = $this->getPageTypeComposerControlDraftValue();
$ux = UserInfo::getByID($uID);
$e = Core::make('helper/validation/error');
if (!is_object($ux)) {
$control = $this->getPageTypeComposerFormLayoutSetControlObject();
$e->add(t('You haven\'t chosen a valid %s', $control->getPageTypeComposerControlLabel()));
return $e;
}
}
public function getPageTypeComposerControlDraftValue()
{
if (is_object($this->page)) {
$c = $this->page;
return $c->getCollectionUserID();
}
}
}
|
Move DB Str import to single line so it can be completely cleaned up on site generation | <?php
return [
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
/*
|--------------------------------------------------------------------------
| Cache storage
|--------------------------------------------------------------------------
|
| The cache storage will use database 1 as to not conflict with
| PHPREDIS_SESSION's being set.
|
*/
'client' => 'predis',
'default' => [
'database' => 1,
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
],
'sessions' => [
'database' => 0,
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
],
/*
|--------------------------------------------------------------------------
| Redis prefix
|--------------------------------------------------------------------------
|
| The prefix is used to easily identify data in the database. Running
| php artisan cache:clear however will clear ALL cache for the
| default Redis database 1.
|
*/
'options' => [
'prefix' => Illuminate\Support\Str::slug(env('APP_NAME', 'laravel')).':',
],
],
];
| <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
/*
|--------------------------------------------------------------------------
| Cache storage
|--------------------------------------------------------------------------
|
| The cache storage will use database 1 as to not conflict with
| PHPREDIS_SESSION's being set.
|
*/
'client' => 'predis',
'default' => [
'database' => 1,
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
],
'sessions' => [
'database' => 0,
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
],
/*
|--------------------------------------------------------------------------
| Redis prefix
|--------------------------------------------------------------------------
|
| The prefix is used to easily identify data in the database. Running
| php artisan cache:clear however will clear ALL cache for the
| default Redis database 1.
|
*/
'options' => [
'prefix' => Str::slug(env('APP_NAME', 'laravel')).':',
],
],
];
|
Save buffered image as bmp | // Get JAFFE database from http://www.kasrl.org/jaffe_info.html
// Extract pics in folder named "jaffe"
// package image_test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class svq {
public static void main(String[] args) {
// read image
BufferedImage input = null;
try {
input = ImageIO.read(new File("jaffe/KA.AN1.39.tiff.bmp"));
} catch (IOException e) {
throw new RuntimeException(e);
}
// to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write( input, "bmp", baos );
baos.flush();
} catch (IOException e) {
}
byte[] bytearray = baos.toByteArray();
// to BufferedImage
ByteArrayInputStream bais = new ByteArrayInputStream(bytearray);
BufferedImage output = null;
try {
output = ImageIO.read(bais);
bais.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// save result
try {
ImageIO.write(output, "BMP", new File("test.bmp"));
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Done!");
}
} | // Get JAFFE database from http://www.kasrl.org/jaffe_info.html
// Extract pics in folder named "jaffe"
// package image_test;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class svq {
public static void main(String[] args) {
// read image
BufferedImage input = null;
try {
input = ImageIO.read(new File("jaffe/KA.AN1.39.tiff.bmp"));
} catch (IOException e) {
throw new RuntimeException(e);
}
// to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write( input, "bmp", baos );
baos.flush();
} catch (IOException e) {
}
byte[] bytearray = baos.toByteArray();
// to BufferedImage
ByteArrayInputStream bais = new ByteArrayInputStream(bytearray);
BufferedImage output = null;
try {
output = ImageIO.read(bais);
bais.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("Done!");
}
} |
Replace thriftpy dependency with thriftpy2 | """setup.py - build script for parquet-python."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='parquet',
version='1.2',
description='Python support for Parquet file format',
author='Joe Crobak',
author_email='[email protected]',
url='https://github.com/jcrobak/parquet-python',
license='Apache License 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
packages=['parquet'],
install_requires=[
'python-snappy',
'thriftpy2',
],
extras_require={
':python_version=="2.7"': [
"backports.csv",
],
},
entry_points={
'console_scripts': [
'parquet = parquet.__main__:main',
]
},
package_data={'parquet': ['*.thrift']},
include_package_data=True,
)
| """setup.py - build script for parquet-python."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='parquet',
version='1.2',
description='Python support for Parquet file format',
author='Joe Crobak',
author_email='[email protected]',
url='https://github.com/jcrobak/parquet-python',
license='Apache License 2.0',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
packages=['parquet'],
install_requires=[
'python-snappy',
'thriftpy>=0.3.6',
],
extras_require={
':python_version=="2.7"': [
"backports.csv",
],
},
entry_points={
'console_scripts': [
'parquet = parquet.__main__:main',
]
},
package_data={'parquet': ['*.thrift']},
include_package_data=True,
)
|
Add DRF as a dev dependency | import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'cas': [
'django-cas-client>=1.2.0',
],
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'djangorestframework>3.3',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| import sys
from setuptools import find_packages, setup
VERSION = '2.0.dev0'
install_requires = [
'django-local-settings>=1.0a10',
'stashward',
]
if sys.version_info[:2] < (3, 4):
install_requires.append('enum34')
setup(
name='django-arcutils',
version=VERSION,
url='https://github.com/PSU-OIT-ARC/django-arcutils',
author='PSU - OIT - ARC',
author_email='[email protected]',
description='Common utilities used in ARC Django projects',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
extras_require={
'cas': [
'django-cas-client>=1.2.0',
],
'ldap': [
'certifi>=2015.11.20.1',
'ldap3>=1.0.3',
],
'dev': [
'django>=1.7,<1.9',
'flake8',
'ldap3',
'mock',
'model_mommy',
],
},
entry_points="""
[console_scripts]
arcutils = arcutils.__main__:main
""",
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Correct path in South triple definition. | from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return 'IntegerField'
def to_python(self, value):
return self.enumeration.to_item(value)
def get_db_prep_save(self, value, connection=None):
if value is None:
return value
return self.to_python(value).value
def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=False):
def prepare(value):
v = self.to_python(value)
return self.get_db_prep_save(v, connection=connection)
if lookup_type in ('exact', 'lt', 'lte', 'gt', 'gte'):
return [prepare(value)]
elif lookup_type == 'in':
return [prepare(v) for v in value]
elif lookup_type == 'isnull':
return []
raise TypeError("Lookup type %r not supported." % lookup_type)
def south_field_triple(self):
from south.modelsinspector import introspector
args, kwargs = introspector(self)
return ('django.db.models.fields.IntegerField', args, kwargs)
| from django.db import models
class EnumField(models.Field):
__metaclass__ = models.SubfieldBase
def __init__(self, enumeration, *args, **kwargs):
self.enumeration = enumeration
kwargs.setdefault('choices', enumeration.get_choices())
super(EnumField, self).__init__(*args, **kwargs)
def get_internal_type(self):
return 'IntegerField'
def to_python(self, value):
return self.enumeration.to_item(value)
def get_db_prep_save(self, value, connection=None):
if value is None:
return value
return self.to_python(value).value
def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=False):
def prepare(value):
v = self.to_python(value)
return self.get_db_prep_save(v, connection=connection)
if lookup_type in ('exact', 'lt', 'lte', 'gt', 'gte'):
return [prepare(value)]
elif lookup_type == 'in':
return [prepare(v) for v in value]
elif lookup_type == 'isnull':
return []
raise TypeError("Lookup type %r not supported." % lookup_type)
def south_field_triple(self):
from south.modelsinspector import introspector
args, kwargs = introspector(self)
return ('django.db.models.fields.Integerfield', args, kwargs)
|
Make the envelope stripping in wrap smarter | <?php namespace Purplapp\Adn;
use stdClass;
use GuzzleHttp\Message\Response;
trait DataContainerTrait
{
private $data = [];
private $dataEnvelope = [];
public static function wrap($data)
{
if ($data instanceof stdClass) {
return static::wrapObject($data);
} elseif ($data instanceof Response) {
return static::wrapResponse($data);
} elseif (is_array($data)) {
return static::wrapArray($data);
}
throw new InvalidArgumentException(gettype($data) . " is not a valid wrappable");
}
private static function wrapObject(stdClass $object)
{
return new static($object);
}
private static function wrapResponse(Response $response)
{
$payload = $response->json(["object" => true]);
// strip the envelope
if (isset($payload->data) && isset($payload->meta)) {
return new static($payload->data);
}
return new static($payload);
}
private static function wrapArray(array $array)
{
return new static((object) $array);
}
public function __construct($data)
{
$this->data = $data;
$this->init();
}
public function __get($key)
{
if (method_exists($this, $key)) {
return $this->$key();
}
return $this->data->$key;
}
public function __isset($key)
{
return method_exists($this, $key) || isset($this->data->$key);
}
public function init()
{
// no-op
}
}
| <?php namespace Purplapp\Adn;
use stdClass;
use GuzzleHttp\Message\Response;
trait DataContainerTrait
{
private $data = [];
private $dataEnvelope = [];
public static function wrap($data)
{
if ($data instanceof stdClass) {
return static::wrapObject($data);
} elseif ($data instanceof Response) {
return static::wrapResponse($data);
} elseif (is_array($data)) {
return static::wrapArray($data);
}
throw new InvalidArgumentException(gettype($data) . " is not a valid wrappable");
}
private static function wrapObject(stdClass $object)
{
return new static($object);
}
private static function wrapResponse(Response $response)
{
return new static($response->json(["object" => true])->data);
}
private static function wrapArray(array $array)
{
return new static((object) $array);
}
public function __construct($data)
{
$this->data = $data;
$this->init();
}
public function __get($key)
{
if (method_exists($this, $key)) {
return $this->$key();
}
return $this->data->$key;
}
public function __isset($key)
{
return method_exists($this, $key) || isset($this->data->$key);
}
public function init()
{
// no-op
}
}
|
Allow null dates to be formatted... | <?php
namespace Code16\Sharp\Form\Fields\Formatters;
use Carbon\Carbon;
use Code16\Sharp\Form\Fields\SharpFormDateField;
use Code16\Sharp\Form\Fields\SharpFormField;
class DateFormatter extends SharpFieldFormatter
{
/**
* @param SharpFormField $field
* @param $value
* @return mixed
*/
function toFront(SharpFormField $field, $value)
{
if($value instanceof Carbon || $value instanceof \DateTime) {
return $value->format($this->getFormat($field));
}
return $value;
}
/**
* @param SharpFormField $field
* @param string $attribute
* @param $value
* @return string
*/
function fromFront(SharpFormField $field, string $attribute, $value)
{
return $value
? Carbon::parse($value)
->setTimezone(config("app.timezone"))
->format($this->getFormat($field))
: null;
}
/**
* @param SharpFormDateField $field
* @return string
*/
protected function getFormat($field)
{
if(!$field->hasTime()) {
return "Y-m-d";
}
if(!$field->hasDate()) {
return "H:i:s";
}
return "Y-m-d H:i:s";
}
} | <?php
namespace Code16\Sharp\Form\Fields\Formatters;
use Carbon\Carbon;
use Code16\Sharp\Form\Fields\SharpFormDateField;
use Code16\Sharp\Form\Fields\SharpFormField;
class DateFormatter extends SharpFieldFormatter
{
/**
* @param SharpFormField $field
* @param $value
* @return mixed
*/
function toFront(SharpFormField $field, $value)
{
if($value instanceof Carbon || $value instanceof \DateTime) {
return $value->format($this->getFormat($field));
}
return $value;
}
/**
* @param SharpFormField $field
* @param string $attribute
* @param $value
* @return string
*/
function fromFront(SharpFormField $field, string $attribute, $value)
{
return Carbon::parse($value)
->setTimezone(config("app.timezone"))
->format($this->getFormat($field));
}
/**
* @param SharpFormDateField $field
* @return string
*/
protected function getFormat($field)
{
if(!$field->hasTime()) {
return "Y-m-d";
}
if(!$field->hasDate()) {
return "H:i:s";
}
return "Y-m-d H:i:s";
}
} |
Allow override on toolbar items through attribute
Use can add "toolbar" attribute in directive to override toolbar items.
e.g.
<div simditor name="content" ng-model="content" toolbar="['title', 'bold', 'italic', 'underline', 'strikethrough', '|', 'ol', 'ul', 'blockquote', 'table']" form-required="true"></div> | /*global window,location*/
(function (window) {
'use strict';
var Simditor = window.Simditor;
var directives = angular.module('simditor',[]);
directives.directive('simditor', function () {
var TOOLBAR_DEFAULT = ['title', 'bold', 'italic', 'underline', 'strikethrough', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent'];
return {
require: "?^ngModel",
link: function (scope, element, attrs, ngModel) {
element.append("<div style='height:300px;'></div>");
var toolbar = scope.$eval(attrs.toolbar) || TOOLBAR_DEFAULT;
scope.simditor = new Simditor({
textarea: element.children()[0],
pasteImage: true,
toolbar: toolbar,
defaultImage: 'assets/images/image.png',
upload: location.search === '?upload' ? {
url: '/upload'
} : false
});
function readViewText() {
var html = element.find('.simditor-body').html();
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
var $target = element.find('.simditor-body');
ngModel.$render = function () {
scope.simditor.focus();
$target.prepend(ngModel.$viewValue);
};
element.on('blur keyup change', function () {
scope.$apply(readViewText);
});
}
};
});
}(window));
| /*global window,location*/
(function (window) {
'use strict';
var Simditor = window.Simditor;
var directives = angular.module('simditor',[]);
directives.directive('simditor', function () {
return {
require: "?^ngModel",
link: function (scope, element, attrs, ngModel) {
element.append("<div style='height:300px;'></div>");
scope.simditor = new Simditor({
textarea: element.children()[0],
pasteImage: true,
toolbar: ['title', 'bold', 'italic', 'underline', 'strikethrough', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent'],
defaultImage: 'assets/images/image.png',
upload: location.search === '?upload' ? {
url: '/upload'
} : false
});
function readViewText() {
var html = element.find('.simditor-body').html();
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
var $target = element.find('.simditor-body');
ngModel.$render = function () {
scope.simditor.focus();
$target.prepend(ngModel.$viewValue);
};
element.on('blur keyup change', function () {
scope.$apply(readViewText);
});
}
};
});
}(window)); |
Complete a sentence in a comment | import angr
from .shellcode_manager import ShellcodeManager
from rex.exploit import CannotExploit
import logging
l = logging.getLogger("rex.exploit.Exploit")
class Exploit(object):
'''
Exploit object which can leak flags or set registers
'''
def __init__(self, crash):
'''
:param crash: an exploitable crash object
:param use_rop_cache: should rop gadgets be cached?
:param rop_cache_file: which filename to use for a rop cache
'''
if not crash.exploitable():
raise CannotExploit("crash cannot be exploited")
self.crash = crash
self.binary = crash.binary
self.os = crash.project.loader.main_bin.os
project = angr.Project(self.binary)
# let's put together our rop gadgets
self.rop = project.analyses.ROP()
# and let's gather some shellcode
self.shellcode = ShellcodeManager(project)
self.payloads = [ ]
def initialize(self):
l.info("accumulating rop gadgets")
self.rop.find_gadgets()
for technique in Techniques[self.os]:
p = technique(self.crash, self.rop, self.shellcode)
try:
l.debug("applying technique %s", p.name)
self.payloads.append(p.apply())
except CannotExploit as e:
l.debug("technique failed: %s", e.message)
from .techniques import Techniques
| import angr
from .shellcode_manager import ShellcodeManager
from rex.exploit import CannotExploit
import logging
l = logging.getLogger("rex.exploit.Exploit")
class Exploit(object):
'''
Exploit object which can leak flags or set registers
'''
def __init__(self, crash):
'''
:param crash: an exploitable crash object
:param use_rop_cache: should rop gadgets be cached?
:param rop_cache_file: which filename to use for a rop cache
'''
if not crash.exploitable():
raise CannotExploit("crash cannot be exploited")
self.crash = crash
self.binary = crash.binary
self.os = crash.project.loader.main_bin.os
project = angr.Project(self.binary)
# let's put together our rop gadgets
self.rop = project.analyses.ROP()
# and let's gather some
self.shellcode = ShellcodeManager(project)
self.payloads = [ ]
def initialize(self):
l.info("accumulating rop gadgets")
self.rop.find_gadgets()
for technique in Techniques[self.os]:
p = technique(self.crash, self.rop, self.shellcode)
try:
l.debug("applying technique %s", p.name)
self.payloads.append(p.apply())
except CannotExploit as e:
l.debug("technique failed: %s", e.message)
from .techniques import Techniques
|
Add splix to spam watcher | import BaseWatcher from './BaseWatcher';
/**
* This checks for people spamming links.
*/
class LinkSpamWatcher extends BaseWatcher {
constructor(bot) {
super(bot);
}
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string}
*/
method = [
'message',
'messageUpdate'
];
async action(method, message, updatedMessage) {
if (method === 'messageUpdate') {
message = updatedMessage;
}
if (
message.cleanContent.toLowerCase().indexOf('giftsofsteam.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steamdigitalgift.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steam.cubecode.site') !== -1 ||
message.cleanContent.toLowerCase().indexOf('hellcase.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('fatalpvp.serv.nu') !== -1 ||
message.cleanContent.toLowerCase().indexOf('splix.io') !== -1
) {
const warningMessage = await message.reply(`This link is not allowed to be posted as it is a known hoax/spam/scam.`);
this.addWarningToUser(message);
message.delete();
warningMessage.delete(60000);
}
}
}
export default LinkSpamWatcher; | import BaseWatcher from './BaseWatcher';
/**
* This checks for people spamming links.
*/
class LinkSpamWatcher extends BaseWatcher {
constructor(bot) {
super(bot);
}
usesBypassRules = true;
/**
* The method this watcher should listen on.
*
* @type {string}
*/
method = [
'message',
'messageUpdate'
];
async action(method, message, updatedMessage) {
if (method === 'messageUpdate') {
message = updatedMessage;
}
if (
message.cleanContent.toLowerCase().indexOf('giftsofsteam.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steamdigitalgift.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('steam.cubecode.site') !== -1 ||
message.cleanContent.toLowerCase().indexOf('hellcase.com') !== -1 ||
message.cleanContent.toLowerCase().indexOf('fatalpvp.serv.nu') !== -1
) {
const warningMessage = await message.reply(`This link is not allowed to be posted as it is a known hoax/spam/scam.`);
this.addWarningToUser(message);
message.delete();
warningMessage.delete(60000);
}
}
}
export default LinkSpamWatcher; |
Fix globals case in UMD | /*globals define */
'use strict';
var root = this; // jshint ignore:line
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['es6-promise'], function (es6Promise) {
return (root.httppleasepromises = factory(es6Promise.Promise));
});
} else if (typeof exports === 'object') {
module.exports = factory(require('es6-promise').Promise);
} else {
root.httppleasepromises = factory(root.Promise);
}
}(function (Promise) {
return {
processRequest: function (req) {
var resolve, reject,
oldOnload = req.onload,
oldOnerror = req.onerror,
promise = new Promise(function (a, b) {
resolve = a;
reject = b;
});
req.onload = function (res) {
var result;
if (oldOnload) {
result = oldOnload.apply(this, arguments);
}
resolve(res);
return result;
};
req.onerror = function (err) {
var result;
if (oldOnerror) {
result = oldOnerror.apply(this, arguments);
}
reject(err);
return result;
};
req.then = function () {
return promise.then.apply(promise, arguments);
};
req['catch'] = function () {
return promise['catch'].apply(promise, arguments);
};
}
};
}));
| /*globals define */
'use strict';
var root = this; // jshint ignore:line
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['es6-promise'], function (es6Promise) {
return (root.httppleasepromises = factory(es6Promise));
});
} else if (typeof exports === 'object') {
module.exports = factory(require('es6-promise'));
} else {
root.httppleasepromises = factory(root.Promise);
}
}(function (es6Promise) {
var Promise = es6Promise.Promise;
return {
processRequest: function (req) {
var resolve, reject,
oldOnload = req.onload,
oldOnerror = req.onerror,
promise = new Promise(function (a, b) {
resolve = a;
reject = b;
});
req.onload = function (res) {
var result;
if (oldOnload) {
result = oldOnload.apply(this, arguments);
}
resolve(res);
return result;
};
req.onerror = function (err) {
var result;
if (oldOnerror) {
result = oldOnerror.apply(this, arguments);
}
reject(err);
return result;
};
req.then = function () {
return promise.then.apply(promise, arguments);
};
req['catch'] = function () {
return promise['catch'].apply(promise, arguments);
};
}
};
}));
|
Use manual route definition over the route resource shortcut | <?php
use Illuminate\Routing\Router;
$router->model('menus', 'Modules\Menu\Entities\Menu');
$router->model('menuitem', 'Modules\Menu\Entities\Menuitem');
$router->group(['prefix' => '/menu'], function () {
get('menus', ['as' => 'admin.menu.menu.index', 'uses' => 'MenuController@index']);
get('menus/create', ['as' => 'admin.menu.menu.create', 'uses' => 'MenuController@create']);
post('menus', ['as' => 'admin.menu.menu.store', 'uses' => 'MenuController@store']);
get('menus/{menus}/edit', ['as' => 'admin.menu.menu.edit', 'uses' => 'MenuController@edit']);
put('menus/{menus}', ['as' => 'admin.menu.menu.update', 'uses' => 'MenuController@update']);
delete('menus/{menus}', ['as' => 'admin.menu.menu.destroy', 'uses' => 'MenuController@destroy']);
get('menus/{menus}/menuitem', ['as' => 'dashboard.menuitem.index', 'uses' => 'MenuItemController@index']);
get('menus/{menus}/menuitem/create', ['as' => 'dashboard.menuitem.create', 'uses' => 'MenuItemController@create']);
post('menus/{menus}/menuitem', ['as' => 'dashboard.menuitem.store', 'uses' => 'MenuItemController@store']);
get('menus/{menus}/menuitem/{menuitem}/edit', ['as' => 'dashboard.menuitem.edit', 'uses' => 'MenuItemController@edit']);
put('menus/{menus}/menuitem/{menuitem}', ['as' => 'dashboard.menuitem.update', 'uses' => 'MenuItemController@update']);
delete('menus/{menus}/menuitem/{menuitem}', ['as' => 'dashboard.menuitem.destroy', 'uses' => 'MenuItemController@destroy']);
});
| <?php
use Illuminate\Routing\Router;
$router->model('menus', 'Modules\Menu\Entities\Menu');
$router->model('menuitem', 'Modules\Menu\Entities\Menuitem');
$router->group(['prefix' => '/menu'], function (Router $router) {
$router->resource('menus', 'MenuController', [
'except' => ['show'],
'names' => [
'index' => 'admin.menu.menu.index',
'create' => 'admin.menu.menu.create',
'store' => 'admin.menu.menu.store',
'edit' => 'admin.menu.menu.edit',
'update' => 'admin.menu.menu.update',
'destroy' => 'admin.menu.menu.destroy',
],
]);
$router->resource('menus.menuitem', 'MenuItemController', [
'except' => ['show'],
'names' => [
'index' => 'dashboard.menuitem.index',
'create' => 'dashboard.menuitem.create',
'store' => 'dashboard.menuitem.store',
'edit' => 'dashboard.menuitem.edit',
'update' => 'dashboard.menuitem.update',
'destroy' => 'dashboard.menuitem.destroy',
],
]);
});
|
Migrate API call to use fetch | const fetch = require('isomorphic-unfetch');
const streamify = require('into-stream');
module.exports = async options => {
if (!options.key) {
throw new Error('Error: key needed to use FEC API,' +
'specify using options.key, ' +
'or get one at https://api.data.gov/signup/');
}
const baseURL = options.baseURL || 'https://api.open.fec.gov/v1/';
const endpoint = options.committee ?
`committee/${options.committee}/filings/` :
'efile/filings';
const params = {
sort: options.sort || '-receipt_date',
per_page: options.perPage || 100,
page: options.page || 1,
api_key: options.key
};
// https://stackoverflow.com/a/34209399
const query = Object.keys(params)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
.join('&');
const response = await fetch(`${baseURL}${endpoint}?${query}`);
const data = await response.json();
return streamify.object(data.results.map(filing => {
if (filing.fec_file_id) {
return {
...filing,
fec_file_id: parseInt(
filing.fec_file_id
.replace('FEC-', '')
.replace('SEN-','')
)
}
}
return filing;
}));
};
| const axios = require('axios');
const through2 = require('through2');
const JSONStream = require('JSONStream');
function processRow(filing, enc, next) {
if (filing.fec_file_id) {
filing.fec_file_id = parseInt(
filing.fec_file_id
.replace('FEC-', '')
.replace('SEN-','')
);
}
this.push(filing);
next();
}
module.exports = async options => {
if (!options.key) {
throw new Error('Error: key needed to use FEC API,' +
'specify using options.key, ' +
'or get one at https://api.data.gov/signup/');
}
const outStream = options.out || process.stdout;
const baseURL = options.baseURL || 'https://api.open.fec.gov/v1/';
const sort = options.sort || '-receipt_date';
const perPage = options.perPage || 100;
const page = options.page || 1;
const endpoint = options.committee ?
`committee/${options.committee}/filings/` :
'efile/filings';
const apiKey = options.key;
const fecAPI = axios.create({
baseURL
});
const response = await fecAPI.get(endpoint, {
params: {
sort,
per_page: perPage,
page,
api_key: apiKey
},
responseType: 'stream'
});
return response.data
.pipe(JSONStream.parse('results.*'))
.pipe(
through2.obj(
processRow
)
);
};
|
Allow passing engine arguments to connect(). | import pkg_resources
from sqlalchemy import MetaData, Table, create_engine, orm
from .tables import metadata
def connect(uri=None, session_args={}, engine_args={}):
"""Connects to the requested URI. Returns a session object.
With the URI omitted, attempts to connect to a default SQLite database
contained within the package directory.
Calling this function also binds the metadata object to the created engine.
"""
# Default to a URI within the package, which was hopefully created at some point
if not uri:
sqlite_path = pkg_resources.resource_filename('pokedex',
'data/pokedex.sqlite')
uri = 'sqlite:///' + sqlite_path
### Do some fixery for MySQL
if uri[0:5] == 'mysql':
# MySQL uses latin1 for connections by default even if the server is
# otherwise oozing with utf8; charset fixes this
if 'charset' not in uri:
uri += '?charset=utf8'
# Tables should be InnoDB, in the event that we're creating them, and
# use UTF-8 goddammit!
for table in metadata.tables.values():
table.kwargs['mysql_engine'] = 'InnoDB'
table.kwargs['mysql_charset'] = 'utf8'
### Connect
engine = create_engine(uri, **engine_args)
conn = engine.connect()
metadata.bind = engine
all_session_args = dict(autoflush=True, autocommit=False, bind=engine)
all_session_args.update(session_args)
sm = orm.sessionmaker(**all_session_args)
session = orm.scoped_session(sm)
return session
| import pkg_resources
from sqlalchemy import MetaData, Table, create_engine, orm
from .tables import metadata
def connect(uri=None, **kwargs):
"""Connects to the requested URI. Returns a session object.
With the URI omitted, attempts to connect to a default SQLite database
contained within the package directory.
Calling this function also binds the metadata object to the created engine.
"""
# Default to a URI within the package, which was hopefully created at some point
if not uri:
sqlite_path = pkg_resources.resource_filename('pokedex',
'data/pokedex.sqlite')
uri = 'sqlite:///' + sqlite_path
### Do some fixery for MySQL
if uri[0:5] == 'mysql':
# MySQL uses latin1 for connections by default even if the server is
# otherwise oozing with utf8; charset fixes this
if 'charset' not in uri:
uri += '?charset=utf8'
# Tables should be InnoDB, in the event that we're creating them, and
# use UTF-8 goddammit!
for table in metadata.tables.values():
table.kwargs['mysql_engine'] = 'InnoDB'
table.kwargs['mysql_charset'] = 'utf8'
### Connect
engine = create_engine(uri)
conn = engine.connect()
metadata.bind = engine
session_args = dict(autoflush=True, autocommit=False, bind=engine)
session_args.update(kwargs)
sm = orm.sessionmaker(**session_args)
session = orm.scoped_session(sm)
return session
|
Check for the binary option being passed to the md5 hasher. If so, always use default encoding. | var crypto = require('crypto')
, fs = require('fs');
(function(undefined) {
'use strict';
module.exports = {
sha256: function(key, data) {
return crypto.createHmac('sha256', key).update(data, 'utf8').digest('hex');
},
md5: function(buffer, callback, options) {
// String?
if (options && options.type === 'string') {
var encoding = options.binary ? undefined : 'utf8';
return setImmediate(
callback,
undefined,
crypto.createHash('md5').update(buffer, encoding).digest('hex')
);
}
// File, then.
fs.stat(buffer, function(err, stats) {
if (err || !stats.isFile()) {
return callback('File does not exist (' + buffer + ')');
}
var md5 = crypto.createHash('md5');
var stream = fs.createReadStream(buffer);
stream.on('data', function(data) {
md5.update(data);
});
stream.on('end', function() {
callback(undefined, md5.digest('hex'), stats);
});
});
}
};
})();
| var crypto = require('crypto')
, fs = require('fs');
(function(undefined) {
'use strict';
module.exports = {
sha256: function(key, data) {
return crypto.createHmac('sha256', key).update(data, 'utf8').digest('hex');
},
md5: function(buffer, callback, options) {
// String?
if (options && options.type === 'string') {
var encoding = buffer instanceof Buffer ? undefined : 'utf8';
return setImmediate(
callback,
undefined,
crypto.createHash('md5').update(buffer, encoding).digest('hex')
);
}
// File, then.
fs.stat(buffer, function(err, stats) {
if (err || !stats.isFile()) {
return callback('File does not exist (' + buffer + ')');
}
var md5 = crypto.createHash('md5');
var stream = fs.createReadStream(buffer);
stream.on('data', function(data) {
md5.update(data);
});
stream.on('end', function() {
callback(undefined, md5.digest('hex'), stats);
});
});
}
};
})();
|
Check for wrong or non-existing stop or trip id | <?php
namespace GtfsMerger\Merger;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use Nette\Caching\Cache;
use Nette\InvalidStateException;
class StopTimeLimitations implements MergerInterface
{
/** @var Cache */
private $tripsIdsCache;
/** @var Cache */
private $stopsIdsCache;
function __construct(
Cache $tripsIdsCache,
Cache $stopsIdsCache
)
{
$this->tripsIdsCache = $tripsIdsCache;
$this->stopsIdsCache = $stopsIdsCache;
}
/**
* @param resource $stream
* @return array
*/
public function merge($stream)
{
$items = [];
$header = fgetcsv($stream);
while(($data = fgetcsv($stream)) !== false) {
$data = array_combine($header, $data);
$currentId = $data['trip_id'] ?? null;
$newId = $this->tripsIdsCache->load($currentId);
if ($newId === null) {
throw new InvalidStateException('Unknown trip ID: ' . $currentId);
}
$data['trip_id'] = $newId;
$currentId = $data['stop_id'] ?? null;
$newId = $this->stopsIdsCache->load($currentId);
if ($newId === null) {
throw new InvalidStateException('Unknown stop ID: ' . $currentId);
}
$data['stop_id'] = $newId;
$items[] = $data;
}
return $items;
}
}
| <?php
namespace GtfsMerger\Merger;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use Nette\Caching\Cache;
use Nette\InvalidStateException;
class StopTimeLimitations implements MergerInterface
{
/** @var Cache */
private $tripsIdsCache;
/** @var Cache */
private $stopsIdsCache;
function __construct(
Cache $tripsIdsCache,
Cache $stopsIdsCache
)
{
$this->tripsIdsCache = $tripsIdsCache;
$this->stopsIdsCache = $stopsIdsCache;
}
/**
* @param resource $stream
* @return array
*/
public function merge($stream)
{
$items = [];
$header = fgetcsv($stream);
while(($data = fgetcsv($stream)) !== false) {
$data = array_combine($header, $data);
$currentId = $data['trip_id'];
$newId = $this->tripsIdsCache->load($currentId);
if ($newId === null) {
throw new InvalidStateException('Unknown trip ID: ' . $currentId);
}
$data['trip_id'] = $newId;
$currentId = $data['stop_id'];
$newId = $this->stopsIdsCache->load($currentId);
if ($newId === null) {
throw new InvalidStateException('Unknown stop ID: ' . $currentId);
}
$data['stop_id'] = $newId;
$items[] = $data;
}
return $items;
}
}
|
Use chunkhash instead of hash for filenames | var path = require('path');
var ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
search: './resources/assets/js/search.js',
episode: './resources/assets/js/episode.js',
index: './resources/assets/js/index.js',
app: './resources/assets/js/app.js',
hammer: './resources/assets/js/hammer.js',
rules: './resources/assets/js/rules.js',
upload: './resources/assets/js/upload.js',
translate: './resources/assets/js/translate.js',
},
output: {
filename: 'js/[name].[chunkhash].bundle.js',
path: path.resolve(__dirname, 'public/')
},
plugins: [
new ManifestPlugin({
fileName: '../resources/assets/manifest.json'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory=true',
options: {
presets: ['env']
}
}
}
]
}
}; | var path = require('path');
var ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
entry: {
search: './resources/assets/js/search.js',
episode: './resources/assets/js/episode.js',
index: './resources/assets/js/index.js',
app: './resources/assets/js/app.js',
hammer: './resources/assets/js/hammer.js',
rules: './resources/assets/js/rules.js',
upload: './resources/assets/js/upload.js',
translate: './resources/assets/js/translate.js',
},
output: {
filename: 'js/[name].[hash].bundle.js',
path: path.resolve(__dirname, 'public/')
},
plugins: [
new ManifestPlugin({
fileName: '../resources/assets/manifest.json'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader?cacheDirectory=true',
options: {
presets: ['env']
}
}
}
]
}
}; |
Allow formatter to be overridden. | (function() {
'use strict';
var _ = require('lodash');
function format(pkg) {
var name = pkg.id;
var version = pkg.doc['dist-tags'].latest;
var link = 'https://www.npmjs.org/package/' + name;
return 'Package <' + link + '|' + name + '@' + version + '> published';
};
var NpmSlack = function(opts) {
this._npm = opts.npm;
this._slack = opts.slack;
this._npmPackages = opts.npmPackages;
this._slackParams = opts.slackParams;
this._format = opts.format || format;
this._addNpmHandlers();
};
NpmSlack.prototype._addNpmHandlers = function() {
this._npm.on('error', console.error);
this._npm.on('data', this._handleNpmPackage.bind(this));
};
NpmSlack.prototype._handleNpmPackage = function(pkg) {
if (!_.contains(this._npmPackages, pkg.id)) {
return;
}
this._sendToSlack(this._format(pkg));
};
NpmSlack.prototype._sendToSlack = function(text) {
console.log(text);
this._slack.webhook(
_.extend({}, this._slackParams, {text: text}),
this._handleSlackResponse.bind(this)
);
};
NpmSlack.prototype._handleSlackResponse = function(error, response) {
if (error !== null) {
console.error('-- ' + error);
}
};
module.exports = NpmSlack;
})();
| (function() {
'use strict';
var _ = require('lodash');
var NpmSlack = function(opts) {
this._npm = opts.npm;
this._slack = opts.slack;
this._npmPackages = opts.npmPackages;
this._slackParams = opts.slackParams;
this._addNpmHandlers();
};
NpmSlack.prototype._addNpmHandlers = function() {
this._npm.on('error', console.error);
this._npm.on('data', this._handleNpmPackage.bind(this));
};
NpmSlack.prototype._handleNpmPackage = function(pkg) {
if (!_.contains(this._npmPackages, pkg.id)) {
return;
}
this._sendToSlack(this._format(pkg));
};
NpmSlack.prototype._format = function(pkg) {
var name = pkg.id;
var version = pkg.doc['dist-tags'].latest;
var link = 'https://www.npmjs.org/package/' + name;
return 'Package <' + link + '|' + name + '@' + version + '> published';
};
NpmSlack.prototype._sendToSlack = function(text) {
console.log(text);
this._slack.webhook(
_.extend({}, this._slackParams, {text: text}),
this._handleSlackResponse.bind(this)
);
};
NpmSlack.prototype._handleSlackResponse = function(error, response) {
if (error !== null) {
console.error('-- ' + error);
}
};
module.exports = NpmSlack;
})();
|
Make sure config returns proper value. | <?php
/**
* File: Config.php
* User: zacharydubois
* Date: 2015-12-30
* Time: 20:33
* Project: Digital-Footprint-Profile
*/
namespace dfp;
class Config {
private
$config,
$DataStore;
/**
* Config constructor.
*
* Sets the file to the configuration and grabs the current configuration contents.
*/
public function __construct() {
// Create DataStore object.
$this->DataStore = new DataStore();
// Grab the current configuration.
$this->DataStore->setFile(CONFIGURATION);
$this->config = $this->DataStore->read();
}
/**
* Retrieves Configuration Parameters
*
* Retrieves configuration options from the configuration array.
*
* @param string $option
* @param string $param
* @return array|string|bool
*/
public function get($option, $param) {
if (!isset($this->config[$option][$param]) || $this->config[$option][$param] === '') {
// Make sure values actually exist.
return false;
}
return $this->config[$option][$param];
}
/**
* Set Configuration
*
* Merges new values with existing.
*
* @param array $payload
* @return true
* @throws Exception
*/
public function set(array $payload) {
$config = array_merge($payload, $this->config);
if (!$this->DataStore->write($config)) {
throw new Exception("Failed to write config using config->set.");
}
return true;
}
} | <?php
/**
* File: Config.php
* User: zacharydubois
* Date: 2015-12-30
* Time: 20:33
* Project: Digital-Footprint-Profile
*/
namespace dfp;
class Config {
private
$config,
$DataStore;
/**
* Config constructor.
*
* Sets the file to the configuration and grabs the current configuration contents.
*/
public function __construct() {
// Create DataStore object.
$this->DataStore = new DataStore();
// Grab the current configuration.
$this->DataStore->setFile(CONFIGURATION);
$this->config = $this->DataStore->read();
}
/**
* Retrieves Configuration Parameters
*
* Retrieves configuration options from the configuration array.
*
* @param string $option
* @param string|null $param
* @return array|string|bool
*/
public function get($option, $param = null) {
if ((!isset($this->config[$option]) && $param === null) || (!isset($this->config[$option][$param]) && $param !== null)) {
// Make sure values actually exist.
return false;
}
return $this->config[$option];
}
/**
* Set Configuration
*
* Merges new values with existing.
*
* @param array $payload
* @return true
* @throws Exception
*/
public function set(array $payload) {
$config = array_merge($payload, $this->config);
if (!$this->DataStore->write($config)) {
throw new Exception("Failed to write config using config->set.");
}
return true;
}
} |
Remove authed state on logout success | import {
LOGIN_USER_REQUEST, LOGIN_USER_SUCCESS, LOGIN_USER_FAILURE,
AUTH_USER_REQUEST, AUTH_USER_SUCCESS, AUTH_USER_FAILURE,
LOGOUT_USER_REQUEST, LOGOUT_USER_SUCCESS
} from '../constants/ActionTypes'
const initialState = {
user: null,
isAuthenticated: false,
isAuthenticating: false,
error: null,
token: null
}
export default function Auth(state = initialState, action) {
switch (action.type) {
case AUTH_USER_REQUEST:
return {
...state,
user: null,
isAuthenticating: true,
error: null
}
case AUTH_USER_SUCCESS:
const auth = action.response.entities.auth[action.response.result];
if(auth.token){
localStorage.setItem('token', auth.token);
}
return {
...state,
user: auth.user,
isAuthenticated: true,
isAuthenticating: false,
error: null
}
case AUTH_USER_FAILURE:
return {
...state,
user: null,
isAuthenticated: false,
isAuthenticating: false,
error: action.error
}
/*
case LOGOUT_USER_REQUEST:
return {
...initialState
}*/
case LOGOUT_USER_SUCCESS:
localStorage.removeItem('token');
return {
...initialState
}
default:
return state
}
}
| import {
LOGIN_USER_REQUEST, LOGIN_USER_SUCCESS, LOGIN_USER_FAILURE,
AUTH_USER_REQUEST, AUTH_USER_SUCCESS, AUTH_USER_FAILURE,
LOGOUT_USER_REQUEST
} from '../constants/ActionTypes'
const initialState = {
user: null,
isAuthenticated: false,
isAuthenticating: false,
error: null,
token: null
}
export default function Auth(state = initialState, action) {
switch (action.type) {
case AUTH_USER_REQUEST:
return {
...state,
user: null,
isAuthenticating: true,
error: null
}
case AUTH_USER_SUCCESS:
const auth = action.response.entities.auth[action.response.result];
if(auth.token){
localStorage.setItem('token', auth.token);
}
return {
...state,
user: auth.user,
isAuthenticated: true,
isAuthenticating: false,
error: null
}
case AUTH_USER_FAILURE:
return {
...state,
user: null,
isAuthenticated: false,
isAuthenticating: false,
error: action.error
}
case LOGOUT_USER_REQUEST:
localStorage.removeItem('token');
return {
...initialState
}
default:
return state
}
}
|
Make sure protobuf comes from pypi
Without this, it gets the outdated zip package from googlecode and fail. | #!/usr/bin/env python
import glob
import os
import subprocess
import platform
from setuptools import setup, find_packages
def make_docs():
if not os.path.exists('docs'):
os.mkdir('docs')
subprocess.call(['pydoc', '-w', 'riak'])
for name in glob.glob('*.html'):
os.rename(name, 'docs/%s' % name)
install_requires = ["riak_pb >=1.2.0, < 1.3.0"]
requires = ["riak_pb(>=1.2.0,<1.3.0)"]
tests_require = []
if platform.python_version() < '2.7':
tests_require.append("unittest2")
setup(
name='riak',
version='1.5.1',
packages = find_packages(),
requires = requires,
install_requires = install_requires,
tests_require = tests_require,
package_data = {'riak' : ['erl_src/*']},
description='Python client for Riak',
zip_safe=True,
options={'easy_install': {'allow_hosts': 'pypi.python.org'}},
include_package_data=True,
license='Apache 2',
platforms='Platform Independent',
author='Basho Technologies',
author_email='[email protected]',
test_suite='riak.tests.suite',
url='https://github.com/basho/riak-python-client',
classifiers = ['License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Database']
)
| #!/usr/bin/env python
import glob
import os
import subprocess
import platform
from setuptools import setup, find_packages
def make_docs():
if not os.path.exists('docs'):
os.mkdir('docs')
subprocess.call(['pydoc', '-w', 'riak'])
for name in glob.glob('*.html'):
os.rename(name, 'docs/%s' % name)
install_requires = ["riak_pb >=1.2.0, < 1.3.0"]
requires = ["riak_pb(>=1.2.0,<1.3.0)"]
tests_require = []
if platform.python_version() < '2.7':
tests_require.append("unittest2")
setup(
name='riak',
version='1.5.1',
packages = find_packages(),
requires = requires,
install_requires = install_requires,
tests_require = tests_require,
package_data = {'riak' : ['erl_src/*']},
description='Python client for Riak',
zip_safe=True,
include_package_data=True,
license='Apache 2',
platforms='Platform Independent',
author='Basho Technologies',
author_email='[email protected]',
test_suite='riak.tests.suite',
url='https://github.com/basho/riak-python-client',
classifiers = ['License :: OSI Approved :: Apache Software License',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Topic :: Database']
)
|
Check configuration file rather than env variable | import os
import logging
import json
from logging.config import dictConfig
from gluon.storage import Storage
from gluon.contrib.appconfig import AppConfig
# app_config use to cache values in production
app_config = AppConfig(reload=True)
# settings is used to avoid cached values in production
settings = Storage()
# LOGGING CONFIGURATIONS
settings.logging_config = dict(main=os.path.join(request.folder,
'logging.json'),
scheduler=os.path.join(request.folder,
'logging-scheduler.json'))
# INITIALIZE LOGGING
if os.path.exists(settings.logging_config['main']):
try:
config = json.loads(open(settings.logging_config['main']).read())
logging.config.dictConfig(config)
except ValueError as e:
pass
logger = logging.getLogger(settings.app_name)
# DATABASE CONFIGURATION
# Check whether POSTGRES_ENABLED env var is set to True or not.
# If so, generate connection string.
if app_config.has_key('postgres'):
settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format(
u=app_config.get('postgres.username'),
p=app_config.get('postgres.password'),
h=app_config.get('postgres.hostname'),
po=app_config.get('postgres.port'),
db=app_config.get('postgres.database'))
else:
settings.db_uri = app_config.get('db.uri')
| import os
import logging
import json
from logging.config import dictConfig
from gluon.storage import Storage
from gluon.contrib.appconfig import AppConfig
# app_config use to cache values in production
app_config = AppConfig(reload=True)
# settings is used to avoid cached values in production
settings = Storage()
# LOGGING CONFIGURATIONS
settings.logging_config = dict(main=os.path.join(request.folder,
'logging.json'),
scheduler=os.path.join(request.folder,
'logging-scheduler.json'))
# INITIALIZE LOGGING
if os.path.exists(settings.logging_config['main']):
try:
config = json.loads(open(settings.logging_config['main']).read())
logging.config.dictConfig(config)
except ValueError as e:
pass
logger = logging.getLogger(settings.app_name)
# DATABASE CONFIGURATION
# Check whether POSTGRES_ENABLED env var is set to True or not.
# If so, generate connection string.
if os.environ['POSTGRES_ENABLED'] == 'True':
settings.db_uri = 'postgres://{u}:{p}@{h}:{po}/{db}'.format(
u=app_config.get('postgres.username'),
p=app_config.get('postgres.password'),
h=app_config.get('postgres.hostname'),
po=app_config.get('postgres.port'),
db=app_config.get('postgres.database'))
else:
settings.db_uri = app_config.get('db.uri')
|
Add the 3.2 trove classifier since it's technically supported for now. | import os
from setuptools import setup
setup(name='django-contact-form',
version='1.2',
zip_safe=False, # eggs are the devil.
description='Generic contact-form application for Django',
long_description=open(os.path.join(os.path.dirname(__file__),
'README.rst')).read(),
author='James Bennett',
author_email='[email protected]',
url='https://github.com/ubernostrum/django-contact-form/',
packages=['contact_form', 'contact_form.tests'],
test_suite='contact_form.runtests.run_tests',
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities'],
)
| import os
from setuptools import setup
setup(name='django-contact-form',
version='1.2',
zip_safe=False, # eggs are the devil.
description='Generic contact-form application for Django',
long_description=open(os.path.join(os.path.dirname(__file__),
'README.rst')).read(),
author='James Bennett',
author_email='[email protected]',
url='https://github.com/ubernostrum/django-contact-form/',
packages=['contact_form', 'contact_form.tests'],
test_suite='contact_form.runtests.run_tests',
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Framework :: Django :: 1.9',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Utilities'],
)
|
Use the default file upload max memory size | """
@author: Ferdinand E. Silva
@email: [email protected]
@website: http://ferdinandsilva.com
"""
import os
from django.conf import settings
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=None):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit or settings.FILE_UPLOAD_MAX_MEMORY_SIZE
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
| """
@author: Ferdinand E. Silva
@email: [email protected]
@website: http://ferdinandsilva.com
"""
import os
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=1024):
self.allowedExtensions = allowedExtensions or []
self.sizeLimit = sizeLimit
def handleUpload(self, request, uploadDirectory):
#read file info from stream
uploaded = request.read
#get file size
fileSize = int(uploaded.im_self.META["CONTENT_LENGTH"])
#get file name
fileName = uploaded.im_self.META["HTTP_X_FILE_NAME"]
#check first for allowed file extensions
#read the file content, if it is not read when the request is multi part then the client get an error
fileContent = uploaded(fileSize)
if self._getExtensionFromFileName(fileName) in self.allowedExtensions or ".*" in self.allowedExtensions:
#check file size
if fileSize <= self.sizeLimit:
#upload file
#write file
file = open(os.path.join(uploadDirectory, fileName), "wb+")
file.write(fileContent)
file.close()
return json.dumps({"success": True})
else:
return json.dumps({"error": "File is too large."})
else:
return json.dumps({"error": "File has an invalid extension."})
def _getExtensionFromFileName(self, fileName):
filename, extension = os.path.splitext(fileName)
return extension
|
Check python version and possibly only import some things |
########################################################################
# #
# This script was written by Thomas Heavey in 2017. #
# [email protected] [email protected] #
# #
# Copyright 2017 Thomas J. Heavey IV #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or #
# implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
########################################################################
from __future__ import absolute_import
import sys
from . import para_temp_setup
if sys.version_info.major == 2:
# These (at this point) require python 2 because of gromacs and MDAnalysis
from . import energyHisto
from . import CoordinateAnalysis
|
########################################################################
# #
# This script was written by Thomas Heavey in 2017. #
# [email protected] [email protected] #
# #
# Copyright 2017 Thomas J. Heavey IV #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or #
# implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
########################################################################
from __future__ import absolute_import
from . import energyHisto
from . import para_temp_setup
from . import CoordinateAnalysis
|
Test for new comment property. | package com.uwetrottmann.getglue.services;
import com.uwetrottmann.getglue.BaseTestCase;
import com.uwetrottmann.getglue.entities.GetGlueInteraction;
import com.uwetrottmann.getglue.entities.GetGlueInteractionResource;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
public class InteractionServiceTest extends BaseTestCase {
public static final String SAMPLE_INTERACTION = "getgluejava/2013-10-24T18:30:38Z";
public void test_get() {
InteractionService service = getManager().interactionService();
GetGlueInteractionResource resource = service.get(SAMPLE_INTERACTION);
assertThat(resource).isNotNull();
assertThat(resource.interaction).isNotNull();
assertThat(resource.interaction._object).isNotNull();
assertThat(resource.interaction._object.id).isEqualTo("tv_shows/how_i_met_your_mother");
assertThat(resource.interaction._object.title).isEqualTo("How I Met Your Mother");
assertThat(resource.interaction.comment).isEqualTo("Testing getglue-java.");
}
public void test_votes() {
InteractionService service = getManager().interactionService();
List<GetGlueInteraction> resource = service.votes(SAMPLE_INTERACTION);
assertThat(resource).isNotNull();
}
public void test_replies() {
InteractionService service = getManager().interactionService();
List<GetGlueInteraction> resource = service.replies(SAMPLE_INTERACTION);
assertThat(resource).isNotNull();
}
}
| package com.uwetrottmann.getglue.services;
import com.uwetrottmann.getglue.BaseTestCase;
import com.uwetrottmann.getglue.entities.GetGlueInteraction;
import com.uwetrottmann.getglue.entities.GetGlueInteractionResource;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
public class InteractionServiceTest extends BaseTestCase {
public static final String SAMPLE_INTERACTION = "getgluejava/2013-10-24T18:30:38Z";
public void test_get() {
InteractionService service = getManager().interactionService();
GetGlueInteractionResource resource = service.get(SAMPLE_INTERACTION);
assertThat(resource).isNotNull();
assertThat(resource.interaction).isNotNull();
assertThat(resource.interaction._object).isNotNull();
assertThat(resource.interaction._object.id).isEqualTo("tv_shows/how_i_met_your_mother");
assertThat(resource.interaction._object.title).isEqualTo("How I Met Your Mother");
}
public void test_votes() {
InteractionService service = getManager().interactionService();
List<GetGlueInteraction> resource = service.votes(SAMPLE_INTERACTION);
assertThat(resource).isNotNull();
}
public void test_replies() {
InteractionService service = getManager().interactionService();
List<GetGlueInteraction> resource = service.replies(SAMPLE_INTERACTION);
assertThat(resource).isNotNull();
}
}
|
example: Add example of removing physics force | FamousFramework.scene('famous-tests:physics:basic:particle', {
behaviors: {
'.particle': {
'size': [200, 200],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'style': {
'background': 'whitesmoke',
'border-radius': '50%'
}
},
'.one': {
'position': function(position1) {
return position1;
}
},
'.two': {
'position': function(position2) {
return position2;
}
}
},
events: {
'$lifecycle': {
'post-load': function($state) {
$state
.applyPhysicsForce('gravity1D', [ 'position1' ])
.applyPhysicsConstraint('distance', [ 'position1', 'position2' ], {
length: 400
});
}
},
'.one': {
'click': function($state) {
$state.removePhysicsForce('gravity1D');
}
}
},
states: {
'position1': [0, 0, 0],
'position2': [0, -200, 0]
},
tree: `
<node class="particle one"></node>
<node class="particle two"></node>
`
});
| FamousFramework.scene('famous-tests:physics:basic:particle', {
behaviors: {
'.particle': {
'size': [200, 200],
'align': [0.5, 0.5],
'mount-point': [0.5, 0.5],
'style': {
'background': 'whitesmoke',
'border-radius': '50%'
}
},
'.one': {
'position': function(position1) {
return position1;
}
},
'.two': {
'position': function(position2) {
return position2;
}
}
},
events: {
'$lifecycle': {
'post-load': function($state) {
$state
.applyPhysicsForce('gravity1D', [ 'position1' ])
.applyPhysicsConstraint('distance', [ 'position1', 'position2' ], {
length: 400
});
}
}
},
states: {
'position1': [0, 0, 0],
'position2': [0, -200, 0]
},
tree: `
<node class="particle one"></node>
<node class="particle two"></node>
`
});
|
Add extra read(...) method for performance | package org.bouncycastle.asn1;
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
class DefiniteLengthInputStream
extends LimitedInputStream
{
private int _length;
DefiniteLengthInputStream(
InputStream in,
int length)
{
super(in);
if (length < 0)
{
throw new IllegalArgumentException("negative lengths not allowed");
}
this._length = length;
}
public int read()
throws IOException
{
if (_length > 0)
{
int b = _in.read();
if (b < 0)
{
throw new EOFException();
}
--_length;
return b;
}
setParentEofDetect(true);
return -1;
}
public int read(byte[] buf, int off, int len)
throws IOException
{
if (_length > 0)
{
int toRead = Math.min(len, _length);
int numRead = _in.read(buf, off, toRead);
if (numRead < 0)
throw new EOFException();
_length -= numRead;
return numRead;
}
setParentEofDetect(true);
return -1;
}
byte[] toByteArray()
throws IOException
{
byte[] bytes = new byte[_length];
if (_length > 0)
{
int pos = 0;
do
{
int read = _in.read(bytes, pos, _length - pos);
if (read < 0)
{
throw new EOFException();
}
pos += read;
}
while (pos < _length);
_length = 0;
}
setParentEofDetect(true);
return bytes;
}
}
| package org.bouncycastle.asn1;
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
class DefiniteLengthInputStream
extends LimitedInputStream
{
private int _length;
DefiniteLengthInputStream(
InputStream in,
int length)
{
super(in);
if (length < 0)
{
throw new IllegalArgumentException("negative lengths not allowed");
}
this._length = length;
}
public int read()
throws IOException
{
if (_length > 0)
{
int b = _in.read();
if (b < 0)
{
throw new EOFException();
}
--_length;
return b;
}
setParentEofDetect(true);
return -1;
}
byte[] toByteArray()
throws IOException
{
byte[] bytes = new byte[_length];
if (_length > 0)
{
int pos = 0;
do
{
int read = _in.read(bytes, pos, _length - pos);
if (read < 0)
{
throw new EOFException();
}
pos += read;
}
while (pos < _length);
_length = 0;
}
setParentEofDetect(true);
return bytes;
}
}
|
Fix for cluster detail page | (function() {
"use strict";
var app = angular.module("TendrlModule");
app.controller("clusterDetailController", clusterDetailController);
/*@ngInject*/
function clusterDetailController($state, $stateParams, utils, $scope, $rootScope) {
var vm = this;
vm.tabList = { "Host": 1 };
vm.setTab = setTab;
vm.isTabSet = isTabSet;
/* Adding clusterId in scope so that it will be accessible inside child directive */
$scope.clusterId = $stateParams.clusterId;
if (!$rootScope.clusterData) {
utils.getObjectList("Cluster")
.then(function(data) {
$rootScope.clusterData = data;
_setClusterDetail();
});
} else {
_setClusterDetail();
}
function _setClusterDetail() {
vm.clusterObj = utils.getClusterDetails($scope.clusterId);
vm.clusterName = vm.clusterObj.cluster_name || "NA";
if (vm.clusterObj.sds_name === "glusterfs") {
vm.tabList.FileShare = 2;
} else {
vm.tabList.Pool = 2;
vm.tabList.RBD = 3;
}
vm.activeTab = vm.tabList["Host"];
}
function setTab(newTab) {
vm.activeTab = newTab;
}
function isTabSet(tabNum) {
return vm.activeTab === tabNum;
}
}
})();
| (function() {
"use strict";
var app = angular.module("TendrlModule");
app.controller("clusterDetailController", clusterDetailController);
/*@ngInject*/
function clusterDetailController($state, $stateParams, utils, $scope, $rootScope) {
var vm = this;
vm.tabList = { "Host": 1 };
vm.setTab = setTab;
vm.isTabSet = isTabSet;
/* Adding clusterId in scope so that it will be accessible inside child directive */
$scope.clusterId = $stateParams.clusterId;
if (!$rootScope.clusterData) {
$state.go("cluster");
} else {
vm.clusterObj = utils.getClusterDetails($scope.clusterId);
vm.clusterName = vm.clusterObj.cluster_name || "NA";
if (vm.clusterObj.sds_name === "glusterfs") {
vm.tabList.FileShare = 2;
} else {
vm.tabList.Pool = 2;
vm.tabList.RBD = 3;
}
vm.activeTab = vm.tabList["Host"];
}
function setTab(newTab) {
vm.activeTab = newTab;
}
function isTabSet(tabNum) {
return vm.activeTab === tabNum;
}
}
})();
|
Copy over the tracers as well | <?php
namespace Hoopak;
use Hoopak\Annotation;
class Trace
{
/**
* Create a Trace.
*/
public function __construct($name, $traceId=null, $spanId=null, $parentSpanId=null, $tracers=array())
{
$this->name = $name;
if ($traceId) {
$this->traceId = $traceId;
} else {
$this->traceId = $this->_id();
}
if ($spanId) {
$this->spanId = $spanId;
} else {
$this->spanId = $this->_id();
}
$this->parentSpanId = $parentSpanId;
$this->_tracers = $tracers;
$this->_endpoint = null;
}
/**
* Record an annotation
*/
public function record($annotation)
{
if (!$annotation->endpoint && $this->_endpoint) {
$annotation->endpoint = $this->_endpoint;
}
foreach ($this->_tracers as $tracer) {
$tracer->record($this, $annotation);
}
}
/**
* Create a child of this trace
*/
public function child($name)
{
$trace = new self($name, $this->traceId, null, $this->spanId);
$trace->_tracers = $this->_tracers;
$trace->setEndpoint($this->_endpoint);
return $trace;
}
/**
* Set the endpoint
*/
public function setEndpoint($endpoint)
{
$this->_endpoint = $endpoint;
}
private static function _id()
{
return rand(0, pow(2,56)-1);
}
}
| <?php
namespace Hoopak;
use Hoopak\Annotation;
class Trace
{
/**
* Create a Trace.
*/
public function __construct($name, $traceId=null, $spanId=null, $parentSpanId=null, $tracers=array())
{
$this->name = $name;
if ($traceId) {
$this->traceId = $traceId;
} else {
$this->traceId = $this->_id();
}
if ($spanId) {
$this->spanId = $spanId;
} else {
$this->spanId = $this->_id();
}
$this->parentSpanId = $parentSpanId;
$this->_tracers = $tracers;
$this->_endpoint = null;
}
/**
* Record an annotation
*/
public function record($annotation)
{
if (!$annotation->endpoint && $this->_endpoint) {
$annotation->endpoint = $this->_endpoint;
}
foreach ($this->_tracers as $tracer) {
$tracer->record($this, $annotation);
}
}
/**
* Create a child of this trace
*/
public function child($name)
{
$trace = new self($name, $this->traceId, null, $this->spanId);
$trace->setEndpoint($this->_endpoint);
return $trace;
}
/**
* Set the endpoint
*/
public function setEndpoint($endpoint)
{
$this->_endpoint = $endpoint;
}
private static function _id()
{
return rand(0, pow(2,56)-1);
}
}
|
Fix AppVeyor build or break it in a different way | from .checks import (check_quantity,
check_relativistic,
_check_quantity,
_check_relativistic)
from .exceptions import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError,
MissingAtomicDataError,
ChargeError,
InvalidIonError,
InvalidIsotopeError,
InvalidElementError,
InvalidParticleError,
DataStandardError,
PlasmaPyWarning,
PhysicsWarning,
CouplingWarning,
RelativityWarning,
AtomicWarning,
MissingAtomicDataWarning)
from .pytest_helpers import (
run_test,
run_test_equivalent_calls,
call_string,
InconsistentTypeError,
UnexpectedResultError,
UnexpectedExceptionError,
RunTestError,
IncorrectResultError,
MissingExceptionError,
MissingWarningError,
assert_can_handle_nparray,
)
from . import roman
| from .checks import (check_quantity,
check_relativistic,
_check_quantity,
_check_relativistic)
from .exceptions import (PlasmaPyError,
PhysicsError,
RelativityError,
AtomicError,
MissingAtomicDataError,
ChargeError,
InvalidIonError,
InvalidIsotopeError,
InvalidElementError,
InvalidParticleError,
DataStandardError,
PlasmaPyWarning,
PhysicsWarning,
CouplingWarning,
RelativityWarning,
AtomicWarning,
MissingAtomicDataWarning)
from .pytest_helpers import (
run_test,
run_test_equivalent_calls,
call_string,
InconsistentTypeError,
UnexpectedResultError,
UnexpectedExceptionError,
RunTestError,
IncorrectResultError,
MissingExceptionError,
MissingWarningError,
assert_can_handle_nparray,
)
import roman
|
Use $uibModalInstance in login controller | export default /*@ngInject*/class LoginController{
constructor(user,$uibModalInstance){
this.user = user;
this.$uibModalInstance = $uibModalInstance;
this.data = {};
this.loginFields = [{
key: 'email',
type: 'horizontalInput',
templateOptions: {
type: 'email',
label: 'E-Mail',
required: true,
placeholder: '[email protected]',
maxlength: 20
},
validation: {
messages: {
'userCheck': '$viewValue+" ist kein registrierter Benutzer"'
}
},
ngModelAttrs: {
'exists': {
value: 'user-check'
}
},
modelOptions: {
updateOn: 'default blur',
debounce: {default: 500, blur: 0}
}
},
{
key: 'password',
type: 'horizontalInput',
templateOptions: {
type: 'password',
label: 'Passwort',
required: true,
placeholder: 'unlösbar',
minlength: 8
}
}];
}
login(){
return this.user.authenticate(this.data,true)
.then(
(data) => {
return this.$uibModalInstance.close(data);
},
(e) => {
this.message = e.data;
return e;
}
);
}
cancel(){
this.$uibModalInstance.dismiss('cancel');
}
}
| export default /*@ngInject*/class LoginController{
constructor(user,$modalInstance){
this.user = user;
this.$modalInstance = $modalInstance;
this.data = {};
this.loginFields = [{
key: 'email',
type: 'horizontalInput',
templateOptions: {
type: 'email',
label: 'E-Mail',
required: true,
placeholder: '[email protected]',
maxlength: 20
},
validation: {
messages: {
'userCheck': '$viewValue+" ist kein registrierter Benutzer"'
}
},
ngModelAttrs: {
'exists': {
value: 'user-check'
}
},
modelOptions: {
updateOn: 'default blur',
debounce: {default: 500, blur: 0}
}
},
{
key: 'password',
type: 'horizontalInput',
templateOptions: {
type: 'password',
label: 'Passwort',
required: true,
placeholder: 'unlösbar',
minlength: 8
}
}];
}
login(){
return this.user.authenticate(this.data,true)
.then(
(data) => {
return this.$modalInstance.close(data);
},
(e) => {
this.message = e.data;
return e;
}
);
}
cancel(){
this.$modalInstance.dismiss('cancel');
}
}
|
Update validation check for paper bundles. | #!/usr/bin/python3
from random import randint
class Student:
def __init__(self, id):
self.id = id
self.papers = []
def assign_paper(self, paper):
self.papers.append(paper)
def __str__(self):
return str(self.id) + ": " + str(self.papers)
class Paper:
def __init__(self, id):
self.id = id
def create_bundle_graph(n, k):
students = [Student(x + 1) for x in range(n)]
papers = [Paper(x + 1) for x in range(n)]
while True:
for i in range(k):
inavai_pap = set()
for j in range(len(students)):
paper = None
while True:
paper = papers[randint(0, len(papers) - 1)]
if paper.id == students[j].id:
continue
if paper.id not in inavai_pap and paper.id not in students[j].papers:
inavai_pap.add(paper.id)
break
students[j].assign_paper(paper.id)
# make sure not more than one paper is assigned to every two people
success = True
for i in range(n):
for j in range(i + 1, n):
cnt = len(set(students[i].papers).intersection(set(students[j].papers)))
if cnt >= 2:
success = False
break
if not success:
break
if success:
break
return students
| #!/usr/bin/python3
from random import randint
class Student:
def __init__(self, id):
self.id = id
self.papers = []
def assign_paper(self, paper):
self.papers.append(paper)
def __str__(self):
return str(self.id) + ": " + str(self.papers)
class Paper:
def __init__(self, id):
self.id = id
def create_bundle_graph(n, k):
students = [Student(x + 1) for x in range(n)]
papers = [Paper(x + 1) for x in range(n)]
while True:
for i in range(k):
inavai_pap = set()
for j in range(len(students)):
paper = None
while True:
paper = papers[randint(0, len(papers) - 1)]
if paper.id == students[j].id:
continue
if paper.id not in inavai_pap and paper.id not in students[j].papers:
inavai_pap.add(paper.id)
break
students[j].assign_paper(paper.id)
# make sure not more than one paper is assigned to every two people
success = True
for i in range(n):
for j in range(i + 1, n):
cnt = 0
for l in range(k):
if students[i].papers[l] == students[j].papers[l]:
cnt = cnt + 1
if cnt >= 2:
success = False
break
if not success:
break
if not success:
break
if success:
break
return students
|
Add a general 'loading script' to ignore list | window._trackJs = {
onError: function(payload, error) {
function itemExistInList(item, list) {
for (var i = 0; i < list.length; i++) {
if (item.indexOf(list[i]) > -1) {
return true;
}
}
return false;
}
var ignorableErrors = [
// General script error, not actionable
"[object Event]",
// General script error, not actionable
"Script error.",
// error when user interrupts script loading, nothing to fix
"Error loading script",
// an error caused by DealPly (http://www.dealply.com/) chrome extension
"DealPly",
// this error is reported when a post request returns error, i.e. html body
// the details provided in this case are completely useless, thus discarded
"Unexpected token <"
];
if (itemExistInList(payload.message, ignorableErrors)) {
return false;
}
payload.network = payload.network.filter(function(item) {
// ignore random errors from Intercom
if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) {
return false;
}
return true;
});
return true;
}
};
| window._trackJs = {
onError: function(payload, error) {
function itemExistInList(item, list) {
for (var i = 0; i < list.length; i++) {
if (item.indexOf(list[i]) > -1) {
return true;
}
}
return false;
}
var ignorableErrors = [
// General script error, not actionable
"[object Event]",
// General script error, not actionable
"Script error.",
// an error caused by DealPly (http://www.dealply.com/) chrome extension
"DealPly",
// this error is reported when a post request returns error, i.e. html body
// the details provided in this case are completely useless, thus discarded
"Unexpected token <"
];
if (itemExistInList(payload.message, ignorableErrors)) {
return false;
}
payload.network = payload.network.filter(function(item) {
// ignore random errors from Intercom
if (item.statusCode === 403 && payload.message.indexOf("intercom") > -1) {
return false;
}
return true;
});
return true;
}
};
|
Remove scripting for now, just git pull | <?php
require 'core.php';
// No unauthenticated deploys!
protectPage();
// Run relevant deploy.
$hash = $_GET['project'];
$targets = getDeployTargets();
foreach ($targets as $target)
{
if ($target->getIdentifier() == $hash)
{
$result = shell_exec('/usr/bin/git pull 2>&1'); // Execute script.
if ($result == null)
{
echo json_encode([
'status' => 'warning',
'message' => 'It doesn\'t look like your website deployed properly. Executing your script returned null.',
'result' => $result,
]); // Null output from script.
}
else if ($result == '0')
{
echo json_encode([
'status' => 'success',
'message' => 'Your website should be online and ready! Your script ran without a problem.',
'result' => $result,
]); // If script returns 0, that means success.
}
else if ($result == '1') {
echo json_encode([
'status' => 'danger',
'message' => 'There was a problem deploying your site. Your script returned a failure.',
'result' => $result,
]); // If script returns 1, that means failure.
}
else
{
echo json_encode([
'status' => 'info',
'message' => 'Your script returned something weird. You should look into this further.',
'result' => $result,
]); // If script returns something else, we dunno.
}
}
}
| <?php
require 'core.php';
// No unauthenticated deploys!
protectPage();
// Run relevant deploy.
$hash = $_GET['project'];
$targets = getDeployTargets();
foreach ($targets as $target)
{
if ($target->getIdentifier() == $hash)
{
$result = exec($target->getDeployCommand() . ' 2>&1'); // Execute script.
if ($result == null)
{
echo json_encode([
'status' => 'warning',
'message' => 'It doesn\'t look like your website deployed properly. Executing your script returned null.',
'result' => $result,
]); // Null output from script.
}
else if ($result == '0')
{
echo json_encode([
'status' => 'success',
'message' => 'Your website should be online and ready! Your script ran without a problem.',
'result' => $result,
]); // If script returns 0, that means success.
}
else if ($result == '1') {
echo json_encode([
'status' => 'danger',
'message' => 'There was a problem deploying your site. Your script returned a failure.',
'result' => $result,
]); // If script returns 1, that means failure.
}
else
{
echo json_encode([
'status' => 'info',
'message' => 'Your script returned something weird. You should look into this further.',
'result' => $result,
]); // If script returns something else, we dunno.
}
}
}
|
Disable pythonxerbla.c patch for win32 (the MSVC linker failes on multiple defined symbols) when using optimized lapack. |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg',parent_package,top_path)
config.add_data_dir('tests')
# Configure lapack_lite
lapack_info = get_info('lapack_opt',0) # and {}
def get_lapack_lite_sources(ext, build_dir):
if not lapack_info:
print "### Warning: Using unoptimized lapack ###"
return ext.depends[:-1]
else:
if sys.platform=='win32':
print "### Warning: pythonxerbla.c is disabled ###"
return ext.depends[:1]
return ext.depends[:2]
config.add_extension('lapack_lite',
sources = [get_lapack_lite_sources],
depends= ['lapack_litemodule.c',
'pythonxerbla.c',
'zlapack_lite.c', 'dlapack_lite.c',
'blas_lite.c', 'dlamch.c',
'f2c_lite.c','f2c.h'],
extra_info = lapack_info
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
config = Configuration('linalg',parent_package,top_path)
config.add_data_dir('tests')
# Configure lapack_lite
lapack_info = get_info('lapack_opt',0) # and {}
def get_lapack_lite_sources(ext, build_dir):
if not lapack_info:
print "### Warning: Using unoptimized lapack ###"
return ext.depends[:-1]
else:
return ext.depends[:2]
config.add_extension('lapack_lite',
sources = [get_lapack_lite_sources],
depends= ['lapack_litemodule.c',
'pythonxerbla.c',
'zlapack_lite.c', 'dlapack_lite.c',
'blas_lite.c', 'dlamch.c',
'f2c_lite.c','f2c.h'],
extra_info = lapack_info
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
|
Add TODO about using an enum instead of an unconstrained string
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1519 0d517254-b314-0410-acde-c619094fa49f | package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
// TODO: This ought to be the java.util.Calendar constant for the day, or a custom enum
private String dayOfTheWeek;
@Transient
public String getDisplayName() {
return getDayOfTheWeek();
}
@Transient
public int getDayOfTheWeekInteger() {
return mapDayNameToInteger(getDayOfTheWeek());
}
public String getDayOfTheWeek() {
return this.dayOfTheWeek;
}
public void setDayOfTheWeek(String dayOfTheWeek) {
this.dayOfTheWeek = dayOfTheWeek;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DayOfTheWeek that = (DayOfTheWeek) o;
if (dayOfTheWeek != null ? !dayOfTheWeek.equals(that.dayOfTheWeek) : that.dayOfTheWeek != null)
return false;
return true;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("Id = ");
sb.append(getId());
sb.append(" DayOfTheWeek = ");
sb.append(getDayOfTheWeek());
sb.append(super.toString());
return sb.toString();
}
}
| package edu.northwestern.bioinformatics.studycalendar.domain;
import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
/**
* @author Nataliya Shurupova
*/
@Entity
@DiscriminatorValue(value="2")
public class DayOfTheWeek extends Holiday {
private String dayOfTheWeek;
@Transient
public String getDisplayName() {
return getDayOfTheWeek();
}
@Transient
public int getDayOfTheWeekInteger() {
return mapDayNameToInteger(getDayOfTheWeek());
}
public String getDayOfTheWeek() {
return this.dayOfTheWeek;
}
public void setDayOfTheWeek(String dayOfTheWeek) {
this.dayOfTheWeek = dayOfTheWeek;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DayOfTheWeek that = (DayOfTheWeek) o;
if (dayOfTheWeek != null ? !dayOfTheWeek.equals(that.dayOfTheWeek) : that.dayOfTheWeek != null)
return false;
return true;
}
@Override
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("Id = ");
sb.append(getId());
sb.append(" DayOfTheWeek = ");
sb.append(getDayOfTheWeek());
sb.append(super.toString());
return sb.toString();
}
}
|
Remove widget specific code from soap data source | <?php
namespace ATPViz\DataSource;
class SOAP extends AbstractDataSource
{
public function getData()
{
$options = $this->getOptions();
$url = $options['url'];
$namespace = $options['namespace'];
$client = new \ATP\Soap\Client($url, $namespace);
$headers = array();
foreach($options['headers'] as $name => $params)
{
$header = new \ATP\Soap\Header($namespace, $name);
foreach($params as $name => $value)
{
$header->$name = $value;
}
$headers[] = $header;
}
$client->__setHeaders($headers);
$function = $options['function'];
$node = $client->$function();
if(isset($options['dataElement']))
{
$nodes = explode("\\", $options['dataElement']);
foreach($nodes as $curNode)
{
$node = $node[$curNode];
}
}
if($options['extractAttributes'])
{
foreach($node as &$item)
{
if(isset($item['@attributes']))
{
$item = array_merge($item, $item['@attributes']);
unset($item['@attributes']);
}
}
}
$columns = count($node) > 0 ? array_keys($node[0]) : array();
return array(
'columns' => $columns,
'data' => $node,
);
}
}
| <?php
namespace ATPViz\DataSource;
class SOAP extends AbstractDataSource
{
public function getData()
{
$options = $this->getOptions();
$url = $options['url'];
$namespace = $options['namespace'];
$client = new \ATP\Soap\Client($url, $namespace);
$headers = array();
foreach($options['headers'] as $name => $params)
{
$header = new \ATP\Soap\Header($namespace, $name);
foreach($params as $name => $value)
{
$header->$name = $value;
}
$headers[] = $header;
}
$client->__setHeaders($headers);
$node = $client->GetAllSCADAAnalogs();
if(isset($options['dataElement']))
{
$nodes = explode("\\", $options['dataElement']);
foreach($nodes as $curNode)
{
$node = $node[$curNode];
}
}
if($options['extractAttributes'])
{
foreach($node as &$item)
{
if(isset($item['@attributes']))
{
$item = array_merge($item, $item['@attributes']);
unset($item['@attributes']);
}
}
}
$columns = count($node) > 0 ? array_keys($node[0]) : array();
return array(
'columns' => $columns,
'data' => $node,
);
}
}
|
Correct dependency to TYPO3 version to ensure that the correct forms are loaded | <?php
/***************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
***************************************************************/
$EM_CONF[$_EXTKEY] = array (
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend for TYPO3 CMS 6.2, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'shy' => 0,
'version' => '6.2.6-dev',
'dependencies' => '',
'conflicts' => '',
'priority' => 'top',
'loadOrder' => '',
'module' => '',
'state' => 'beta',
'uploadfolder' => 0,
'createDirs' => '',
'modify_tables' => 'tt_content',
'clearcacheonload' => 1,
'lockType' => '',
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'CGLcompliance' => NULL,
'CGLcompliance_note' => NULL,
'constraints' => array(
'depends' => array(
'typo3' => '6.2.4-6.3.99',
'css_styled_content' => '6.2.0-6.3.99',
'realurl' => '1.12.8-1.12.99',
),
'conflicts' => array(
'fluidpages' => '*',
'dyncss' => '*',
),
'suggests' => array()
),
); | <?php
/***************************************************************
* Extension Manager/Repository config file for ext "bootstrap_package".
***************************************************************/
$EM_CONF[$_EXTKEY] = array (
'title' => 'Bootstrap Package',
'description' => 'Bootstrap Package delivers a full configured frontend for TYPO3 CMS 6.2, based on the Bootstrap CSS Framework.',
'category' => 'templates',
'shy' => 0,
'version' => '6.2.6-dev',
'dependencies' => '',
'conflicts' => '',
'priority' => 'top',
'loadOrder' => '',
'module' => '',
'state' => 'beta',
'uploadfolder' => 0,
'createDirs' => '',
'modify_tables' => 'tt_content',
'clearcacheonload' => 1,
'lockType' => '',
'author' => 'Benjamin Kott',
'author_email' => '[email protected]',
'author_company' => 'private',
'CGLcompliance' => NULL,
'CGLcompliance_note' => NULL,
'constraints' => array(
'depends' => array(
'typo3' => '6.2.0-6.3.99',
'css_styled_content' => '6.2.0-6.3.99',
'realurl' => '1.12.8-1.12.99',
),
'conflicts' => array(
'fluidpages' => '*',
'dyncss' => '*',
),
'suggests' => array()
),
); |
Refactor file type registry to use services | <?php
namespace Becklyn\AssetsBundle\File;
use Becklyn\AssetsBundle\Asset\Asset;
use Becklyn\AssetsBundle\File\Type\CssFile;
use Becklyn\AssetsBundle\File\Type\FileType;
use Becklyn\AssetsBundle\File\Type\GenericFile;
use Becklyn\AssetsBundle\File\Type\JavaScriptFile;
use Becklyn\AssetsBundle\File\Type\SvgFile;
class FileTypeRegistry
{
/**
* The file types mapped by file extension
*
* @var array<string,FileType>
*/
private $fileTypes = [];
/**
* @var GenericFile
*/
private $genericFileType;
/**
*
* @param array $fileTypes
*/
public function __construct (array $fileTypes, GenericFile $genericFileType)
{
$this->fileTypes = $fileTypes;
$this->genericFileType = $genericFileType;
}
/**
* @param Asset $asset
* @return FileType
*/
public function getFileType (Asset $asset) : FileType
{
return $this->fileTypes[$asset->getFileType()] ?? $this->genericFileType;
}
/**
* Returns whether the given asset should be imported deferred
*
* @param Asset $asset
* @return bool
*/
public function importDeferred (Asset $asset) : bool
{
$fileType = $this->getFileType($asset);
return $fileType->importDeferred();
}
}
| <?php
namespace Becklyn\AssetsBundle\File;
use Becklyn\AssetsBundle\Asset\Asset;
use Becklyn\AssetsBundle\File\Type\CssFile;
use Becklyn\AssetsBundle\File\Type\FileType;
use Becklyn\AssetsBundle\File\Type\GenericFile;
use Becklyn\AssetsBundle\File\Type\JavaScriptFile;
use Becklyn\AssetsBundle\File\Type\SvgFile;
class FileTypeRegistry
{
/**
* @var array<string,FileType>
*/
private $extensions = [];
/**
* @var GenericFile
*/
private $genericFileType;
/**
*
* @param array $fileTypes
*/
public function __construct (array $fileTypes)
{
$this->extensions = [
"js" => new JavaScriptFile(),
"css" => new CssFile(),
"svg" => new SvgFile(),
];
$this->genericFileType = new GenericFile();
}
/**
* @param Asset $asset
* @return FileType
*/
public function getFileType (Asset $asset) : FileType
{
return $this->extensions[$asset->getFileType()] ?? $this->genericFileType;
}
/**
* Returns whether the given asset should be imported deferred
*
* @param Asset $asset
* @return bool
*/
public function importDeferred (Asset $asset) : bool
{
$fileType = $this->getFileType($asset);
return $fileType->importDeferred();
}
}
|
Add six package version specifier | import os.path
from ez_setup import use_setuptools
use_setuptools(min_version='0.6')
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.1dev',
description='Spatial Analysis and Data Exploration',
long_description=long_description,
author='Synthicity',
author_email='[email protected]',
url='https://github.com/synthicity/spandex',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(exclude=['*.tests']),
install_requires=[
'GDAL>=1.7', # Python 3 support.
'GeoAlchemy2>=0.2.1', # Bug fix for schemas other than public.
'pandas>=0.13.1',
'psycopg2>=2.5', # connection and cursor context managers.
'six>=1.4', # Mapping for urllib.
'SQLAlchemy>=0.8' # GeoAlchemy2 support.
],
extras_require={
'rastertoolz': ['numpy>=1.8.0', 'rasterio>=0.12', 'rasterstats>=0.4',
'shapely>=1.3.2']
}
)
| import os.path
from ez_setup import use_setuptools
use_setuptools(min_version='0.6')
from setuptools import setup, find_packages
# read README as the long description
readme = 'README' if os.path.exists('README') else 'README.md'
with open(readme, 'r') as f:
long_description = f.read()
setup(
name='spandex',
version='0.1dev',
description='Spatial Analysis and Data Exploration',
long_description=long_description,
author='Synthicity',
author_email='[email protected]',
url='https://github.com/synthicity/spandex',
classifiers=[
'Development Status :: 4 - Beta',
'Programming Language :: Python :: 2.7',
],
packages=find_packages(exclude=['*.tests']),
install_requires=[
'GDAL>=1.7', # Python 3 support.
'GeoAlchemy2>=0.2.1', # Bug fix for schemas other than public.
'pandas>=0.13.1',
'psycopg2>=2.5', # connection and cursor context managers.
'six',
'SQLAlchemy>=0.8' # GeoAlchemy2 support.
],
extras_require={
'rastertoolz': ['numpy>=1.8.0', 'rasterio>=0.12', 'rasterstats>=0.4',
'shapely>=1.3.2']
}
)
|
Add null default to getList options param | <?php
declare(strict_types=1);
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\Gandi\Api;
/**
* @author Jérôme Pogeant <[email protected]>
*/
final class Domain extends AbstractApi
{
/**
* @param array $domain
* @param array|null $options
*
* @return array
*/
public function isAvailable(array $domain, array $options = null): array
{
return $this->getGandi()->getClient()->domain->available($domain, $options);
}
/**
* @param string $domain
*
* @return array
*/
public function info(string $domain): array
{
return $this->getGandi()->getClient()->domain->info($domain);
}
/**
* @param array|null $options
*
* @return array
*/
public function getList(array $options = null): array
{
return $this->getGandi()->getClient()->domain->list($options);
}
/**
* @param array $domain
* @param array|null $options
*
* @return array
*/
public function renew(array $domain, array $options = null): array
{
return $this->getGandi()->getClient()->domain->renew($domain, $options);
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of the Nexylan packages.
*
* (c) Nexylan SAS <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nexy\Gandi\Api;
/**
* @author Jérôme Pogeant <[email protected]>
*/
final class Domain extends AbstractApi
{
/**
* @param array $domain
* @param array|null $options
*
* @return array
*/
public function isAvailable(array $domain, array $options = null): array
{
return $this->getGandi()->getClient()->domain->available($domain, $options);
}
/**
* @param string $domain
*
* @return array
*/
public function info(string $domain): array
{
return $this->getGandi()->getClient()->domain->info($domain);
}
/**
* @param array $options
*
* @return array
*/
public function getList(array $options): array
{
return $this->getGandi()->getClient()->domain->list($options);
}
/**
* @param array $domain
* @param array|null $options
*
* @return array
*/
public function renew(array $domain, array $options = null): array
{
return $this->getGandi()->getClient()->domain->renew($domain, $options);
}
}
|
Write cluster_tendrl_context to proper location
Currently it is written to clusters/<node-id>/TendrlContext
This is fixed in this PR
tendrl-bug-id: Tendrl/commons#302
Signed-off-by: nnDarshan <[email protected]> | import json
import logging
import os
import socket
import uuid
from tendrl.commons.etcdobj import EtcdObj
from tendrl.commons.utils import cmd_utils
from tendrl.commons import objects
LOG = logging.getLogger(__name__)
class ClusterTendrlContext(objects.BaseObject):
def __init__(
self,
integration_id=None,
cluster_id=None,
cluster_name=None,
sds_name=None,
sds_version=None,
*args, **kwargs):
super(ClusterTendrlContext, self).__init__(*args, **kwargs)
self.value = 'clusters/%s/TendrlContext'
# integration_id is the Tendrl generated cluster UUID
self.integration_id = integration_id
self.cluster_id=cluster_id
self.cluster_name=cluster_name
self.sds_name=sds_name
self.sds_version=sds_version
self._etcd_cls = _ClusterTendrlContextEtcd
class _ClusterTendrlContextEtcd(EtcdObj):
"""A table of the cluster tendrl context, lazily updated
"""
__name__ = 'clusters/%s/TendrlContext'
_tendrl_cls = ClusterTendrlContext
def render(self):
self.__name__ = self.__name__ % NS.tendrl_context.integration_id
return super(_ClusterTendrlContextEtcd, self).render()
| import json
import logging
import os
import socket
import uuid
from tendrl.commons.etcdobj import EtcdObj
from tendrl.commons.utils import cmd_utils
from tendrl.commons import objects
LOG = logging.getLogger(__name__)
class ClusterTendrlContext(objects.BaseObject):
def __init__(
self,
integration_id=None,
cluster_id=None,
cluster_name=None,
sds_name=None,
sds_version=None,
*args, **kwargs):
super(ClusterTendrlContext, self).__init__(*args, **kwargs)
self.value = 'clusters/%s/TendrlContext'
# integration_id is the Tendrl generated cluster UUID
self.integration_id = integration_id
self.cluster_id=cluster_id
self.cluster_name=cluster_name
self.sds_name=sds_name
self.sds_version=sds_version
self._etcd_cls = _ClusterTendrlContextEtcd
class _ClusterTendrlContextEtcd(EtcdObj):
"""A table of the cluster tendrl context, lazily updated
"""
__name__ = 'clusters/%s/TendrlContext'
_tendrl_cls = ClusterTendrlContext
def render(self):
self.__name__ = self.__name__ % NS.node_context.node_id
return super(_ClusterTendrlContextEtcd, self).render()
|
Handle select/unselect of a single row | /**
* Handling of BUIC listings.
*
* @mixin
* @namespace Bolt.buic.listing
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic.listing mixin container.
*
* @private
* @type {Object}
*/
var listing = {};
/**
* Bind BUIC listings.
*
* @static
* @function init
* @memberof Bolt.buic.listing
*
* @param {Object} buic
*/
listing.init = function (buic) {
// Select/unselect all rows in a listing section.
$(buic).find('tr.header input:checkbox[name="checkRow"]').on('click', function () {
var setStatus = this.checked;
$(this).closest('tbody').find('td input:checkbox[name="checkRow"]').each(function () {
this.checked = setStatus;
rowSelection(this);
});
});
// On check/unchecking a row selector.
$(buic).find('td input:checkbox[name="checkRow"]').on('click', function () {
rowSelection(this);
});
};
/**
* Handle row selection.
*
* @private
* @static
* @function rowSelection
* @memberof Bolt.files
*
* @param {object} checkbox - Checkbox clicked.
*/
function rowSelection(checkbox) {
var row = $(checkbox).closest('tr');
if (checkbox.checked) {
row.addClass('row-checked');
} else {
row.removeClass('row-checked');
}
}
// Apply mixin container
bolt.buic.listing = listing;
})(Bolt || {}, jQuery);
| /**
* Handling of BUIC listings.
*
* @mixin
* @namespace Bolt.buic.listing
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic.listing mixin container.
*
* @private
* @type {Object}
*/
var listing = {};
/**
* Bind BUIC listings.
*
* @static
* @function init
* @memberof Bolt.buic.listing
*
* @param {Object} buic
*/
listing.init = function (buic) {
// Select/unselect all rows in a listing section.
$(buic).find('tr.header input:checkbox[name="checkRow"]').on('click', function () {
var setStatus = this.checked;
$(this).closest('tbody').find('td input:checkbox[name="checkRow"]').each(function () {
var row = $(this).closest('tr');
this.checked = setStatus;
if (setStatus) {
row.addClass('row-checked');
} else {
row.removeClass('row-checked');
}
});
});
};
// Apply mixin container
bolt.buic.listing = listing;
})(Bolt || {}, jQuery);
|
Fix SonarQube issues: not all of them. | /**
*
*/
package normalization;
import datastructures.AttributeJoint;
import datastructures.DFJoint;
import dependency.ADependency;
import dependency.FunctionalDependency;
/**
* @author Pavel Nichita
*
*/
public final class Normalization {
private Normalization() {
// Private constructor to hide the implicit public one.
}
/**
* Calculates all attributes that are being implied by {@code attrJoint} in
* {@code dfJoint}.
*
* The algorithm used is Ullman.
*
* @param attrJoint Attribute joint to who'm calculate ullman.
* @param dfJoint Where to calculate.
* @return an attribute joint with all the attributes implied.
*/
public static AttributeJoint simpleUllman(AttributeJoint attrJoint, DFJoint dfJoint){
AttributeJoint result = new AttributeJoint(attrJoint);
boolean isChanged;
do {
isChanged = false;
for (ADependency df:dfJoint) {
if (df.getClass() == new FunctionalDependency().getClass()) {
if (df.getAntecedent().isContained(result) && !(df.getConsequent().isContained(result))) {
result.addAttributes(df.getConsequent());
isChanged = true;
}
}
}
} while (isChanged);
return result;
}
}
| /**
*
*/
package normalization;
import datastructures.AttributeJoint;
import datastructures.DFJoint;
import dependency.ADependency;
import dependency.FunctionalDependency;
/**
* @author Pavel Nichita
*
*/
public final class Normalization {
/**
* Calculates all attributes that are being implied by {@code attrJoint} in
* {@code dfJoint}.
*
* The algorithm used is Ullman.
*
* @param attrJoint Attribute joint to who'm calculate ullman.
* @param dfJoint Where to calculate.
* @return an attribute joint with all the attributes implied.
*/
public static AttributeJoint simpleUllman(AttributeJoint attrJoint, DFJoint dfJoint){
AttributeJoint result = new AttributeJoint(attrJoint);
boolean isChanged;
do {
isChanged = false;
for (ADependency df:dfJoint) {
if (df.getClass() == new FunctionalDependency().getClass())
if (df.getAntecedent().isContained(result) && !(df.getConsequent().isContained(result))) {
result.addAttributes(df.getConsequent());
isChanged = true;
}
}
} while (isChanged);
return result;
}
}
|
Fix bug with Overleaf commits swapping name and email. | package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;
import uk.ac.ic.wlgitbridge.util.Util;
/**
* Created by Winston on 06/11/14.
*/
public class SnapshotInfo implements Comparable<SnapshotInfo> {
private int versionId;
private String comment;
private WLUser user;
private String createdAt;
public SnapshotInfo(int versionID, String createdAt, String name, String email) {
this(versionID, "Update on " + Util.getServiceName() + ".", email, name, createdAt);
}
public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) {
versionId = versionID;
this.comment = comment;
user = new WLUser(name, email);
this.createdAt = createdAt;
}
public int getVersionId() {
return versionId;
}
public String getComment() {
return comment;
}
public WLUser getUser() {
return user;
}
public String getCreatedAt() {
return createdAt;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SnapshotInfo)) {
return false;
}
SnapshotInfo that = (SnapshotInfo) obj;
return versionId == that.versionId;
}
@Override
public int compareTo(SnapshotInfo o) {
return Integer.compare(versionId, o.versionId);
}
}
| package uk.ac.ic.wlgitbridge.writelatex.api.request.getsavedvers;
import uk.ac.ic.wlgitbridge.util.Util;
/**
* Created by Winston on 06/11/14.
*/
public class SnapshotInfo implements Comparable<SnapshotInfo> {
private int versionId;
private String comment;
private WLUser user;
private String createdAt;
public SnapshotInfo(int versionID, String createdAt, String name, String email) {
this(versionID, "Update on " + Util.getServiceName() + ".", name, email, createdAt);
}
public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) {
versionId = versionID;
this.comment = comment;
user = new WLUser(name, email);
this.createdAt = createdAt;
}
public int getVersionId() {
return versionId;
}
public String getComment() {
return comment;
}
public WLUser getUser() {
return user;
}
public String getCreatedAt() {
return createdAt;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SnapshotInfo)) {
return false;
}
SnapshotInfo that = (SnapshotInfo) obj;
return versionId == that.versionId;
}
@Override
public int compareTo(SnapshotInfo o) {
return Integer.compare(versionId, o.versionId);
}
}
|
Add hash and eq methods | """
File: abstract_constraint.py
Purpose: Define a constraint, in an abstract sense, related to a number of actors.
"""
from abc import ABCMeta, abstractmethod
class AbstractConstraint(object):
"""
Class that represents a constraint, a set of actors that define a constraint amongst themselves.
ParameterMap: A map from template note to contextual note..
"""
__metaclass__ = ABCMeta
def __init__(self, actors):
self.__actors = list(actors)
@property
def actors(self):
return list(self.__actors)
@abstractmethod
def clone(self, new_actors=None):
"""
Clone the constraint.
:return:
"""
@abstractmethod
def verify(self, solution_context):
"""
Verify that the actor map parameters are consistent with constraint.
:params solution_context: aka pmap, map of actors to ContextualNotes.
:return: Boolean if verification holds.
May throw Exception dependent on implementation.
"""
@abstractmethod
def values(self, solution_context, v_note):
"""
Method to generate all possible note values for actor v_note's target.
The method returns a set of values for v_note.
:param solution_context: includes parameter map.
:param v_note: source actor, whose target values we are computing.
:return: The set of all possible values for v_note's target.
Note: The return value is a set!
"""
def __hash__(self):
return hash(len(self.actors))
def __eq__(self, other):
if not isinstance(other, AbstractConstraint):
return NotImplemented
return self is other | """
File: abstract_constraint.py
Purpose: Define a constraint, in an abstract sense, related to a number of actors.
"""
from abc import ABCMeta, abstractmethod
class AbstractConstraint(object):
"""
Class that represents a constraint, a set of actors that define a constraint amongst themselves.
ParameterMap: A map from template note to contextual note..
"""
__metaclass__ = ABCMeta
def __init__(self, actors):
self.__actors = list(actors)
@property
def actors(self):
return list(self.__actors)
@abstractmethod
def clone(self, new_actors=None):
"""
Clone the constraint.
:return:
"""
@abstractmethod
def verify(self, solution_context):
"""
Verify that the actor map parameters are consistent with constraint.
:params solution_context: aka pmap, map of actors to ContextualNotes.
:return: Boolean if verification holds.
May throw Exception dependent on implementation.
"""
@abstractmethod
def values(self, solution_context, v_note):
"""
Method to generate all possible note values for actor v_note's target.
The method returns a set of values for v_note.
:param solution_context: includes parameter map.
:param v_note: source actor, whose target values we are computing.
:return: The set of all possible values for v_note's target.
Note: The return value is a set!
"""
|
Set creationDate and modifiedDate when reading content from external sources to be able to calculate different eTag. | package org.unitedinternet.cosmo.ext;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.hibernate.EntityConverter;
import org.unitedinternet.cosmo.model.hibernate.HibNoteItem;
import net.fortuna.ical4j.model.Calendar;
/**
* Helper class that allows translating <code>Calendar</code> objects to <code>NoteItem</code>-s.
*
* @author daniel grigore
*
*/
public class ContentConverter {
private final EntityConverter entityConverter;
public ContentConverter(EntityConverter entityConverter) {
super();
this.entityConverter = entityConverter;
}
public Set<NoteItem> asItems(Calendar calendar) {
Set<NoteItem> items = new HashSet<>();
if (calendar != null) {
Set<ICalendarItem> calendarItems = this.entityConverter.convertCalendar(calendar);
for (ICalendarItem item : calendarItems) {
/**
* Only VEVENT are supported currently. VTODO or VJOURNAL are not yet supported.
*/
if (item instanceof HibNoteItem) {
HibNoteItem noteItem = (HibNoteItem) item;
Date now = new Date();
noteItem.setCreationDate(now);
noteItem.setModifiedDate(now);
items.add(noteItem);
noteItem.setName(noteItem.getIcalUid() + ".ics");
}
}
}
return items;
}
}
| package org.unitedinternet.cosmo.ext;
import java.util.HashSet;
import java.util.Set;
import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.hibernate.EntityConverter;
import net.fortuna.ical4j.model.Calendar;
/**
* Helper class that allows translating <code>Calendar</code> objects to <code>NoteItem</code>-s.
*
* @author daniel grigore
*
*/
public class ContentConverter {
private final EntityConverter entityConverter;
public ContentConverter(EntityConverter entityConverter) {
super();
this.entityConverter = entityConverter;
}
public Set<NoteItem> asItems(Calendar calendar) {
Set<NoteItem> items = new HashSet<>();
if (calendar != null) {
Set<ICalendarItem> calendarItems = this.entityConverter.convertCalendar(calendar);
for (ICalendarItem item : calendarItems) {
/**
* Only VEVENT are supported currently. VTODO or VJOURNAL are not yet supported.
*/
if (item instanceof NoteItem) {
items.add((NoteItem) item);
item.setName(item.getIcalUid() + ".ics");
}
}
}
return items;
}
}
|
Update to unexpected v10's addAssertion syntax [ci skip]. | /*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 <any>', 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 });
};
var exifData = exifParser.create(subject).parse();
if (exifData && exifData.startMarker) {
delete exifData.startMarker;
}
return expect(exifData, 'to satisfy', value);
});
}
};
| /*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 });
};
var exifData = exifParser.create(subject).parse();
if (exifData && exifData.startMarker) {
delete exifData.startMarker;
}
return expect(exifData, 'to satisfy', value);
});
}
};
|
Add comments in StripeJS mock | // StripeJS fixture for using Stripe in feature specs. Mimics credit card form and Element objects.
// Based on: https://github.com/thoughtbot/fake_stripe/blob/v0.3.0/lib/fake_stripe/assets/v3.js
// The original has been adapted to work with OFN (see commit history for details).
class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.classList.add('StripeElement');
el.innerHTML = `
<input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text">
<input name="exp-date" placeholder="MM / YY" size="6" type="text">
<input name="cvc" placeholder="CVC" size="3" type="text">
`;
}
addEventListener(event) {
return true;
}
}
window.Stripe = () => {
const fetchLastFour = () => {
return document.getElementById("stripe-cardnumber").value.substr(-4, 4);
};
return {
createPaymentMethod: () => {
return new Promise(resolve => {
resolve({
paymentMethod: {
id: "pm_123",
card: {
brand: 'visa',
last4: fetchLastFour(),
exp_month: "10",
exp_year: "2050"
}
}
});
});
},
elements: () => {
return {
create: (type, options) => new Element()
};
},
createToken: card => {
return new Promise(resolve => {
resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } });
});
}
};
};
| class Element {
mount(el) {
if (typeof el === "string") {
el = document.querySelector(el);
}
el.classList.add('StripeElement');
el.innerHTML = `
<input id="stripe-cardnumber" name="cardnumber" placeholder="Card number" size="16" type="text">
<input name="exp-date" placeholder="MM / YY" size="6" type="text">
<input name="cvc" placeholder="CVC" size="3" type="text">
`;
}
addEventListener(event) {
return true;
}
}
window.Stripe = () => {
const fetchLastFour = () => {
return document.getElementById("stripe-cardnumber").value.substr(-4, 4);
};
return {
createPaymentMethod: () => {
return new Promise(resolve => {
resolve({
paymentMethod: {
id: "pm_123",
card: {
brand: 'visa',
last4: fetchLastFour(),
exp_month: "10",
exp_year: "2050"
}
}
});
});
},
elements: () => {
return {
create: (type, options) => new Element()
};
},
createToken: card => {
return new Promise(resolve => {
resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } });
});
}
};
};
|
Make it work with last fman version (0.7) on linux | from fman import DirectoryPaneCommand, show_alert
from urllib.parse import urlparse
import os.path
from shutil import copytree, copyfile
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(selected_files) == 0 and self.get_chosen_files()):
if len(selected_files) == 0 and self.get_chosen_files():
selected_files.append(self.get_chosen_files()[0])
#
# Loop through each file/directory selected.
#
for filedir in selected_files:
p = urlparse(filedir)
filepath = os.path.abspath(os.path.join(p.netloc, p.path))
if os.path.isdir(filepath):
#
# It is a directory. Process as a directory.
#
newDir = filepath + "-copy"
copytree(filepath, newDir)
else:
if os.path.isfile(filepath):
#
# It is a file. Process as a file.
#
dirPath, ofilenmc = os.path.split(filepath)
ofilenm, ext = os.path.splitext(ofilenmc)
nfilenm = os.path.join(dirPath,ofilenm + "-copy" + ext)
copyfile(filepath, nfilenm)
else:
show_alert('Bad file path : {0}'.format(filepath))
| from fman import DirectoryPaneCommand, show_alert
import distutils
from distutils import dir_util, file_util
import os.path
class DuplicateFileDir(DirectoryPaneCommand):
def __call__(self):
selected_files = self.pane.get_selected_files()
if len(selected_files) >= 1 or (len(selected_files) == 0 and self.get_chosen_files()):
if len(selected_files) == 0 and self.get_chosen_files():
selected_files.append(self.get_chosen_files()[0])
#
# Loop through each file/directory selected.
#
for filedir in selected_files:
if os.path.isdir(filedir):
#
# It is a directory. Process as a directory.
#
newDir = filedir + "-copy"
distutils.dir_util.copy_tree(filedir,newDir)
else:
#
# It is a file. Process as a file.
#
dirPath, ofilenmc = os.path.split(filedir)
ofilenm, ext = os.path.splitext(ofilenmc)
nfilenm = os.path.join(dirPath,ofilenm + "-copy" + ext)
distutils.file_util.copy_file(filedir,nfilenm)
|