text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add test for getLastError selector
|
import * as selectors from '../src/selectors'
describe('selectors', () => {
it('includes selector to get session data', () => {
const state = {
session: {
data: { token: 'abcde' }
}
}
const result = selectors.getSessionData(state)
expect(result).toEqual({ token: 'abcde' })
})
it('includes selector to get isAuthenticated', () => {
const state = {
session: {
isAuthenticated: true
}
}
const result = selectors.getIsAuthenticated(state)
expect(result).toEqual(true)
})
it('includes selector to get authenticator', () => {
const state = {
session: {
authenticator: 'credentials'
}
}
const result = selectors.getAuthenticator(state)
expect(result).toEqual('credentials')
})
it('includes selector to get isRestored', () => {
const state = {
session: {
isRestored: false
}
}
const result = selectors.getIsRestored(state)
expect(result).toEqual(false)
})
it('includes selector to get lastError', () => {
const state = {
session: {
lastError: 'You shall not pass'
}
}
const result = selectors.getLastError(state)
expect(result).toEqual('You shall not pass')
})
})
|
import * as selectors from '../src/selectors'
describe('selectors', () => {
it('includes selector to get session data', () => {
const state = {
session: {
data: { token: 'abcde' }
}
}
const result = selectors.getSessionData(state)
expect(result).toEqual({ token: 'abcde' })
})
it('includes selector to get isAuthenticated', () => {
const state = {
session: {
isAuthenticated: true
}
}
const result = selectors.getIsAuthenticated(state)
expect(result).toEqual(true)
})
it('includes selector to get authenticator', () => {
const state = {
session: {
authenticator: 'credentials'
}
}
const result = selectors.getAuthenticator(state)
expect(result).toEqual('credentials')
})
it('includes selector to get isRestored', () => {
const state = {
session: {
isRestored: false
}
}
const result = selectors.getIsRestored(state)
expect(result).toEqual(false)
})
})
|
Update tag for search on StackOverflow
Since the emberjs tag has been renamed to ember.js. A search for the "old" tag doesn't return any results...
|
require('dashboard/core');
Dashboard.DataSource = Ember.Object.extend({
getLatestTweets: function(callback) {
Ember.$.getJSON('http://search.twitter.com/search.json?callback=?&q=ember.js%20OR%20emberjs%20OR%20ember-data%20OR%20emberjs', callback);
},
getLatestStackOverflowQuestions: function(callback) {
Ember.$.getJSON('https://api.stackexchange.com/2.0/search?pagesize=20&order=desc&sort=activity&tagged=ember.js&site=stackoverflow&callback=?', callback);
},
getLatestRedditEntries: function(callback) {
Ember.$.getJSON('http://www.reddit.com/r/emberjs/new.json?sort=new&jsonp=?', callback);
},
getLatestGitHubEvents: function(callback) {
Ember.$.getJSON('https://api.github.com/repos/emberjs/ember.js/events?page=1&per_page=100&callback=?', callback);
}
});
|
require('dashboard/core');
Dashboard.DataSource = Ember.Object.extend({
getLatestTweets: function(callback) {
Ember.$.getJSON('http://search.twitter.com/search.json?callback=?&q=ember.js%20OR%20emberjs%20OR%20ember-data%20OR%20emberjs', callback);
},
getLatestStackOverflowQuestions: function(callback) {
Ember.$.getJSON('https://api.stackexchange.com/2.0/search?pagesize=20&order=desc&sort=activity&tagged=emberjs&site=stackoverflow&callback=?', callback);
},
getLatestRedditEntries: function(callback) {
Ember.$.getJSON('http://www.reddit.com/r/emberjs/new.json?sort=new&jsonp=?', callback);
},
getLatestGitHubEvents: function(callback) {
Ember.$.getJSON('https://api.github.com/repos/emberjs/ember.js/events?page=1&per_page=100&callback=?', callback);
}
});
|
Fix a bug that will lead to error when external_login() is called
|
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
data = dict(data)
data_log = {'user': data.get('user', 'external')}
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data_log, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
|
import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request: user = %s data = %s, url = %s"%(session['username'], data, url))
result = requests.post(endpoint + url, data = data).json()
if (result.get('success', None) == "false" and (result.get('reason', None) == "Unauthorized Action" or result.get('Unauthorized', None) == 'True')):
abort(401)
logger.info ("Docklet Response: user = %s result = %s, url = %s"%(session['username'], result, url))
return result
#except:
#abort(500)
@classmethod
def unauthorizedpost(self, url = '/', data = None):
logger.info("Docklet Unauthorized Request: data = %s, url = %s" % (data, url))
result = requests.post(endpoint + url, data = data).json()
logger.info("Docklet Unauthorized Response: result = %s, url = %s"%(result, url))
return result
|
Correct inconsistent quote usage, release 0.1.0.
|
#!/usr/bin/env python
from setuptools import setup
setup(
name="Tigger",
version="0.1.0",
packages=["tigger",],
license="MIT",
description="Command-line tagging tool.",
long_description="Tigger is a command-line tagging tool written in " +
"python, intended for tracking tags on files in a form which can " +
"be transferred with the files while remaining out of sight " +
"normally (much like git's metadata, except not so clever).",
entry_points={
"console_scripts": [
"tigger = tigger.app:main",
],
},
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='Tigger',
version='0.1.0',
packages=['tigger',],
license='MIT',
description="Command-line tagging tool.",
long_description="Tigger is a command-line tagging tool written in " +
"python, intended for tracking tags on files in a form which can " +
"be transferred with the files while remaining out of sight " +
"normally (much like git's metadata, except not so clever).",
entry_points={
"console_scripts": [
"tigger = tigger.app:main",
],
},
)
|
Switch to paorwise method for PopcornTime
|
// @flow
const Rx = require('rx')
const _ = require('lodash')
const PopcornTime = require('../../sources/PopcornTime')
// const INTERVAL: number = 1000 * 60 * 60 // 1 hour TODO: Move to config
const INTERVAL: number = 1000 * 5 // 5 seconds
// every INTERVAL seconds, check the source for inputs, diff the incoming inputs with a stored previous inputs array, update that array and then only emit events that had atleast 1 "diffed" input
// let lastCheckedEpisodes = [];
const source$ = Rx.Observable
.interval(INTERVAL)
.exhaustMap(() => PopcornTime({ shows: ['tt4179452', 'tt3530232', 'tt2575988'] })) // TODO: Don't hardcode. Move to config, and then to input
.pairwise()
.map(([a, b]) => _.differenceBy(b, a, 'tvdb_id'))
.filter(episodes => episodes.length)
// source$
// .map(episodes => episodes.map(e => e.title))
// .subscribe(console.log)
module.exports = source$
|
// @flow
const Rx = require('rx')
const _ = require('lodash')
const PopcornTime = require('../../sources/PopcornTime')
const INTERVAL: number = 1000 * 60 * 60 // 1 hour
// const INTERVAL: number = 1000 * 5 // 5 seconds
// every INTERVAL seconds, check the source for inputs, diff the incoming inputs with a stored previous inputs array, update that array and then only emit events that had atleast 1 "diffed" input
let lastCheckedEpisodes = [];
const source = Rx.Observable
.interval(INTERVAL)
.exhaustMap(() => PopcornTime({ shows: ['tt4179452', 'tt3530232', 'tt2575988'] }))
.map(episodes => _.differenceBy(episodes, lastCheckedEpisodes, 'tvdb_id'))
.do(episodes => lastCheckedEpisodes = lastCheckedEpisodes.concat(episodes))
.filter(episodes => episodes.length)
.skip(1) // comment if you want the initial list of events
// source
// .map(episodes => episodes.map(e => e.title))
// .subscribe(console.log)
module.exports = source
|
Make longer line by default for divider option.
svn commit r2832
|
<?php
require_once 'Swat/SwatFlydownOption.php';
/**
* A class representing a divider in a flydown
*
* This class is for semantic purposed only. The flydown handles all the
* displaying of dividers and regular flydown options.
*
* @package Swat
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatFlydownDivider extends SwatFlydownOption
{
/**
* Creates a flydown option
*
* @param mixed $value value of the option.
* @param string $title displayed title of the divider. This defaults to
* two em dashes.
*/
public function __construct($value, $title = null)
{
if ($title === null)
$title = str_repeat('—', 6);
$this->value = $value;
$this->title = $title;
}
}
?>
|
<?php
require_once 'Swat/SwatFlydownOption.php';
/**
* A class representing a divider in a flydown
*
* This class is for semantic purposed only. The flydown handles all the
* displaying of dividers and regular flydown options.
*
* @package Swat
* @copyright 2005 silverorange
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
*/
class SwatFlydownDivider extends SwatFlydownOption
{
/**
* Creates a flydown option
*
* @param mixed $value value of the option.
* @param string $title displayed title of the divider. This defaults to
* two em dashes.
*/
public function __construct($value, $title = '——')
{
$this->value = $value;
$this->title = $title;
}
}
?>
|
Check for file and line before assignment
If the file, line, or both are missing, this breaks completely.
|
<?php
namespace Airbrake\Errors;
/**
* Error wrapper that mimics Exception API. For internal usage.
*/
class Base
{
private $message;
private $file;
private $line;
private $trace;
public function __construct($message, $trace = [])
{
$this->message = $message;
$frame = array_shift($trace);
if ($frame != null) {
if (isset($frame['file'])) {
$this->file = $frame['file'];
}
if (isset($frame['line'])) {
$this->line = $frame['line'];
}
}
$this->trace = $trace;
}
public function getMessage()
{
return $this->message;
}
public function getFile()
{
return $this->file;
}
public function getLine()
{
return $this->line;
}
public function getTrace()
{
return $this->trace;
}
}
|
<?php
namespace Airbrake\Errors;
/**
* Error wrapper that mimics Exception API. For internal usage.
*/
class Base
{
private $message;
private $file;
private $line;
private $trace;
public function __construct($message, $trace = [])
{
$this->message = $message;
$frame = array_shift($trace);
if ($frame != null) {
$this->file = $frame['file'];
$this->line = $frame['line'];
}
$this->trace = $trace;
}
public function getMessage()
{
return $this->message;
}
public function getFile()
{
return $this->file;
}
public function getLine()
{
return $this->line;
}
public function getTrace()
{
return $this->trace;
}
}
|
Move cortex:autoload & cortex:activate commands to cortex/foundation module responsibility
|
<?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Console\Command;
class InstallCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:install:foundation {--f|force : Force the operation to run when in production.} {--r|resource=* : Specify which resources to publish.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install Cortex Foundation Module.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
$this->call('cortex:publish:foundation', ['--force' => $this->option('force'), '--resource' => $this->option('resource')]);
$this->call('cortex:migrate:foundation', ['--force' => $this->option('force')]);
$this->call('cortex:seed:foundation');
}
}
|
<?php
declare(strict_types=1);
namespace Cortex\Foundation\Console\Commands;
use Illuminate\Console\Command;
class InstallCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cortex:install:foundation {--f|force : Force the operation to run when in production.} {--r|resource=* : Specify which resources to publish.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install Cortex Foundation Module.';
/**
* Execute the console command.
*
* @return void
*/
public function handle(): void
{
$this->alert($this->description);
$this->call('cortex:publish:foundation', ['--force' => $this->option('force'), '--resource' => $this->option('resource')]);
$this->call('cortex:migrate:foundation', ['--force' => $this->option('force')]);
$this->call('cortex:seed:foundation');
$this->call('cortex:autoload:foundation', ['--force' => $this->option('force')]);
$this->call('cortex:activate:foundation', ['--force' => $this->option('force')]);
}
}
|
Load service w/ apt items
|
// Module dependencies.
var express = require('express');
var router = express.Router();
var api = {};
// ALL
api.appointmentItems = function(req) {
return req.store.recordCollection('AppointmentItem', {include: ['service']});
};
// GET
api.appointmentItem = function(req) {
return req.store.recordItemById('AppointmentItem', req.params.id, {include: ['service']});
};
// POST
api.addAppointmentItem = function(req) {
return req.store.createRecord('AppointmentItem', {
include: ['service'],
beforeSave(model, save) {
model.client = req.user;
save();
},
});
};
// PUT
api.editAppointmentItem = function(req) {
return req.store.updateRecord('AppointmentItem', req.params.id, {include: ['service']});
};
// DELETE
api.deleteAppointmentItem = function(req) {
return req.store.destroyRecord('AppointmentItem', req.params.id);
};
router.get('/appointmentItems', api.appointmentItems);
router.post('/appointmentItems', api.addAppointmentItem);
router.route('/appointmentItems/:id')
.get(api.appointmentItem)
.put(api.editAppointmentItem)
.delete(api.deleteAppointmentItem);
module.exports = router;
|
// Module dependencies.
var express = require('express');
var router = express.Router();
var api = {};
// ALL
api.appointmentItems = function(req) {
return req.store.recordCollection('AppointmentItem');
};
// GET
api.appointmentItem = function(req) {
return req.store.recordItemById('AppointmentItem', req.params.id);
};
// POST
api.addAppointmentItem = function(req) {
return req.store.createRecord('AppointmentItem', {
beforeSave(model, save) {
model.client = req.user;
save();
},
});
};
// PUT
api.editAppointmentItem = function(req) {
return req.store.updateRecord('AppointmentItem', req.params.id);
};
// DELETE
api.deleteAppointmentItem = function(req) {
return req.store.destroyRecord('AppointmentItem', req.params.id);
};
router.get('/appointmentItems', api.appointmentItems);
router.post('/appointmentItems', api.addAppointmentItem);
router.route('/appointmentItems/:id')
.get(api.appointmentItem)
.put(api.editAppointmentItem)
.delete(api.deleteAppointmentItem);
module.exports = router;
|
Make create a class method.
|
import re
class RegexFactory(object):
"""Generates a regex pattern."""
WORD_GROUP = '({0}|\*)'
SEP = '/'
def _generate_pattern(self, path):
"""Generates a regex pattern."""
# Split the path up into a list using the forward slash as a
# delimiter.
words = (word for word in path.split(self.SEP) if word)
# Compose a list of regular expression groups for each word in
# the path.
patterns = (self.WORD_GROUP.format(re.escape(word)) for word in words)
# Implode the list into a single regex pattern that will match
# the path pattern format.
return '^{0}$'.format(('\,').join(patterns))
@classmethod
def create(cls, path):
rf = cls()
pattern = rf._generate_pattern(path)
return re.compile(pattern, re.ASCII | re.MULTILINE)
|
import re
class RegexFactory(object):
"""Generates a regex pattern."""
WORD_GROUP = '({0}|\*)'
SEP = '/'
def _generate_pattern(self, path):
"""Generates a regex pattern."""
# Split the path up into a list using the forward slash as a
# delimiter.
words = (word for word in path.split(self.SEP) if word)
# Compose a list of regular expression groups for each word in
# the path.
patterns = (self.WORD_GROUP.format(re.escape(word)) for word in words)
# Implode the list into a single regex pattern that will match
# the path pattern format.
return '^{0}$'.format(('\,').join(patterns))
def create(self, path):
pattern = self._generate_pattern(path)
return re.compile(pattern, re.ASCII | re.MULTILINE)
|
Add target _blank to ahref
|
import React from 'react';
/**
* Header Component.
*/
const Header = () =>
<nav>
<div className="nav-wrapper teal darken-3">
<div className="container">
<a href="/nepali-names" className="brand-logo">
Nepali Names
</a>
<a
className="grey-text text-lighten-4 right"
href="https://github.com/mesaugat/nepali-names"
target="_blank"
rel="noopener noreferrer"
>
<i
className="fa fa-github material-icons"
title="GitHub"
aria-hidden="true"
/>
</a>
</div>
</div>
</nav>;
export default Header;
|
import React from 'react';
/**
* Header Component.
*/
const Header = () => (
<nav>
<div className="nav-wrapper teal darken-3">
<div className="container">
<a href="/nepali-names" className="brand-logo">
Nepali Names
</a>
<a
className="grey-text text-lighten-4 right"
href="https://github.com/mesaugat/nepali-names"
>
<i
className="fa fa-github material-icons"
title="GitHub"
target="_blank"
rel="noopener noreferrer"
aria-hidden="true"
/>
</a>
</div>
</div>
</nav>
);
export default Header;
|
Fix to allow more flexible version numbers
|
#!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "egrep -or 'Mininet [0-9\.]+\w*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
|
#!/usr/bin/python
from subprocess import check_output as co
from sys import exit
# Actually run bin/mn rather than importing via python path
version = 'Mininet ' + co( 'PYTHONPATH=. bin/mn --version', shell=True )
version = version.strip()
# Find all Mininet path references
lines = co( "grep -or 'Mininet \w\+\.\w\+\.\w\+[+]*' *", shell=True )
error = False
for line in lines.split( '\n' ):
if line and 'Binary' not in line:
fname, fversion = line.split( ':' )
if version != fversion:
print "%s: incorrect version '%s' (should be '%s')" % (
fname, fversion, version )
error = True
if error:
exit( 1 )
|
Disable some annoying JSCS stuff
|
// server.js
//jscs:disable requireTrailingComma, disallowQuotedKeysInObjects
'use strict';
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser'); // Pull info from HTML POST
const methodOverride = require('method-override'); // Simulate DELETE and PUT
const argv = require('yargs');
// =============================================================================
// Configuration
// DB Config
const DB_URL = argv.db || process.env.DATABASE_URL;
mongoose.connect(DB_URL);
// Set static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// Log every request to the console
app.use(morgan('dev'));
// Parse application/x-www-form-unlencoded, JSON, and vnd.api+json as JSON
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
// =============================================================================
// Initilize app
app.listen(8080);
console.log('App is running on port 8080');
|
// server.js
'use strict';
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser'); // Pull info from HTML POST
const methodOverride = require('method-override'); // Simulate DELETE and PUT
const argv = require('yargs');
// =============================================================================
// Configuration
// DB Config
const DB_URL = argv.db || process.env.DATABASE_URL;
mongoose.connect(DB_URL);
// Set static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// Log every request to the console
app.use(morgan('dev'));
// Parse application/x-www-form-unlencoded, JSON, and vnd.api+json as JSON
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
// =============================================================================
// Initilize app
app.listen(8080);
console.log('App is running on port 8080');
|
Add style to the attendee
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './Attendee.css';
import Clap from '../../components/Clap/Clap.container';
class Atendee extends Component {
constructor(props) {
super(props);
this.confettiClass = 'button button--large button--circle button--withChrome u-baseColor--buttonNormal button--withIcon button--withSvgIcon clapButton js-actionMultirecommendButton clapButton--largePill u-relative u-foreground u-width60 u-height60 u-accentColor--textNormal u-accentColor--buttonNormal is-touched';
this.pulsatingClass = 'button button--large button--circle button--withChrome u-baseColor--buttonNormal button--withIcon button--withSvgIcon clapButton js-actionMultirecommendButton clapButton--largePill u-relative u-foreground u-accentColor--textNormal u-accentColor--buttonNormal is-touched';
}
componentWillMount() {
// this.props.join();
}
render() {
return (
<button className={this.pulsatingClass} style={{ top: 14, padding: 2 }}>
<Clap />
</button>
);
}
}
Atendee.propTypes = {
join: PropTypes.func.isRequired,
};
export default Atendee;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './Attendee.css';
import Clap from '../../components/Clap/Clap.container';
class Atendee extends Component {
constructor(props) {
super(props);
this.confettiClass = 'button button--large button--circle button--withChrome u-baseColor--buttonNormal button--withIcon button--withSvgIcon clapButton js-actionMultirecommendButton clapButton--largePill u-relative u-foreground u-width60 u-height60 u-accentColor--textNormal u-accentColor--buttonNormal is-touched';
this.pulsatingClass = 'button button--large button--circle button--withChrome u-baseColor--buttonNormal button--withIcon button--withSvgIcon clapButton js-actionMultirecommendButton clapButton--largePill u-relative u-foreground u-width60 u-height60 u-accentColor--textNormal u-accentColor--buttonNormal is-touched';
}
componentWillMount() {
// this.props.join();
}
render() {
return (
<button className={this.pulsatingClass} style={{ top: 14, padding: 2 }}>
<Clap />
</button>
);
}
}
Atendee.propTypes = {
join: PropTypes.func.isRequired,
};
export default Atendee;
|
[chore] Add ngAnimate module to uploadcontroller.js
|
angular.module('upload', [
'utils',
'ngAnimate'
])
.controller('uploadController', [
'$scope',
'$http',
'$stateParams',
'$rootScope',
'fileTransfer',
'webRTC',
'packetHandlers',
'fileUpload',
function($scope, $http, $stateParams, $rootScope, fileTransfer, webRTC, packetHandlers, fileUpload) {
console.log('upload controller loaded');
$scope.incomingFileTransfers = fileTransfer.incomingFileTransfers;
$scope.outgoingFileTransfers = fileTransfer.outgoingFileTransfers;
$scope.acceptFileOffer = fileUpload.acceptFileOffer;
$scope.rejectFileOffer = fileUpload.rejectFileOffer;
$scope.offers = fileTransfer.offers;
console.log('upload scope', $scope.offers);
}]);
|
angular.module('upload', [
'utils'
])
.controller('uploadController', [
'$scope',
'$http',
'$stateParams',
'$rootScope',
'fileTransfer',
'webRTC',
'packetHandlers',
'fileUpload',
function($scope, $http, $stateParams, $rootScope, fileTransfer, webRTC, packetHandlers, fileUpload) {
console.log('upload controller loaded');
$scope.incomingFileTransfers = fileTransfer.incomingFileTransfers;
$scope.outgoingFileTransfers = fileTransfer.outgoingFileTransfers;
$scope.acceptFileOffer = fileUpload.acceptFileOffer;
$scope.rejectFileOffer = fileUpload.rejectFileOffer;
$scope.offers = fileTransfer.offers;
console.log('upload scope', $scope.offers);
}]);
|
Make namespace check more robust
|
import {NAMESPACE, PREFIX} from './constants';
const ast = require('parametric-svg-ast');
const arrayFrom = require('array-from');
const startsWith = require('starts-with');
const ELEMENT_NODE = 1;
const getChildren = ({children, childNodes}) => (children ?
arrayFrom(children) :
arrayFrom(childNodes).filter(({nodeType}) => nodeType === ELEMENT_NODE)
);
const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => (
('namespaceURI' in node ?
node.namespaceURI === namespace :
(prefix !== null && startsWith(node.name, `${prefix}:`))
)
);
const getLocalName = (node) => ('namespaceURI' in node ?
node.localName :
node.name.replace(new RegExp(`^.*?:`), '')
);
const crawl = (parentAddress) => (attributes, element, indexInParent) => {
const address = parentAddress.concat(indexInParent);
const currentAttributes = arrayFrom(element.attributes)
.filter((node) => nodeBelongsToNamespace({
namespace: NAMESPACE,
prefix: PREFIX,
}, node))
.map((attribute) => ({
address,
name: getLocalName(attribute),
dependencies: [], // Proof of concept
relation: () => Number(attribute.value), // Proof of concept
}));
return getChildren(element).reduce(
crawl(address),
attributes.concat(currentAttributes)
);
};
export default (root) => {
const attributes = getChildren(root).reduce(crawl([]), []);
return ast({attributes, defaults: []});
};
|
import {NAMESPACE, PREFIX} from './constants';
const ast = require('parametric-svg-ast');
const arrayFrom = require('array-from');
const startsWith = require('starts-with');
const ELEMENT_NODE = 1;
const getChildren = ({children, childNodes}) => (children ?
arrayFrom(children) :
arrayFrom(childNodes).filter(({nodeType}) => nodeType === ELEMENT_NODE)
);
const nodeBelongsToNamespace = ({namespace, prefix = null}, node) => (
node.namespaceURI === namespace ||
(prefix !== null && startsWith(node.name, `${prefix}:`))
);
const getLocalName = (node) => (
(node.namespaceURI && node.localName) ||
node.name.replace(new RegExp(`^.*?:`), '')
);
const crawl = (parentAddress) => (attributes, element, indexInParent) => {
const address = parentAddress.concat(indexInParent);
const currentAttributes = arrayFrom(element.attributes)
.filter((node) => nodeBelongsToNamespace({
namespace: NAMESPACE,
prefix: PREFIX,
}, node))
.map((attribute) => ({
address,
name: getLocalName(attribute),
dependencies: [], // Proof of concept
relation: () => Number(attribute.value), // Proof of concept
}));
return getChildren(element).reduce(
crawl(address),
attributes.concat(currentAttributes)
);
};
export default (root) => {
const attributes = getChildren(root).reduce(crawl([]), []);
return ast({attributes, defaults: []});
};
|
Use get for loading dialog.
|
<?php
/**
* Copyright (c) 2012 Thomas Tanghus <thomas@tanghus.net>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
function bailOut($msg) {
OC_JSON::error(array('data' => array('message' => $msg)));
OC_Log::write('core', 'ajax/vcategories/addToFavorites.php: '.$msg, OC_Log::DEBUG);
exit();
}
function debug($msg) {
OC_Log::write('core', 'ajax/vcategories/addToFavorites.php: '.$msg, OC_Log::DEBUG);
}
require_once '../../../lib/base.php';
OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
$type = isset($_GET['type']) ? $_GET['type'] : null;
if(is_null($type)) {
$l = OC_L10N::get('core');
bailOut($l->t('Object type not provided.'));
}
$categories = new OC_VCategories($type);
$ids = $categories->getFavorites($type)) {
OC_JSON::success(array('ids' => $ids));
|
<?php
/**
* Copyright (c) 2012 Thomas Tanghus <thomas@tanghus.net>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
function bailOut($msg) {
OC_JSON::error(array('data' => array('message' => $msg)));
OC_Log::write('core', 'ajax/vcategories/addToFavorites.php: '.$msg, OC_Log::DEBUG);
exit();
}
function debug($msg) {
OC_Log::write('core', 'ajax/vcategories/addToFavorites.php: '.$msg, OC_Log::DEBUG);
}
require_once '../../../lib/base.php';
OCP\JSON::checkLoggedIn();
OCP\JSON::callCheck();
$type = isset($_POST['type']) ? $_POST['type'] : null;
if(is_null($type)) {
$l = OC_L10N::get('core');
bailOut($l->t('Object type not provided.'));
}
$categories = new OC_VCategories($type);
$ids = $categories->getFavorites($type)) {
OC_JSON::success(array('ids' => $ids));
|
Fix the keywords, url, and description.
|
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
# with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
# README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="django-name",
version="pre-release",
packages=find_packages(),
include_package_data=True,
license="BSD",
description="Name Authority App for Django.",
# long_description=README,
keywords="django name citation",
author="University of North Texas Libraries",
# cmdclass={'test': PyTest},
url="https://github.com/unt-libraries/django-name",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: System Administrators",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application :: User Management"
]
)
|
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
# with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
# README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="django-name",
version="1.0.0",
packages=find_packages(),
include_package_data=True,
license="BSD",
description="A Django application for inviting users to a site.",
# long_description=README,
keywords="django invite invitation",
author="University of North Texas Libraries",
# cmdclass={'test': PyTest},
url="https://github.com/unt-libraries/django-invite",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: System Administrators",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application :: User Management"
]
)
|
Add showcase flag in networkset.
|
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSet extends NdexExternalObject {
private String name;
private String description;
private UUID ownerId;
private List<UUID> networks;
private boolean showcased;
private Map<String, Object> properties;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
properties = new HashMap<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UUID getOwnerId() {
return ownerId;
}
public void setOwnerId(UUID ownerId) {
this.ownerId = ownerId;
}
public List<UUID> getNetworks() {
return networks;
}
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public boolean isShowcased() {
return showcased;
}
public void setShowcased(boolean showcased) {
this.showcased = showcased;
}
}
|
package org.ndexbio.model.object;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class NetworkSet extends NdexExternalObject {
private String name;
private String description;
private UUID ownerId;
private List<UUID> networks;
public NetworkSet () {
super();
networks = new ArrayList<>(30);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UUID getOwnerId() {
return ownerId;
}
public void setOwnerId(UUID ownerId) {
this.ownerId = ownerId;
}
public List<UUID> getNetworks() {
return networks;
}
public void setNetworks(List<UUID> networks) {
this.networks = networks;
}
}
|
Add placeholder link to workshop fold
|
'use strict';
import React from 'react';
import { Link } from 'react-router';
var WorkshopFold = React.createClass({
displayName: 'WorkshopFold',
render: function () {
return (
<section className='workshop-fold'>
<div className='inner'>
<header className='workshop-fold__header'>
<h1 className='workshop-fold__title'>Hold a Workshop</h1>
<div className='prose prose--responsive'>
<p>Interested in convening various members of your community around open air quality data? We can help!</p>
<p><Link to='/community' className='workshop-go-button' title='Learn more'><span>Learn how</span></Link></p>
</div>
</header>
<figure className='workshop-fold__media'>
<img src='/assets/graphics/content/view--community-workshops/workshop-fold-media.jpg' alt='Cover image' width='830' height='830' />
</figure>
</div>
</section>
);
}
});
module.exports = WorkshopFold;
|
'use strict';
import React from 'react';
var WorkshopFold = React.createClass({
displayName: 'WorkshopFold',
render: function () {
return (
<section className='workshop-fold'>
<div className='inner'>
<header className='workshop-fold__header'>
<h1 className='workshop-fold__title'>Hold a Workshop</h1>
<div className='prose prose--responsive'>
<p>Interested in convening various members of your community around open air quality data? We can help!</p>
<p><a href='#' className='workshop-go-button' title='Learn more'><span>Learn how</span></a></p>
</div>
</header>
<figure className='workshop-fold__media'>
<img src='/assets/graphics/content/view--community-workshops/workshop-fold-media.jpg' alt='Cover image' width='830' height='830' />
</figure>
</div>
</section>
);
}
});
module.exports = WorkshopFold;
|
Fix preserve3d's IE11/Win10 false positive
|
/*!
{
"name": "CSS Transform Style preserve-3d",
"property": "preserve3d",
"authors": ["denyskoch", "aFarkas"],
"tags": ["css"],
"notes": [{
"name": "MDN Docs",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style"
},{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/1748"
}]
}
!*/
/* DOC
Detects support for `transform-style: preserve-3d`, for getting a proper 3D perspective on elements.
*/
define(['Modernizr', 'createElement', 'docElement'], function(Modernizr, createElement, docElement) {
Modernizr.addTest('preserve3d', function() {
var outerDiv, innerDiv;
var CSS = window.CSS;
var result = true;
if (!CSS || !CSS.supports || !CSS.supports('(transform-style: preserve-3d)')) {
outerDiv = createElement('div');
innerDiv = createElement('div');
outerDiv.style.cssText = 'transform-style: preserve-3d; transform-origin: right; transform: rotateY(40deg);';
innerDiv.style.cssText = 'width: 9px; height: 1px; background: #000; transform-origin: right; transform: rotateY(40deg);';
outerDiv.appendChild(innerDiv);
docElement.appendChild(outerDiv);
result = innerDiv.getBoundingClientRect();
docElement.removeChild(outerDiv);
result = result.width && result.width < 4;
}
return result;
});
});
|
/*!
{
"name": "CSS Transform Style preserve-3d",
"property": "preserve3d",
"authors": ["denyskoch", "aFarkas"],
"tags": ["css"],
"notes": [{
"name": "MDN Docs",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style"
},{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/1748"
}]
}
!*/
/* DOC
Detects support for `transform-style: preserve-3d`, for getting a proper 3D perspective on elements.
*/
define(['Modernizr', 'createElement', 'docElement'], function(Modernizr, createElement, docElement) {
Modernizr.addTest('preserve3d', function() {
var outerDiv = createElement('div');
var innerDiv = createElement('div');
outerDiv.style.cssText = 'transform-style: preserve-3d; transform-origin: right; transform: rotateY(40deg);';
innerDiv.style.cssText = 'width: 9px; height: 1px; background: #000; transform-origin: right; transform: rotateY(40deg);';
outerDiv.appendChild(innerDiv);
docElement.appendChild(outerDiv);
var result = innerDiv.getBoundingClientRect();
docElement.removeChild(outerDiv);
return result.width && result.width < 4;
});
});
|
Fix bug from previous PR.
|
import immutable from 'immutable';
import authStore from '../auth/store';
import intlStore from '../intl/store';
import todosStore from '../todos/store';
import usersStore from '../users/store';
export default function(state, action, payload) {
// Create immutable from JSON asap to prevent side effects accidents.
if (!action) state = immutable.fromJS(state);
// Btw, this can be refactored, but leaving it explicit for now.
state = state
.update('auth', (s) => authStore(s, action, payload))
.update('intl', (s) => intlStore(s, action, payload))
.update('todos', (s) => todosStore(s, action, payload))
.update('users', (s) => usersStore(s, action, payload));
// We can reduce and compose stores. Note we don't need no waitFor.
state = state
// Reduced store.
.update('msg', (s) => state.get('intl').messages);
// Composed store example:
// .update('foo', (s) => fooStore(s, state.get('auth'), action, payload));
return state;
}
|
import immutable from 'immutable';
import authStore from '../auth/store';
import intlStore from '../intl/store';
import todosStore from '../todos/store';
import usersStore from '../users/store';
export default function(state, action, payload) {
// Create immutable from JSON asap to prevent side effects accidents.
if (!action) return immutable.fromJS(state);
// Btw, this can be refactored, but leaving it explicit for now.
state = state
.update('auth', (s) => authStore(s, action, payload))
.update('intl', (s) => intlStore(s, action, payload))
.update('todos', (s) => todosStore(s, action, payload))
.update('users', (s) => usersStore(s, action, payload));
// We can reduce and compose stores. Note we don't need no waitFor.
state = state
// Reduced store.
.update('msg', (s) => state.get('intl').messages);
// Composed store example:
// .update('foo', (s) => fooStore(s, state.get('auth'), action, payload));
return state;
}
|
Fix spelling errors in test names
|
from hypothesis import (
given,
settings,
)
from eth_abi import (
encode_abi,
decode_abi,
encode_single,
decode_single,
)
from tests.common.strategies import (
multi_strs_values,
single_strs_values,
)
@settings(max_examples=1000)
@given(multi_strs_values)
def test_multi_abi_reversibility(types_and_values):
"""
Tests round trip encoding and decoding for basic types and lists of basic
types.
"""
types, values = types_and_values
encoded_values = encode_abi(types, values)
decoded_values = decode_abi(types, encoded_values)
assert values == decoded_values
@settings(max_examples=1000)
@given(single_strs_values)
def test_single_abi_reversibility(type_and_value):
"""
Tests round trip encoding and decoding for basic types and lists of basic
types.
"""
_type, value = type_and_value
encoded_value = encode_single(_type, value)
decoded_value = decode_single(_type, encoded_value)
assert value == decoded_value
|
from hypothesis import (
given,
settings,
)
from eth_abi import (
encode_abi,
decode_abi,
encode_single,
decode_single,
)
from tests.common.strategies import (
multi_strs_values,
single_strs_values,
)
@settings(max_examples=1000)
@given(multi_strs_values)
def test_multi_abi_reversability(types_and_values):
"""
Tests round trip encoding and decoding for basic types and lists of basic
types.
"""
types, values = types_and_values
encoded_values = encode_abi(types, values)
decoded_values = decode_abi(types, encoded_values)
assert values == decoded_values
@settings(max_examples=1000)
@given(single_strs_values)
def test_single_abi_reversability(type_and_value):
"""
Tests round trip encoding and decoding for basic types and lists of basic
types.
"""
_type, value = type_and_value
encoded_value = encode_single(_type, value)
decoded_value = decode_single(_type, encoded_value)
assert value == decoded_value
|
Change delimiter detection to allow string "---" to appear in front matter
|
<?php
namespace Spatie\YamlFrontMatter;
use Exception;
use Symfony\Component\Yaml\Yaml;
class Parser
{
protected $yamlParser;
public function __construct()
{
$this->yamlParser = new Yaml();
}
public function parse(string $content) : Document
{
$pattern = '/[\s\r\n]---[\s\r\n]/s';
$parts = preg_split($pattern, PHP_EOL . ltrim($content));
if (count($parts) === 1) {
return new Document([], $content);
}
$matter = $this->yamlParser->parse($parts[1]);
$body = implode(PHP_EOL . "---" . PHP_EOL, array_slice($parts, 2));
return new Document($matter, $body);
}
}
|
<?php
namespace Spatie\YamlFrontMatter;
use Exception;
use Symfony\Component\Yaml\Yaml;
class Parser
{
protected $yamlParser;
public function __construct()
{
$this->yamlParser = new Yaml();
}
public function parse(string $content) : Document
{
// Parser regex borrowed from the `devster/frontmatter` package
// https://github.com/devster/frontmatter/blob/bb5d2c7/src/Parser.php#L123
$pattern = "/^\s*(?:---)[\n\r\s]*(.*?)[\n\r\s]*(?:---)[\s\n\r]*(.*)$/s";
$parts = [];
$match = preg_match($pattern, $content, $parts);
if ($match === false) {
throw new Exception('An error occurred while extracting the front matter from the contents');
}
if ($match === 0) {
return new Document([], $content);
}
$matter = $this->yamlParser->parse($parts[1]);
$body = $parts[2];
return new Document($matter, $body);
}
}
|
Handle the empty er folder and blank ER case properly.
|
var JSONDumper = function() {
this.onBrowserLog = function(browser, log, type) {
if( type != "dump" ) {
return;
}
var objectMerge = require( 'object-merge' );
var fs = require( 'fs' );
var logObj = JSON.parse(log.substring(1, log.length-1));
var fileObj;
var data;
for( var file in logObj ) {
data = fs.readFileSync("test/er/" + file + ".json", { "flag": "a+"});
fileObj = data.length != 0 ? JSON.parse(data.toString()) : {};
fileObj = objectMerge( fileObj, logObj[file] );
fs.writeFileSync("test/er/" + file + ".json", JSON.stringify(fileObj, null, " "));
}
};
};
module.exports = {
'reporter:json-dumper': ['type', JSONDumper]
};
|
var JSONDumper = function() {
this.onBrowserLog = function(browser, log, type) {
if( type != "dump" ) {
return;
}
var objectMerge = require( 'object-merge' );
var fs = require( 'fs' );
var logObj = JSON.parse(log.substring(1, log.length-1));
var fileObj;
var data;
for( var file in logObj ) {
data = fs.readFileSync("test/er/" + file + ".json", { "flag": "a+"});
fileObj = JSON.parse(data.toString());
fileObj = objectMerge( fileObj, logObj[file] );
fs.writeFileSync("test/er/" + file + ".json", JSON.stringify(fileObj, null, " "));
}
};
};
module.exports = {
'reporter:json-dumper': ['type', JSONDumper]
};
|
Add unit test for iteration loop parsing
|
from tests.infrastructure.test_utils import parse_local, validate_types
from thinglang.lexer.values.numeric import NumericValue
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.blocks.iteration_loop import IterationLoop
from thinglang.parser.blocks.loop import Loop
from thinglang.parser.values.binary_operation import BinaryOperation
from thinglang.parser.values.method_call import MethodCall
def validate_loop(node, condition):
assert isinstance(node, Loop)
if isinstance(condition, list):
validate_types(node.value.arguments, condition, (BinaryOperation, MethodCall), lambda x: x.arguments)
else:
assert isinstance(node.value, condition)
def test_simple_loop_conditionals():
validate_loop(parse_local('while i < 5'), [Identifier, NumericValue])
validate_loop(parse_local('while i < j'), [Identifier, Identifier])
def test_method_call_loop_conditionals():
validate_loop(parse_local('while i < Threshold.current(1, 5)'), [Identifier, [NumericValue, NumericValue]])
def test_iteration_loop_parsing():
loop = parse_local('for number n in numbers')
assert isinstance(loop, IterationLoop)
assert loop.target == Identifier('n')
assert loop.target_type == Identifier('number')
assert loop.collection == Identifier('numbers')
|
from tests.infrastructure.test_utils import parse_local, validate_types
from thinglang.lexer.values.numeric import NumericValue
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.blocks.loop import Loop
from thinglang.parser.values.binary_operation import BinaryOperation
from thinglang.parser.values.method_call import MethodCall
def validate_loop(node, condition):
assert isinstance(node, Loop)
if isinstance(condition, list):
validate_types(node.value.arguments, condition, (BinaryOperation, MethodCall), lambda x: x.arguments)
else:
assert isinstance(node.value, condition)
def test_simple_loop_conditionals():
validate_loop(parse_local('while i < 5'), [Identifier, NumericValue])
validate_loop(parse_local('while i < j'), [Identifier, Identifier])
def test_method_call_loop_conditionals():
validate_loop(parse_local('while i < Threshold.current(1, 5)'), [Identifier, [NumericValue, NumericValue]])
|
Set NODE_ENV correctly in prod to speed up React
|
import { remote } from 'electron';
import '../rendererEmitter';
import './core';
import SettingsController from '../../main/utils/Settings';
if (process.env['TEST_SPEC']) { // eslint-disable-line
global.Settings = new SettingsController('.test', true);
} else {
global.Settings = new SettingsController();
}
Settings.uncouple();
require(`./${process.platform}`);
require('./translations');
process.env['NODE_ENV'] = remote.getGlobal('DEV_MODE') ? 'development' : 'production';
document.addEventListener('DOMContentLoaded', () => {
require('./windowThemeHandler');
const nativeFrameAtLaunch = Settings.get('nativeFrame');
document.body.classList.toggle('native-frame', nativeFrameAtLaunch);
Emitter.on('window:fullscreen', (event, state) => {
if (nativeFrameAtLaunch) return;
if (state.state) document.body.classList.add('native-frame');
if (!state.state) document.body.classList.remove('native-frame');
});
document.addEventListener('dragover', (event) => {
event.preventDefault();
return false;
}, false);
document.addEventListener('drop', (event) => {
event.preventDefault();
return false;
}, false);
});
|
import '../rendererEmitter';
import './core';
import SettingsController from '../../main/utils/Settings';
if (process.env['TEST_SPEC']) { // eslint-disable-line
global.Settings = new SettingsController('.test', true);
} else {
global.Settings = new SettingsController();
}
Settings.uncouple();
require(`./${process.platform}`);
require('./translations');
document.addEventListener('DOMContentLoaded', () => {
require('./windowThemeHandler');
const nativeFrameAtLaunch = Settings.get('nativeFrame');
document.body.classList.toggle('native-frame', nativeFrameAtLaunch);
Emitter.on('window:fullscreen', (event, state) => {
if (nativeFrameAtLaunch) return;
if (state.state) document.body.classList.add('native-frame');
if (!state.state) document.body.classList.remove('native-frame');
});
document.addEventListener('dragover', (event) => {
event.preventDefault();
return false;
}, false);
document.addEventListener('drop', (event) => {
event.preventDefault();
return false;
}, false);
});
|
Add refreshTokenLifetime and accessTokenLifetime for token lifetime
|
// Reference : http://danialk.github.io/blog/2013/02/23/authentication-using-passportjs/
var CONFIG = module.exports = {};
var LocalStrategy = require('passport-local').Strategy;
var oauthserver = require('node-oauth2-server');
var memorystore = require("../model/oauth.js");
CONFIG.passport = function (passport) {
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
done(null,user);
});
// Local Auth
passport.use(new LocalStrategy( function(username, password, done) {
var user = {"uid":"testid"};
return done(null, user);
}));
}
CONFIG.facebook = function(passport) {
}
CONFIG.oauth2 = function(app) {
app.oauth = oauthserver({
model: memorystore,
grants: ['authorization_code','refresh_token'],
debug: true,
refreshTokenLifetime: 3600 *10,
accessTokenLifetime: 60*60*20
});
app.all('/oauth/token', app.oauth.grant());
app.use(app.oauth.errorHandler());
};
|
// Reference : http://danialk.github.io/blog/2013/02/23/authentication-using-passportjs/
var CONFIG = module.exports = {};
var LocalStrategy = require('passport-local').Strategy;
var oauthserver = require('node-oauth2-server');
var memorystore = require("../model/oauth.js");
CONFIG.passport = function (passport) {
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
done(null,user);
});
// Local Auth
passport.use(new LocalStrategy( function(username, password, done) {
var user = {"uid":"testid"};
return done(null, user);
}));
}
CONFIG.facebook = function(passport) {
}
CONFIG.oauth2 = function(app) {
app.oauth = oauthserver({
model: memorystore,
grants: ['authorization_code','refresh_token'],
debug: true
});
app.all('/oauth/token', app.oauth.grant());
app.use(app.oauth.errorHandler());
};
|
Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug
|
import winbrew
class Openssl(winbrew.Formula):
url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz'
homepage = 'http://www.openssl.org'
sha1 = ''
build_deps = ()
deps = ()
def install(self):
self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL')
self.system('ms\\\\do_ms.bat')
self.system('nmake -f ms\\\\nt.mak')
self.lib('out32\\libeay32.lib')
self.lib('out32\\ssleay32.lib')
self.includes('include\\openssl', dest='openssl')
#self.system('nmake -f ms\\ntdll.mak install')
# Dynamic libraries
def test(self):
self.system('nmake -f ms\\\\nt.mak test')
|
import winbrew
class Openssl(winbrew.Formula):
url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz'
homepage = 'http://www.openssl.org'
sha1 = ''
build_deps = ()
deps = ()
def install(self):
self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL')
self.system('ms\\\\do_ms.bat')
self.system('nmake -f ms\\\\nt.mak')
self.lib('out32\\libeay32.lib')
self.lib('out32\\ssleay32.lib')
self.includes('include\\openssl', dest='openssl')
#self.system('nmake -f ms\\ntdll.mak install')
# Dynamic libraries
def test(self):
self.system('nmake -f ms\\\\nt.mak test')
|
:new: Add a message key helper; also cleanup unused
|
'use babel'
import minimatch from 'minimatch'
export function showError(e) {
atom.notifications.addError(`[Linter] ${e.message}`, {
detail: e.stack,
dismissable: true
})
}
export function shouldTriggerLinter(linter, wasTriggeredOnChange, scopes) {
if (wasTriggeredOnChange && !linter.lintOnFly) {
return false
}
return scopes.some(function (scope) {
return linter.grammarScopes.indexOf(scope) !== -1
})
}
export function isPathIgnored(filePath, ignoredGlob) {
const projectPaths = atom.project.getPaths()
const projectPathsLength = projectPaths.length
let repository = null
for (let i = 0; i < projectPathsLength; ++i) {
const projectPath = projectPaths[i]
if (filePath.indexOf(projectPath) === 0) {
repository = atom.project.getRepositories()[i]
break
}
}
if (repository !== null && repository.isProjectAtRoot() && repository.isPathIgnored(filePath)) {
return true
}
return minimatch(filePath, ignoredGlob)
}
export function messageKey(message) {
return (message.text || message.html) + '$' + message.class + '$' + message.name + '$' + (
message.range ? (message.range.start.column + ':' + message.range.start.row + message.range.end.column + ':' + message.range.end.row) : ''
)
}
|
'use babel'
import minimatch from 'minimatch'
export function showError(e) {
atom.notifications.addError(`[Linter] ${e.message}`, {
detail: e.stack,
dismissable: true
})
}
export function shouldTriggerLinter(linter, wasTriggeredOnChange, scopes) {
if (wasTriggeredOnChange && !linter.lintOnFly) {
return false
}
return scopes.some(function (scope) {
return linter.grammarScopes.indexOf(scope) !== -1
})
}
export function requestUpdateFrame(callback) {
setTimeout(callback, 100)
}
export function debounce(callback, delay) {
let timeout = null
return function(arg) {
clearTimeout(timeout)
timeout = setTimeout(() => {
callback.call(this, arg)
}, delay)
}
}
export function isPathIgnored(filePath, ignoredGlob) {
const projectPaths = atom.project.getPaths()
const projectPathsLength = projectPaths.length
let repository = null
for (let i = 0; i < projectPathsLength; ++i) {
const projectPath = projectPaths[i]
if (filePath.indexOf(projectPath) === 0) {
repository = atom.project.getRepositories()[i]
break
}
}
if (repository !== null && repository.isProjectAtRoot() && repository.isPathIgnored(filePath)) {
return true
}
return minimatch(filePath, ignoredGlob)
}
|
Replace condition to patch distutils.dist.log
As `distutils.log.Log` was backfilled for compatibility we no longer can
use this as a condition.
|
import sys
import inspect
import logging
import distutils.log
from . import monkey
def _not_warning(record):
return record.levelno < logging.WARNING
def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
for compatibility with distutils.log but may change in
the future.
"""
err_handler = logging.StreamHandler()
err_handler.setLevel(logging.WARNING)
out_handler = logging.StreamHandler(sys.stdout)
out_handler.addFilter(_not_warning)
handlers = err_handler, out_handler
logging.basicConfig(
format="{message}", style='{', handlers=handlers, level=logging.DEBUG)
if inspect.ismodule(distutils.dist.log):
monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
# For some reason `distutils.log` module is getting cached in `distutils.dist`
# and then loaded again when patched,
# implying: id(distutils.log) != id(distutils.dist.log).
# Make sure the same module object is used everywhere:
distutils.dist.log = distutils.log
def set_threshold(level):
logging.root.setLevel(level*10)
return set_threshold.unpatched(level)
|
import sys
import logging
import distutils.log
from . import monkey
def _not_warning(record):
return record.levelno < logging.WARNING
def configure():
"""
Configure logging to emit warning and above to stderr
and everything else to stdout. This behavior is provided
for compatibility with distutils.log but may change in
the future.
"""
err_handler = logging.StreamHandler()
err_handler.setLevel(logging.WARNING)
out_handler = logging.StreamHandler(sys.stdout)
out_handler.addFilter(_not_warning)
handlers = err_handler, out_handler
logging.basicConfig(
format="{message}", style='{', handlers=handlers, level=logging.DEBUG)
if hasattr(distutils.log, 'Log'):
monkey.patch_func(set_threshold, distutils.log, 'set_threshold')
# For some reason `distutils.log` module is getting cached in `distutils.dist`
# and then loaded again when patched,
# implying: id(distutils.log) != id(distutils.dist.log).
# Make sure the same module object is used everywhere:
distutils.dist.log = distutils.log
def set_threshold(level):
logging.root.setLevel(level*10)
return set_threshold.unpatched(level)
|
Handle fast forward in update-coverity-branch.py
|
#!/usr/bin/env python
# Update the coverity branch from the master branch.
# It is not done automatically because Coverity Scan limits
# the number of submissions per day.
from __future__ import print_function
import shutil, tempfile
from subprocess import check_output, STDOUT
class Git:
def __init__(self, dir):
self.dir = dir
def __call__(self, *args):
output = check_output(['git'] + list(args), cwd=self.dir, stderr=STDOUT)
print(output)
return output
dir = tempfile.mkdtemp()
try:
git = Git(dir)
git('clone', '-b', 'coverity', 'git@github.com:cppformat/cppformat.git', dir)
output = git('merge', '-X', 'theirs', '--no-commit', 'origin/master')
if 'Fast-forward' not in output:
git('reset', 'HEAD', '.travis.yml')
git('checkout', '--', '.travis.yml')
git('commit', '-m', 'Update coverity branch')
git('push')
finally:
shutil.rmtree(dir)
|
#!/usr/bin/env python
# Update the coverity branch from the master branch.
# It is not done automatically because Coverity Scan limits
# the number of submissions per day.
from __future__ import print_function
import shutil, tempfile
from subprocess import check_call
class Git:
def __init__(self, dir):
self.dir = dir
def __call__(self, *args):
check_call(['git'] + list(args), cwd=self.dir)
dir = tempfile.mkdtemp()
try:
git = Git(dir)
git('clone', '-b', 'coverity', 'git@github.com:cppformat/cppformat.git', dir)
git('merge', '-X', 'theirs', '--no-commit', 'origin/master')
git('reset', 'HEAD', '.travis.yml')
git('checkout', '--', '.travis.yml')
git('commit', '-m', 'Update coverity branch')
git('push')
finally:
shutil.rmtree(dir)
|
Fix Tap constructor, pass start and end time via command line arguments.
|
// this needs to be modified to work with the new java 7 date class
package tap.sample;
import tap.*;
import quantbench.Candle;
public class Subscribe {
// Usage: hadoop jar yourjar.jar -s 2011-01-03 10:40:00.000 -e 2011-01-03 10:50:00.000
public static main(String[] args) throws Exception {
CommandOptions o = new CommandOptions(args);
Tap tap = new Tap(o);
Pipe<Candle> candles = tap.subscribe("//cta/candle/1min[AAPL]");
while (candles.more()) {
Candle m = candles.get();
Date time = Tap.newDate(m.getStartTime());
System.out.println(time.toString + " symbol " + m.getSymbol() +
" open " + m.getOpen() + " volume " + m.getVolume());
}
}
}
|
// this needs to be modified to work with the new java 7 date class
package tap.sample;
import tap.*;
import quantbench.Candle;
public class Subscribe {
public static main(String[] args) throws Exception {
Tap tap = new Tap();
tap.startTime("2011-01-03 10:40:00.000");
tap.endTime("2011-01-03 10:50:00.000");
Pipe<Candle> candles = tap.subscribe("//cta/candle/1min[AAPL]");
while (candles.more()) {
Candle m = candles.get();
Date time = Tap.newDate(m.getStartTime());
System.out.println(time.toString + " symbol " + m.getSymbol() +
" open " + m.getOpen() + " volume " + m.getVolume());
}
}
}
|
Build proper dnslink, pass recordName as parameter
|
var DigitalOcean = require('do-wrapper')
var Promise = require('bluebird')
module.exports = function initializeModule (options) {
var api = Promise.promisifyAll(new DigitalOcean(options.DOApiKey, 10))
function testAccountKey () {
api.account(function (err, res, body) {
if (err) { console.log(err) }
console.log(body)
})
}
// TODO Set domainName and domainRecordID in env.
function setDNS (domainName, domainRecordId, domainRecordName, path) {
api.domainRecordsUpdate(domainName, domainRecordId, {
type: 'TXT',
name: domainRecordName,
data: 'dnslink='+path
}, function (err, data) {
if (err) {
console.log(err)
} else {
console.log('Success:', data)
}
})
}
return {
testAccountKey: testAccountKey,
setDNS: setDNS
}
}
|
var DigitalOcean = require('do-wrapper')
var Promise = require('bluebird')
module.exports = function initializeModule (options) {
var api = Promise.promisifyAll(new DigitalOcean(options.DOApiKey, 10))
function testAccountKey () {
api.account(function (err, res, body) {
if (err) { console.log(err) }
console.log(body)
})
}
// TODO Set domainName and domainRecordID in env.
function setDNS (domainName, domainRecordId, hash) {
api.domainRecordsUpdate(domainName, domainRecordId, {
type: 'TXT',
name: 'h',
data: hash
}, function (err, data) {
if (err) {
console.log(err)
} else {
console.log('Success:', data)
}
})
}
return {
testAccountKey: testAccountKey,
setDNS: setDNS
}
}
|
Fix typo in variable name in formatNumber
|
// Copyright 2016 Albert Nigmatzianov. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package util
import (
"os"
"path/filepath"
"strconv"
"strings"
)
const (
millisecondsInSecond = 1000
secondsInMinute = 60
minutesInHour = 60
)
func ParseDuration(duration int) (seconds, minutes, hours int) {
seconds = duration / millisecondsInSecond
if seconds >= secondsInMinute {
minutes = seconds / secondsInMinute
seconds -= minutes * secondsInMinute
}
if minutes >= minutesInHour {
hours = minutes / minutesInHour
minutes -= hours * minutesInHour
}
return
}
func DurationString(seconds, minutes, hours int) (duration string) {
duration = formatNumber(minutes) + ":" + formatNumber(seconds)
if hours > 0 {
duration = formatNumber(hours) + ":" + duration
}
return
}
func formatNumber(num int) (formatted string) {
if num < 10 {
formatted += "0"
}
formatted += strconv.Itoa(num)
return
}
func SanitizePath(path string) string {
if strings.HasPrefix(path, "~") {
path = strings.Replace(path, "~", os.Getenv("HOME"), 1)
}
return filepath.Clean(path)
}
|
// Copyright 2016 Albert Nigmatzianov. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package util
import (
"os"
"path/filepath"
"strconv"
"strings"
)
const (
millisecondsInSecond = 1000
secondsInMinute = 60
minutesInHour = 60
)
func ParseDuration(duration int) (seconds, minutes, hours int) {
seconds = duration / millisecondsInSecond
if seconds >= secondsInMinute {
minutes = seconds / secondsInMinute
seconds -= minutes * secondsInMinute
}
if minutes >= minutesInHour {
hours = minutes / minutesInHour
minutes -= hours * minutesInHour
}
return
}
func DurationString(seconds, minutes, hours int) (duration string) {
duration = formatNumber(minutes) + ":" + formatNumber(seconds)
if hours > 0 {
duration = formatNumber(hours) + ":" + duration
}
return
}
func formatNumber(num int) (formated string) {
if num < 10 {
formated += "0"
}
formated += strconv.Itoa(num)
return
}
func SanitizePath(path string) string {
if strings.HasPrefix(path, "~") {
path = strings.Replace(path, "~", os.Getenv("HOME"), 1)
}
return filepath.Clean(path)
}
|
Update example plot script with new API
|
import os
import matplotlib.pyplot as plt
plt.style.use("ggplot")
plt.rcParams["figure.figsize"] = 10, 5
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.size"] = 12
import pyhector
from pyhector import rcp26, rcp45, rcp60, rcp85
path = os.path.join(os.path.dirname(__file__),
'./example-plot.png')
for rcp in [rcp26, rcp45, rcp60, rcp85]:
output = pyhector.run(rcp, {"core": {"endDate": 2100}})
temp = output["temperature.Tgav"]
temp = temp.loc[1850:] - temp.loc[1850:1900].mean()
temp.plot(label=rcp.name.split("_")[0])
plt.title("Global mean temperature")
plt.ylabel("°C over pre-industrial (1850-1900 mean)")
plt.legend(loc="best")
plt.savefig(path, dpi=96)
|
import os
import matplotlib.pyplot as plt
plt.style.use("ggplot")
plt.rcParams["figure.figsize"] = 10, 5
plt.rcParams["font.family"] = "serif"
plt.rcParams["font.size"] = 12
import pyhector
from pyhector import rcp26, rcp45, rcp60, rcp85
path = os.path.join(os.path.dirname(__file__),
'./example-plot.png')
for rcp in [rcp26, rcp45, rcp60, rcp85]:
output, _ = pyhector.run(rcp, {"core": {"endDate": 2100}})
temp = output["temperature.Tgav"]
temp = temp.loc[1850:] - temp.loc[1850:1900].mean()
temp.plot(label=rcp.name.split("_")[0])
plt.title("Global mean temperature")
plt.ylabel("°C over pre-industrial (1850-1900 mean)")
plt.legend(loc="best")
plt.savefig(path, dpi=96)
|
Fix redundant declaration of the same variable.
|
'use strict';
var expect = require('chai').expect;
var angular = require('angular');
var calculatorModule = require('./calculator.service');
describe('calculator', function() {
var calculator;
beforeEach(function() {
angular.mock.module(calculatorModule.moduleName);
angular.mock.inject([calculatorModule.factoryName, function(_calculator_) {
calculator = _calculator_;
}]);
});
it ('should add two numbers', function() {
var result = calculator.calculate('+', 5, 3);
expect(result).to.equal(8);
});
it ('should subtract two numbers', function() {
var result = calculator.calculate('-', 5, 3);
expect(result).to.equal(2);
});
it ('should multiply two numbers', function() {
var result = calculator.calculate('*', 5, 3);
expect(result).to.equal(15);
result = calculator.calculate('x', 10, 3);
expect(result).to.equal(30);
});
it ('should divide two numbers', function() {
var result = calculator.calculate('/', 6, 3);
expect(result).to.equal(2);
});
it ('should raise a number to a power', function() {
var result = calculator.calculate('^', 2, 8);
expect(result).to.equal(256);
});
});
|
'use strict';
var expect = require('chai').expect;
var angular = require('angular');
var calculatorModule = require('./calculator.service');
describe('calculator', function() {
var calculator;
beforeEach(function() {
angular.mock.module(calculatorModule.moduleName);
angular.mock.inject([calculatorModule.factoryName, function(_calculator_) {
calculator = _calculator_;
}]);
});
it ('should add two numbers', function() {
var result = calculator.calculate('+', 5, 3);
expect(result).to.equal(8);
});
it ('should subtract two numbers', function() {
var result = calculator.calculate('-', 5, 3);
expect(result).to.equal(2);
});
it ('should multiply two numbers', function() {
var result = calculator.calculate('*', 5, 3);
expect(result).to.equal(15);
var result = calculator.calculate('x', 10, 3);
expect(result).to.equal(30);
});
it ('should divide two numbers', function() {
var result = calculator.calculate('/', 6, 3);
expect(result).to.equal(2);
});
it ('should raise a number to a power', function() {
var result = calculator.calculate('^', 2, 8);
expect(result).to.equal(256);
});
});
|
Make Calendar events and recurrence types optional.
|
<?php
namespace Plummer\Calendar;
class Calendar
{
protected $name;
protected $events;
protected $recurrenceTypes;
protected function __construct($name, array $events, array $recurrenceTypes)
{
$this->name = $name;
$this->addEvents($events);
$this->addRecurrenceTypes($recurrenceTypes);
}
public static function make($name, array $events = [], array $recurrenceTypes = [])
{
return new static($name, $events, $recurrenceTypes);
}
public function addEvents(array $events)
{
foreach($events as $event) {
$this->addEvent($event);
}
}
public function addEvent(Event $event)
{
$this->events[] = $event;
}
public function addRecurrenceTypes(array $recurrenceTypes)
{
foreach($recurrenceTypes as $recurrenceType) {
$this->addRecurrenceType($recurrenceType);
}
}
public function addRecurrenceType(RecurrenceInterface $recurrenceType)
{
$this->recurrenceTypes[] = $recurrenceType;
}
}
|
<?php
namespace Plummer\Calendar;
class Calendar
{
protected $name;
protected $events;
protected $recurrenceTypes;
protected function __construct($name, array $events, array $recurrenceTypes)
{
$this->name = $name;
$this->addEvents($events);
$this->addRecurrenceTypes($recurrenceTypes);
}
public static function make($name, array $events, array $recurrenceTypes)
{
return new static($name, $events, $recurrenceTypes);
}
public function addEvents(array $events)
{
foreach($events as $event) {
$this->addEvent($event);
}
}
public function addEvent(Event $event)
{
$this->events[] = $event;
}
public function addRecurrenceTypes(array $recurrenceTypes)
{
foreach($recurrenceTypes as $recurrenceType) {
$this->addRecurrenceType($recurrenceType);
}
}
public function addRecurrenceType(RecurrenceInterface $recurrenceType)
{
$this->recurrenceTypes[] = $recurrenceType;
}
}
|
Fix home page logic error
|
( function ( mw, $ ) {
$( function () {
// For some odd reason, these had fixed min-style:600px
// That sucks. Removing it (they're handled at HitchwikiVector/resources/styles/forms.less instead)
$(".sf-select2-container").attr("style", "");
// Don't allow adding new content for non logged in users
// wgUserId returns null when not logged in
// Styles regarding this are under navigation.less
if(mw.config.get('wgUserId')) {
$("body").addClass("hw-user-logged");
}
else {
$("body").addClass("hw-user-nonlogged");
}
// Move Special buttons to the footer at front page
if(mw.config.get('wgPageName') == 'Main_Page') {
$("#mw-page-actions").insertAfter("#mw-content-text");
$(".mw-main-edit-button").insertAfter("#mw-content-text");
}
} );
}( mediaWiki, jQuery ) );
|
( function ( mw, $ ) {
$( function () {
// For some odd reason, these had fixed min-style:600px
// That sucks. Removing it (they're handled at HitchwikiVector/resources/styles/forms.less instead)
$(".sf-select2-container").attr("style", "");
// Don't allow adding new content for non logged in users
// wgUserId returns null when not logged in
// Styles regarding this are under navigation.less
if(mw.config.get('wgUserId')) {
$("body").addClass("hw-user-logged");
}
else {
$("body").addClass("hw-user-nonlogged");
}
// Move Special buttons to the footer at front page
if(mw.config.get('wgPageName') != 'Main_Page') {
$("#mw-page-actions").insertAfter("#mw-content-text");
$(".mw-main-edit-button").insertAfter("#mw-content-text");
}
} );
}( mediaWiki, jQuery ) );
|
Refactor output for zip archive and download
|
"""
Utilities for downloading historical data in a given AOI.
Python 3.5
"""
import requests
import io
import zipfile
import os
from time import strftime
import logging
import yaml
from model import aircraft_report
from model import report_receiver
from utils import postgres as pg_utils
logger = logging.getLogger(__name__)
zip_dir = 'output'
# current_date_stamp = strftime('%y-%m-%d')
current_date_stamp = '2017-10-01'
# temporary config load while testing
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.yml'), 'r') as yaml_config_file:
local_config = yaml.load(yaml_config_file)
adsbe_download_base_url = local_config['adsbe_url']
def get_and_load_archive_data_by_date(zip_url):
req = requests.get(zip_url)
res_zip = zipfile.ZipFile(io.BytesIO(req.content))
if not os.path.exists(zip_dir):
os.makedirs(zip_dir)
res_zip.extractall(zip_dir)
aircraft_report.get_aircraft_data_from_files(os.path.join(os.path.dirname(os.path.realpath(__file__)), zip_dir))
# dl_url = adsbe_download_base_url + '{}.zip'.format(current_date_stamp)
# print(dl_url)
# get_archive_zip(dl_url)
|
"""
Utilities for downloading historical data in a given AOI.
Python 3.5
"""
import requests
import io
import zipfile
import os
from time import strftime
import logging
import yaml
from model import aircraft_report
from model import report_receiver
from utils import postgres as pg_utils
logger = logging.getLogger(__name__)
# current_date_stamp = strftime('%y-%m-%d')
current_date_stamp = '2017-10-01'
# temporary config load while testing
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.yml'), 'r') as yaml_config_file:
local_config = yaml.load(yaml_config_file)
adsbe_download_base_url = local_config['adsbe_url']
def get_archive_zip(zip_url):
req = requests.get(zip_url)
res_zip = zipfile.ZipFile(io.BytesIO(req.content))
if not os.path.exists('output'):
os.makedirs('output')
return res_zip.extractall('output')
aircraft_report.get_aircraft_data_from_files(os.path.join(os.getcwd(), 'output'))
# dl_url = adsbe_download_base_url + '{}.zip'.format(current_date_stamp)
# print(dl_url)
# get_archive_zip(dl_url)
|
[security][symfony] Fix fatal error on old symfony versions.
PHP Fatal error: Undefined class constant 'ABSOLUTE_URL' in ....
|
<?php
namespace Payum\Core\Bridge\Symfony\Security;
use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class TokenFactory extends AbstractGenericTokenFactory
{
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
protected $urlGenerator;
/**
* @param UrlGeneratorInterface $urlGenerator
* @param StorageInterface $tokenStorage
* @param StorageRegistryInterface $storageRegistry
* @param string $capturePath
* @param string $notifyPath
*/
public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
{
$this->urlGenerator = $urlGenerator;
parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
}
/**
* @param string $path
* @param array $parameters
*
* @return string
*/
protected function generateUrl($path, array $parameters = array())
{
return $this->urlGenerator->generate($path, $parameters, true);
}
}
|
<?php
namespace Payum\Core\Bridge\Symfony\Security;
use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\AbstractGenericTokenFactory;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Storage\StorageInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class TokenFactory extends AbstractGenericTokenFactory
{
/**
* @var \Symfony\Component\Routing\RouterInterface
*/
protected $urlGenerator;
/**
* @param UrlGeneratorInterface $urlGenerator
* @param StorageInterface $tokenStorage
* @param StorageRegistryInterface $storageRegistry
* @param string $capturePath
* @param string $notifyPath
*/
public function __construct(UrlGeneratorInterface $urlGenerator, StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry, $capturePath, $notifyPath)
{
$this->urlGenerator = $urlGenerator;
parent::__construct($tokenStorage, $storageRegistry, $capturePath, $notifyPath);
}
/**
* @param string $path
* @param array $parameters
*
* @return string
*/
protected function generateUrl($path, array $parameters = array())
{
return $this->urlGenerator->generate($path, $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
}
}
|
Change client login route to avoid conflicting with laravel bootstrap route
|
<?php
$this->router->get('admin/login', [
'as' => 'admin.login',
'uses' => 'Admin\Auth\LoginController@showLoginForm',
]);
$this->router->post('admin/login', [
'uses'=> 'Admin\Auth\LoginController@login',
]);
$this->router->get('login', [
'as' => 'client.login',
'uses' => 'Client\Auth\LoginController@showLoginForm',
]);
$this->router->post('login', [
'uses'=> 'Client\Auth\LoginController@login',
]);
$this->router->get('password/reset', [
'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm',
]);
$this->router->post('password/reset', [
'uses' => 'Auth\ResetPasswordController@reset',
]);
$this->router->get('password/reset/{token}', [
'uses' => 'Auth\ResetPasswordController@showResetForm',
]);
$this->router->post('password/email', [
'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail'
]);
|
<?php
$this->router->get('admin/login', [
'as' => 'admin.login',
'uses' => 'Admin\Auth\LoginController@showLoginForm',
]);
$this->router->post('admin/login', [
'uses'=> 'Admin\Auth\LoginController@login',
]);
$this->router->get('/', [
'as' => 'client.login',
'uses' => 'Client\Auth\LoginController@showLoginForm',
]);
$this->router->post('login', [
'uses'=> 'Client\Auth\LoginController@login',
]);
$this->router->get('password/reset', [
'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm',
]);
$this->router->post('password/reset', [
'uses' => 'Auth\ResetPasswordController@reset',
]);
$this->router->get('password/reset/{token}', [
'uses' => 'Auth\ResetPasswordController@showResetForm',
]);
$this->router->post('password/email', [
'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail'
]);
|
Add tests requirements to install requirements
|
#!/usr/bin/python
# -*- coding: utf8 -*-
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
test_requirements = [
'factory_boy == 1.1.5',
]
setup(
name='caminae',
version='1.0.dev0',
author='Makina Corpus',
author_email='geobi@makina-corpus.com',
url='http://makina-corpus.com',
description="Caminae",
long_description=open(os.path.join(here, 'README.rst')).read(),
install_requires = [
'django == 1.4',
'South == 0.7.5',
'psycopg2 == 2.4.1',
'GDAL == 1.9.1',
'django-modeltranslation == 0.3.3',
'django-leaflet == 0.0.2',
'django-geojson',
] + test_requirements,
tests_requires = test_requirements,
packages=find_packages(),
classifiers = ['Natural Language :: English',
'Environment :: Web Environment',
'Framework :: Django',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.5'],
)
|
#!/usr/bin/python
# -*- coding: utf8 -*-
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='caminae',
version='1.0.dev0',
author='Makina Corpus',
author_email='geobi@makina-corpus.com',
url='http://makina-corpus.com',
description="Caminae",
long_description=open(os.path.join(here, 'README.rst')).read(),
install_requires = [
'django == 1.4',
'South == 0.7.5',
'psycopg2 == 2.4.1',
'GDAL == 1.9.1',
'django-modeltranslation == 0.3.3',
'django-leaflet == 0.0.2',
'django-geojson',
],
tests_requires = [
'factory_boy == 1.1.5',
],
packages=find_packages(),
classifiers = ['Natural Language :: English',
'Environment :: Web Environment',
'Framework :: Django',
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.5'],
)
|
Fix JSON parsing bug, ingredients displayed correctly again.
|
$('#suggestions').typed({
strings: ["chocolate chip cookies", "brownies", "pancakes"],
typeSpeed: 50,
backSpeed: 15,
backDelay: 1500,
loop: true
});
$('#recipe-form').submit(function() {
get_recipe($('#recipe-title').val());
return false;
});
function get_recipe(title) {
var url = '/recipe/search/' + title;
$.get(url,
function(data) {
$('#ingredients').empty();
$('#method').empty();
$('#title').text("Recipe for " + data.title);
for (i = 0; i < data.ingredients.length; i++) {
$('#ingredients').append('<li>' + data.ingredients[i][0] + data.ingredients[i][1] + " " + data.ingredients[i][2] + '</li>');
}
for (i = 0; i < data.method.length; i++) {
$('#method').append('<li>' + data.method[i] + '</li>');
}
}
);
}
|
$('#suggestions').typed({
strings: ["chocolate chip cookies", "brownies", "pancakes"],
typeSpeed: 50,
backSpeed: 15,
backDelay: 1500,
loop: true,
});
$('#recipe-form').submit(function() {
get_recipe($('#recipe-title').val());
return false;
});
function get_recipe(title) {
var url = '/recipe/search/' + title;
$.get(url,
function(data) {
$('#ingredients').empty();
$('#method').empty();
data = JSON.parse(data);
$('#title').text("Recipe for " + data.title);
for (i = 0; i < data.ingredients.length; i++) {
$('#ingredients').append('<li>' + data.ingredients[i][0] + data.ingredients[i][1] + " " + data.ingredients[i][2] + '</li>');
}
for (i = 0; i < data.method.length; i++) {
$('#method').append('<li>' + data.method[i] + '</li>');
}
});
}
|
Allow for data as well as file upload.
|
<?php
namespace Metrique\Plonk\Http\Requests;
use Metrique\Plonk\Http\Requests\Request;
class PlonkStoreRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'file' => 'required_without:data|image|max:5120',
'data' => 'required_without:file|string',
'title' => 'required|string|min:3|max:255',
'alt' => 'required|string|min:3|max:255',
];
}
}
|
<?php
namespace Metrique\Plonk\Http\Requests;
use Metrique\Plonk\Http\Requests\Request;
class PlonkStoreRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'file' => 'required|image|max:5120',
'title' => 'required|min:3|max:255',
'alt' => 'required|min:3|max:255',
];
}
}
|
Fix vista de nuevo permiso por portafolio
|
<h1>Entregar Permisos Portafolio</h1>
<a href="<?php echo base_url()?>portafolio">Volver</a>
<?php
if ($this->session->flashdata('ControllerMessage')!='') {
?>
<p style="color:red;"><?php echo $this->session->flashdata('ControllerMessage'); ?></p>
<?php
}
?>
<?php
$atributos = array('id'=>'nuevopermiso','name'=>'nuevopermiso');
echo form_open_multipart(null,$atributos);
?>
<p>Nombre</p>
<input type="text" id="usuarioid" name="usuarioid" placeholder="Ingresa el ID del usuario a agregar!" required/>
<!-- Esto debería recibir un nombre -->
<br>
<select id="permisoid" name="permisoid">
<?php
foreach ($permisos as $per)
{
?>
<option value="<?php echo $per->PER_ID ?>"><?php echo $per->PER_DESCRIPCION ?></option>
<?php
}
?>
</select>
<input type="hidden" id="id" name="id" value="<?php echo $id ?>">
<br>
<input type="submit" value="Agregar Permiso"/>
<?php
echo form_close();
?>
|
<h1>Entregar Permisos Portafolio</h1>
<a href="<?php echo base_url()?>portafolio">Volver</a>
<?php
if ($this->session->flashdata('ControllerMessage')!='') {
?>
<p style="color:red;"><?php echo $this->session->flashdata('ControllerMessage'); ?></p>
<?php
}
?>
<?php
$atributos = array('id'=>'nuevopermiso','name'=>'nuevopermiso');
echo form_open_multipart(null,$atributos);
?>
<p>Nombre</p>
<!--<input type="text" id="usuarioid" name="usuarioid" placeholder="Ingresa el ID del usuario a agregar!"/>-->
<!-- Esto debería recibir un nombre -->
<br>
<select id="permisoid" name="permisoid">
<?php
foreach ($permisos as $per)
{
?>
<option value="<?php echo $per->PER_ID ?>"><?php echo $per->PER_DESCRIPCION ?></option>
<?php
}
?>
</select>
<input type="hidden" id="id" name="id" value="<?php echo $id ?>">
<br>
<input type="submit" value="Agregar Permiso"/>
<?php
echo form_close();
?>
|
Use numeric value to turn off no-process-exit rule
|
#!/usr/bin/env node
// reason: this is the main entry to the module walker. if something
// goes wrong it has to decide what exit code to return. hence, it
// has to be able to use process.exit()
/* eslint no-process-exit: 0 */
import cli from 'commander';
import main from './lib/main';
import {loadConfigFromCLI} from './lib/configuration';
import {collect,findBaseDir} from './lib/collectInput';
import {parseImports} from './lib/parseImports';
import {printDot} from './lib/printDot';
cli.arguments('<files>', 'Files or folders containing files of the project to analyze')
.parse(process.argv);
try {
main(cli, {loadConfigFromCLI, collect, findBaseDir, parseImports, printDot});
} catch (e) {
console.error(`An error occurred: ${e}`);
cli.outputHelp((helpText) => {
console.log(helpText);
process.exit(1);
});
}
|
#!/usr/bin/env node
// reason: this is the main entry to the module walker. if something
// goes wrong it has to decide what exit code to return. hence, it
// has to be able to use process.exit()
/* eslint no-process-exit: "off" */
import cli from 'commander';
import main from './lib/main';
import {loadConfigFromCLI} from './lib/configuration';
import {collect,findBaseDir} from './lib/collectInput';
import {parseImports} from './lib/parseImports';
import {printDot} from './lib/printDot';
cli.arguments('<files>', 'Files or folders containing files of the project to analyze')
.parse(process.argv);
try {
main(cli, {loadConfigFromCLI, collect, findBaseDir, parseImports, printDot});
} catch (e) {
console.error(`An error occurred: ${e}`);
cli.outputHelp((helpText) => {
console.log(helpText);
process.exit(1);
});
}
|
Add method to fetch a single event
|
from base import BaseClient
EVENTS_API_VERSION = 'v1'
class EventsClient(BaseClient):
def _get_path(self, subpath):
return 'events/%s/%s' % (EVENTS_API_VERSION, subpath)
def get_events(self, **options):
return self._call('events', **options)
def get_event(self, event_id, **options):
return self._call('events/%s' % event_id, **options)
def create_event(self, description, create_date, url, event_type, **options):
event_data = {
'description': description,
'createDate': create_date,
'url': url,
'eventType': event_type
}
return self._call('events', params=event_data, method='POST', **options)
|
from base import BaseClient
EVENTS_API_VERSION = 'v1'
class EventsClient(BaseClient):
def _get_path(self, subpath):
return 'events/%s/%s' % (EVENTS_API_VERSION, subpath)
def get_events(self, **options):
return self._call('events', **options)
def create_event(self, description, create_date, url, event_type, **options):
event_data = {
'description': description,
'createDate': create_date,
'url': url,
'eventType': event_type
}
return self._call('events', params=event_data, method='POST', **options)
|
Revert "Don't make dirs on startup"
This reverts commit 17243b31fc6c8d8f4bb0dc7e11e2601800e80bb0.
|
import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
@sideboard.lib.on_startup
def create_data_dirs():
from uber.config import c
for directory in c.DATA_DIRS.values():
if not os.path.exists(directory):
log.info('Creating directory {}'.format(directory))
os.makedirs(directory, mode=0o744)
|
import os
from decimal import Decimal
from pockets.autolog import log
from uber._version import __version__ # noqa: F401
def on_load():
"""
Called by sideboard when the uber plugin is loaded.
"""
# Note: The following imports have side effects
from uber import config # noqa: F401
from uber import api # noqa: F401
from uber import automated_emails # noqa: F401
from uber import custom_tags # noqa: F401
from uber import jinja # noqa: F401
from uber import menu # noqa: F401
from uber import models # noqa: F401
from uber import model_checks # noqa: F401
from uber import sep_commands # noqa: F401
from uber import server # noqa: F401
from uber import tasks # noqa: F401
# sideboard must be imported AFTER the on_load() function is declared,
# otherwise on_load() won't exist yet when sideboard looks for it.
import sideboard # noqa: E402
# NOTE: this will decrease the precision of some serialized decimal.Decimals
sideboard.lib.serializer.register(Decimal, lambda n: float(n))
|
Fix type name of initial content element of new sections
`editableTextBlock` was a temporary name.
REDMINE-17338, REDMINE-17339
|
import Backbone from 'backbone';
import {
configurationContainer,
entryTypeEditorControllerUrls,
failureTracking,
delayedDestroying,
ForeignKeySubsetCollection
} from 'pageflow/editor';
export const Chapter = Backbone.Model.extend({
mixins: [
configurationContainer({
autoSave: true,
includeAttributesInJSON: ['position']
}),
delayedDestroying,
entryTypeEditorControllerUrls.forModel({resources: 'chapters'}),
failureTracking
],
initialize(attributes, options) {
this.sections = new ForeignKeySubsetCollection({
parent: options.sections,
parentModel: this,
foreignKeyAttribute: 'chapterId',
parentReferenceAttribute: 'chapter'
});
this.entry = options.entry;
},
addSection(attributes) {
const section = this.sections.create({
position: this.sections.length,
chapterId: this.id,
...attributes
}, {
contentElements: this.entry.contentElements
});
section.once('sync', () => {
section.contentElements.create({
typeName: 'textBlock',
configuration: {
}
});
});
}
});
|
import Backbone from 'backbone';
import {
configurationContainer,
entryTypeEditorControllerUrls,
failureTracking,
delayedDestroying,
ForeignKeySubsetCollection
} from 'pageflow/editor';
export const Chapter = Backbone.Model.extend({
mixins: [
configurationContainer({
autoSave: true,
includeAttributesInJSON: ['position']
}),
delayedDestroying,
entryTypeEditorControllerUrls.forModel({resources: 'chapters'}),
failureTracking
],
initialize(attributes, options) {
this.sections = new ForeignKeySubsetCollection({
parent: options.sections,
parentModel: this,
foreignKeyAttribute: 'chapterId',
parentReferenceAttribute: 'chapter'
});
this.entry = options.entry;
},
addSection(attributes) {
const section = this.sections.create({
position: this.sections.length,
chapterId: this.id,
...attributes
}, {
contentElements: this.entry.contentElements
});
section.once('sync', () => {
section.contentElements.create({
typeName: 'editableTextBlock',
configuration: {
}
});
});
}
});
|
Update and refactor MainCtrl spec
Whoops, #197 broke that spec. Used the opportunity to refactor the file
a bit.
|
"use strict";
describe('MainCtrl', function() {
beforeEach(module('arethusa'));
it('sets scope values', inject(function($controller, $rootScope) {
var scope = $rootScope.$new();
var state = {
init: function() {},
allLoaded: false
};
var notifier = {
init: function() {},
success: function() {},
info: function() {},
error: function() {}
};
var configurator = {
configurationFor: function(name) {
return { plugins: {}, template: "template"};
}
};
var saver = { init: function() {} };
var mainCtrlInits = {
$scope: scope,
configurator: configurator,
state: state,
notifier: notifier,
saver: saver
};
var ctrl = $controller('MainCtrl', mainCtrlInits);
expect(scope.state).toBe(state);
expect(scope.plugins).toBeUndefined();
expect(scope.template).toBe("template");
}));
});
|
"use strict";
describe('MainCtrl', function() {
beforeEach(module('arethusa'));
it('sets scope values', inject(function($controller, $rootScope) {
var scope = $rootScope.$new();
var mystate = {
init: function() {},
allLoaded: false
};
var notifier = {
init: function() {},
success: function() {},
info: function() {},
error: function() {}
};
var ctrl = $controller('MainCtrl', {$scope:scope, state:mystate, notifier:notifier, configurator: {
configurationFor: function(name) {
return { plugins: {}, template: "template"};
}
}});
expect(scope.state).toBe(mystate);
expect(scope.plugins).toBeUndefined();
expect(scope.template).toBe("template");
}));
});
|
Set heights after images have loaded
|
if (typeof jQuery === 'undefined') {
throw new Error('The jQuery equal height extension requires jQuery!');
}
jQuery.fn.equalHeight = function() {
var $ = jQuery;
var that = this;
var setHeights = function() {
var elems = {};
var cont = $(that);
// Reset the elements heights
cont.each(function() {
$(this).height('');
});
// Create a mapping of elements and the max height for all elements at that top offset
cont.each(function() {
var t = $(this).offset().top;
if (typeof elems[t] == "undefined") elems[t] = {maxHeight: 0, e: []};
elems[t].e.push($(this));
elems[t].maxHeight = Math.max($(this).outerHeight(), elems[t].maxHeight);
});
// Apply the max height to all elements in each offset class
for (var t in elems) {
var mh = elems[t].maxHeight;
for (var i in elems[t].e) {
var e = elems[t].e[i];
var padding = e.outerHeight() - e.height();
e.height(mh - padding);
}
}
};
setHeights();
$(window).resize(setHeights);
$(this).find('img').load(setHeights);
};
|
if (typeof jQuery === 'undefined') {
throw new Error('The jQuery equal height extension requires jQuery!');
}
jQuery.fn.equalHeight = function() {
var $ = jQuery;
var that = this;
var setHeights = function() {
var elems = {};
var cont = $(that);
// Reset the elements heights
cont.each(function() {
$(this).height('');
});
// Create a mapping of elements and the max height for all elements at that top offset
cont.each(function() {
var t = $(this).offset().top;
if (typeof elems[t] == "undefined") elems[t] = {maxHeight: 0, e: []};
elems[t].e.push($(this));
elems[t].maxHeight = Math.max($(this).outerHeight(), elems[t].maxHeight);
});
// Apply the max height to all elements in each offset class
for (var t in elems) {
var mh = elems[t].maxHeight;
for (var i in elems[t].e) {
var e = elems[t].e[i];
var padding = e.outerHeight() - e.height();
e.height(mh - padding);
}
}
};
setHeights();
setTimeout(setHeights, 100); // Set heights after page elements have rendered, is there a more elegant way to do this?
$(window).resize(setHeights);
};
|
Update placeholder in translation string.
|
<?php
namespace Crud\Error\Exception;
use Cake\Error\Exception;
use Cake\ORM\Entity;
use Cake\Utility\Hash;
/**
* Exception containing validation errors from the model. Useful for API
* responses where you need an error code in response
*
*/
class ValidationException extends Exception {
/**
* List of validation errors that occurred in the model
*
* @var array
*/
protected $_validationErrors = [];
/**
* How many validation errors are there?
*
* @var integer
*/
protected $_validationErrorCount = 0;
/**
* Constructor
*
* @param array $error list of validation errors
* @param integer $code code to report to client
* @return void
*/
public function __construct(Entity $entity, $code = 412) {
$this->_validationErrors = array_filter((array)$entity->errors());
$flat = Hash::flatten($this->_validationErrors);
$errorCount = $this->_validationErrorCount = count($flat);
$this->message = __dn('crud', 'A validation error occurred', '{0} validation errors occurred', $errorCount, [$errorCount]);
parent::__construct($this->message, $code);
}
/**
* Returns the list of validation errors
*
* @return array
*/
public function getValidationErrors() {
return $this->_validationErrors;
}
/**
* How many validation errors are there?
*
* @return integer
*/
public function getValidationErrorCount() {
return $this->_validationErrorCount;
}
}
|
<?php
namespace Crud\Error\Exception;
use Cake\Error\Exception;
use Cake\ORM\Entity;
use Cake\Utility\Hash;
/**
* Exception containing validation errors from the model. Useful for API
* responses where you need an error code in response
*
*/
class ValidationException extends Exception {
/**
* List of validation errors that occurred in the model
*
* @var array
*/
protected $_validationErrors = [];
/**
* How many validation errors are there?
*
* @var integer
*/
protected $_validationErrorCount = 0;
/**
* Constructor
*
* @param array $error list of validation errors
* @param integer $code code to report to client
* @return void
*/
public function __construct(Entity $entity, $code = 412) {
$this->_validationErrors = array_filter((array)$entity->errors());
$flat = Hash::flatten($this->_validationErrors);
$errorCount = $this->_validationErrorCount = count($flat);
$this->message = __dn('crud', 'A validation error occurred', '%d validation errors occurred', $errorCount, [$errorCount]);
parent::__construct($this->message, $code);
}
/**
* Returns the list of validation errors
*
* @return array
*/
public function getValidationErrors() {
return $this->_validationErrors;
}
/**
* How many validation errors are there?
*
* @return integer
*/
public function getValidationErrorCount() {
return $this->_validationErrorCount;
}
}
|
Correct font format terminology; PostScript (a.k.a. Type 1) is a different thing.
|
'use strict';
var assert = require('assert');
var mocha = require('mocha');
var describe = mocha.describe;
var it = mocha.it;
var opentype = require('../src/opentype.js');
describe('OpenType.js', function() {
it('can load a TrueType font', function() {
var font = opentype.loadSync('./fonts/Roboto-Black.ttf');
assert.equal(font.familyName, 'Roboto Bk');
assert.equal(font.unitsPerEm, 2048);
assert.equal(font.glyphs.length, 1037);
var aGlyph = font.charToGlyph('A');
assert.equal(aGlyph.name, 'A');
assert.equal(aGlyph.unicode, 65);
assert.equal(aGlyph.path.commands.length, 18);
});
it('can load a OpenType/CFF font', function() {
var font = opentype.loadSync('./fonts/FiraSansOT-Medium.otf');
assert.equal(font.familyName, 'Fira Sans OT Medium');
assert.equal(font.unitsPerEm, 1000);
assert.equal(font.glyphs.length, 1151);
var aGlyph = font.charToGlyph('A');
assert.equal(aGlyph.name, 'A');
assert.equal(aGlyph.unicode, 65);
assert.equal(aGlyph.path.commands.length, 14);
});
});
|
'use strict';
var assert = require('assert');
var mocha = require('mocha');
var describe = mocha.describe;
var it = mocha.it;
var opentype = require('../src/opentype.js');
describe('OpenType.js', function() {
it('can load a TrueType font', function() {
var font = opentype.loadSync('./fonts/Roboto-Black.ttf');
assert.equal(font.familyName, 'Roboto Bk');
assert.equal(font.unitsPerEm, 2048);
assert.equal(font.glyphs.length, 1037);
var aGlyph = font.charToGlyph('A');
assert.equal(aGlyph.name, 'A');
assert.equal(aGlyph.unicode, 65);
assert.equal(aGlyph.path.commands.length, 18);
});
it('can load a PostScript font', function() {
var font = opentype.loadSync('./fonts/FiraSansOT-Medium.otf');
assert.equal(font.familyName, 'Fira Sans OT Medium');
assert.equal(font.unitsPerEm, 1000);
assert.equal(font.glyphs.length, 1151);
var aGlyph = font.charToGlyph('A');
assert.equal(aGlyph.name, 'A');
assert.equal(aGlyph.unicode, 65);
assert.equal(aGlyph.path.commands.length, 14);
});
});
|
Fix Image Admin for components where multiple exist for one db id
|
<?php
class Kwc_Abstract_Image_ImageFile extends Kwf_Form_Field_File
{
public function __construct($fieldname = null, $fieldLabel = null)
{
parent::__construct($fieldname, $fieldLabel);
$this->setXtype('kwc.imagefile');
$this->setAllowOnlyImages(true);
}
public function load($row, $postData = array())
{
$ret = parent::load($row, $postData);
$component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row->component_id, array('ignoreVisible' => true, 'limit' => 1));
if ($component) { //component can be non-existent if it's in a not selected card
if (is_instance_of($component->componentClass, 'Kwc_Abstract_Image_Component')) {
$contentWidth = $component->getComponent()->getMaxContentWidth();
} else {
$contentWidth = $component->getComponent()->getContentWidth();
}
$ret[$this->getFieldName()]['contentWidth'] = $contentWidth;
}
return $ret;
}
}
|
<?php
class Kwc_Abstract_Image_ImageFile extends Kwf_Form_Field_File
{
public function __construct($fieldname = null, $fieldLabel = null)
{
parent::__construct($fieldname, $fieldLabel);
$this->setXtype('kwc.imagefile');
$this->setAllowOnlyImages(true);
}
public function load($row, $postData = array())
{
$ret = parent::load($row, $postData);
$component = Kwf_Component_Data_Root::getInstance()->getComponentByDbId($row->component_id, array('ignoreVisible' => true));
if ($component) { //component can be non-existent if it's in a not selected card
if (is_instance_of($component->componentClass, 'Kwc_Abstract_Image_Component')) {
$contentWidth = $component->getComponent()->getMaxContentWidth();
} else {
$contentWidth = $component->getComponent()->getContentWidth();
}
$ret[$this->getFieldName()]['contentWidth'] = $contentWidth;
}
return $ret;
}
}
|
Fix notification preferences not being enabled by default
|
<?php namespace Flarum\Extend;
use Illuminate\Foundation\Application;
use Flarum\Core\Models\Notification;
use Flarum\Core\Models\User;
class NotificationType implements ExtenderInterface
{
protected $class;
protected $enabled = [];
public function __construct($class)
{
$this->class = $class;
}
public function enableByDefault($method)
{
$this->enabled[] = $method;
return $this;
}
public function extend(Application $app)
{
$notifier = $app['flarum.notifier'];
$class = $this->class;
$notifier->registerType($class);
Notification::registerType($class);
foreach ($notifier->getMethods() as $method => $sender) {
if ($sender::compatibleWith($class)) {
User::registerPreference(User::notificationPreferenceKey($class::getType(), $method), 'boolval', in_array($method, $this->enabled));
}
}
}
}
|
<?php namespace Flarum\Extend;
use Illuminate\Foundation\Application;
use Flarum\Core\Models\Notification;
use Flarum\Core\Models\User;
class NotificationType implements ExtenderInterface
{
protected $class;
protected $enabled = [];
public function __construct($class)
{
$this->class = $class;
}
public function enableByDefault($method)
{
$this->enabled[] = $method;
return $this;
}
public function extend(Application $app)
{
$notifier = $app['flarum.notifier'];
$class = $this->class;
$notifier->registerType($class);
Notification::registerType($class);
foreach ($notifier->getMethods() as $method => $sender) {
if ($sender::compatibleWith($class)) {
User::registerPreference(User::notificationPreferenceKey($class::getType(), $method), 'boolval', isset($this->enabled[$method]));
}
}
}
}
|
Adjust spacing between Page.Actions items
|
// @flow
import baseStyles from '../../../styles/resets/baseStyles.css.js'
import styled from '../../styled'
export const config = {
marginBottom: 100,
padding: '12px 0',
spacing: 10,
}
export const ActionsUI = styled('div')`
${baseStyles} display: flex;
flex-direction: row-reverse;
margin-left: -${config.spacing}px;
margin-right: -${config.spacing}px;
margin-bottom: ${config.marginBottom}px;
padding: ${config.padding};
&.is-left {
flex-direction: row;
}
&.is-right {
flex-direction: row-reverse;
}
`
export const ActionsItemUI = styled('div')`
min-width: 0;
margin: 0 ${config.spacing}px;
`
export const ActionsBlockUI = styled('div')`
flex: 1;
max-width: 100%;
min-width: 0;
`
export default ActionsUI
|
// @flow
import baseStyles from '../../../styles/resets/baseStyles.css.js'
import styled from '../../styled'
export const config = {
marginBottom: 100,
padding: '12px 0',
spacing: 5,
}
export const ActionsUI = styled('div')`
${baseStyles} display: flex;
flex-direction: row-reverse;
margin-left: -${config.spacing}px;
margin-right: -${config.spacing}px;
margin-bottom: ${config.marginBottom}px;
padding: ${config.padding};
&.is-left {
flex-direction: row;
}
&.is-right {
flex-direction: row-reverse;
}
`
export const ActionsItemUI = styled('div')`
min-width: 0;
margin: 0 ${config.spacing}px;
`
export const ActionsBlockUI = styled('div')`
flex: 1;
max-width: 100%;
min-width: 0;
`
export default ActionsUI
|
Add locale formatting to stats numbers
This addresses issue #10.
|
import React from 'react'
import injectSheet from 'react-jss'
import styles from './styles'
const GenResults = ({ classes, newLine, results, stats }) => {
let joinedResults = Array.prototype.join.call(results, `${newLine ? '\n' : ' '}`).trim()
let words = stats.words
let maxWords = stats.maxWords
let filtered = stats.filtered
const statsText = () => {
if (filtered > 0) {
return `words: ${words.toLocaleString()} (${filtered.toLocaleString()} filtered out); maximum different words: ${maxWords.toLocaleString()}`
} else {
return `words: ${words.toLocaleString()}; maximum different words: ${maxWords.toLocaleString()}`
}
}
return (
<div className={classes.results}>
<div className={classes.output}>
<p className={classes.outText}>
{joinedResults}
</p>
</div>
<div className={classes.stats}>
<p className={classes.statsText}>
{statsText()}
</p>
</div>
</div>
)
}
export default injectSheet(styles)(GenResults)
|
import React from 'react'
import injectSheet from 'react-jss'
import styles from './styles'
const GenResults = ({ classes, newLine, results, stats }) => {
let joinedResults = Array.prototype.join.call(results, `${newLine ? '\n' : ' '}`).trim()
let words = stats.words
let maxWords = stats.maxWords
let filtered = stats.filtered
const statsText = () => {
if (filtered > 0) {
return `words: ${words} (${filtered} filtered out); maximum different words: ${maxWords}`
} else {
return `words: ${words}; maximum different words: ${maxWords}`
}
}
return (
<div className={classes.results}>
<div className={classes.output}>
<p className={classes.outText}>
{joinedResults}
</p>
</div>
<div className={classes.stats}>
<p className={classes.statsText}>
{statsText()}
</p>
</div>
</div>
)
}
export default injectSheet(styles)(GenResults)
|
Fix help docstring and glob parsing
|
#!/usr/bin/env python
import argparse
import glob
import os
from pytrthree import TRTHIterator
from corintick import Corintick, ValidationError
def main(args):
db = Corintick(args.config)
files = glob.glob(os.path.expanduser(args.files))
for ric, df in TRTHIterator(files):
cols = args.columns if args.columns else df.columns
try:
db.write(ric, df[cols], collection=args.collection)
except ValidationError as e:
db.logger.error(e)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Parse TRTH files and insert into Corintick.')
parser.add_argument('--config', type=argparse.FileType('r'), required=True,
help='Corintick configuration (YAML file)')
parser.add_argument('--files', type=str, default='*', required=True,
help='Glob of files to insert')
parser.add_argument('--columns', nargs='*', type=str,
help='Columns to be inserted (optional)')
parser.add_argument('--collection', type=str, default=None,
help='Collection to insert to (optional)')
args = parser.parse_args()
main(args)
|
#!/usr/bin/env python
import argparse
import glob
from pytrthree import TRTHIterator
from corintick import Corintick, ValidationError
def main(args):
db = Corintick(args.config)
files = glob.glob(args.files)
for ric, df in TRTHIterator(files):
cols = args.columns if args.columns else df.columns
try:
db.write(ric, df[cols], collection=args.collection)
except ValidationError as e:
db.logger.error(e)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Parse TRTH files and insert into Corintick.')
parser.add_argument('--config', type=argparse.FileType('r'), required=True,
help='Corintick configuration (YAML file)')
parser.add_argument('--files', type=str, default='*', required=True,
help='Glob of files to download')
parser.add_argument('--columns', nargs='*', type=str,
help='Columns to be inserted (optional)')
parser.add_argument('--collection', type=str, default=None,
help='Collection to insert to (optional)')
args = parser.parse_args()
main(args)
|
Fix issue with nested headers on page in admin area
|
'use strict';
(function ($) {
var showBanner = function (content) {
if (content) {
$('header.site-header').after(content)
}
}
var getBannerHost = function () {
var local = window.location.host.startsWith('ckan-gateway')
if (local) {
return 'http://localhost:8000'
}
var production = window.location.host.startsWith('catalogue')
return production ? '//data.govt.nz' : '//diadata-uat.cwp.govt.nz'
}
var getBanner = function () {
$.ajax({
url: getBannerHost() + '/api/banner',
success: function (banner) {
if (banner.enabled) {
showBanner(banner.content)
}
}
})
}
getBanner();
})($)
|
'use strict';
(function ($) {
var showBanner = function (content) {
if (content) {
$('header').after(content)
}
}
var getBannerHost = function () {
var local = window.location.host.startsWith('ckan-gateway')
if (local) {
return 'http://localhost:8000'
}
var production = window.location.host.startsWith('catalogue')
return production ? '//data.govt.nz' : '//diadata-uat.cwp.govt.nz'
}
var getBanner = function () {
$.ajax({
url: getBannerHost() + '/api/banner',
success: function (banner) {
if (banner.enabled) {
showBanner(banner.content)
}
}
})
}
getBanner();
})($)
|
Add a service to get the posts
|
// we don't need to use a variable
// or the from keyword when importing a css/styl file
// thanks the the styles loader it gets added as a
// <style> tag in the head by default but can be changed
import 'normalize.css';
import {appDirective} from './app.directive';
// the angular libs are just common js
// and therefore we can assume they were
// exported using the default keyword in ES2015
// so we can import each module
// with any name we see fit.
// Note that the actual value are just strings except angular itself
// because that's how angular decided to export
// their auxillary modules
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngAnimate from 'angular-animate';
// because we exported a named variable
// without using default keyword
// we must import it with the brackets
import {home} from './components/home/home';
import {blog} from './components/blog/blog';
import {common} from './components/common/common';
import {shared} from './shared/shared';
angular.module('app', [
uiRouter,
ngAnimate,
// home is the module, the angular module
// because that's what we exported in home.js
// all angular modules have a name
// property who's value is the name you set the
// module to be
home.name,
blog.name,
common.name,
shared.name
])
.directive('app', appDirective);
|
// we don't need to use a variable
// or the from keyword when importing a css/styl file
// thanks the the styles loader it gets added as a
// <style> tag in the head by default but can be changed
import 'normalize.css';
import {appDirective} from './app.directive';
// the angular libs are just common js
// and therefore we can assume they were
// exported using the default keyword in ES2015
// so we can import each module
// with any name we see fit.
// Note that the actual value are just strings except angular itself
// because that's how angular decided to export
// their auxillary modules
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngAnimate from 'angular-animate';
// because we exported a named variable
// without using default keyword
// we must import it with the brackets
import {home} from './components/home/home';
import {blog} from './components/blog/blog';
// TODO: register common with app
// TODO: register shared with app
angular.module('app', [
uiRouter,
ngAnimate,
// home is the module, the angular module
// because that's what we exported in home.js
// all angular modules have a name
// property who's value is the name you set the
// module to be
home.name,
blog.name
])
.directive('app', appDirective);
|
Update SimpleMap to hash both keys and values for benefit; Hashable is Hasher; Don't assume go-wire
|
package merkle
type Tree interface {
Size() (size int)
Height() (height int8)
Has(key []byte) (has bool)
Proof(key []byte) (value []byte, proof []byte, exists bool) // TODO make it return an index
Get(key []byte) (index int, value []byte, exists bool)
GetByIndex(index int) (key []byte, value []byte)
Set(key []byte, value []byte) (updated bool)
Remove(key []byte) (value []byte, removed bool)
HashWithCount() (hash []byte, count int)
Hash() (hash []byte)
Save() (hash []byte)
Load(hash []byte)
Copy() Tree
Iterate(func(key []byte, value []byte) (stop bool)) (stopped bool)
IterateRange(start []byte, end []byte, ascending bool, fx func(key []byte, value []byte) (stop bool)) (stopped bool)
}
type Hasher interface {
Hash() []byte
}
type Byteser interface {
Bytes() []byte
}
|
package merkle
type Tree interface {
Size() (size int)
Height() (height int8)
Has(key []byte) (has bool)
Proof(key []byte) (value []byte, proof []byte, exists bool) // TODO make it return an index
Get(key []byte) (index int, value []byte, exists bool)
GetByIndex(index int) (key []byte, value []byte)
Set(key []byte, value []byte) (updated bool)
Remove(key []byte) (value []byte, removed bool)
HashWithCount() (hash []byte, count int)
Hash() (hash []byte)
Save() (hash []byte)
Load(hash []byte)
Copy() Tree
Iterate(func(key []byte, value []byte) (stop bool)) (stopped bool)
IterateRange(start []byte, end []byte, ascending bool, fx func(key []byte, value []byte) (stop bool)) (stopped bool)
}
type Hasher interface {
Hash() []byte
}
|
Update docs versions for 2.x
|
# Global configuration information used across all the
# translations of documentation.
#
# Import the base theme configuration
from cakephpsphinx.config.all import *
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
release = '2.x'
# The search index version.
search_version = 'chronos-2'
# The marketing display name for the book.
version_name = ''
# Project name shown in the black header bar
project = 'Chronos'
# Other versions that display in the version picker menu.
version_list = [
{'name': '1.x', 'number': '/chronos/1.x', 'title': '1.x'},
{'name': '2.x', 'number': '/chronos/2.x', 'title': '2.x', 'current': True},
]
# Languages available.
languages = ['en', 'fr', 'ja', 'pt']
# The GitHub branch name for this version of the docs
# for edit links to point at.
branch = '2.x'
# Current version being built
version = '2.x'
# Language in use for this directory.
language = 'en'
show_root_link = True
repository = 'cakephp/chronos'
source_path = 'docs/'
is_prerelease = True
|
# Global configuration information used across all the
# translations of documentation.
#
# Import the base theme configuration
from cakephpsphinx.config.all import *
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
release = '1.x'
# The search index version.
search_version = 'chronos-1'
# The marketing display name for the book.
version_name = ''
# Project name shown in the black header bar
project = 'Chronos'
# Other versions that display in the version picker menu.
version_list = [
{'name': '1.x', 'number': '/chronos/1.x', 'title': '1.x', 'current': True},
]
# Languages available.
languages = ['en', 'fr', 'ja', 'pt']
# The GitHub branch name for this version of the docs
# for edit links to point at.
branch = 'master'
# Current version being built
version = '1.x'
# Language in use for this directory.
language = 'en'
show_root_link = True
repository = 'cakephp/chronos'
source_path = 'docs/'
|
SDC-9109: Add RUNNING_ERROR to pipeline states available for notifications.
Change-Id: Idb02918672c1057a1bb94653c6f100374373cd89
Reviewed-on: https://review.streamsets.net/14850
Reviewed-by: Jarcec Cecho <df2d427dacaa504f2ede0aed47c4cdf043778b95@streamsets.com>
Tested-by: StreamSets CI <809627f37325a679986bd660c7713476a56d59cd@streamsets.com>
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.config;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;
import java.io.Serializable;
@GenerateResourceBundle
public enum PipelineState implements Label, Serializable {
RUNNING("Running"),
START_ERROR("Start Error"),
RUN_ERROR("Run Error"),
RUNNING_ERROR("Running Error"),
STOPPED("Stopped"),
FINISHED("Finished"),
DISCONNECTED("Disconnected"),
CONNECTING("Connecting"),
STOP_ERROR("Stop Error"),
;
private final String label;
PipelineState(String label) {
this.label = label;
}
@Override
public String getLabel() {
return label;
}
}
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.config;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;
import java.io.Serializable;
@GenerateResourceBundle
public enum PipelineState implements Label, Serializable {
RUNNING("Running"),
START_ERROR("Start Error"),
RUN_ERROR("Run Error"),
STOPPED("Stopped"),
FINISHED("Finished"),
DISCONNECTED("Disconnected"),
CONNECTING("Connecting"),
STOP_ERROR("Stop Error"),
;
private final String label;
PipelineState(String label) {
this.label = label;
}
@Override
public String getLabel() {
return label;
}
}
|
Add reflection to problem execution
|
package com.ejpm.euler;
import com.ejpm.euler.problem.Problem;
import java.util.logging.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
System.out.println("Project Euler Solutions");
new App().executeProblems();
System.out.println("DONE");
}
public void executeProblems() {
final String classPackage = "com.ejpm.euler.problem.impl";
for (int i = 0; i < 900; i++) {
final String className = classPackage.concat(".Problem") + i;
try {
final Class<?> c = Class.forName(className);
final Problem problem = (Problem) c.newInstance();
problem.execute();
} catch (ClassNotFoundException ex) {
} catch (InstantiationException | IllegalAccessException ex) {
java.util.logging.Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
|
package com.ejpm.euler;
import com.ejpm.euler.problem.impl.Problem1;
import com.ejpm.euler.problem.impl.Problem2;
import com.ejpm.euler.problem.impl.Problem3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class App {
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
new App().proceed();
}
public void proceed() {
System.out.println("Project Euler Solutions");
//final Reflection
new Problem1().execute();
new Problem2().execute();
new Problem3().execute();
}
}
|
Add the function (not class) to actions as is now required
|
from twisted.words.protocols import irc
from txircd.modbase import Command, Module
class PassCommand(Command, Module):
def onUse(self, user, params):
if user.registered == 0:
user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return
if not params:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters")
return
user.password = params[0]
def onRegister(self, user):
if self.ircd.server_password and self.ircd.server_password != user.password:
user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None)
return False
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.passcmd = PassCommand()
def spawn():
return {
"actions": {
"register": [self.passcmd.onRegister]
},
"commands": {
"PASS": self.passcmd
}
}
def cleanup():
self.ircd.actions.remove(self.passcmd)
del self.ircd.commands["PASS"]
del self.passcmd
|
from twisted.words.protocols import irc
from txircd.modbase import Command, Module
class PassCommand(Command, Module):
def onUse(self, user, params):
if user.registered == 0:
user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return
if not params:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "PASS", ":Not enough parameters")
return
user.password = params[0]
def onRegister(self, user):
if self.ircd.server_password and self.ircd.server_password != user.password:
user.sendMessage("ERROR", ":Closing link: ({}@{}) [Access denied]".format(user.username, user.hostname), to=None, prefix=None)
return False
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
self.passcmd = PassCommand()
def spawn():
return {
"actions": {
"register": [self.passcmd]
},
"commands": {
"PASS": self.passcmd
}
}
def cleanup():
self.ircd.actions.remove(self.passcmd)
del self.ircd.commands["PASS"]
del self.passcmd
|
Fix - icon alignment in onboarding modal (calendar ready)
|
import { Alert, Icon } from 'react-components';
import { c } from 'ttag';
import React from 'react';
import calendarSvg from 'design-system/assets/img/pm-images/calendar.svg';
const CalendarReady = () => {
const supportIcon = <Icon key="support-icon" name="support1" className="alignsub" />;
return (
<>
<Alert>{c('Info')
.t`Your new calendar is now ready. All events in your calendar are encrypted and inaccessible to anybody other than you.`}</Alert>
<div className="aligncenter mb1">
<img src={calendarSvg} alt="" />
</div>
<Alert>{c('Info')
.jt`If you encounter a problem, you can reach our support team by clicking the ${supportIcon} button.`}</Alert>
</>
);
};
export default CalendarReady;
|
import { Alert, Icon } from 'react-components';
import { c } from 'ttag';
import React from 'react';
import calendarSvg from 'design-system/assets/img/pm-images/calendar.svg';
const CalendarReady = () => {
const supportIcon = <Icon key="support-icon" name="support1" />;
return (
<>
<Alert>{c('Info')
.t`Your new calendar is now ready. All events in your calendar are encrypted and inaccessible to anybody other than you.`}</Alert>
<div className="aligncenter">
<img src={calendarSvg} alt="Calendar" />
</div>
<Alert>{c('Info')
.jt`If you encounter a problem, you can reach our support team by clicking the ${supportIcon} button.`}</Alert>
</>
);
};
export default CalendarReady;
|
Allow all languages on pretix
|
from pretix.settings import * # noqa
SECRET_KEY = "{{secret_key}}"
LOGGING["handlers"]["mail_admins"]["include_html"] = True # noqa
STATICFILES_STORAGE = (
"django.contrib.staticfiles.storage.ManifestStaticFilesStorage" # noqa
)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "{{database_name}}",
"USER": "{{database_username}}",
"PASSWORD": "{{database_password}}",
"HOST": "{{database_host}}",
"PORT": "5432",
}
}
# Allow all the languages
# see: pretix/settings.py#L425-L435
LANGUAGES = [(k, v) for k, v in ALL_LANGUAGES] # noqa
USE_X_FORWARDED_HOST = True
SITE_URL = "https://tickets.pycon.it"
MAIL_FROM = SERVER_EMAIL = DEFAULT_FROM_EMAIL = "noreply@pycon.it"
EMAIL_HOST = "email-smtp.us-east-1.amazonaws.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "{{mail_user}}"
EMAIL_HOST_PASSWORD = "{{mail_password}}"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_SUBJECT_PREFIX = "[PyCon Tickets] "
|
from pretix.settings import * # noqa
SECRET_KEY = "{{secret_key}}"
LOGGING["handlers"]["mail_admins"]["include_html"] = True # noqa
STATICFILES_STORAGE = (
"django.contrib.staticfiles.storage.ManifestStaticFilesStorage" # noqa
)
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "{{database_name}}",
"USER": "{{database_username}}",
"PASSWORD": "{{database_password}}",
"HOST": "{{database_host}}",
"PORT": "5432",
}
}
USE_X_FORWARDED_HOST = True
SITE_URL = "https://tickets.pycon.it"
MAIL_FROM = SERVER_EMAIL = DEFAULT_FROM_EMAIL = "noreply@pycon.it"
EMAIL_HOST = "email-smtp.us-east-1.amazonaws.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "{{mail_user}}"
EMAIL_HOST_PASSWORD = "{{mail_password}}"
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_SUBJECT_PREFIX = "[PyCon Tickets] "
|
Add cy-GB and es-ES languages
|
'use strict';
module.exports = {
defaultLangTag: 'en',
primary: [
'ar',
'da',
'de',
'en',
'es',
'fi',
'fr',
'ja',
'ko',
'nb',
'nl',
'pt',
'sv',
'tr',
'zh'
],
regions: [
'ar-SA',
'cy-GB',
'da-DK',
'de-DE',
'en-CA',
'en-GB',
'en-US',
'es-MX',
'es-ES',
'fi-FI',
'fr-CA',
'fr-FR',
'fr-ON',
'ko-KR',
'nb-NO',
'nl-NL',
'pt-BR',
'sv-SE',
'tr-TR',
'zh-CN',
'zh-TW'
],
aliases: {
'en-AU': 'en-GB'
}
};
|
'use strict';
module.exports = {
defaultLangTag: 'en',
primary: [
'ar',
'da',
'de',
'en',
'es',
'fi',
'fr',
'ja',
'ko',
'nb',
'nl',
'pt',
'sv',
'tr',
'zh'
],
regions: [
'ar-SA',
'da-DK',
'de-DE',
'en-CA',
'en-GB',
'en-US',
'es-MX',
'fi-FI',
'fr-CA',
'fr-FR',
'fr-ON',
'ko-KR',
'nb-NO',
'nl-NL',
'pt-BR',
'sv-SE',
'tr-TR',
'zh-CN',
'zh-TW'
],
aliases: {
'en-AU': 'en-GB'
}
};
|
Use .attr instead of .data to get json selector. Prevents evaluation of [x] as array
|
// ===================================================
// DOM Outline with event handlers
// ===================================================
$(function(){
var $selector_box = $("#selector");
var selector_val = "";
var DomOutlineHandlers = {
'click': function(e){
selector_val = $(e).attr('data-json-selector');
$selector_box.val(selector_val);
},
'mouseover': function(e){
$(".DomOutline").show();
},
'mouseout': function(e){
$(".DomOutline").hide();
},
}
var DOutline = DomOutline({
handlers: DomOutlineHandlers,
filter: 'code span:not(.hljs-attribute)'
})
DOutline.start()
});
|
// ===================================================
// DOM Outline with event handlers
// ===================================================
$(function(){
var $selector_box = $("#selector");
var selector_val = "";
var DomOutlineHandlers = {
'click': function(e){
selector_val = $(e).data('json-selector');
$selector_box.val(selector_val);
},
'mouseover': function(e){
$(".DomOutline").show();
},
'mouseout': function(e){
$(".DomOutline").hide();
},
}
var DOutline = DomOutline({
handlers: DomOutlineHandlers,
filter: 'code span:not(.hljs-attribute)'
})
DOutline.start()
});
|
Remove compression (done at NGINX level)
|
/* jshint node: true, browser: false */
'use strict';
// CREATE HTTP SERVER AND PROXY
var app = require('express')();
var proxy = require('http-proxy').createProxyServer({});
proxy.on('error', function(e) {
console.error(e);
}); //ignore errors
// LOAD CONFIGURATION
var oneDay = 86400000;
var cacheTag = Math.random() * 0x80000000 | 0;
app.use(require('morgan')('dev'));
app.set('port', process.env.PORT || 2000);
app.use('/favicon.ico', require('serve-static')(__dirname + '/favicon.ico', { maxAge: oneDay }));
// Configure routes
app.use('/app', require('serve-static')(__dirname + '/app'));
app.all('/app/*', function(req, res) { res.status(404).send(); } );
app.all('/api/*', function(req, res) { proxy.web(req, res, { target: 'https://api.cbd.int:443', secure: false } ); } );
// Configure index.html
app.get('/*', function (req, res) {
res.cookie('cachetag', cacheTag);
res.sendFile(__dirname + '/app/index.html');
});
// Start server
app.listen(app.get('port'), function () {
console.log('Server listening on %j', this.address());
});
|
/* jshint node: true, browser: false */
'use strict';
// CREATE HTTP SERVER AND PROXY
var app = require('express')();
var proxy = require('http-proxy').createProxyServer({});
proxy.on('error', function(e) {
console.error(e);
}); //ignore errors
// LOAD CONFIGURATION
var oneDay = 86400000;
var cacheTag = Math.random() * 0x80000000 | 0;
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.set('port', process.env.PORT || 2000);
app.use('/favicon.ico', require('serve-static')(__dirname + '/favicon.ico', { maxAge: oneDay }));
// Configure routes
app.use('/app', require('serve-static')(__dirname + '/app'));
app.all('/app/*', function(req, res) { res.status(404).send(); } );
app.all('/api/*', function(req, res) { proxy.web(req, res, { target: 'https://api.cbd.int:443', secure: false } ); } );
// Configure index.html
app.get('/*', function (req, res) {
res.cookie('cachetag', cacheTag);
res.sendFile(__dirname + '/app/index.html');
});
// Start server
app.listen(app.get('port'), function () {
console.log('Server listening on %j', this.address());
});
|
Update measured Focal Lengths for C920.
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H622 V625
# Microsoft Lifecam HD-3000: H652 V?
#
PFL_H_C920 = 622
PFL_V_C920 = 625
PFL_H_LC3000 = 652
PFL_V_LC3000 = 652
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFocalLengthAtGivenDistance(self, perceivedSize, knownDistance):
focalLength = perceivedSize * knownDistance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
# Calculate the distance to an object of known size.
# We need to know the perceived focal length for this to work.
#
# Known Focal Length values for calibrated cameras
# Logitech C920: H620 V?
# Microsoft Lifecam HD-3000: H652 V?
#
class TriangleSimilarityDistanceCalculator:
knownSize = 0
focalLength = 0;
def __init__(self, knownSize, perceivedFocalLength = None):
self.knownSize = knownSize
self.focalLength = perceivedFocalLength
# Call this to calibrate a camera and then use the calibrated focalLength value
# when using this class to calculate real distances.
def CalculatePerceivedFOVAtGivenDistance(self, perceivedSize, distance):
focalLength = perceivedSize * distance / float(self.knownSize)
return focalLength
# This will return the real world distance of the known object.
def CalcualteDistance(self, perceivedSize):
if self.focalLength == None:
raise ValueError("Did you forget to calibrate this camera and set the perceived focal length?")
distance = self.knownSize * self.focalLength / float(perceivedSize)
return distance
|
Fix shape unpacking ((height, width), not (w, h)).
|
"""
=================
Template Matching
=================
In this example, we use template matching to identify the occurrence of an
image patch (in this case, a sub-image centered on the camera man's head).
Since there's only a single match, the maximum value in the `match_template`
result` corresponds to the head location. If you expect multiple matches, you
should use a proper peak-finding function.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.feature import match_template
image = data.camera()
head = image[70:170, 180:280]
result = match_template(image, head)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))
ax1.imshow(head)
ax1.set_axis_off()
ax1.set_title('template')
ax2.imshow(image)
ax2.set_axis_off()
ax2.set_title('image')
# highlight matched region
xy = np.unravel_index(np.argmax(result), result.shape)[::-1] #-1 flips ij to xy
hface, wface = head.shape
rect = plt.Rectangle(xy, wface, hface, edgecolor='r', facecolor='none')
ax2.add_patch(rect)
plt.show()
|
"""
=================
Template Matching
=================
In this example, we use template matching to identify the occurrence of an
image patch (in this case, a sub-image centered on the camera man's head).
Since there's only a single match, the maximum value in the `match_template`
result` corresponds to the head location. If you expect multiple matches, you
should use a proper peak-finding function.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.feature import match_template
image = data.camera()
head = image[70:170, 180:280]
result = match_template(image, head)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4))
ax1.imshow(head)
ax1.set_axis_off()
ax1.set_title('template')
ax2.imshow(image)
ax2.set_axis_off()
ax2.set_title('image')
# highlight matched region
xy = np.unravel_index(np.argmax(result), result.shape)[::-1] #-1 flips ij to xy
wface, hface = head.shape
rect = plt.Rectangle(xy, wface, hface, edgecolor='r', facecolor='none')
ax2.add_patch(rect)
plt.show()
|
Fix over writing previous addToResult calls
I noticed that multiple calls to the addToResult method in the org.apache.camel.component.aws.ddb.AbstractDdbCommand within the child class org.apache.camel.component.aws.ddb.ScanCommand caused the next call to over write the previous calls to addToResult in the header results. The end result is only having the last result value returned in the out message which is the SCANNED_COUNT header.
The exchange.getOut() already passes back the "In" Message or creates a new Message object if no out message exists does not need to copy over the "In" message into the "Out" message.
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.aws.common;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
public final class AwsExchangeUtil {
private AwsExchangeUtil() {
}
public static Message getMessageForResponse(final Exchange exchange) {
if (exchange.getPattern().isOutCapable()) {
return exchange.getOut();
}
return exchange.getIn();
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.aws.common;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
public final class AwsExchangeUtil {
private AwsExchangeUtil() {
}
public static Message getMessageForResponse(final Exchange exchange) {
if (exchange.getPattern().isOutCapable()) {
Message out = exchange.getOut();
out.copyFrom(exchange.getIn());
return out;
}
return exchange.getIn();
}
}
|
Switch pytest fixture to function scope
Still use the class's get_data method for fixture data
|
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="function")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
data = request.instance.get_data()
load_stock_data(data, conn)
# request.cls.addCleanup(load_stock_data, data, conn)
return conn
|
# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
import rethinkdb
from mockthink import MockThink
from mockthink.test.common import as_db_and_table, load_stock_data
def pytest_addoption(parser):
group = parser.getgroup("mockthink", "Mockthink Testing")
group._addoption("--run", dest="conn_type", default="mockthink", action="store",
choices=["mockthink", "rethink"],
help="Select whether tests are run on a mockthink connection or rethink connection or both")
@pytest.fixture(scope="class")
def conn(request):
cfg = request.config
conn_type = cfg.getvalue("conn_type")
if conn_type == "rethink":
try:
conn = rethinkdb.connect('localhost', 30000) # TODO add config
except rethinkdb.errors.ReqlDriverError:
pytest.exit("Unable to connect to rethink")
elif conn_type == "mockthink":
conn = MockThink(as_db_and_table('nothing', 'nothing', [])).get_conn()
else:
pytest.exit("Unknown mockthink test connection type: " + conn_type)
load_stock_data(request.cls.get_data(), conn)
return conn
|
Add translation URLs as required by Oscar
Fixes #5.
|
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url
from oscar.app import shop
from oscar_mws.dashboard.app import application as mws_app
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
# i18n URLS need to live outside of i18n_patterns scope of the shop
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^dashboard/', include(mws_app.urls)),
url(r'', include(shop.urls)),
)
if settings.DEBUG:
urlpatterns += patterns(
'',
url(
r'^media/(?P<path>.*)$',
'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}
),
)
|
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url
from oscar.app import shop
from oscar_mws.dashboard.app import application as mws_app
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^dashboard/', include(mws_app.urls)),
url(r'', include(shop.urls)),
)
if settings.DEBUG:
urlpatterns += patterns(
'',
url(
r'^media/(?P<path>.*)$',
'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}
),
)
|
Update comment & expose transformDecl
That will allow direct usage un a plugin to avoid multiple loop to
apply transformation directly in a global plugin
|
/**
* Module dependencies.
*/
var reduceCSSCalc = require("reduce-css-calc")
/**
* Expose plugin & helper
*/
module.exports = plugin
module.exports.transformDecl = transformDecl
/**
* PostCSS plugin to reduce calc() function calls.
*/
function plugin() {
return function(style) {
style.eachDecl(transformDecl)
}
}
/**
* Reduce CSS calc on a declaration object
*
* @param {object} dec [description]
*/
function transformDecl(dec) {
if (!dec.value) {
return
}
try {
dec.value = transform(dec.value)
}
catch (err) {
err.position = dec.position
throw err
}
}
/**
* Reduce CSS calc() on a declaration value
*
* @param {String} string
* @return {String}
*/
function transform(string) {
if (string.indexOf("calc(") === -1) {
return string
}
return reduceCSSCalc(string)
}
|
/**
* Module dependencies.
*/
var reduceCSSCalc = require("reduce-css-calc")
/**
* Expose `plugin`.
*/
module.exports = plugin
/**
* Plugin to convert all function calls.
*
* @param {Object} stylesheet
*/
function plugin() {
return function(style) {
style.eachDecl(function declaration(dec) {
if (!dec.value) {
return
}
try {
dec.value = convert(dec.value)
}
catch (err) {
err.position = dec.position
throw err
}
})
}
}
/**
* Reduce CSS calc()
*
* @param {String} string
* @return {String}
*/
function convert(string) {
if (string.indexOf("calc(") === -1) {
return string
}
return reduceCSSCalc(string)
}
|
Rename referral portal -> Acute admissions
|
"""
Referral routes for OPAL acute
"""
from referral import ReferralRoute
from acute import models
class ClerkingRoute(ReferralRoute):
name = 'Acute Take'
description = 'Add a patient to the Acute Take list'
page_title = 'Acute Admissions'
target_teams = ['take']
success_link = '/#/list/take'
verb = 'Book in'
progressive_verb = 'Booking in'
past_verb = 'Booked in'
def post_create(self, episode, user):
"""
Auto Populate clerked by
"""
name = user.first_name[:1] + ' ' + user.last_name
models.Clerking.objects.create(episode=episode, clerked_by=name)
return
|
"""
Referral routes for OPAL acute
"""
from referral import ReferralRoute
from acute import models
class ClerkingRoute(ReferralRoute):
name = 'Acute Take'
description = 'Add a patient to the Acute Take list'
target_teams = ['take']
success_link = '/#/list/take'
verb = 'Book in'
progressive_verb = 'Booking in'
past_verb = 'Booked in'
def post_create(self, episode, user):
"""
Auto Populate clerked by
"""
name = user.first_name[:1] + ' ' + user.last_name
models.Clerking.objects.create(episode=episode, clerked_by=name)
return
|
Add serial number incrementation method
|
package org.cryptonit.cloud.timestamping;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.X509Certificate;
import org.bouncycastle.tsp.*;
import org.bouncycastle.util.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Mathias Brossard
*/
public class Authority {
private final BigInteger one = new BigInteger("1");
private static Logger LOGGER;
KeyPair key;
X509Certificate crt;
Store certs;
BigInteger serial;
synchronized private BigInteger getNextSerial() {
BigInteger s = serial;
serial.add(one);
return s;
}
public TimeStampResponse timestamp(TimeStampRequest request) {
TimeStampResponse response = null;
return response;
}
public Authority(KeyPair key, X509Certificate crt, Store certs) {
LOGGER = LoggerFactory.getLogger(Authority.class);
this.key = key;
this.crt = crt;
this.certs = certs;
this.serial = new BigInteger("1");
}
}
|
package org.cryptonit.cloud.timestamping;
import org.bouncycastle.tsp.*;
import org.bouncycastle.util.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.*;
import java.security.cert.X509Certificate;
/**
* @author Mathias Brossard
*/
public class Authority {
private static Logger LOGGER;
KeyPair key;
X509Certificate crt;
Store certs;
BigInteger serial;
public TimeStampResponse timestamp(TimeStampRequest request) {
TimeStampResponse response = null;
return response;
}
public Authority(KeyPair key, X509Certificate crt, Store certs) {
LOGGER = LoggerFactory.getLogger(Authority.class);
this.key = key;
this.crt = crt;
this.certs = certs;
this.serial = new BigInteger("1");
}
}
|
Index the URL of the WidgyPage.
This way, you don't have to fetch the page object when you want to put a
link in the search results.
|
from haystack import indexes
from widgy.contrib.widgy_mezzanine import get_widgypage_model
from widgy.templatetags.widgy_tags import render_root
from widgy.utils import html_to_plaintext
from .signals import widgypage_pre_index
WidgyPage = get_widgypage_model()
class PageIndex(indexes.SearchIndex, indexes.Indexable):
title = indexes.CharField(model_attr='title')
date = indexes.DateTimeField(model_attr='publish_date')
description = indexes.CharField(model_attr='description')
keywords = indexes.MultiValueField()
get_absolute_url = indexes.CharField(model_attr='get_absolute_url')
text = indexes.CharField(document=True)
def full_prepare(self, *args, **kwargs):
widgypage_pre_index.send(sender=self)
return super(PageIndex, self).full_prepare(*args, **kwargs)
def get_model(self):
return WidgyPage
def index_queryset(self, using=None):
return self.get_model().objects.published()
def prepare_text(self, obj):
html = render_root({}, obj, 'root_node')
content = html_to_plaintext(html)
keywords = ' '.join(self.prepare_keywords(obj))
return ' '.join([obj.title, keywords, obj.description,
content])
def prepare_keywords(self, obj):
return [unicode(k) for k in obj.keywords.all()]
|
from haystack import indexes
from widgy.contrib.widgy_mezzanine import get_widgypage_model
from widgy.templatetags.widgy_tags import render_root
from widgy.utils import html_to_plaintext
from .signals import widgypage_pre_index
WidgyPage = get_widgypage_model()
class PageIndex(indexes.SearchIndex, indexes.Indexable):
title = indexes.CharField(model_attr='title')
date = indexes.DateTimeField(model_attr='publish_date')
description = indexes.CharField(model_attr='description')
keywords = indexes.MultiValueField()
text = indexes.CharField(document=True)
def full_prepare(self, *args, **kwargs):
widgypage_pre_index.send(sender=self)
return super(PageIndex, self).full_prepare(*args, **kwargs)
def get_model(self):
return WidgyPage
def index_queryset(self, using=None):
return self.get_model().objects.published()
def prepare_text(self, obj):
html = render_root({}, obj, 'root_node')
content = html_to_plaintext(html)
keywords = ' '.join(self.prepare_keywords(obj))
return ' '.join([obj.title, keywords, obj.description,
content])
def prepare_keywords(self, obj):
return [unicode(k) for k in obj.keywords.all()]
|
Use python2 pyyaml instead of python3.
|
import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib2')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
|
import os
import sys
def fix_imports():
here = os.path.dirname(__file__)
dirs = [
os.path.normpath(os.path.join(here, '..', '..')),
os.path.normpath(os.path.join(here, 'babel')),
os.path.normpath(os.path.join(here, 'dulwich')),
os.path.normpath(os.path.join(here, 'google-apputils-python')),
os.path.normpath(os.path.join(here, 'httplib2', 'python2')),
os.path.normpath(os.path.join(here, 'pytz')),
os.path.normpath(os.path.join(here, 'pyyaml', 'lib3')),
os.path.normpath(os.path.join(here, 'requests')),
]
sys.path.extend(dirs)
|
Remove useless spacing in the tests
|
var replace = require("../str-replace");
var expect = require("expect.js");
describe("Replace first", function() {
it("should replace first occurrences", function() {
expect(replace("a").from("aa").with("e")).to.be("ea");
});
it("should replace first occurrences ignoring the case", function() {
expect(replace("a").ignoringCase().from("AA").with("e")).to.be("eA");
});
});
describe("Replace all", function() {
it("should replace all occurrences", function() {
expect(replace.all("/").from("/home/dir").with("\\")).to.be("\\home\\dir");
});
it("should replace all occurrences ignoring the case", function() {
var replaceAllHouseIgnoringCase = replace.all("house").ignoringCase();
expect(replaceAllHouseIgnoringCase.from("Many Houses").with("Horse")).to.be("Many Horses");
expect(replace.all("house").from("Many Houses").with("Horse")).to.be("Many Houses");
});
});
|
var replace = require("../str-replace");
var expect = require("expect.js");
describe("Replace first", function() {
it("should replace first occurrences", function() {
expect(replace("a").from("aa").with("e")).to.be("ea");
});
it("should replace first occurrences ignoring the case", function() {
expect(replace("a").ignoringCase().from("AA").with("e")).to.be("eA");
});
});
describe("Replace all", function() {
it("should replace all occurrences", function() {
expect(replace.all("/").from("/home/dir").with("\\")).to.be("\\home\\dir");
});
it("should replace all occurrences ignoring the case", function() {
var replaceAllHouseIgnoringCase = replace.all("house").ignoringCase();
expect(replaceAllHouseIgnoringCase.from("Many Houses").with("Horse")).to.be("Many Horses");
expect(replace.all("house").from("Many Houses").with("Horse")).to.be("Many Houses");
});
});
|
Update User model class with flask-login methods
|
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
class User(UserMixin):
"""Represents a user who can Create, Read, Update & Delete his own bucketlists"""
counter = 0
users = {}
def __init__(self, email, username, password):
"""Constructor class to initialize class"""
self.email = email
self.username = username
self.password = password
User.counter += 1
def create_user(self):
""" Class to create and store a user object """
self.users.update({
self.counter: {
'email': self.email,
'username': self.username,
'password': self.password
}
})
return self.users
def is_active(self):
"""True, as all users are active."""
return True
def get_id(self):
"""Return the email address to satisfy Flask-Login's requirements."""
return self.email
def is_authenticated(self):
"""Return True if the user is authenticated."""
return True
def is_anonymous(self):
"""False, as anonymous users aren't supported."""
return False
|
from werkzeug.security import generate_password_hash, check_password_hash
class User(object):
"""represents a user who can CRUD his own bucketlists"""
users = {}
def __init__(self, email, username, password):
"""Constructor class to initialize class"""
self.email = email
self.username = username
self.password = generate_password_hash(password)
def create_user(self):
""" Class to create and store a user object """
self.users.update({
self.email: {
'email': self.email,
'username': self.username,
'password': self.password
}
})
return self.users
|
Fix to input handler to support space -> underscore conversion.
|
/*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.utilities.gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.terasology.input.Input;
import org.terasology.input.InputType;
import java.lang.reflect.Type;
/**
* @author Immortius
*/
public class InputHandler implements JsonSerializer<Input>, JsonDeserializer<Input> {
@Override
public Input deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return InputType.parse(json.getAsString().replace(" ", "_"));
}
@Override
public JsonElement serialize(Input src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
|
/*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.utilities.gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.terasology.input.Input;
import org.terasology.input.InputType;
import java.lang.reflect.Type;
/**
* @author Immortius
*/
public class InputHandler implements JsonSerializer<Input>, JsonDeserializer<Input> {
@Override
public Input deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return InputType.parse(json.getAsString());
}
@Override
public JsonElement serialize(Input src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
|
chore(pins): Update pins for dictionary to release tag
- Update pins for dictionary to release tag
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.12#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@6d404dbd1dd45ed35d0aef6d33c43dbbd982930d#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
Revert "make some changes that will be undone"
This reverts commit 0321c6fc0d445be8db71fee1a09b7c5f952d7ca8.
|
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
|
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
//added some shit
|
Add uploads form laguage composer
|
<?php
namespace Milax\Mconsole\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposersServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
view()->composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer');
view()->composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer');
view()->composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer');
view()->composer(['mconsole::forms.upload', 'mconsole::uploads.form'], 'Milax\Mconsole\Composers\UploadFormComposer');
view()->composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer');
view()->composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer');
view()->composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer');
view()->composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer');
}
}
|
<?php
namespace Milax\Mconsole\Providers;
use Illuminate\Support\ServiceProvider;
class ViewComposersServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
view()->composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer');
view()->composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer');
view()->composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer');
view()->composer('mconsole::forms.upload', 'Milax\Mconsole\Composers\UploadFormComposer');
view()->composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer');
view()->composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer');
view()->composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer');
view()->composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer');
}
}
|
Change confusing blob data string
(from "ten-bytes!" into "1234567890")
|
'use strict'
describe('/#/complain', function () {
protractor.beforeEach.login({ email: 'admin@juice-sh.op', password: 'admin123' })
describe('challenge "uploadSize"', function () {
it('should be possible to upload files greater 100 KB', function () {
browser.executeScript(function () {
var over100KB = Array.apply(null, Array(10101)).map(String.prototype.valueOf, '1234567890')
var blob = new Blob(over100KB, { type: 'application/pdf' })
var data = new FormData()
data.append('file', blob, 'invalidSizeForClient.pdf')
var request = new XMLHttpRequest()
request.open('POST', '/file-upload')
request.send(data)
})
})
protractor.expect.challengeSolved({ challenge: 'uploadSize' })
})
describe('challenge "uploadType"', function () {
it('should be possible to upload files with other extension than .pdf', function () {
browser.executeScript(function () {
var data = new FormData()
var blob = new Blob([ 'test' ], { type: 'application/x-msdownload' })
data.append('file', blob, 'invalidTypeForClient.exe')
var request = new XMLHttpRequest()
request.open('POST', '/file-upload')
request.send(data)
})
})
protractor.expect.challengeSolved({ challenge: 'uploadType' })
})
})
|
'use strict'
describe('/#/complain', function () {
protractor.beforeEach.login({ email: 'admin@juice-sh.op', password: 'admin123' })
describe('challenge "uploadSize"', function () {
it('should be possible to upload files greater 100 KB', function () {
browser.executeScript(function () {
var over100KB = Array.apply(null, Array(10101)).map(String.prototype.valueOf, 'ten-bytes!')
var blob = new Blob(over100KB, { type: 'application/pdf' })
var data = new FormData()
data.append('file', blob, 'invalidSizeForClient.pdf')
var request = new XMLHttpRequest()
request.open('POST', '/file-upload')
request.send(data)
})
})
protractor.expect.challengeSolved({ challenge: 'uploadSize' })
})
describe('challenge "uploadType"', function () {
it('should be possible to upload files with other extension than .pdf', function () {
browser.executeScript(function () {
var data = new FormData()
var blob = new Blob([ 'test' ], { type: 'application/x-msdownload' })
data.append('file', blob, 'invalidTypeForClient.exe')
var request = new XMLHttpRequest()
request.open('POST', '/file-upload')
request.send(data)
})
})
protractor.expect.challengeSolved({ challenge: 'uploadType' })
})
})
|
Use escape byte encoded in hex and not in octal
|
var CLI = require('../lib/clui.js'),
clc = require('cli-color');
var Line = CLI.Line;
Progress = CLI.Progress;
var statuses = [0, 0, 0, 0, 0];
var lengths = [10, 20, 30, 40, 50];
console.log('\nCtrl/Command + C to quit...\n\n\n\n\n\n\n\n\n');
function drawProgress () {
process.stdout.write('\x1b[9A');
var blankLine = new Line().fill().output();
var headers = new Line()
.padding(2)
.column('Item', 20, [clc.cyan])
.column('Progress', 40, [clc.cyan])
.fill()
.output();
blankLine.output();
for(var index in lengths) {
var thisProgressBar = new Progress(20);
var websiteLine = new Line()
.padding(2)
.column('Item #' + index, 20, [clc.cyan])
.column(thisProgressBar.update(statuses[index], lengths[index]), 40)
.fill()
.output();
}
blankLine.output();
}
var statusTimer = setInterval(drawProgress, 100);
var incrementTimer = setInterval(function () {
for(var index in lengths)
{
if(statuses[index] < lengths[index])
statuses[index]++;
}
}, 500);
|
var CLI = require('../lib/clui.js'),
clc = require('cli-color');
var Line = CLI.Line;
Progress = CLI.Progress;
var statuses = [0, 0, 0, 0, 0];
var lengths = [10, 20, 30, 40, 50];
console.log('\nCtrl/Command + C to quit...\n\n\n\n\n\n\n\n\n');
function drawProgress () {
process.stdout.write('\033[9A');
var blankLine = new Line().fill().output();
var headers = new Line()
.padding(2)
.column('Item', 20, [clc.cyan])
.column('Progress', 40, [clc.cyan])
.fill()
.output();
blankLine.output();
for(var index in lengths) {
var thisProgressBar = new Progress(20);
var websiteLine = new Line()
.padding(2)
.column('Item #' + index, 20, [clc.cyan])
.column(thisProgressBar.update(statuses[index], lengths[index]), 40)
.fill()
.output();
}
blankLine.output();
}
var statusTimer = setInterval(drawProgress, 100);
var incrementTimer = setInterval(function () {
for(var index in lengths)
{
if(statuses[index] < lengths[index])
statuses[index]++;
}
}, 500);
|
AndroidResource: Add a UiautoApk resource type.
When moving to Uiautomation 2, tests are now complied into apk files rather than
jar files. To avoid conflicts with regular workload apks a new resource type is
added to retrieve the test files which will be renamed to have the extension
.uiautoapk
|
# Copyright 2014-2015 ARM Limited
#
# 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 wlauto.common.resources import FileResource
class ReventFile(FileResource):
name = 'revent'
def __init__(self, owner, stage):
super(ReventFile, self).__init__(owner)
self.stage = stage
class JarFile(FileResource):
name = 'jar'
class ApkFile(FileResource):
name = 'apk'
def __init__(self, owner, platform=None):
super(ApkFile, self).__init__(owner)
self.platform = platform
def __str__(self):
return '<{}\'s {} APK>'.format(self.owner, self.platform)
class UiautoApkFile(FileResource):
name = 'uiautoapk'
def __init__(self, owner, platform=None):
super(UiautoApkFile, self).__init__(owner)
self.platform = platform
def __str__(self):
return '<{}\'s {} UiAuto APK>'.format(self.owner, self.platform)
|
# Copyright 2014-2015 ARM Limited
#
# 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 wlauto.common.resources import FileResource
class ReventFile(FileResource):
name = 'revent'
def __init__(self, owner, stage):
super(ReventFile, self).__init__(owner)
self.stage = stage
class JarFile(FileResource):
name = 'jar'
class ApkFile(FileResource):
name = 'apk'
def __init__(self, owner, platform=None):
super(ApkFile, self).__init__(owner)
self.platform = platform
def __str__(self):
return '<{}\'s {} APK>'.format(self.owner, self.platform)
|
Debug On. Remove needless tasks.
|
/*
* svg_fallback
*
*
* Copyright (c) 2014 yoksel
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Configuration to be run (and then tested).
svg_fallback: {
options: {
debug: true
},
your_target: {
src: 'test/sources/',
dest: 'test/result/'
}
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
grunt.registerTask('default', ['svg_fallback']);
};
|
/*
* svg_fallback
*
*
* Copyright (c) 2014 yoksel
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Configuration to be run (and then tested).
svg_fallback: {
your_target: {
src: 'test/sources/',
dest: 'test/result/'
}
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.registerTask('default', ['svg_fallback']);
};
|
Return NONE connection type for null.
|
package com.intellij.remote;
import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* This class denotes the type of the source to obtain remote credentials.
*
* @author traff
*/
public enum RemoteConnectionType {
/**
* Currently selected SDK (e.g. <Project default>)
*/
DEFAULT_SDK,
/**
* Web deployment server
*/
DEPLOYMENT_SERVER,
/**
* Remote SDK
*/
REMOTE_SDK,
/**
* Current project vagrant
*/
CURRENT_VAGRANT,
/**
* No source is predefined - it would be asked on request
*/
NONE;
private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class);
@NotNull
public static RemoteConnectionType findByName(@Nullable String name) {
if (name == null) {
return NONE;
}
try {
return valueOf(name);
}
catch (Exception e) {
LOG.error("Cant find RemoteConnectionType with the name " + name, e);
return NONE;
}
}
}
|
package com.intellij.remote;
import com.intellij.openapi.diagnostic.Logger;
/**
* This class denotes the type of the source to obtain remote credentials.
*
* @author traff
*/
public enum RemoteConnectionType {
/**
* Currently selected SDK (e.g. <Project default>)
*/
DEFAULT_SDK,
/**
* Web deployment server
*/
DEPLOYMENT_SERVER,
/**
* Remote SDK
*/
REMOTE_SDK,
/**
* Current project vagrant
*/
CURRENT_VAGRANT,
/**
* No source is predefined - it would be asked on request
*/
NONE;
private static final Logger LOG = Logger.getInstance(RemoteConnectionType.class);
public static RemoteConnectionType findByName(String name) {
try {
return valueOf(name);
}
catch (Exception e) {
LOG.error("Cant find RemoteConnectionType with the name " + name, e);
return NONE;
}
}
}
|
ESLint: Disable failing rules for now
|
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true,
},
},
plugins: ['ember', 'prettier'],
extends: ['eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended'],
env: {
browser: true,
},
rules: {
'prettier/prettier': 'error',
'ember/no-empty-attrs': 'off',
'ember/no-get': 'off',
'ember/no-mixins': 'off',
'ember/require-computed-macros': 'off',
'ember/require-computed-property-dependencies': 'off',
},
overrides: [
// node files
{
files: [
'.eslintrc.js',
'.template-lintrc.js',
'ember-cli-build.js',
'testem.js',
'blueprints/*/index.js',
'config/**/*.js',
'lib/*/index.js',
'server/**/*.js',
],
parserOptions: {
sourceType: 'script',
ecmaVersion: 2018,
},
env: {
browser: false,
node: true,
},
},
],
};
|
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true,
},
},
plugins: ['ember', 'prettier'],
extends: ['eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended'],
env: {
browser: true,
},
rules: {
'prettier/prettier': 'error',
},
overrides: [
// node files
{
files: [
'.eslintrc.js',
'.template-lintrc.js',
'ember-cli-build.js',
'testem.js',
'blueprints/*/index.js',
'config/**/*.js',
'lib/*/index.js',
'server/**/*.js',
],
parserOptions: {
sourceType: 'script',
ecmaVersion: 2018,
},
env: {
browser: false,
node: true,
},
},
],
};
|
Add body parser to test server
- previously handlers called in tests did not receive request.body
|
import {defer} from 'q';
import {createServer, bodyParser} from 'restify';
import registerResources from '../src/register';
import {spyOnServer, stopSpyingOnServer} from './serverSpying';
export default async (resource) => {
const server = await startServer(resource);
return {
server,
async stop() {
stopSpyingOnServer(server);
const deferred = defer();
server.close(() => {
deferred.resolve();
});
return deferred.promise;
}
};
};
async function startServer(resource) {
const server = createServer();
server.use(bodyParser());
spyOnServer(server);
registerResources(server, [resource]);
const deferred = defer();
server.listen(8880, () => {
deferred.resolve(server);
});
return deferred.promise;
}
|
import {defer} from 'q';
import {createServer} from 'restify';
import registerResources from '../src/register';
import {spyOnServer, stopSpyingOnServer} from './serverSpying';
export default async (resource) => {
const server = await startServer(resource);
return {
server,
async stop() {
stopSpyingOnServer(server);
const deferred = defer();
server.close(() => {
deferred.resolve();
});
return deferred.promise;
}
};
};
async function startServer(resource) {
const server = createServer();
spyOnServer(server);
registerResources(server, [resource]);
const deferred = defer();
server.listen(8880, () => {
deferred.resolve(server);
});
return deferred.promise;
}
|
Add comment describing what does the method do
|
#
# Perl (Inline::Perl) helpers
#
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
"""Convert 'bytes' string to 'unicode' if needed.
(http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
if string is not None:
if isinstance(string, bytes):
string = string.decode('utf-8')
return string
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_object_from_bytes_if_needed(obj):
"""Convert object (dictionary, list or string) from 'bytes' string to 'unicode' if needed."""
if isinstance(obj, dict):
result = dict()
for k, v in obj.items():
k = decode_object_from_bytes_if_needed(k)
v = decode_object_from_bytes_if_needed(v)
result[k] = v
elif isinstance(obj, list):
result = list()
for v in obj:
v = decode_object_from_bytes_if_needed(v)
result.append(v)
else:
result = decode_string_from_bytes_if_needed(obj)
return result
|
#
# Perl (Inline::Perl) helpers
#
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_string_from_bytes_if_needed(string):
"""Convert 'bytes' string to 'unicode' if needed.
(http://search.cpan.org/dist/Inline-Python/Python.pod#PORTING_YOUR_INLINE_PYTHON_CODE_FROM_2_TO_3)"""
if string is not None:
if isinstance(string, bytes):
string = string.decode('utf-8')
return string
# FIXME MC_REWRITE_TO_PYTHON: remove after porting all Perl code to Python
def decode_object_from_bytes_if_needed(obj):
if isinstance(obj, dict):
result = dict()
for k, v in obj.items():
k = decode_object_from_bytes_if_needed(k)
v = decode_object_from_bytes_if_needed(v)
result[k] = v
elif isinstance(obj, list):
result = list()
for v in obj:
v = decode_object_from_bytes_if_needed(v)
result.append(v)
else:
result = decode_string_from_bytes_if_needed(obj)
return result
|
Change reports URLs to extend from /children/<slug>.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/changes/types/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/pattern/$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/totals/$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/timeline/$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^reports/changes/types/(?P<slug>[^/.]+)/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^reports/sleep/pattern/(?P<slug>[^/.]+)$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^reports/sleep/totals/(?P<slug>[^/.]+)$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^reports/timeline/(?P<slug>[^/.]+)$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
Set Rocker default version to 1.3.0
|
package nu.studer.gradle.rocker;
import org.gradle.api.Project;
import java.util.Objects;
final class RockerVersion {
private static final String PROJECT_PROPERTY = "rockerVersion";
private static final String DEFAULT = "1.3.0";
private final String versionString;
private RockerVersion(String versionString) {
this.versionString = versionString;
}
static void applyDefaultVersion(Project project) {
project.getExtensions().getExtraProperties().set(PROJECT_PROPERTY, DEFAULT);
}
static RockerVersion fromProject(Project project) {
return from(Objects.requireNonNull(project.getExtensions().getExtraProperties().get(PROJECT_PROPERTY)).toString());
}
private static RockerVersion from(String versionString) {
return new RockerVersion(versionString);
}
String asString() {
return versionString;
}
}
|
package nu.studer.gradle.rocker;
import org.gradle.api.Project;
import java.util.Objects;
final class RockerVersion {
private static final String PROJECT_PROPERTY = "rockerVersion";
private static final String DEFAULT = "1.2.2";
private final String versionString;
private RockerVersion(String versionString) {
this.versionString = versionString;
}
static void applyDefaultVersion(Project project) {
project.getExtensions().getExtraProperties().set(PROJECT_PROPERTY, DEFAULT);
}
static RockerVersion fromProject(Project project) {
return from(Objects.requireNonNull(project.getExtensions().getExtraProperties().get(PROJECT_PROPERTY)).toString());
}
private static RockerVersion from(String versionString) {
return new RockerVersion(versionString);
}
String asString() {
return versionString;
}
}
|
Use keys from filter object in allowed properties.
|
var evals = [ 'undefined', 'null', 'false', 'true' ];
var _filters = {
regex: function(value) {
return new RegExp(value, 'i');
},
exists: function(value) {
if(value === true)
return { $ne: null };
else
return { $eq: null };
}
};
module.exports = function(properties, filters) {
properties = _.union(properties, _.keys(filters));
filters = _.mapValues(filters, function(value, key) {
return _.isString(value) ? _filters[value] : value;
});
return function(req, res, next) {
req.query = _.mapValues(_.pick(req.query, properties), function(value, key) {
value = decodeURIComponent(value);
if(evals.indexOf(value) > -1) value = eval(value);
return filters[key] ? filters[key](value) : value;
});
next();
};
};
|
var evals = [ 'undefined', 'null', 'false', 'true' ];
var _filters = {
regex: function(value) {
return new RegExp(value, 'i');
},
exists: function(value) {
if(value === true)
return { $ne: null };
else
return { $eq: null };
}
};
module.exports = function(properties, filters) {
filters = _.mapValues(filters, function(value, key) {
return _.isString(value) ? _filters[value] : value;
});
return function(req, res, next) {
req.query = _.mapValues(_.pick(req.query, properties), function(value, key) {
value = decodeURIComponent(value);
if(evals.indexOf(value) > -1) value = eval(value);
return filters[key] ? filters[key](value) : value;
});
next();
};
};
|
Remove lock file before installing
|
<?php
namespace MaxBucknell\Gulp\Console\Command;
use MaxBucknell\Gulp\Model\Filesystem;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Install extends Command
{
/**
* @var Filesystem
*/
private $filesystem;
public function __construct(
Filesystem $filesystem,
$name = null
) {
parent::__construct($name);
$this->filesystem = $filesystem;
}
protected function configure()
{
$this->setName('setup:gulp:install');
$this->setDescription('Install all NPM dependencies');
$this->addOption(
'npm',
null,
InputOption::VALUE_NONE,
'Whether to use npm instead of yarn'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$executable = $input->getOption('npm') ? 'npm' : 'yarn';
$directory = $this->filesystem->getAbsoluteLocation();
chdir($directory);
passthru("rm -rf package-lock.json");
passthru("$executable install");
}
}
|
<?php
namespace MaxBucknell\Gulp\Console\Command;
use MaxBucknell\Gulp\Model\Filesystem;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Install extends Command
{
/**
* @var Filesystem
*/
private $filesystem;
public function __construct(
Filesystem $filesystem,
$name = null
) {
parent::__construct($name);
$this->filesystem = $filesystem;
}
protected function configure()
{
$this->setName('setup:gulp:install');
$this->setDescription('Install all NPM dependencies');
$this->addOption(
'npm',
null,
InputOption::VALUE_NONE,
'Whether to use npm instead of yarn'
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$executable = $input->getOption('npm') ? 'npm' : 'yarn';
$directory = $this->filesystem->getAbsoluteLocation();
chdir($directory);
passthru("$executable install");
}
}
|
Check for multiple target routes for deciding when to transition.
|
var route = Ember.Route.extend({
model: function() {
return this.store.all('task');
},
afterModel: function(tasks, transition) {
if (transition.targetName == "tasks.index" || transition.targetName == "tasks") {
if($(document).width() > 700) {
Ember.run.next(this, function(){
var task = this.controllerFor('tasks')
.get('pendingTasks.firstObject');
if(task) {
this.transitionTo('task', tasks.get('firstObject'));
}
})
} else {
this.transitionToRoute('mobileTasks');
}
}
},
actions: {
error: function(reason, tsn) {
var application = this.controllerFor('application');
application.get('handleError').bind(application)(reason, tsn);
}
}
});
module.exports = route;
|
var route = Ember.Route.extend({
model: function() {
return this.store.all('task');
},
afterModel: function(tasks, transition) {
if (transition.targetName == "tasks.index") {
if($(document).width() > 700) {
Ember.run.next(this, function(){
var task = this.controllerFor('tasks')
.get('pendingTasks.firstObject');
if(task) {
this.transitionTo('task', tasks.get('firstObject'));
}
})
} else {
this.transitionToRoute('mobileTasks');
}
}
},
actions: {
error: function(reason, tsn) {
var application = this.controllerFor('application');
application.get('handleError').bind(application)(reason, tsn);
}
}
});
module.exports = route;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.