text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Tag error, rolling to 0.7.2 | """setup.py file."""
import uuid
from setuptools import setup
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-ansible",
version='0.7.2',
packages=["napalm_ansible"],
author="David Barroso, Kirk Byers, Mircea Ulinic",
author_email="dbarrosop@dravetech.com, ktbyers@twb-tech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-base",
include_package_data=True,
install_requires=reqs,
entry_points={
'console_scripts': [
'napalm-ansible=napalm_ansible:main',
],
}
)
| """setup.py file."""
import uuid
from setuptools import setup
from pip.req import parse_requirements
install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name="napalm-ansible",
version='0.7.1',
packages=["napalm_ansible"],
author="David Barroso, Kirk Byers, Mircea Ulinic",
author_email="dbarrosop@dravetech.com, ktbyers@twb-tech.com",
description="Network Automation and Programmability Abstraction Layer with Multivendor support",
classifiers=[
'Topic :: Utilities',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS',
],
url="https://github.com/napalm-automation/napalm-base",
include_package_data=True,
install_requires=reqs,
entry_points={
'console_scripts': [
'napalm-ansible=napalm_ansible:main',
],
}
)
|
Convert scroll top to Object | /*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2018 GwtMaterialDesign
* %%
* 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.
* #L%
*/
package gwt.material.design.client.js;
import gwt.material.design.client.base.helper.ScrollHelper;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* JSInterop util for {@link ScrollHelper}
*
* @author kevzlou7979@gmail.com
*/
@JsType(isNative = true, name = "Object", namespace = JsPackage.GLOBAL)
public class ScrollOption {
@JsProperty
public Object scrollTop;
} | /*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2018 GwtMaterialDesign
* %%
* 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.
* #L%
*/
package gwt.material.design.client.js;
import gwt.material.design.client.base.helper.ScrollHelper;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* JSInterop util for {@link ScrollHelper}
*
* @author kevzlou7979@gmail.com
*/
@JsType(isNative = true, name = "Object", namespace = JsPackage.GLOBAL)
public class ScrollOption {
@JsProperty
public double scrollTop;
} |
Fix the order of routes | var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
// Set up the /favicon.ico
app.use(loopback.favicon());
// request pre-processing middleware
app.use(loopback.compress());
// -- Add your pre-processing middleware here --
// boot scripts mount components like REST API
boot(app, __dirname);
require('./push-demo')(app);
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path');
app.use(loopback.static(path.resolve(__dirname, '../client/public')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());
// The ultimate error handler.
app.use(loopback.errorHandler());
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log('Web server listening at: %s', app.get('url'));
});
};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
| var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
// Set up the /favicon.ico
app.use(loopback.favicon());
// request pre-processing middleware
app.use(loopback.compress());
// -- Add your pre-processing middleware here --
// boot scripts mount components like REST API
boot(app, __dirname);
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path');
app.use(loopback.static(path.resolve(__dirname, '../client/public')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());
// The ultimate error handler.
app.use(loopback.errorHandler());
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log('Web server listening at: %s', app.get('url'));
});
};
require('./push-demo')(app);
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
|
Format comments for generating docs using dox |
/* global textistics:false */
(function (window, undefined) {
/**
* An object for observing and comparing current text selections.
*
* When instantiated, captures the current selection and computes a count
* of words and characters selected.
*
* May be compared for equality against other EquatableSelection instances.
*
* Should be treated as immutable.
*/
function EquatableSelection() {
var selection = window.getSelection();
if (selection && selection.rangeCount === 1) {
this.text = selection.toString();
this.wordCount = textistics.wordCountInSelection(selection);
this.characterCount = textistics.characterCountInSelection(selection);
}
}
/**
* Return true if two EquatableSelection objects are equal, false otherwise
*/
EquatableSelection.prototype.isEqual = function (other) {
return other &&
this.wordCount === other.wordCount &&
this.characterCount === other.characterCount &&
this.text === other.text;
};
window.EquatableSelection = EquatableSelection;
})(this);
|
/* global textistics:false */
(function (window, undefined) {
/*
* An object for observing and comparing current text selections.
*
* When instantiated, captures the current selection and computes a count
* of words and characters selected.
*
* May be compared for equality against other EquatableSelection instances.
*
* Should be treated as immutable.
*/
function EquatableSelection() {
var selection = window.getSelection();
if (selection && selection.rangeCount === 1) {
this.text = selection.toString();
this.wordCount = textistics.wordCountInSelection(selection);
this.characterCount = textistics.characterCountInSelection(selection);
}
}
/*
* Return true if two EquatableSelection objects are equal, false otherwise
*/
EquatableSelection.prototype.isEqual = function (other) {
return other &&
this.wordCount === other.wordCount &&
this.characterCount === other.characterCount &&
this.text === other.text;
};
window.EquatableSelection = EquatableSelection;
})(this);
|
Replace `mount` calls with `shallow` in <Post> tests | import { expect } from 'chai';
import { mount, shallow } from 'enzyme';
import React from 'react';
import Post from '../../src/js/components/Post';
describe('<Post/>', () => {
const post = {
id: 0,
title: 'Test Post',
content: 'empty',
description: 'empty',
author: 'bot',
slug: 'test-post',
tags: ['test', 'react'],
};
it('renders post title', () => {
const result = shallow(<Post post={post} />);
expect(result.find('.post__title').text()).to.eq('Test Post');
});
it('renders post metadata', () => {
const result = mount(<Post post={post} />);
expect(result.find('.post__meta').text()).to.eq(' a few seconds ago');
});
it('renders post image', () => {
const postWithImage = { ...post, img: 'image.png' };
const result = shallow(<Post post={postWithImage} />);
expect(result.find('.post__image').length).to.eq(1);
});
it('renders no image if missing', () => {
const result = mount(<Post post={post} />);
expect(result.find('.post__image').length).to.eq(0);
});
});
| import { expect } from 'chai';
import { mount } from 'enzyme';
import React from 'react';
import Post from '../../src/js/components/Post';
describe('<Post/>', () => {
const post = {
id: 0,
title: 'Test Post',
content: 'empty',
description: 'empty',
author: 'bot',
slug: 'test-post',
tags: ['test', 'react'],
};
it('renders post title', () => {
const result = mount(<Post post={post} />);
expect(result.find('.post__title').text()).to.eq('Test Post');
});
it('renders post metadata', () => {
const result = mount(<Post post={post} />);
expect(result.find('.post__meta').text()).to.eq(' a few seconds ago');
});
it('renders post image', () => {
const postWithImage = { ...post, img: 'image.png' };
const result = mount(<Post post={postWithImage} />);
expect(result.find('.post__image').length).to.eq(1);
});
it('renders no image if missing', () => {
const result = mount(<Post post={post} />);
expect(result.find('.post__image').length).to.eq(0);
});
});
|
Remove body from methods interface | <?php
/*
* HiPay fullservice SDK
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT License
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/mit-license.php
*
* @copyright Copyright (c) 2016 - HiPay
* @license http://opensource.org/licenses/mit-license.php MIT License
*
*/
namespace HiPay\Fullservice\Model;
/**
* Model Interface
*
* Created for futhers features.
* Not used for the moment but implemented
*
* @package HiPay\Fullservice
* @author Kassim Belghait <kassim@sirateck.com>
* @copyright Copyright (c) 2016 - HiPay
* @license http://opensource.org/licenses/mit-license.php MIT License
* @link https://github.com/hipay/hipay-fullservice-sdk-php
*/
interface ModelInterface {
/**
* Return Json representation of public attributes
* @return string Json representation
*/
public function toJson();
/**
* Return public attributes accessible by getter in ARRAY format
* @return array public attributes array
*/
public function toArray();
} | <?php
/*
* HiPay fullservice SDK
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT License
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/mit-license.php
*
* @copyright Copyright (c) 2016 - HiPay
* @license http://opensource.org/licenses/mit-license.php MIT License
*
*/
namespace HiPay\Fullservice\Model;
/**
* Model Interface
*
* Created for futhers features.
* Not used for the moment but implemented
*
* @package HiPay\Fullservice
* @author Kassim Belghait <kassim@sirateck.com>
* @copyright Copyright (c) 2016 - HiPay
* @license http://opensource.org/licenses/mit-license.php MIT License
* @link https://github.com/hipay/hipay-fullservice-sdk-php
*/
interface ModelInterface {
/**
* Return Json representation of public attributes
* @return string Json representation
*/
public function toJson(){
}
/**
* Return public attributes accessible by getter in ARRAY format
* @return array public attributes array
*/
public function toArray(){
}
} |
Add new death modifier to SetupParams | package response
import (
"fmt"
"warcluster/entities"
)
type ServerParams struct {
baseResponse
HomeSPM float64 //ships per minute
PlanetsSPM map[string]float64
ShipsDeathModifier float64
Races map[string]entities.Race
}
func NewServerParams() *ServerParams {
var planetSizeIdx int8
r := new(ServerParams)
r.Races = make(map[string]entities.Race)
r.PlanetsSPM = make(map[string]float64)
r.Command = "server_params"
for _, race := range entities.Races {
r.Races[race.Name] = race
}
r.HomeSPM = 60 / float64(entities.ShipCountTimeMod(1, true))
for planetSizeIdx = 1; planetSizeIdx <= 10; planetSizeIdx++ {
planetSPM := float64(entities.ShipCountTimeMod(planetSizeIdx, false))
r.PlanetsSPM[fmt.Sprintf("%v", planetSizeIdx)] = 60 / planetSPM
}
r.ShipsDeathModifier = entities.Settings.ShipsDeathModifier
return r
}
func (_ *ServerParams) Sanitize(*entities.Player) {}
| package response
import (
"fmt"
"warcluster/entities"
)
type ServerParams struct {
baseResponse
HomeSPM float64 //ships per minute
PlanetsSPM map[string]float64
Races map[string]entities.Race
}
func NewServerParams() *ServerParams {
var planetSizeIdx int8
r := new(ServerParams)
r.Races = make(map[string]entities.Race)
r.PlanetsSPM = make(map[string]float64)
r.Command = "server_params"
for _, race := range entities.Races {
r.Races[race.Name] = race
}
r.HomeSPM = 60 / float64(entities.ShipCountTimeMod(1, true))
for planetSizeIdx = 1; planetSizeIdx <= 10; planetSizeIdx++ {
planetSPM := float64(entities.ShipCountTimeMod(planetSizeIdx, false))
r.PlanetsSPM[fmt.Sprintf("%v", planetSizeIdx)] = 60 / planetSPM
}
return r
}
func (_ *ServerParams) Sanitize(*entities.Player) {}
|
Use outlet to show repositories | require('dashboard/core');
require('dashboard/github_data_source');
Dashboard.Router = Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router) {
router.transitionTo('user', {
username: 'pangratz'
});
}
}),
user: Ember.Route.extend({
route: '/:username',
connectOutlets: function(router, context) {
// create the data source which connects to GitHub API
var dataSource = Dashboard.GitHubDataSource.create();
// initialize repositoriesController
var repositoriesController = router.get('repositoriesController');
repositoriesController.set('dataSource', dataSource);
repositoriesController.set('content', []);
repositoriesController.loadWatchedRepositories(context.username);
// connect {{outlet}} with repositoriesController & RepositoriesView
router.get('applicationController').connectOutlet('repositories');
}
})
})
});
| require('dashboard/core');
require('dashboard/github_data_source');
Dashboard.Router = Ember.Router.extend({
root: Ember.Route.extend({
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router) {
router.transitionTo('user', {
username: 'pangratz'
});
}
}),
user: Ember.Route.extend({
route: '/:username',
connectOutlets: function(router, context) {
// create the data source which connects to GitHub API
var dataSource = Dashboard.GitHubDataSource.create();
// initialize repositoriesController
var repositoriesController = router.get('repositoriesController');
repositoriesController.set('dataSource', dataSource);
repositoriesController.set('content', []);
repositoriesController.loadWatchedRepositories(context.username);
// finally add a view which renders repositories template for given controller
Ember.View.create({
templateName: 'repositories',
controller: repositoriesController
}).append();
}
})
})
});
|
Fix tile data for push command bug | var parser = require('./parser');
var Interpreter = require('./interpreter');
function TileAction(tile, tileX, tileY, key, data, renderer, callback) {
this.tile = tile;
this.key = key;
this.data = data;
this.tileX = tileX;
this.tileY = tileY;
this.renderer = renderer;
this.callback = callback;
}
TileAction.prototype.exec = function() {
this.before = this.tile[this.key];
this.tile[this.key] = this.data;
this.update();
}
TileAction.prototype.undo = function() {
this.tile[this.key] = this.before;
this.update();
}
TileAction.prototype.update = function() {
// Fill the data with 0 if it's required and null.
var command = Interpreter.CommandMap[this.tile.command];
if(command != null && command.argument && this.tile.data == null) {
this.tile.data = 0;
}
if(this.tile.command == 'push' && this.tile.data > 9) {
// Force set data to 0 as it can't handle larger than 9
this.tile.data = 0;
}
this.tile.original = parser.encodeSyllable(this.tile);
this.renderer.map.set(this.tileX, this.tileY, this.tile);
this.renderer.updateTile(this.tileX, this.tileY);
if(this.callback) this.callback();
}
module.exports = TileAction;
| var parser = require('./parser');
var Interpreter = require('./interpreter');
function TileAction(tile, tileX, tileY, key, data, renderer, callback) {
this.tile = tile;
this.key = key;
this.data = data;
this.tileX = tileX;
this.tileY = tileY;
this.renderer = renderer;
this.callback = callback;
}
TileAction.prototype.exec = function() {
this.before = this.tile[this.key];
this.tile[this.key] = this.data;
this.update();
}
TileAction.prototype.undo = function() {
this.tile[this.key] = this.before;
this.update();
}
TileAction.prototype.update = function() {
// Fill the data with 0 if it's required and null.
var command = Interpreter.CommandMap[this.tile.command];
if(command != null && command.argument && this.tile.data == null) {
this.tile.data = 0;
}
this.tile.original = parser.encodeSyllable(this.tile);
this.renderer.map.set(this.tileX, this.tileY, this.tile);
this.renderer.updateTile(this.tileX, this.tileY);
if(this.callback) this.callback();
}
module.exports = TileAction;
|
Add use_srtp extension registration from RFC 5764 | package org.bouncycastle.crypto.tls;
public class ExtensionType
{
/*
* RFC 6066 1.1.
*/
public static final int server_name = 0;
public static final int max_fragment_length = 1;
public static final int client_certificate_url = 2;
public static final int trusted_ca_keys = 3;
public static final int truncated_hmac = 4;
public static final int status_request = 5;
/*
* RFC 4492 5.1.
*/
public static final int elliptic_curves = 10;
public static final int ec_point_formats = 11;
/*
* RFC 5054 2.8.1.
*/
public static final int srp = 12;
/*
* RFC 5246 7.4.1.4.
*/
public static final int signature_algorithms = 13;
/*
* RFC 5764 9.
*/
public static final int use_srtp = 14;
/*
* RFC 5746 3.2.
*/
public static final int renegotiation_info = 0xff01;
}
| package org.bouncycastle.crypto.tls;
public class ExtensionType
{
/*
* RFC 6066 1.1.
*/
public static final int server_name = 0;
public static final int max_fragment_length = 1;
public static final int client_certificate_url = 2;
public static final int trusted_ca_keys = 3;
public static final int truncated_hmac = 4;
public static final int status_request = 5;
/*
* RFC 4492 5.1.
*/
public static final int elliptic_curves = 10;
public static final int ec_point_formats = 11;
/*
* RFC 5054 2.8.1.
*/
public static final int srp = 12;
/*
* RFC 5246 7.4.1.4.
*/
public static final int signature_algorithms = 13;
/*
* RFC 5746 3.2.
*/
public static final int renegotiation_info = 0xff01;
}
|
Fix links assignment on some AJAX requests | import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
const {auth} = links
return {
...response,
auth: {links: auth},
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}} // eslint-disable-line no-throw-literal
}
}
| import axios from 'axios'
let links
export default async function AJAX({
url,
resource,
id,
method = 'GET',
data = {},
params = {},
headers = {},
}) {
try {
const basepath = window.basepath || ''
let response
url = `${basepath}${url}`
if (!links) {
const linksRes = (response = await axios({
url: `${basepath}/chronograf/v1`,
method: 'GET',
}))
links = linksRes.data
}
const {auth} = links
if (resource) {
url = id
? `${basepath}${links[resource]}/${id}`
: `${basepath}${links[resource]}`
}
response = await axios({
url,
method,
data,
params,
headers,
})
return {
auth,
...response,
}
} catch (error) {
const {response} = error
const {auth} = links
throw {...response, auth: {links: auth}} // eslint-disable-line no-throw-literal
}
}
|
Fix concating watch glob masks | module.exports = function(gulp, config) {
return function(done) {
var c = require('better-console')
c.info('watch reload')
var browsersync = require('browser-sync')
var fs = require('fs')
var watch = require('gulp-watch')
var filter = require('gulp-filter')
var options = {}
if(config.proxy) {
options.proxy = config.proxy
} else {
options.server = { baseDir: config.dist_folder }
}
browsersync(options)
var glob = [config.dist_folder + '/**/*.*']
if(config.watch) {
glob = glob.concat(config.watch)
}
var handleReloadFile = function(file) {
// files only
if(!fs.existsSync(file.path) || !fs.lstatSync(file.path).isFile()) {
return false
}
c.log('- handling reload', file.path)
browsersync.reload(file.path)
}
return watch(glob, { base: config.dir }).pipe(filter(handleReloadFile))
}
}
| module.exports = function(gulp, config) {
return function(done) {
var c = require('better-console')
c.info('watch reload')
var browsersync = require('browser-sync')
var fs = require('fs')
var watch = require('gulp-watch')
var filter = require('gulp-filter')
var options = {}
if(config.proxy) {
options.proxy = config.proxy
} else {
options.server = { baseDir: config.dist_folder }
}
browsersync(options)
var glob = [config.dist_folder + '/**/*.*']
if(config.watch) glob.concat(config.watch)
var handleReloadFile = function(file) {
// files only
if(!fs.existsSync(file.path) || !fs.lstatSync(file.path).isFile()) {
return false
}
c.log('- handling reload', file.path)
browsersync.reload(file.path)
}
return watch(glob, { base: config.dir }).pipe(filter(handleReloadFile))
}
}
|
Add utility method to getCurrentScript | module.exports = {
getViewPortInfo: function getViewPort () {
var e = document.documentElement
var g = document.getElementsByTagName('body')[0]
var x = window.innerWidth || e.clientWidth || g.clientWidth
var y = window.innerHeight || e.clientHeight || g.clientHeight
return {
width: x,
height: y
}
},
mergeObject: function (o1, o2) {
var a
var o3 = {}
for (a in o1) {
o3[a] = o1[a]
}
for (a in o2) {
o3[a] = o2[a]
}
return o3
},
isUndefined: function (obj) {
return (typeof obj) === 'undefined'
},
getCurrentScript: function () {
// Source http://www.2ality.com/2014/05/current-script.html
return document.currentScript || (function () {
var scripts = document.getElementsByTagName('script')
return scripts[scripts.length - 1]
})()
}
}
| module.exports = {
getViewPortInfo: function getViewPort () {
var e = document.documentElement
var g = document.getElementsByTagName('body')[0]
var x = window.innerWidth || e.clientWidth || g.clientWidth
var y = window.innerHeight || e.clientHeight || g.clientHeight
return {
width: x,
height: y
}
},
mergeObject: function (o1, o2) {
var a
var o3 = {}
for (a in o1) {
o3[a] = o1[a]
}
for (a in o2) {
o3[a] = o2[a]
}
return o3
},
isUndefined: function (obj) {
return (typeof obj) === 'undefined'
}
}
|
Remove duplicate AOS js call | @extends('page::page-layouts.default')
@section('title', 'Laravel Pages')
@section('body')
@include('page::shared.header', ["class_name" => "landing bg-5"])
@include('page::shared.nav')
<section class="sub-header text-center">
<div class="container">
<h1>
Just add content...
</h1>
<p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto.
</p>
</div>
</section>
@include('page::shared.footer')
@endsection
@push('styles')
<style type="text/css">
.logo {
display: none;
}
</style>
@endpush
@push('scripts')
<script>
$(document).ready(function(){
$('.logo').fadeToggle( 5000, "linear" );
})
</script>
@endpush
| @extends('page::page-layouts.default')
@section('title', 'Laravel Pages')
@section('body')
@include('page::shared.header', ["class_name" => "landing bg-5"])
@include('page::shared.nav')
<section class="sub-header text-center">
<div class="container">
<h1>
Just add content...
</h1>
<p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est error quae nostrum beatae, iusto accusantium repudiandae accusamus veritatis, voluptatum nesciunt dolorem aspernatur saepe a asperiores.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea doloribus similique officiis laudantium ratione praesentium. Voluptatibus, commodi saepe molestias ea iure optio dignissimos. Non, iusto.
</p>
</div>
</section>
@include('page::shared.footer')
@endsection
@push('styles')
<style type="text/css">
.logo {
display: none;
}
</style>
@endpush
@push('scripts')
<script src="/packages/aos/aos.js"></script>
<script>
AOS.init();
$(document).ready(function(){
$('.logo').fadeToggle( 5000, "linear" );
})
</script>
@endpush
|
Add reason to exception detail. | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.sync.login;
/**
* A Exception that occurs while a user tries to log in to, or access their Firefox Sync account.
*
* Note that the exceptions returned by {@link #getCause()} may include user info like email addresses
* so be careful how you log them.
* todo: ^ do we want to strip the stuff ourselves?
*/
public class FirefoxSyncLoginException extends Exception {
private final FailureReason failureReason;
FirefoxSyncLoginException(final String message, final FailureReason failureReason) {
super(message + ". " + failureReason.toString());
this.failureReason = failureReason;
}
FirefoxSyncLoginException(final Throwable cause, final FailureReason failureReason) {
super(failureReason.toString(), cause);
this.failureReason = failureReason;
}
/**
* Gets the reason this exception was thrown. Normally, this would be handled by the type of the exception thrown
* but because these Exceptions are not thrown but passed by callback, this is used instead.
*
* @return the reason this exception was thrown.
*/
public FailureReason getFailureReason() { return failureReason; }
public enum FailureReason {
ACCOUNT_NEEDS_VERIFICATION, // TODO: how to document these for public use?
FAILED_TO_LOAD_ACCOUNT,
SERVER_RESPONSE_UNEXPECTED,
UNKNOWN,
}
}
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.sync.login;
/**
* A Exception that occurs while a user tries to log in to, or access their Firefox Sync account.
*
* Note that the exceptions returned by {@link #getCause()} may include user info like email addresses
* so be careful how you log them.
* todo: ^ do we want to strip the stuff ourselves?
*/
public class FirefoxSyncLoginException extends Exception {
private final FailureReason failureReason;
FirefoxSyncLoginException(final String message, final FailureReason failureReason) {
super(message);
this.failureReason = failureReason;
}
FirefoxSyncLoginException(final Throwable cause, final FailureReason failureReason) {
super(cause);
this.failureReason = failureReason; // TODO: add message?
}
/**
* Gets the reason this exception was thrown. Normally, this would be handled by the type of the exception thrown
* but because these Exceptions are not thrown but passed by callback, this is used instead.
*
* @return the reason this exception was thrown.
*/
public FailureReason getFailureReason() { return failureReason; }
public enum FailureReason {
ACCOUNT_NEEDS_VERIFICATION, // TODO: how to document these for public use?
FAILED_TO_LOAD_ACCOUNT,
SERVER_RESPONSE_UNEXPECTED,
UNKNOWN,
}
}
|
Fix a compilation error in the tests. | /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.iod.client.api.textindexing;
import com.hp.autonomy.iod.client.util.MultiMap;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Setter
@Accessors(chain = true)
public class ListIndexesRequestBuilder {
/**
* @param indexTypes The value of the type parameter
*/
private Set<IndexType> indexTypes = new HashSet<>();
/**
* @param indexFlavors The value of the flavor parameter
*/
private Set<IndexFlavor> indexFlavors = new HashSet<>();
/**
* @return A map of parameters suitable for use with {@link ListIndexesService}.
*/
public Map<String, Object> build() {
final Map<String, Object> map = new MultiMap<>();
for(final IndexType indexType : indexTypes) {
map.put("type", indexType);
}
for (final IndexFlavor indexFlavor : indexFlavors) {
map.put("flavor", indexFlavor);
}
return map;
}
}
| /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.iod.client.api.textindexing;
import com.hp.autonomy.iod.client.util.MultiMap;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
@Setter
@Accessors(chain = true)
public class ListIndexesRequestBuilder {
/**
* @param indexTypes The value of the type parameter
*/
private final Set<IndexType> indexTypes = Collections.emptySet();
/**
* @param indexFlavors The value of the flavor parameter
*/
private final Set<IndexFlavor> indexFlavors = Collections.emptySet();
/**
* @return A map of parameters suitable for use with {@link ListIndexesService}.
*/
public Map<String, Object> build() {
final Map<String, Object> map = new MultiMap<>();
for(final IndexType indexType : indexTypes) {
map.put("type", indexType);
}
for (final IndexFlavor indexFlavor : indexFlavors) {
map.put("flavor", indexFlavor);
}
return map;
}
}
|
Replace mock with use of AnnotationDocMocker. | package uk.ac.ebi.quickgo.annotation.service.converter;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.Annotation;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.when;
/**
* @author Tony Wardell
* Date: 29/04/2016
* Time: 17:39
* Created with IntelliJ IDEA.
*/
@RunWith(MockitoJUnitRunner.class)
public class AnnotationDocConverterImplTest {
@Test
public void convertSuccessfully(){
AnnotationDocConverter docConverter = new AnnotationDocConverterImpl();
Annotation model = docConverter.convert( AnnotationDocMocker.createAnnotationDoc("A0A000"));
assertThat(model.assignedBy, equalTo("InterPro"));
}
}
| package uk.ac.ebi.quickgo.annotation.service.converter;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.Annotation;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.when;
/**
* @author Tony Wardell
* Date: 29/04/2016
* Time: 17:39
* Created with IntelliJ IDEA.
*/
@RunWith(MockitoJUnitRunner.class)
public class AnnotationDocConverterImplTest {
private static final String UNI_PROT = "UniProt";
@Mock
private AnnotationDocument annotationDocument;
@Before
public void setup(){
when(annotationDocument.assignedBy).thenReturn(UNI_PROT);
}
@Test
@Ignore //Doesn't use methods.
public void convertSuccessfully(){
AnnotationDocConverter docConverter = new AnnotationDocConverterImpl();
Annotation model = docConverter.convert(annotationDocument);
assertThat(model.assignedBy, equalTo(UNI_PROT));
}
}
|
Fix bug by resetting dateMap during update | const Logger = require('franston')('jobs/update-cache')
const GithubActivity = require('../models/github-activity')
const GithubCache = require('../models/github-cache')
const Series = require('run-series')
let dateMap = {}
function saveActivityCounts (date, next) {
let count = dateMap[date]
let options = {
upsert: true,
setDefaultsOnInsert: true
}
GithubCache.update({ date }, { date, total: count }, options, (err) => {
if (err) return (Logger.error(err), next(err))
return next()
})
}
function updateCache (done) {
dateMap = {}
GithubActivity.find({}, (err, found) => {
if (err) return done(err)
found.forEach((event) => {
let date = new Date(event.created).toDateString()
if (dateMap.hasOwnProperty(date)) dateMap[date] += parseInt(event.count, 10)
else dateMap[date] = parseInt(event.count, 10)
})
return Series(Object.keys(dateMap).map((date) => saveActivityCounts.bind(null, date)))
})
}
module.exports = function updateActivityCache () {
Logger.info('Running job...')
updateCache((err) => {
if (err) return Logger.error(`error: ${err.message}`)
return Logger.info('...completed')
})
}
| const Logger = require('franston')('jobs/update-cache')
const GithubActivity = require('../models/github-activity')
const GithubCache = require('../models/github-cache')
const Series = require('run-series')
let dateMap = {}
function saveActivityCounts (date, next) {
let count = dateMap[date]
let options = {
upsert: true,
setDefaultsOnInsert: true
}
GithubCache.update({ date }, { date, total: count }, options, (err) => {
if (err) return (Logger.error(err), next(err))
return next()
})
}
function updateCache (done) {
GithubActivity.find({}, (err, found) => {
if (err) return done(err)
found.forEach((event) => {
let date = new Date(event.created).toDateString()
if (dateMap.hasOwnProperty(date)) dateMap[date] += parseInt(event.count, 10)
else dateMap[date] = parseInt(event.count, 10)
})
return Series(Object.keys(dateMap).map((date) => saveActivityCounts.bind(null, date)))
})
}
module.exports = function updateActivityCache () {
Logger.info('Running job...')
updateCache((err) => {
if (err) return Logger.error(`error: ${err.message}`)
return Logger.info('...completed')
})
}
|
Use Ember.K instead of noOp | import Ember from 'ember';
import redux from 'npm:redux';
import reducers from '../reducers/index';
import enhancers from '../enhancers/index';
import optional from '../reducers/optional';
import middlewareConfig from '../middleware/index';
const { assert, isArray, K } = Ember;
// Handle "classic" middleware exports (i.e. an array), as well as the hash option
const extractMiddlewareConfig = (mc) => {
assert(
'Middleware must either be an array, or a hash containing a `middleware` property',
isArray(mc) || mc.middleware
);
return isArray(mc) ? { middleware: mc } : mc;
}
// Destructure the middleware array and the setup thunk into two different variables
const { middleware, setup = K } = extractMiddlewareConfig(middlewareConfig);
var { createStore, applyMiddleware, combineReducers, compose } = redux;
var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore);
export default Ember.Service.extend({
init() {
this.store = createStoreWithMiddleware(optional(combineReducers(reducers)));
setup(this.store);
this._super(...arguments);
},
getState() {
return this.store.getState();
},
dispatch(action) {
return this.store.dispatch(action);
},
subscribe(func) {
return this.store.subscribe(func);
}
});
| import Ember from 'ember';
import redux from 'npm:redux';
import reducers from '../reducers/index';
import enhancers from '../enhancers/index';
import optional from '../reducers/optional';
import middlewareConfig from '../middleware/index';
const { assert, isArray } = Ember;
// Util for handling the case where no setup thunk was created in middleware
const noOp = () => {};
// Handle "classic" middleware exports (i.e. an array), as well as the hash option
const extractMiddlewareConfig = (mc) => {
assert(
'Middleware must either be an array, or a hash containing a `middleware` property',
isArray(mc) || mc.middleware
);
return isArray(mc) ? { middleware: mc } : mc;
}
// Destructure the middleware array and the setup thunk into two different variables
const { middleware, setup = noOp } = extractMiddlewareConfig(middlewareConfig);
var { createStore, applyMiddleware, combineReducers, compose } = redux;
var createStoreWithMiddleware = compose(applyMiddleware(...middleware), enhancers)(createStore);
export default Ember.Service.extend({
init() {
this.store = createStoreWithMiddleware(optional(combineReducers(reducers)));
setup(this.store);
this._super(...arguments);
},
getState() {
return this.store.getState();
},
dispatch(action) {
return this.store.dispatch(action);
},
subscribe(func) {
return this.store.subscribe(func);
}
});
|
Verify binding of private final fields | package org.javersion.object;
import static org.assertj.core.api.Assertions.*;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import org.junit.Test;
public class JavaTimeTest {
@Versionable
public static class DT {
private final Instant instant = Instant.now();
private final LocalDate localDate = LocalDate.now();
private final LocalDateTime localDateTime = LocalDateTime.now();
}
private ObjectSerializer<DT> serializer = new ObjectSerializer<>(DT.class);
@Test
public void write_read() {
final DT dt = new DT();
DT dtCopy = serializer.fromPropertyMap(serializer.toPropertyMap(dt));
assertThat(dtCopy.instant).isEqualTo(dt.instant);
assertThat(dtCopy.localDate).isEqualTo(dt.localDate);
assertThat(dtCopy.localDateTime).isEqualTo(dt.localDateTime);
}
}
| package org.javersion.object;
import static org.assertj.core.api.Assertions.*;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import org.junit.Test;
public class JavaTimeTest {
@Versionable
public static class DT {
final Instant instant = Instant.now();
final LocalDate localDate = LocalDate.now();
final LocalDateTime localDateTime = LocalDateTime.now();
}
private ObjectSerializer<DT> serializer = new ObjectSerializer<>(DT.class);
@Test
public void write_read() {
final DT dt = new DT();
DT dtCopy = serializer.fromPropertyMap(serializer.toPropertyMap(dt));
assertThat(dtCopy.instant).isEqualTo(dt.instant);
assertThat(dtCopy.localDate).isEqualTo(dt.localDate);
assertThat(dtCopy.localDateTime).isEqualTo(dt.localDateTime);
}
}
|
Update cdn host to use ssl | /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
dotEnv: {
clientAllowedKeys: ['CDN_HOST']
},
fingerprint: {
extensions: ['js', 'css', 'png', 'jpg', 'gif', 'map', 'woff', 'eot', 'svg', 'ttf', 'woff2', 'otf'],
prepend: 'https://drwikejswixhx.cloudfront.net/'
}
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
return app.toTree();
};
| /* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
dotEnv: {
clientAllowedKeys: ['CDN_HOST']
},
fingerprint: {
extensions: ['js', 'css', 'png', 'jpg', 'gif', 'map', 'woff', 'eot', 'svg', 'ttf', 'woff2', 'otf'],
prepend: 'http://cdn.busdetective.com/'
}
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
return app.toTree();
};
|
Add district feed to match score notification | from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self.event = match.event.get()
self._event_feed = self.event.key_name
self._district_feed = self.event.event_district_enum
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.event.name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
| from consts.notification_type import NotificationType
from helpers.model_to_dict import ModelToDict
from notifications.base_notification import BaseNotification
class MatchScoreNotification(BaseNotification):
def __init__(self, match):
self.match = match
self._event_feed = match.event.id
# TODO Add notion of District to Match model?
@property
def _type(self):
return NotificationType.MATCH_SCORE
def _build_dict(self):
data = {}
data['message_type'] = NotificationType.type_names[self._type]
data['message_data'] = {}
data['message_data']['event_name'] = self.match.event.get().name
data['message_data']['match'] = ModelToDict.matchConverter(self.match)
return data
|
Add test_certificate.pem to the release | from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.3',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = 'boris70@gmail.com',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1.3',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
package_data={'furs_fiscal': ['certs/*.pem']},
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
) | from distutils.core import setup
setup(
name = 'furs_fiscal',
packages = ['furs_fiscal'],
version = '0.1.0',
description = 'Python library for simplified communication with FURS (Financna uprava Republike Slovenije).',
author = 'Boris Savic',
author_email = 'boris70@gmail.com',
url = 'https://github.com/boris-savic/python-furs-fiscal',
download_url = 'https://github.com/boris-savic/python-furs-fiscal/tarball/0.1',
keywords = ['FURS', 'fiscal', 'fiscal register', 'davcne blagajne'],
classifiers = [],
install_requires=[
'requests',
'python-jose',
'pyOpenSSL',
'urllib3',
'pyasn1',
'ndg-httpsclient'
]
) |
Add example of building your own struct mapping atlas, with details.
Signed-off-by: Eric Myhre <2346ad27d7568ba9896f1b7da6b5991251debdf2@exultant.us> | package refmt_test
import (
"bytes"
"fmt"
"github.com/polydawn/refmt"
"github.com/polydawn/refmt/obj/atlas"
)
func ExampleJsonEncodeAtlasDefaults() {
type MyType struct {
X string
Y int
}
MyType_AtlasEntry := atlas.BuildEntry(MyType{}).
StructMap().Autogenerate().
Complete()
atl := atlas.MustBuild(
MyType_AtlasEntry,
// this is a vararg... stack more entries here!
)
var buf bytes.Buffer
encoder := refmt.NewAtlasedJsonEncoder(&buf, atl)
err := encoder.Marshal(MyType{"a", 1})
fmt.Println(buf.String())
fmt.Printf("%v\n", err)
// Output:
// {"x":"a","y":1}
// <nil>
}
func ExampleJsonEncodeAtlasCustom() {
type MyType struct {
X string
Y int
}
MyType_AtlasEntry := atlas.BuildEntry(MyType{}).
StructMap().
AddField("X", atlas.StructMapEntry{SerialName: "overrideName"}).
// and no "Y" mapping at all!
Complete()
atl := atlas.MustBuild(
MyType_AtlasEntry,
// this is a vararg... stack more entries here!
)
var buf bytes.Buffer
encoder := refmt.NewAtlasedJsonEncoder(&buf, atl)
err := encoder.Marshal(MyType{"a", 1})
fmt.Println(buf.String())
fmt.Printf("%v\n", err)
// Output:
// {"overrideName":"a"}
// <nil>
}
| package refmt_test
import (
"bytes"
"fmt"
"github.com/polydawn/refmt"
"github.com/polydawn/refmt/obj/atlas"
)
func ExampleJsonEncodeDefaults() {
type MyType struct {
X string
Y int
}
MyType_AtlasEntry := atlas.BuildEntry(MyType{}).
StructMap().Autogenerate().
Complete()
atl := atlas.MustBuild(
MyType_AtlasEntry,
// this is a vararg... stack more entries here!
)
var buf bytes.Buffer
encoder := refmt.NewAtlasedJsonEncoder(&buf, atl)
err := encoder.Marshal(MyType{"a", 1})
fmt.Println(buf.String())
fmt.Printf("%v\n", err)
// Output:
// {"x":"a","y":1}
// <nil>
}
|
Add a test for no files | package uploader
import (
"github.com/matthew-andrews/s3up/objects"
"strings"
"testing"
"time"
)
type stubS3Client struct{}
func (stub stubS3Client) UploadFile(string, objects.File) error {
time.Sleep(50 * time.Millisecond)
return nil
}
func uploadThreeFilesWithConcurrency(concurrency int) int64 {
startTime := time.Now()
Upload(stubS3Client{}, "", make([]objects.File, 3), concurrency)
duration := time.Since(startTime).Nanoseconds()
return int64(duration / int64(time.Millisecond))
}
func TestOneAtATime(t *testing.T) {
duration := uploadThreeFilesWithConcurrency(1)
if duration < 100 {
t.Fatalf("uploader was too quick. 3 times 50ms one at a time can't be less than 100ms. but it was %v", duration)
}
}
func TestThreeAtATime(t *testing.T) {
duration := uploadThreeFilesWithConcurrency(3)
if duration > 100 {
t.Fatalf("uploader was too slow. 3 times 50ms three at a time can't be more than 100ms. but it was %v", duration)
}
}
func TestNoFiles(t *testing.T) {
err := Upload(stubS3Client{}, "", make([]objects.File, 0), 1)
if strings.Contains(err.Error(), "No files found") == false {
t.Fatal("The error that was expected was not thrown")
}
}
| package uploader
import (
"github.com/matthew-andrews/s3up/objects"
"testing"
"time"
)
type stubS3Client struct{}
func (stub stubS3Client) UploadFile(string, objects.File) error {
time.Sleep(50 * time.Millisecond)
return nil
}
func uploadThreeFilesWithConcurrency(concurrency int) int64 {
startTime := time.Now()
Upload(stubS3Client{}, "", make([]objects.File, 3), concurrency)
duration := time.Since(startTime).Nanoseconds()
return int64(duration / int64(time.Millisecond))
}
func TestOneAtATime(t *testing.T) {
duration := uploadThreeFilesWithConcurrency(1)
if duration < 100 {
t.Fatalf("uploader was too quick. 3 times 50ms one at a time can't be less than 100ms. but it was %v", duration)
}
}
func TestThreeAtATime(t *testing.T) {
duration := uploadThreeFilesWithConcurrency(3)
if duration > 100 {
t.Fatalf("uploader was too slow. 3 times 50ms three at a time can't be more than 100ms. but it was %v", duration)
}
}
|
Add setVec3Uniform and remove createIndicesBuffer
Draw with gl.TRIANGLES instead of using indices. | export function createShaderProgram(gl, vs, fs) {
var program = gl.createProgram();
function createShader(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
gl.attachShader(program, shader);
}
createShader(gl.VERTEX_SHADER, vs);
createShader(gl.FRAGMENT_SHADER, fs);
gl.linkProgram(program);
return program;
}
export function setFloat32Attribute(gl, program, name, size, array) {
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(array), gl.STATIC_DRAW);
var location = gl.getAttribLocation(program, name);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
}
export function setMat4Uniform(gl, program, name, array) {
var location = gl.getUniformLocation(program, name);
gl.uniformMatrix4fv(location, false, array);
}
export function setVec3Uniform(gl, program, name, x, y, z) {
var location = gl.getUniformLocation(program, name);
gl.uniform3f(location, x, y, z);
}
| export function createShaderProgram(gl, vs, fs) {
var program = gl.createProgram();
function createShader(type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
gl.attachShader(program, shader);
}
createShader(gl.VERTEX_SHADER, vs);
createShader(gl.FRAGMENT_SHADER, fs);
gl.linkProgram(program);
return program;
}
export function setFloat32Attribute(gl, program, name, size, array) {
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(array), gl.STATIC_DRAW);
var location = gl.getAttribLocation(program, name);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, size, gl.FLOAT, false, 0, 0);
}
export function createIndicesBuffer(gl, indices) {
var indicesBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indicesBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
return indicesBuffer;
}
export function setMat4Uniform(gl, program, name, array) {
var location = gl.getUniformLocation(program, name);
gl.uniformMatrix4fv(location, false, array);
}
|
Use pip version of python-payer-api instead. | import os
from distutils.core import setup
from setuptools import find_packages
VERSION = __import__("django_shop_payer_backend").VERSION
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development',
]
install_requires = [
'django-shop>=0.2.0',
'python-payer-api>=0.1.0',
]
setup(
name="django-shop-payer-backend",
description="Payment backend for django SHOP and Payer.",
version=VERSION,
author="Simon Fransson",
author_email="simon@dessibelle.se",
url="https://github.com/dessibelle/django-shop-payer-backend",
download_url="https://github.com/dessibelle/django-shop-payer-backend/archive/%s.tar.gz" % VERSION,
packages=['django_shop_payer_backend'],
install_requires=install_requires,
classifiers=CLASSIFIERS,
license="MIT",
)
| import os
from distutils.core import setup
from setuptools import find_packages
VERSION = __import__("django_shop_payer_backend").VERSION
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development',
]
install_requires = [
'django-shop>=0.2.0',
'python-payer-api==dev',
]
setup(
name="django-shop-payer-backend",
description="Payment backend for django SHOP and Payer.",
version=VERSION,
author="Simon Fransson",
author_email="simon@dessibelle.se",
url="https://github.com/dessibelle/django-shop-payer-backend",
download_url="https://github.com/dessibelle/django-shop-payer-backend/archive/%s.tar.gz" % VERSION,
packages=['django_shop_payer_backend'],
dependency_links = ['https://github.com/dessibelle/python-payer-api/tarball/master#egg=python-payer-api-0.1.0'],
install_requires=install_requires,
classifiers=CLASSIFIERS,
license="MIT",
long_description="""https://github.com/dessibelle/python-payer-api/tarball/master#egg=python-payer-api-dev"""
)
|
Fix JS error in XHR link module | const queryString = require('query-string')
const XHR = require('../lib/xhr')
const XhrLink = {
selector: '.js-xhr',
init (isGlobal = false) {
this.isGlobal = isGlobal
document.addEventListener('click', this.handleClick.bind(this))
},
handleClick (evt) {
const target = evt.target || evt.srcElement
const url = target.getAttribute('href')
const hasXhrClass = target.classList.contains(this.selector.substring(1))
const shouldXhr = target.tagName === 'A' && this.isGlobal ? true : hasXhrClass
if (!url || url.match(/^http:\/\//)) { return }
const path = url.replace(/(\?.*)/, '')
const params = queryString.parse(url)
if (!shouldXhr) { return }
evt.preventDefault()
XHR.request(path, params)
},
}
module.exports = XhrLink
| const queryString = require('query-string')
const XHR = require('../lib/xhr')
const XhrLink = {
selector: '.js-xhr',
init (isGlobal = false) {
this.isGlobal = isGlobal
document.addEventListener('click', this.handleClick.bind(this))
},
handleClick (evt) {
const target = evt.target || evt.srcElement
const url = target.getAttribute('href')
if (!url || url.match(/^http:\/\//)) { return }
const path = url.match(/^(.*)\?/)[1]
const hasXhrClass = target.classList.contains(this.selector.substring(1))
const shouldXhr = target.tagName === 'A' && this.isGlobal ? true : hasXhrClass
const params = queryString.parse(url)
if (!shouldXhr) { return }
evt.preventDefault()
XHR.request(path, params)
},
}
module.exports = XhrLink
|
Change the example address to freenode to match the README. | var IRC = require('../');
var bot = new IRC.Client('irc.freenode.net', 6667, false, 'prawnsbot', 'prawnsbot', {});
bot.connect();
bot.on('registered', function() {
console.log('Connected!');
//bot.join('#prawnsalad');
var channel = bot.channel('#prawnsalad');
channel.join();
channel.say('Hi!');
channel.updateUsers(function() {
console.log(channel.users);
});
});
bot.on('close', function() {
console.log('Connection close');
});
bot.on('privmsg', function(event) {
if (event.msg.indexOf('whois') === 0) {
bot.whois(event.msg.split(' ')[1]);
} else {
event.reply('no');
}
});
bot.on('whois', function(event) {
console.log(event);
});
bot.on('join', function(event) {
console.log('user joined', event);
});
bot.on('userlist', function(event) {
console.log('userlist for', event.channel, event.users);
});
bot.on('part', function(event) {
console.log('user part', event);
});
| var IRC = require('../');
var bot = new IRC.Client('5.39.86.47', 6667, false, 'prawnsbot', 'prawnsbot', {});
bot.connect();
bot.on('registered', function() {
console.log('Connected!');
//bot.join('#prawnsalad');
var channel = bot.channel('#prawnsalad');
channel.join();
channel.say('Hi!');
channel.updateUsers(function() {
console.log(channel.users);
});
});
bot.on('close', function() {
console.log('Connection close');
});
bot.on('privmsg', function(event) {
if (event.msg.indexOf('whois') === 0) {
bot.whois(event.msg.split(' ')[1]);
} else {
event.reply('no');
}
});
bot.on('whois', function(event) {
console.log(event);
});
bot.on('join', function(event) {
console.log('user joined', event);
});
bot.on('userlist', function(event) {
console.log('userlist for', event.channel, event.users);
});
bot.on('part', function(event) {
console.log('user part', event);
});
|
Include Mail 1.1.3 with PHP 5. | <?php
/* This is a list of packages and versions
* that will be used to create the PEAR folder
* in the windows snapshot.
* See win32/build/mkdist.php for more details
* $Id$
*/
$packages = array(
"PEAR" => "1.3.1",
"Mail" => "1.1.3",
"Net_SMTP" => "1.2.5",
"Net_Socket" => "1.0.1",
"PHPUnit" => "2.0.0beta1",
"Console_Getopt" => "1.2",
"DB" => "1.6.2",
"HTTP" => "1.2.3",
"Archive_Tar" => "1.1",
"Pager" => "1.0.8",
"HTML_Template_IT" => "1.1",
"XML_Parser" => "1.0.1",
"XML_RPC" => "1.1.0",
"Net_UserAgent_Detect" => "1.0",
"PEAR_Frontend_Web" => "0.3"
);
?>
| <?php
/* This is a list of packages and versions
* that will be used to create the PEAR folder
* in the windows snapshot.
* See win32/build/mkdist.php for more details
* $Id$
*/
$packages = array(
"PEAR" => "1.3.1",
"Mail" => "1.1.2",
"Net_SMTP" => "1.2.5",
"Net_Socket" => "1.0.1",
"PHPUnit" => "2.0.0beta1",
"Console_Getopt" => "1.2",
"DB" => "1.6.2",
"HTTP" => "1.2.3",
"Archive_Tar" => "1.1",
"Pager" => "1.0.8",
"HTML_Template_IT" => "1.1",
"XML_Parser" => "1.0.1",
"XML_RPC" => "1.1.0",
"Net_UserAgent_Detect" => "1.0",
"PEAR_Frontend_Web" => "0.3"
);
?>
|
Debug log in core plugin | package openmods.core;
import java.util.Map;
import net.minecraft.launchwrapper.Launch;
import openmods.Log;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
//must be lower than all dependent ones
@SortingIndex(16)
@TransformerExclusions({ "openmods.asm.", "openmods.include.", "openmods.core.", "openmods.injector.", "openmods.Log" })
public class OpenModsCorePlugin implements IFMLLoadingPlugin {
public static final String CORE_MARKER = "OpenModsCoreLoaded";
public OpenModsCorePlugin() {
Log.debug("<OpenModsLib %s>\\o", "$LIB-VERSION$");
Launch.blackboard.put(CORE_MARKER, "$LIB-VERSION$");
}
@Override
public String[] getASMTransformerClass() {
return new String[] { "openmods.core.OpenModsClassTransformer" };
}
@Override
public String getModContainerClass() {
return "openmods.core.OpenModsCore";
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
Bootstrap.injectData(data);
}
@Override
public String getAccessTransformerClass() {
return null;
}
}
| package openmods.core;
import java.util.Map;
import net.minecraft.launchwrapper.Launch;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex;
import cpw.mods.fml.relauncher.IFMLLoadingPlugin.TransformerExclusions;
//must be lower than all dependent ones
@SortingIndex(16)
@TransformerExclusions({ "openmods.asm.", "openmods.include.", "openmods.core.", "openmods.injector.", "openmods.Log" })
public class OpenModsCorePlugin implements IFMLLoadingPlugin {
public static final String CORE_MARKER = "OpenModsCoreLoaded";
public OpenModsCorePlugin() {
Launch.blackboard.put(CORE_MARKER, "$LIB-VERSION$");
}
@Override
public String[] getASMTransformerClass() {
return new String[] { "openmods.core.OpenModsClassTransformer" };
}
@Override
public String getModContainerClass() {
return "openmods.core.OpenModsCore";
}
@Override
public String getSetupClass() {
return null;
}
@Override
public void injectData(Map<String, Object> data) {
Bootstrap.injectData(data);
}
@Override
public String getAccessTransformerClass() {
return null;
}
}
|
Use localhost for development server | (function() {
var app, k, v,
__slice = [].slice;
app = angular.module("app", [
"ionic",
"restangular",
"ngAnimate",
'ngGPlaces',
'classy',
"fx.animations",
"google-maps",
"ion-google-place",
"app.modules",
"app.directives",
"app.filters",
"app.models"
]);
app.config(function(RestangularProvider) {
// RestangularProvider.setBaseUrl('http://server4dave.cloudapp.net:9000/api/v1/');
RestangularProvider.setBaseUrl('http://localhost:9000/api/v1/');
RestangularProvider.setDefaultHttpFields({cache: true});
RestangularProvider.setRequestSuffix('/');
RestangularProvider.setRestangularFields({
cache: true,
id: '_id',
route: "restangularRoute",
selfLink: "self.href"
});
});
for (k in GLOBALS) {
v = GLOBALS[k];
app.constant(k, v);
}
if (GLOBALS.WEINRE_ADDRESS && (ionic.Platform.isAndroid() || ionic.Platform.isIOS())) {
addElement(document, "script", {
id: "weinre-js",
src: "http://" + GLOBALS.WEINRE_ADDRESS + "/target/target-script-min.js#anonymous"
});
}
}).call(this);
| (function() {
var app, k, v,
__slice = [].slice;
app = angular.module("app", [
"ionic",
"restangular",
"ngAnimate",
'ngGPlaces',
'classy',
"fx.animations",
"google-maps",
"ion-google-place",
"app.modules",
"app.directives",
"app.filters",
"app.models"
]);
app.config(function(RestangularProvider) {
// RestangularProvider.setBaseUrl('http://server4dave.cloudapp.net:9000/api/v1/');
RestangularProvider.setBaseUrl('http://10.8.29.210:9000/api/v1/');
RestangularProvider.setDefaultHttpFields({cache: true});
RestangularProvider.setRequestSuffix('/');
RestangularProvider.setRestangularFields({
cache: true,
id: '_id',
route: "restangularRoute",
selfLink: "self.href"
});
});
for (k in GLOBALS) {
v = GLOBALS[k];
app.constant(k, v);
}
if (GLOBALS.WEINRE_ADDRESS && (ionic.Platform.isAndroid() || ionic.Platform.isIOS())) {
addElement(document, "script", {
id: "weinre-js",
src: "http://" + GLOBALS.WEINRE_ADDRESS + "/target/target-script-min.js#anonymous"
});
}
}).call(this);
|
Fix typo: protcols -> protocols | 'use strict';
/**
* Module dependencies
*/
import prominence from 'prominence';
import git from 'git-last-commit';
/**
* @swagger
* /meta:
* post:
* summary: Show the misskey's information
* responses:
* 200:
* description: Success
* schema:
* type: object
* properties:
* maintainer:
* description: maintainer's name
* type: string
* commit:
* description: latest commit's hash
* type: string
* secure:
* description: whether the server supports secure protocols
* type: boolean
*
* default:
* description: Failed
* schema:
* $ref: "#/definitions/Error"
*/
/**
* Show core info
*
* @param {Object} params
* @return {Promise<object>}
*/
module.exports = (params) =>
new Promise(async (res, rej) => {
const commit = await prominence(git).getLastCommit();
res({
maintainer: config.maintainer,
commit: commit.shortHash,
secure: config.https.enable
});
});
| 'use strict';
/**
* Module dependencies
*/
import prominence from 'prominence';
import git from 'git-last-commit';
/**
* @swagger
* /meta:
* post:
* summary: Show the misskey's information
* responses:
* 200:
* description: Success
* schema:
* type: object
* properties:
* maintainer:
* description: maintainer's name
* type: string
* commit:
* description: latest commit's hash
* type: string
* secure:
* description: whether the server supports secure protcols
* type: boolean
*
* default:
* description: Failed
* schema:
* $ref: "#/definitions/Error"
*/
/**
* Show core info
*
* @param {Object} params
* @return {Promise<object>}
*/
module.exports = (params) =>
new Promise(async (res, rej) => {
const commit = await prominence(git).getLastCommit();
res({
maintainer: config.maintainer,
commit: commit.shortHash,
secure: config.https.enable
});
});
|
Remove DeprecationWarning superclass for AstropyDeprecationWarning
we do this because in py2.7, DeprecationWarning and subclasses are hidden by default, but we want astropy's deprecations to get shown by default | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
class AstropyWarning(Warning):
"""
The base warning class from which all Astropy warnings should inherit.
Any warning inheriting from this class is handled by the Astropy logger.
"""
class AstropyUserWarning(UserWarning, AstropyWarning):
"""
The primary warning class for Astropy.
Use this if you do not need a specific sub-class.
"""
class AstropyDeprecationWarning(AstropyWarning):
"""
A warning class to indicate a deprecated feature.
"""
class AstropyPendingDeprecationWarning(PendingDeprecationWarning, AstropyWarning):
"""
A warning class to indicate a soon-to-be deprecated feature.
"""
class AstropyBackwardsIncompatibleChangeWarning(AstropyWarning):
"""
A warning class indicating a change in astropy that is incompatible
with previous versions.
The suggested procedure is to issue this warning for the version in
which the change occurs, and remove it for all following versions.
"""
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
class AstropyWarning(Warning):
"""
The base warning class from which all Astropy warnings should inherit.
Any warning inheriting from this class is handled by the Astropy logger.
"""
class AstropyUserWarning(UserWarning, AstropyWarning):
"""
The primary warning class for Astropy.
Use this if you do not need a specific sub-class.
"""
class AstropyDeprecationWarning(DeprecationWarning, AstropyWarning):
"""
A warning class to indicate a deprecated feature.
"""
class AstropyPendingDeprecationWarning(PendingDeprecationWarning, AstropyWarning):
"""
A warning class to indicate a soon-to-be deprecated feature.
"""
class AstropyBackwardsIncompatibleChangeWarning(AstropyWarning):
"""
A warning class indicating a change in astropy that is incompatible
with previous versions.
The suggested procedure is to issue this warning for the version in
which the change occurs, and remove it for all following versions.
"""
|
Add webui logging for API commands | function do_api(url, data) {
console.log('API REQUEST ' + url);
$.get(url, data);
}
function do_command(item, command, val) {
var data = {};
if (val != undefined) {
data["val"] = val;
}
do_api("/api/item/" + item + "/command/" + command, data);
}
function do_scene(scene, action) {
do_api("/api/scene/" + scene + "/command/" + (action?action:""));
}
$(function() {
$(".command").each(function() {
var elm = $(this);
elm.on(elm.data("event"), function() {
if (elm.data("use-val")) {
do_command(elm.data("item"), elm.data("command"), elm.val());
} else {
do_command(elm.data("item"), elm.data("command"));
}
});
});
$(".scene-control").each(function() {
var elm = $(this);
elm.click(function(evt) {
do_scene(elm.data("scene"), elm.data("action"));
});
});
$("form").submit(function(){return false;});
});
| function do_command(item, command, val) {
var data = {};
if (val != undefined) {
data["val"] = val;
}
$.get("/api/item/" + item + "/command/" + command, data);
}
function do_scene(scene, action) {
$.get("/api/scene/" + scene + "/command/" + (action?action:""));
}
$(function() {
$(".command").each(function() {
var elm = $(this);
elm.on(elm.data("event"), function() {
if (elm.data("use-val")) {
do_command(elm.data("item"), elm.data("command"), elm.val());
} else {
do_command(elm.data("item"), elm.data("command"));
}
});
});
$(".scene-control").each(function() {
var elm = $(this);
elm.click(function(evt) {
do_scene(elm.data("scene"), elm.data("action"));
});
});
$("form").submit(function(){return false;});
});
|
Add -version command line flag to print application version. | package main
import (
"flag"
"fmt"
"log"
"os"
"github.com/mendersoftware/artifacts/config"
"github.com/spf13/viper"
)
func main() {
var configPath string
var printVersion bool
flag.StringVar(&configPath, "config", "config.yaml", "Configuration file path. Supports JSON, TOML, YAML and HCL formatted configs.")
flag.BoolVar(&printVersion, "version", false, "Show version")
flag.Parse()
if printVersion {
fmt.Println(CreateVersionString())
os.Exit(0)
}
configuration, err := HandleConfigFile(configPath)
if err != nil {
log.Fatalln(err)
}
log.Fatalln(RunServer(configuration))
}
func HandleConfigFile(filePath string) (config.ConfigReader, error) {
c := viper.New()
c.SetConfigFile(filePath)
// Set default values for config
SetDefaultConfigs(c)
// Find and read the config file
if err := c.ReadInConfig(); err != nil {
return nil, err
}
// Validate config
if err := config.ValidateConfig(c,
ValidateAwsAuth,
ValidateHttps,
); err != nil {
return nil, err
}
return c, nil
}
func SetDefaultConfigs(config *viper.Viper) {
config.SetDefault(SettingListen, SettingListenDefault)
config.SetDefault(SettingAwsS3Region, SettingAwsS3RegionDefault)
config.SetDefault(SettingAweS3Bucket, SettingAwsS3BucketDefault)
}
| package main
import (
"flag"
"log"
"github.com/mendersoftware/artifacts/config"
"github.com/spf13/viper"
)
func main() {
var configPath string
flag.StringVar(&configPath, "config", "config.yaml", "Configuration file path. Supports JSON, TOML, YAML and HCL formatted configs.")
flag.Parse()
c := viper.New()
c.SetConfigFile(configPath)
// Set default values for config
SetDefaultConfigs(c)
// Find and read the config file
if err := c.ReadInConfig(); err != nil {
log.Fatalln(err)
}
// Validate config
if err := config.ValidateConfig(c,
ValidateAwsAuth,
ValidateHttps,
); err != nil {
log.Fatalln(err)
}
log.Fatalln(RunServer(c))
}
func SetDefaultConfigs(config *viper.Viper) {
config.SetDefault(SettingListen, SettingListenDefault)
config.SetDefault(SettingAwsS3Region, SettingAwsS3RegionDefault)
config.SetDefault(SettingAweS3Bucket, SettingAwsS3BucketDefault)
}
|
Use relative imports for consistency; pep8 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import numpy as np
from astropy.tests.helper import pytest
from ..psf import GaussianPSF
try:
from scipy import optimize
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
widths = [0.001, 0.01, 0.1, 1]
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize(('width'), widths)
def test_subpixel_gauss_psf(width):
"""
Test subpixel accuracy of Gaussian PSF by checking the sum o pixels.
"""
gauss_psf = GaussianPSF(width)
y, x = np.mgrid[-10:11, -10:11]
assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12
@pytest.mark.skipif('not HAS_SCIPY')
def test_gaussian_PSF_integral():
"""
Test if Gaussian PSF integrates to unity on larger scales.
"""
psf = GaussianPSF(10)
y, x = np.mgrid[-100:101, -100:101]
assert np.abs(psf(y, x).sum() - 1) < 1E-12
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import division
import numpy as np
from astropy.tests.helper import pytest
from photutils.psf import GaussianPSF
try:
from scipy import optimize
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
widths = [0.001, 0.01, 0.1, 1]
@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize(('width'), widths)
def test_subpixel_gauss_psf(width):
"""
Test subpixel accuracy of Gaussian PSF by checking the sum o pixels.
"""
gauss_psf = GaussianPSF(width)
y, x = np.mgrid[-10:11, -10:11]
assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12
@pytest.mark.skipif('not HAS_SCIPY')
def test_gaussian_PSF_integral():
"""
Test if Gaussian PSF integrates to unity on larger scales.
"""
psf = GaussianPSF(10)
y, x = np.mgrid[-100:101, -100:101]
assert np.abs(psf(y, x).sum() - 1) < 1E-12
|
Revert "Perhaps need to modify the name"
This reverts commit d4ee1a1d91cd13bf0cb844be032eaa527806fad1. | from setuptools import setup
DESCRIPTION = "A Django oriented templated / transaction email abstraction"
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Framework :: Django',
]
setup(
name='django-templated-email',
version='0.4.9',
packages=['templated_email', 'templated_email.backends'],
author='Bradley Whittington',
author_email='radbrad182@gmail.com',
url='http://github.com/bradwhittington/django-templated-email/',
license='MIT',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
)
| from setuptools import setup
DESCRIPTION = "A Django oriented templated / transaction email abstraction"
LONG_DESCRIPTION = None
try:
LONG_DESCRIPTION = open('README.rst').read()
except:
pass
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Framework :: Django',
]
setup(
name='denaje-django-templated-email',
version='0.4.9',
packages=['templated_email', 'templated_email.backends'],
author='Bradley Whittington',
author_email='radbrad182@gmail.com',
url='http://github.com/bradwhittington/django-templated-email/',
license='MIT',
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
platforms=['any'],
classifiers=CLASSIFIERS,
)
|
Use of Winston to output messages in the console | 'use strict';
// Requirements
var winston = module.parent.require('winston');
var watsonDev = require('watson-developer-cloud');
// Methods
var Watson = {};
Watson.response = function(postData) {
var conversation = watsonDev.conversation({
username: 'c9d9cc99-b3e5-44f5-a234-ccae1578e8ae',
password: 'xUtHqarwWpUk',
version: 'v1',
version_date: '2016-09-20'
});
var context = {};
var params = {
workspace_id: 'a05393b7-d022-4bed-ba76-012042930893',
input: {'text': 'hahaha'},
context: context
};
conversation.message(params, function(err, response) {
if (err)
return winston.info(err);
else {
winston.info(JSON.stringify(response, null, 2));
}
});
}
module.exports = Watson;
| 'use strict';
// Requirements
var User = module.parent.require('./user'),
var winston = module.parent.require('winston'),
var watsonDev = require('watson-developer-cloud');
// Methods
var Watson = {};
Watson.response = function(postData) {
var conversation = watsonDev.conversation({
username: 'c9d9cc99-b3e5-44f5-a234-ccae1578e8ae',
password: 'xUtHqarwWpUk',
version: 'v1',
version_date: '2016-09-20'
});
var context = {};
var params = {
workspace_id: 'a05393b7-d022-4bed-ba76-012042930893',
input: {'text': 'hahahaha'},
context: context
};
conversation.message(params, function
(err, response) {
if (err)
return console.log(err);
else
console.log(JSON.stringify(response, null, 2));
});
}
module.exports = Watson;
|
Test for cache file before removing | <?php
require_once('./config.php');
require_once('./functions.php');
// If we're good to clear cache, remove cache file
if(isset($_GET['clearcache']) & in_array($_SERVER['REMOTE_ADDR'],$config['nocache_whitelist']) & is_file($config['cache_file']){
unlink($config['cache_file']);
}
// If we're good to bypass cache, get raw data from RPC
if(isset($_GET['nocache']) & in_array($_SERVER['REMOTE_ADDR'],$config['nocache_whitelist'])){
$data = get_raw_data();
} elseif (is_file($config['cache_file'])) {
// Get cache data
$raw_cache = file_get_contents($config['cache_file']);
$cache = unserialize($raw_cache);
// If the data is still valid, use it. If not, get from RPC
if (time() > ($cache['cache_time']+$config['max_cache_time'])) {
$data = get_raw_data();
} else {
$data = $cache;
}
} else {
$data = get_raw_data();
}
// Add the IP of the server, and include template
$data['server_ip'] = $_SERVER['SERVER_ADDR'];
require_once('./template.html');
?>
| <?php
require_once('./config.php');
require_once('./functions.php');
// If we're good to clear cache, remove cache file
if((isset($_GET['clearcache'])) & (in_array($_SERVER['REMOTE_ADDR'],$config['nocache_whitelist']))){
unlink($config['cache_file']);
}
// If we're good to bypass cache, get raw data from RPC
if((isset($_GET['nocache'])) & (in_array($_SERVER['REMOTE_ADDR'],$config['nocache_whitelist']))){
$data = get_raw_data();
} elseif (is_file($config['cache_file'])) {
// Get cache data
$raw_cache = file_get_contents($config['cache_file']);
$cache = unserialize($raw_cache);
// If the data is still valid, use it. If not, get from RPC
if (time() > ($cache['cache_time']+$config['max_cache_time'])) {
$data = get_raw_data();
} else {
$data = $cache;
}
} else {
$data = get_raw_data();
}
// Add the IP of the server, and include template
$data['server_ip'] = $_SERVER['SERVER_ADDR'];
require_once('./template.html');
?>
|
Remove preffered binding, use obj.__class__ instead of type() | import sys
import os
# Set preferred binding
# os.environ["QT_PREFERRED_BINDING"] = "PySide"
from Qt import QtWidgets, load_ui
def setup_ui(uifile, base_instance=None):
ui = load_ui(uifile)
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith('__') and \
member is not 'staticMetaObject':
setattr(base_instance, member, getattr(ui, member))
return ui
class MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
setup_ui('examples/load_ui_qwidget.ui', self)
def test_load_ui_setup_ui_wrapper():
"""Example: load_ui with setup_ui wrapper
"""
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
# Tests
assert isinstance(window.__class__, QtWidgets.QWidget.__class__)
assert isinstance(window.parent(), type(None))
assert isinstance(window.lineEdit.__class__, QtWidgets.QWidget.__class__)
assert window.lineEdit.text() == ''
window.lineEdit.setText('Hello')
assert window.lineEdit.text() == 'Hello'
app.exit()
| import sys
import os
os.environ["QT_PREFERRED_BINDING"] = "PySide"
from Qt import QtWidgets, load_ui
def setup_ui(uifile, base_instance=None):
ui = load_ui(uifile)
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith('__') and \
member is not 'staticMetaObject':
setattr(base_instance, member, getattr(ui, member))
return ui
class MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
setup_ui('examples/load_ui_qwidget.ui', self)
def test_load_ui_setup_ui_wrapper():
"""Example: load_ui with setup_ui wrapper
"""
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
# Tests
assert isinstance(window.__class__, type(QtWidgets.QWidget))
assert isinstance(window.parent(), type(None))
assert isinstance(window.lineEdit.__class__, type(QtWidgets.QWidget))
assert window.lineEdit.text() == ''
window.lineEdit.setText('Hello')
assert window.lineEdit.text() == 'Hello'
app.exit()
|
Add a note about where got can be got | // got can be found at github.com/gholt/got
//go:generate got valueorderedkeys.got zzz_desirednodes.go p=lowring new=newDesiredNodes T=desiredNodes K=byDesire k=Node V=toDesire v=int32
//go:generate got valueorderedkeys_test.got zzz_desirednodes_test.go p=lowring new=newDesiredNodes T=desiredNodes K=byDesire k=Node V=toDesire v=int32
//go:generate got valueorderedkeys.got zzz_desiredgroups.go p=lowring new=newDesiredGroups T=desiredGroups K=byDesire k=int V=toDesire v=int32
//go:generate got valueorderedkeys_test.got zzz_desiredgroups_test.go p=lowring new=newDesiredGroups T=desiredGroups K=byDesire k=int V=toDesire v=int32
package lowring
| //go:generate got valueorderedkeys.got zzz_desirednodes.go p=lowring new=newDesiredNodes T=desiredNodes K=byDesire k=Node V=toDesire v=int32
//go:generate got valueorderedkeys_test.got zzz_desirednodes_test.go p=lowring new=newDesiredNodes T=desiredNodes K=byDesire k=Node V=toDesire v=int32
//go:generate got valueorderedkeys.got zzz_desiredgroups.go p=lowring new=newDesiredGroups T=desiredGroups K=byDesire k=int V=toDesire v=int32
//go:generate got valueorderedkeys_test.got zzz_desiredgroups_test.go p=lowring new=newDesiredGroups T=desiredGroups K=byDesire k=int V=toDesire v=int32
package lowring
|
Fix missing test
probably got removed in my clumsy merge | import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
"AKD":"/ApplicationExamples/AKD/package.mo",
"N44":"/ApplicationExamples/N44/package.mo",
"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}
# Instance of CITests
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL
sys.exit(1)
else:
# Run Check on App Examples
passAppEx = 1
for package in appExamples.keys():
passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])
# The tests are failing if the number of failed check > 0
if passAppEx:
# Everything is fine
sys.exit(0)
else:
# Exit with error
sys.exit(1)
| import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
"AKD":"/ApplicationExamples/AKD/package.mo",
"N44":"/ApplicationExamples/N44/package.mo",
"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
}
# Instance of CITests
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL
sys.exit(1)
else:
# Run Check on App Examples
passAppEx = 1
for package in appExamples.keys():
passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])
# The tests are failing if the number of failed check > 0
if passAppEx:
# Everything is fine
sys.exit(0)
else:
# Exit with error
sys.exit(1)
|
Support onEnter hooks on IndexRoutes | import { createRoutes } from 'react-router/lib/RouteUtils';
// Wrap the hooks so they don't fire if they're called before
// the store is initialised. This only happens when doing the first
// client render of a route that has an onEnter hook
function makeHooksSafe(routes, store) {
if (Array.isArray(routes)) {
return routes.map((route) => makeHooksSafe(route, store));
}
const onEnter = routes.onEnter;
if (onEnter) {
routes.onEnter = function safeOnEnter(...args) {
try {
store.getState();
} catch (err) {
if (onEnter.length === 3) {
args[2]();
}
// There's no store yet so ignore the hook
return;
}
onEnter.apply(null, args);
};
}
if (routes.childRoutes) {
makeHooksSafe(routes.childRoutes, store);
}
if (routes.indexRoute) {
makeHooksSafe(routes.indexRoute, store);
}
return routes;
}
export default function makeRouteHooksSafe(_getRoutes) {
return (store) => makeHooksSafe(createRoutes(_getRoutes(store)), store);
}
| import { createRoutes } from 'react-router/lib/RouteUtils';
// Wrap the hooks so they don't fire if they're called before
// the store is initialised. This only happens when doing the first
// client render of a route that has an onEnter hook
function makeHooksSafe(routes, store) {
if (Array.isArray(routes)) {
return routes.map((route) => makeHooksSafe(route, store));
}
const onEnter = routes.onEnter;
if (onEnter) {
routes.onEnter = function safeOnEnter(...args) {
try {
store.getState();
} catch (err) {
if (onEnter.length === 3) {
args[2]();
}
// There's no store yet so ignore the hook
return;
}
onEnter.apply(null, args);
};
}
if (routes.childRoutes) {
makeHooksSafe(routes.childRoutes, store);
}
return routes;
}
export default function makeRouteHooksSafe(_getRoutes) {
return (store) => makeHooksSafe(createRoutes(_getRoutes(store)), store);
}
|
Test the Autowired bean of context. | /*
* Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
*
* 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.search.nibrs.route;
import org.apache.camel.CamelContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.search.nibrs.fbi.service.NibrsFbiServiceApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NibrsFbiServiceApplication.class)
public class NibrsRouteApplicationTests {
@Autowired
CamelContext context;
@Test
public void contextLoads() {
Assert.notNull(context, "the camel context should not be null");
}
}
| /*
* Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
*
* 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.search.nibrs.route;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class NibrsRouteApplicationTests {
@Test
public void contextLoads() {
}
}
|
Add locking middleware as default | <?php
namespace Madewithlove\Tactician;
use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
use League\Tactician\Plugins\LockingMiddleware;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind(CommandBus::class, function () {
$middlewares = [];
$middlewares[] = new LockingMiddleware();
$middlewares[] = new CommandHandlerMiddleware(
new ClassNameExtractor(),
new ContainerLocator($this->app),
new HandleInflector()
);
return new CommandBus($middlewares);
});
$this->app->alias(CommandBus::class, 'bus');
}
/**
* @return array
*/
public function provides()
{
return [
CommandBus::class,
'bus',
];
}
}
| <?php
namespace Madewithlove\Tactician;
use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\MethodNameInflector\HandleInflector;
class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind(CommandBus::class, function () {
$middlewares = [];
$middlewares[] = new CommandHandlerMiddleware(
new ClassNameExtractor(),
new ContainerLocator($this->app),
new HandleInflector()
);
return new CommandBus($middlewares);
});
$this->app->alias(CommandBus::class, 'bus');
}
/**
* @return array
*/
public function provides()
{
return [
CommandBus::class,
'bus',
];
}
}
|
Fix errors caused by updating Ramda | import { parse } from 'papaparse'
import {
compose, filter, find, flatten, identity,
join, map, complement, drop, takeWhile, test
} from 'ramda'
const clean = compose(filter(identity), flatten)
const dataRegexp = test(RegExp("^(\\d{4}|Year)$"))
function isData (row) {
return !!find(dataRegexp, row)
}
function getRows (csv) {
const parsed = parse(csv, {
dynamicTyping: false,
header: false,
})
return parsed.data
}
function splitHeaders (rows) {
const header = takeWhile(complement(isData), rows)
const content = takeWhile(isData, drop(header.length, rows))
const footer = drop(header.length + content.length, rows)
return {
content,
header: clean(header),
footer: clean(footer),
}
}
export function cleanup (rawData) {
let {header, content, footer} = splitHeaders(getRows(rawData))
const text = join('\n', map(join('\t'), content))
// Reparse data rows with dynamic typing
const reparsed = parse(text, {
header: true,
dynamicTyping: true,
})
if (reparsed.errors.length > 0) {
console.error("Errors while parsing raw data:", reparsed.errors)
}
return Object.assign(reparsed, {header, footer})
}
| import { parse } from 'papaparse'
import {
compose, filter, find, flatten, identity,
join, map, match, not, drop, takeWhile
} from 'ramda'
const clean = compose(filter(identity), flatten)
const dataRegexp = match(RegExp("^(\\d{4}|Year)$"))
function isData (row) {
return !!find(dataRegexp, row)
}
function getRows (csv) {
const parsed = parse(csv, {
dynamicTyping: false,
header: false,
})
return parsed.data
}
function splitHeaders (rows) {
const header = takeWhile(not(isData), rows)
const content = takeWhile(isData, drop(header.length, rows))
const footer = drop(header.length + content.length, rows)
return {
content,
header: clean(header),
footer: clean(footer),
}
}
export function cleanup (rawData) {
let {header, content, footer} = splitHeaders(getRows(rawData))
const text = join('\n', map(join('\t'), content))
// Reparse data rows with dynamic typing
const reparsed = parse(text, {
header: true,
dynamicTyping: true,
})
if (reparsed.errors.length > 0) {
console.error("Errors while parsing raw data:", reparsed.errors)
}
return Object.assign(reparsed, {header, footer})
}
|
Fix time-based lookups in REST API
Don't encode the datetime argument to bytes; the underlying function
expects a string argument. | """
Whip's REST API
"""
# pylint: disable=missing-docstring
import socket
from flask import Flask, abort, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
try:
key = socket.inet_aton(ip)
except socket.error:
abort(400)
dt = request.args.get('datetime')
info_as_json = db.lookup(key, dt)
if info_as_json is None:
info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json'
return response
| """
Whip's REST API
"""
# pylint: disable=missing-docstring
import socket
from flask import Flask, abort, make_response, request
from .db import Database
app = Flask(__name__)
app.config.from_envvar('WHIP_SETTINGS', silent=True)
db = None
@app.before_first_request
def _open_db():
global db # pylint: disable=global-statement
db = Database(app.config['DATABASE_DIR'])
@app.route('/ip/<ip>')
def lookup(ip):
try:
key = socket.inet_aton(ip)
except socket.error:
abort(400)
dt = request.args.get('datetime')
if dt:
dt = dt.encode('ascii')
else:
dt = None # account for empty parameter value
info_as_json = db.lookup(key, dt)
if info_as_json is None:
info_as_json = b'{}' # empty dict, JSON-encoded
response = make_response(info_as_json)
response.headers['Content-type'] = 'application/json'
return response
|
Revert "Use composed annotation for readability"
This reverts commit a5d03f60e8ee9c33dc22da29615a6ae86c9bf6e4. | package ee.tuleva.onboarding.auth.session;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GenericSessionStore implements Serializable {
@Serial private static final long serialVersionUID = -648103071415508424L;
private final Map<String, Object> sessionAttributes = new HashMap<>();
public <T extends Serializable> void save(T sessionAttribute) {
sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
}
public <T extends Serializable> Optional<T> get(Class clazz) {
@SuppressWarnings("unchecked")
T sessionAttribute = (T) sessionAttributes.get(clazz.getName());
if (sessionAttribute == null) {
return Optional.empty();
}
return Optional.of(sessionAttribute);
}
}
| package ee.tuleva.onboarding.auth.session;
import java.io.Serial;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
@Component
@SessionScope
public class GenericSessionStore implements Serializable {
@Serial private static final long serialVersionUID = -648103071415508424L;
private final Map<String, Object> sessionAttributes = new HashMap<>();
public <T extends Serializable> void save(T sessionAttribute) {
sessionAttributes.put(sessionAttribute.getClass().getName(), sessionAttribute);
}
public <T extends Serializable> Optional<T> get(Class clazz) {
@SuppressWarnings("unchecked")
T sessionAttribute = (T) sessionAttributes.get(clazz.getName());
if (sessionAttribute == null) {
return Optional.empty();
}
return Optional.of(sessionAttribute);
}
}
|
Disable console log for server connection | var MongoClient = require('mongodb').MongoClient;
var URICS = "mongodb://tonyli139:RDyMScAWKpj0Fl1O@p2cluster-shard-00-00-ccvtw.mongodb.net:27017,p2cluster-shard-00-01-ccvtw.mongodb.net:27017,p2cluster-shard-00-02-ccvtw.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=p2Cluster-shard-0&authSource=admin";
var db;
connectDb = function(callback) {
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
//console.log('connected');
return callback(err);
});
}
getDb = function() {
return db;
}
var ObjectID = require('mongodb').ObjectID;
getID = function(id) {
return new ObjectID(id);
}
module.exports = {
connectDb,
getDb,
getID
}
| var MongoClient = require('mongodb').MongoClient;
var URICS = "mongodb://tonyli139:RDyMScAWKpj0Fl1O@p2cluster-shard-00-00-ccvtw.mongodb.net:27017,p2cluster-shard-00-01-ccvtw.mongodb.net:27017,p2cluster-shard-00-02-ccvtw.mongodb.net:27017/<DATABASE>?ssl=true&replicaSet=p2Cluster-shard-0&authSource=admin";
var db;
connectDb = function(callback) {
MongoClient.connect(URICS, function(err, database) {
if (err) throw err;
db = database;
console.log('connected');
return callback(err);
});
}
getDb = function() {
return db;
}
var ObjectID = require('mongodb').ObjectID;
getID = function(id) {
return new ObjectID(id);
}
module.exports = {
connectDb,
getDb,
getID
}
|
Enforce permissions for new & updated thread list | <?php namespace Riari\Forum\Repositories;
use Riari\Forum\Models\Thread;
class Threads extends BaseRepository {
public function __construct(Thread $model)
{
$this->model = $model;
$this->itemsPerPage = config('forum.integration.threads_per_category');
}
public function getRecent($where = array())
{
return $this->model->with('category', 'posts')->recent()->where($where)->orderBy('updated_at', 'desc')->get();
}
public function getNewForUser($userID = 0, $where = array())
{
$threads = $this->getRecent($where);
// If we have a user ID, filter the threads appropriately
if ($userID)
{
$threads = $threads->filter(function($thread)
{
return $thread->userReadStatus;
});
}
// Filter the threads according to the user's permissions
$threads = $threads->filter(function($thread)
{
return $thread->category->userCanView;
});
return $threads;
}
}
| <?php namespace Riari\Forum\Repositories;
use Riari\Forum\Models\Thread;
class Threads extends BaseRepository {
public function __construct(Thread $model)
{
$this->model = $model;
$this->itemsPerPage = config('forum.integration.threads_per_category');
}
public function getRecent($where = array())
{
return $this->model->with('category', 'posts')->recent()->where($where)->orderBy('updated_at', 'desc')->get();
}
public function getNewForUser($userID = 0, $where = array())
{
$threads = $this->getRecent($where);
// If we have a user ID, filter the threads appropriately
if ($userID)
{
$threads = $threads->filter(function($thread) use ($userID)
{
return $thread->userReadStatus;
});
}
return $threads;
}
}
|
Remove previous cheap hack by changing the 'key doesn't exist in map' logic from === 'undefined' to !== 'number' | 'use strict';
var markovDictionaryBuilder = (function() {
function buildDict(wordSet, chainSize) {
console.log("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize);
var map = [];
var dict = [];
for (var i = 0, len = wordSet.length - chainSize; i < len; i++) {
var end = i + parseFloat(chainSize);
var workingSet = wordSet.slice(i, end+1);
var k = workingSet.slice(0, workingSet.length-1);
var n = workingSet.slice(-1);
var dictItem = {
'key' : k.join('/').toLowerCase(),
'words' : k,
'next' : n
};
var mi = map[dictItem.key];
if (typeof(mi) !== 'number') {
var dictIndex = dict.length;
dict.push(dictItem);
map[dictItem.key] = dictIndex;
} else {
dict[mi].next.push(dictItem.next[0]);
}
}
return dict;
}
return {
buildDict : buildDict
};
})(); | 'use strict';
var markovDictionaryBuilder = (function() {
function buildDict(wordSet, chainSize) {
console.log("building dictionary from " + wordSet.length + " words with a chain size of " + chainSize);
var map = [];
var dict = [];
for (var i = 0, len = wordSet.length - chainSize; i < len; i++) {
var end = i + parseFloat(chainSize);
var workingSet = wordSet.slice(i, end+1);
var k = workingSet.slice(0, workingSet.length-1);
var n = workingSet.slice(-1);
var dictItem = {
'key' : k.join('/').toLowerCase(),
'words' : k,
'next' : n
};
//TODO: cheap hack to prevent keywords (e.g. "every") from being parsed as native code (e.g. function)
// revisit this issue, because this is bloody stupid.
var mapKey = "*" + dictItem.key;
var mi = map[mapKey];
if (typeof(mi) === 'undefined') {
var dictIndex = dict.length;
dict.push(dictItem);
map[mapKey] = dictIndex;
} else {
dict[mi].next.push(dictItem.next[0]);
}
}
return dict;
}
return {
buildDict : buildDict
};
})(); |
Use the correct entry point. | 'use strict'
const jspm = require('gulp-jspm')
const sourcemaps = require('gulp-sourcemaps')
const filenames = require('gulp-filenames')
const flatten = require('gulp-flatten')
const hash = require('gulp-hash-filename')
const util = require('gulp-util')
exports.dep = ['bundle:tscompile']
exports.fn = function (gulp, paths, mode, done) {
return gulp.src(paths.src + './main.js', { base: '.' })
.pipe(!mode.production ? sourcemaps.init({loadMaps: true}) : util.noop())
.pipe(jspm({selfExecutingBundle: true, minify: mode.production, mangle: mode.production, fileName: 'app-bundle'}))
.pipe(mode.production ? hash({'format': '{hash}{ext}'}) : util.noop())
.pipe(filenames('appbundle'))
.pipe(!mode.production ? sourcemaps.write('.') : util.noop())
.pipe(flatten())
.pipe(gulp.dest('wwwroot'))
}
| 'use strict'
const jspm = require('gulp-jspm')
const sourcemaps = require('gulp-sourcemaps')
const filenames = require('gulp-filenames')
const flatten = require('gulp-flatten')
const hash = require('gulp-hash-filename')
const util = require('gulp-util')
exports.dep = ['bundle:tscompile']
exports.fn = function (gulp, paths, mode, done) {
return gulp.src(paths.src + './app.js', { base: '.' })
.pipe(!mode.production ? sourcemaps.init({loadMaps: true}) : util.noop())
.pipe(jspm({selfExecutingBundle: true, minify: mode.production, mangle: mode.production, fileName: 'app-bundle'}))
.pipe(mode.production ? hash({'format': '{hash}{ext}'}) : util.noop())
.pipe(filenames('appbundle'))
.pipe(!mode.production ? sourcemaps.write('.') : util.noop())
.pipe(flatten())
.pipe(gulp.dest('wwwroot'))
}
|
Remove ParcelConverter from default mapping | /*
* Copyright 2016 requery.io
*
* 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 io.requery.android;
import io.requery.sql.GenericMapping;
import io.requery.sql.Platform;
/**
* Extended {@link io.requery.sql.Mapping} with useful {@link io.requery.Converter}s added
* specifically for Android.
*/
public class DefaultMapping extends GenericMapping {
public DefaultMapping(Platform platform) {
super(platform);
addConverter(new UriConverter());
}
}
| /*
* Copyright 2016 requery.io
*
* 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 io.requery.android;
import android.os.ParcelUuid;
import io.requery.sql.GenericMapping;
import io.requery.sql.Platform;
/**
* Extended {@link io.requery.sql.Mapping} with useful {@link io.requery.Converter}s added
* specifically for Android.
*/
public class DefaultMapping extends GenericMapping {
public DefaultMapping(Platform platform) {
super(platform);
addConverter(new UriConverter());
addConverter(new ParcelConverter<>(ParcelUuid.class, ParcelUuid.CREATOR));
}
}
|
Allow control of response type for failing permit check | from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func, response_class=http.Forbidden):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return response_class()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
| from __future__ import unicode_literals
# Authentication and Authorisation
from functools import wraps
from . import http
def permit(test_func):
'''Decorate a handler to control access'''
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(self, *args, **kwargs):
if test_func(self, *args, **kwargs):
return view_func(self, *args, **kwargs)
return http.Forbidden()
return _wrapped_view
return decorator
permit_logged_in = permit(
lambda self, *args, **kwargs: self.request.user.is_authenticated()
)
permit_staff = permit(
lambda self, *args, **kwargs: self.request.user.is_staff
)
def permit_groups(*groups):
def in_groups(self, *args, **kwargs):
return self.request.user.groups.filter(name__in=groups).exists()
return permit(in_groups)
|
Handle the fresh install case. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
"""Rename old content types if necessary, remove permissions."""
ContentType = apps.get_model("contenttypes", "ContentType")
for ct in ContentType.objects.filter(app_label="admin"):
try:
old_ct = ContentType.objects.get(
app_label="modoboa_admin", model=ct.model)
except ContentType.DoesNotExist:
continue
old_ct.app_label = "admin"
ct.delete()
old_ct.save()
# Remove DomainAlias permissions from DomainAdmins group
Group = apps.get_model("auth", "Group")
try:
group = Group.objects.get(name="DomainAdmins")
except Group.DoesNotExist:
return
Permission = apps.get_model("auth", "Permission")
ct = ContentType.objects.get(app_label="admin", model="domainalias")
for permission in Permission.objects.filter(content_type=ct):
group.permissions.remove(permission)
class Migration(migrations.Migration):
dependencies = [
('admin', '0001_initial'),
]
operations = [
migrations.RunPython(rename_and_clean),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def rename_and_clean(apps, schema_editor):
"""Rename old content types if necessary, remove permissions."""
ContentType = apps.get_model("contenttypes", "ContentType")
for ct in ContentType.objects.filter(app_label="admin"):
try:
old_ct = ContentType.objects.get(
app_label="modoboa_admin", model=ct.model)
except ContentType.DoesNotExist:
continue
old_ct.app_label = "admin"
ct.delete()
old_ct.save()
# Remove DomainAlias permissions from DomainAdmins group
Group = apps.get_model("auth", "Group")
Permission = apps.get_model("auth", "Permission")
group = Group.objects.get(name="DomainAdmins")
ct = ContentType.objects.get(app_label="admin", model="domainalias")
for permission in Permission.objects.filter(content_type=ct):
group.permissions.remove(permission)
class Migration(migrations.Migration):
dependencies = [
('admin', '0001_initial'),
]
operations = [
migrations.RunPython(rename_and_clean),
]
|
Change webpack bundle filename and use cache for babel | /*
/* (c) 2016 Björn Ricks <bjoern.ricks@gmail.com>
/*
/* See LICENSE comming with the source of daap.js for details.
*/
module.exports = {
entry: './src/daap.js',
output: {
path: './build',
pathinfo: true,
filename: 'daap.bundle.js',
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'eslint',
}
],
loaders: [
{
test: /\.jss$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
},
},
],
},
};
| /*
/* (c) 2016 Björn Ricks <bjoern.ricks@gmail.com>
/*
/* See LICENSE comming with the source of daap.js for details.
*/
module.exports = {
entry: './src/daap.js',
output: {
path: './build',
pathinfo: true,
filename: 'bundle.js',
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'eslint',
}
],
loaders: [
{
test: /\.jss$/,
loader: 'babel',
exclude: /node_modules/,
},
],
},
};
|
tpl/tplimpl: Fix compiling Amber templates that import other templates
Without this patch, amber would try to load templates from the OS filesystem
instead of the layouts virtual filesystem. | // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"html/template"
"github.com/eknkc/amber"
"github.com/spf13/afero"
)
func (t *templateHandler) compileAmberWithTemplate(b []byte, path string, templ *template.Template) (*template.Template, error) {
c := amber.New()
c.Options.VirtualFilesystem = afero.NewHttpFs(t.layoutsFs)
if err := c.ParseData(b, path); err != nil {
return nil, err
}
data, err := c.CompileString()
if err != nil {
return nil, err
}
tpl, err := templ.Funcs(t.amberFuncMap).Parse(data)
if err != nil {
return nil, err
}
return tpl, nil
}
| // Copyright 2017 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tplimpl
import (
"html/template"
"github.com/eknkc/amber"
)
func (t *templateHandler) compileAmberWithTemplate(b []byte, path string, templ *template.Template) (*template.Template, error) {
c := amber.New()
if err := c.ParseData(b, path); err != nil {
return nil, err
}
data, err := c.CompileString()
if err != nil {
return nil, err
}
tpl, err := templ.Funcs(t.amberFuncMap).Parse(data)
if err != nil {
return nil, err
}
return tpl, nil
}
|
Change hard-coded email for admin users | import { setClient } from '../actions'
/**
* Ehhhhhhhhhhhhhh... Needs a little more cleanup, but in general
* we kinda dumbly trust a user from localStorage if there is no user
* in state.
*
* It is entirely possible that I suck at branching logic
*/
const isUser = user => user.id && user.email && user.token
const isAdmin = user => isUser(user) && (user.email === 'bruce@designitcontoso.onmicrosoft.com' || user.email === 'roodmin@designitcontoso.onmicrosoft.com')
const checkStoredAuthorization = (dispatch, verifyUser) => {
const storedUser = localStorage.getItem('user')
if (storedUser) {
const user = JSON.parse(storedUser)
// We need a better system here to verify a user from localStorage
// is who they say they are, and additionally verify the JWT token
// const created = Math.round(createdDate.getTime() / 1000)
// const ttl = 1209600
// const expiry = created + ttl
// if the user has expired return false
// if (created > expiry) return false
dispatch(setClient(user))
return verifyUser(user)
}
return false
}
export function isAuthorizedUser(user, dispatch) {
if (!isUser(user))
return checkStoredAuthorization(dispatch, isUser)
return true
}
export function isAuthorizedAdmin(user, dispatch) {
if (!isUser(user))
return checkStoredAuthorization(dispatch, isAdmin)
return isAdmin(user)
}
| import { setClient } from '../actions'
/**
* Ehhhhhhhhhhhhhh... Needs a little more cleanup, but in general
* we kinda dumbly trust a user from localStorage if there is no user
* in state.
*
* It is entirely possible that I suck at branching logic
*/
const isUser = user => user.id && user.email && user.token
const isAdmin = user => isUser(user) && (user.id === 1 || user.email === 'rasmus@designit.com')
const checkStoredAuthorization = (dispatch, verifyUser) => {
const storedUser = localStorage.getItem('user')
if (storedUser) {
const user = JSON.parse(storedUser)
// We need a better system here to verify a user from localStorage
// is who they say they are, and additionally verify the JWT token
// const created = Math.round(createdDate.getTime() / 1000)
// const ttl = 1209600
// const expiry = created + ttl
// if the user has expired return false
// if (created > expiry) return false
dispatch(setClient(user))
return verifyUser(user)
}
return false
}
export function isAuthorizedUser(user, dispatch) {
if (!isUser(user))
return checkStoredAuthorization(dispatch, isUser)
return true
}
export function isAuthorizedAdmin(user, dispatch) {
if (!isUser(user))
return checkStoredAuthorization(dispatch, isAdmin)
return isAdmin(user)
}
|
Implement $.zepto.isZ in IE support module | // Zepto.js
// (c) 2010-2013 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function(){
// __proto__ doesn't exist on IE<11, so redefine
// the Z function to use object extension instead
if (!('__proto__' in {})) {
$.extend($.zepto, {
Z: function(dom, selector){
dom = dom || []
$.extend(dom, $.fn)
dom.selector = selector || ''
dom.__Z = true
return dom
},
// this is a kludge but works
isZ: function(object){
return $.type(object) === 'array' && '__Z' in object
}
})
}
// getComputedStyle shouldn't freak out when called
// without a valid element as argument
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})()
| // Zepto.js
// (c) 2010-2013 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function(){
// __proto__ doesn't exist on IE<11, so redefine
// the Z function to use object extension instead
if (!('__proto__' in {})) {
$.extend($.zepto, {
Z: function(dom, selector) {
dom = dom || []
$.extend(dom, $.fn)
dom.selector = selector || ''
return dom
}
})
}
// getComputedStyle shouldn't freak out when called
// without a valid element as argument
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})()
|
Add the scroll top when switch channel | define([
'jquery',
'underscore',
'backbone',
'router',
'jquerySidr'
], function($, _, Backbone, Router){
var initialize = function(){
$(document).ready(function() {
$('#sidr').show();
$('#menu').sidr();
$("#sidr li a" ).bind('touchstart click', function() {
if(null != Backbone.history.fragment){
_.each($("#sidr li"),function(li){
$(li).removeClass()
});
$('a[href$="#/'+Backbone.history.fragment+'"]').parent().addClass("active");
$.sidr('close');
window.scrollTo(0,0);
}
});
});
Router.initialize();
};
return {
initialize: initialize
};
});
| define([
'jquery',
'underscore',
'backbone',
'router',
'jquerySidr'
], function($, _, Backbone, Router){
var initialize = function(){
$(document).ready(function() {
$('#sidr').show();
$('#menu').sidr();
$("#sidr li a" ).bind('touchstart click', function() {
if(null != Backbone.history.fragment){
_.each($("#sidr li"),function(li){
$(li).removeClass()
});
$('a[href$="#/'+Backbone.history.fragment+'"]').parent().addClass("active");
$.sidr('close');
}
});
});
Router.initialize();
};
return {
initialize: initialize
};
});
|
Test HTML mapping works for nested innerHTML. | import {enableTracing, disableTracing} from "./tracing/tracing"
import getRootOriginAtChar from "./getRootOriginAtChar"
import {disableProcessHTMLOnInitialLoad} from "./tracing/processElementsAvailableOnInitialLoad"
disableProcessHTMLOnInitialLoad()
fdescribe("HTML Mapping", function(){
beforeEach(function(){
enableTracing()
})
afterEach(function(){
disableTracing()
})
it("Traces a basic string assignment", function(){
var el = document.createElement("div")
el.innerHTML = "Hello"
// <[d]iv>Hello</div>
expect(getRootOriginAtChar(el, 1).origin.action).toBe("createElement")
// <div>[H]ello</div>
var originAndChar = getRootOriginAtChar(el, 5);
expect(originAndChar.origin.action).toBe("Assign InnerHTML")
expect(originAndChar.origin.value[originAndChar.characterIndex]).toBe("H")
})
it("Traces nested HTML assignments", function(){
var el = document.createElement("div")
el.innerHTML = 'Hello <b>World</b>!'
var bTag = el.children[0]
// <b>[W]orld</b>
var originAndChar = getRootOriginAtChar(bTag, 3);
expect(originAndChar.origin.action).toBe("Assign InnerHTML")
expect(originAndChar.origin.value[originAndChar.characterIndex]).toBe("W")
})
})
| import {enableTracing, disableTracing} from "./tracing/tracing"
import getRootOriginAtChar from "./getRootOriginAtChar"
import {disableProcessHTMLOnInitialLoad} from "./tracing/processElementsAvailableOnInitialLoad"
disableProcessHTMLOnInitialLoad()
fdescribe("HTML Mapping", function(){
beforeEach(function(){
enableTracing()
})
afterEach(function(){
disableTracing()
})
it("Traces a basic string assignment", function(){
var el = document.createElement("div")
el.innerHTML = "Hello"
// <[d]iv>Hello</div>
expect(getRootOriginAtChar(el, 1).origin.action).toBe("createElement")
// <div>[H]ello</div>
var originAndChar = getRootOriginAtChar(el, 5);
expect(originAndChar.origin.action).toBe("Assign InnerHTML")
expect(originAndChar.origin.value[originAndChar.characterIndex]).toBe("H")
})
})
|
Update to NuGet v3.4.2 to allow use of environment variables | const fs = require('fs');
const request = require('request');
const nuget = './nuget.exe';
console.info(`Downloading 'nuget.exe'...`);
console.info();
request
.get('https://dist.nuget.org/win-x86-commandline/v3.4.2-rc/nuget.exe')
.on('error', function (err) {
console.error(err);
})
.on('response', function (response) {
if (response.statusCode == 200) {
console.info(`Successfully downloaded 'nuget.exe'.`);
} else {
console.error(`Downloading 'nuget.exe' failed. statusCode '${response.statusCode}'`);
}
})
.pipe(fs.createWriteStream(nuget));
| const fs = require('fs');
const request = require('request');
const nuget = './nuget.exe';
console.info(`Downloading 'nuget.exe'...`);
console.info();
request
.get('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe')
.on('error', function (err) {
console.error(err);
})
.on('response', function (response) {
if (response.statusCode == 200) {
console.info(`Successfully downloaded 'nuget.exe'.`);
} else {
console.error(`Downloading 'nuget.exe' failed. statusCode '${response.statusCode}'`);
}
})
.pipe(fs.createWriteStream(nuget));
|
Split user settings test into two tests | import django_webtest
import django.contrib.auth.models as auth_models
import pylab.accounts.models as accounts_models
class SettingsTests(django_webtest.WebTest):
def setUp(self):
super().setUp()
auth_models.User.objects.create_user('u1')
def test_user_settings(self):
resp = self.app.get('/accounts/settings/', user='u1')
resp.form['first_name'] = 'My'
resp.form['last_name'] = 'Name'
resp.form['email'] = ''
resp = resp.form.submit()
self.assertEqual(resp.status_int, 302)
self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [
('My', 'Name', ''),
])
def test_userprofile_settings(self):
resp = self.app.get('/accounts/settings/', user='u1')
resp.form['language'] = 'en'
resp = resp.form.submit()
self.assertEqual(resp.status_int, 302)
self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),])
| import django_webtest
import django.contrib.auth.models as auth_models
import pylab.accounts.models as accounts_models
class SettingsTests(django_webtest.WebTest):
def setUp(self):
super().setUp()
auth_models.User.objects.create_user('u1')
def test_settings(self):
resp = self.app.get('/accounts/settings/', user='u1')
resp.form['first_name'] = 'My'
resp.form['last_name'] = 'Name'
resp.form['email'] = ''
resp.form['language'] = 'en'
resp = resp.form.submit()
self.assertEqual(resp.status_int, 302)
self.assertEqual(list(auth_models.User.objects.values_list('first_name', 'last_name', 'email')), [
('My', 'Name', ''),
])
self.assertEqual(list(accounts_models.UserProfile.objects.values_list('language')), [('en',),])
|
Update to Flask-Login 0.2.2 and bump version number | """
Flask-GoogleLogin
-----------------
Flask-GoogleLogin extends Flask-Login to use Google's OAuth2 authorization
Links
`````
* `documentation <http://packages.python.org/Flask-GoogleLogin>`_
* `development version <https://github.com/marksteve/flask-googlelogin>`_
"""
from setuptools import setup
setup(
name='Flask-GoogleLogin',
version='0.1.6',
url='https://github.com/marksteve/flask-googlelogin',
license='MIT',
author="Mark Steve Samson",
author_email='hello@marksteve.com',
description="Extends Flask-Login to use Google's OAuth2 authorization",
long_description=__doc__,
py_modules=['flask_googlelogin'],
zip_safe=False,
platforms='any',
install_requires=[
'requests<1.0',
'Flask-Login==0.2.2',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| """
Flask-GoogleLogin
-----------------
Flask-GoogleLogin extends Flask-Login to use Google's OAuth2 authorization
Links
`````
* `documentation <http://packages.python.org/Flask-GoogleLogin>`_
* `development version <https://github.com/marksteve/flask-googlelogin>`_
"""
from setuptools import setup
setup(
name='Flask-GoogleLogin',
version='0.1.5',
url='https://github.com/marksteve/flask-googlelogin',
license='MIT',
author="Mark Steve Samson",
author_email='hello@marksteve.com',
description="Extends Flask-Login to use Google's OAuth2 authorization",
long_description=__doc__,
py_modules=['flask_googlelogin'],
zip_safe=False,
platforms='any',
install_requires=[
'requests<1.0',
'Flask-Login==0.1.3',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Widgets: Use 'load' over 'DOMContentLoaded' to wait for stylesheets. | (function () {
if (!window.postMessage || window.self === window.top) {
return;
}
function reportWidgetSize() {
var D, height, sizeMessage;
D = document;
height = Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
sizeMessage = 'hdo-widget-size:' + height + 'px';
// no sensitive data is being sent here, so * is fine.
window.top.postMessage(sizeMessage, '*');
}
if (window.addEventListener) { // W3C DOM
window.addEventListener('load', reportWidgetSize, false);
} else if (window.attachEvent) { // IE DOM
window.attachEvent("onload", reportWidgetSize);
}
}());
| (function () {
if (!window.postMessage || window.self === window.top) {
return;
}
function reportWidgetSize() {
var D, height, sizeMessage;
D = document;
height = Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
sizeMessage = 'hdo-widget-size:' + height + 'px';
// no sensitive data is being sent here, so * is fine.
window.top.postMessage(sizeMessage, '*');
}
if (window.addEventListener) { // W3C DOM
window.addEventListener('DOMContentLoaded', reportWidgetSize, false);
} else if (window.attachEvent) { // IE DOM
window.attachEvent("onreadystatechange", reportWidgetSize);
}
}());
|
Make default ALA's date the day before yesterday | import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data'
def add_arguments(self, parser):
parser.add_argument('date', nargs='?', type=parse, default=None)
def handle(self, *args, **options):
stations = util.get_or_create_stations()
day = options['date']
if day is None:
day = date.today() - timedelta(2)
logger.info(
'Importing observations of {} ALA stations from {}.'.format(
len(stations),
day
)
)
try:
for station in stations:
util.load(station, day)
util.create_avgs(station, day)
except Exception as e:
self.stdout.write(self.style.ERROR(e))
| import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data'
def add_arguments(self, parser):
parser.add_argument('date', nargs='?', type=parse, default=None)
def handle(self, *args, **options):
stations = util.get_or_create_stations()
day = options['date']
if day is None:
day = date.today() - timedelta(1)
logger.info(
'Importing observations of {} ALA stations from {}.'.format(
len(stations),
day
)
)
try:
for station in stations:
util.load(station, day)
util.create_avgs(station, day)
except Exception as e:
self.stdout.write(self.style.ERROR(e))
|
Add fields for targets and actions | package net.alcuria.umbracraft.definitions.skill;
import net.alcuria.umbracraft.annotations.Tooltip;
import net.alcuria.umbracraft.definitions.Definition;
import net.alcuria.umbracraft.definitions.skill.actions.SkillActionDefinition;
import com.badlogic.gdx.utils.Array;
public class SkillDefinition extends Definition {
@Tooltip("The action sequence when using the skill")
public Array<SkillActionDefinition> actions;
@Tooltip("The multiplier of the base damage")
public float damageMultiplier;
@Tooltip("The cost to use the skill, in EP")
public int epCost;
@Tooltip("The icon to use for the skill")
public String iconId;
public float maxPercentageCost;
@Tooltip("The name of the skill")
public String name;
@Tooltip("The targets of the skill, relative to the drop point")
public Array<SkillPositionDefinition> targets;
@Tooltip("The ATB cost of the skill, in turns")
public float turnCost;
@Override
public String getName() {
return name != null ? name : "Skill";
}
}
| package net.alcuria.umbracraft.definitions.skill;
import net.alcuria.umbracraft.annotations.Tooltip;
import net.alcuria.umbracraft.definitions.Definition;
import com.badlogic.gdx.utils.Array;
public class SkillDefinition extends Definition {
@Tooltip("The multiplier of the base damage")
public float damageMultiplier;
@Tooltip("The cost to use the skill, in EP")
public int epCost;
@Tooltip("The icon to use for the skill")
public String iconId;
public float maxPercentageCost;
@Tooltip("The name of the skill")
public String name;
@Tooltip("The targets of the skill, relative to the drop point")
public Array<SkillPositionDefinition> target;
@Tooltip("The ATB cost of the skill, in turns")
public float turnCost;
@Override
public String getName() {
return name != null ? name : "Skill";
}
}
|
Enable Dates test for select tests with literals | /*
* Copyright 2013, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query;
public class SelectUseLiteralsBase extends SelectBase {
public SelectUseLiteralsBase() {
configuration.setUseLiterals(true);
}
@Override
public void Limit_and_Offset2() {
// not supported
}
@Override
public void Path_Alias() {
// not supported
}
}
| /*
* Copyright 2013, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query;
public class SelectUseLiteralsBase extends SelectBase {
public SelectUseLiteralsBase() {
configuration.setUseLiterals(true);
}
@Override
public void Dates() {
// not supported
}
@Override
public void Limit_and_Offset2() {
// not supported
}
@Override
public void Path_Alias() {
// not supported
}
}
|
Allow for a wildcard address | import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
def main(address_pattern=None):
my_name = input("Name: ")
nw0.advertise(my_name, address_pattern)
while True:
services = [(name, address) for (name, address) in nw0.discover_all() if name != my_name]
for name, address in services:
topic, message = nw0.wait_for_notification(address, "quote", wait_for_s=0)
if topic:
print("%s says: %s" % (name, message))
quote = random.choice(quotes)
nw0.send_notification(address, "quote", quote)
time.sleep(0.5)
if __name__ == '__main__':
main(*sys.argv[1:])
| import sys
print(sys.version_info)
import random
import time
import networkzero as nw0
quotes = [
"Humpty Dumpty sat on a wall",
"Hickory Dickory Dock",
"Baa Baa Black Sheep",
"Old King Cole was a merry old sould",
]
my_name = input("Name: ")
nw0.advertise(my_name)
while True:
services = [(name, address) for (name, address) in nw0.discover_all() if name != my_name]
for name, address in services:
topic, message = nw0.wait_for_notification(address, "quote", wait_for_s=0)
if topic:
print("%s says: %s" % (name, message))
quote = random.choice(quotes)
nw0.send_notification(address, "quote", quote)
time.sleep(0.5)
|
Remove non-needed merge when setting Listener component state | const React = require("react")
export class Listener extends React.Component {
constructor(props) {
super(props)
const {dispatcher, initialState} = this.props
const ffux = dispatcher(initialState)
this.state = {
ffux,
model: {
state: ffux.getInitialState(),
actions: ffux.getActions()
}
}
}
componentWillMount() {
this.setState({
stop: this.state.ffux.listen(model => this.setState({model}))
})
}
componentWillReceiveProps(nextProps) {
const {dispatcher} = nextProps
const prevDispatcher = this.state.dispatcher
if (dispatcher !== prevDispatcher) {
if (this.state.stop) {
this.state.stop()
}
const ffux = dispatcher(this.state.model.state)
this.setState({
ffux,
dispatcher,
stop: ffux.listen(model => this.setState({model}))
})
}
}
render() {
return React.cloneElement(this.props.children, this.state.model)
}
}
| const React = require("react")
const {merge} = require("./util")
export class Listener extends React.Component {
constructor(props) {
super(props)
const {dispatcher, initialState} = this.props
const ffux = dispatcher(initialState)
this.state = {
ffux,
model: {
state: ffux.getInitialState(),
actions: ffux.getActions()
}
}
}
componentWillMount() {
this.setState(merge(this.state, {
stop: this.state.ffux.listen(model => this.setState(merge(this.state, {model})))
}))
}
componentWillReceiveProps(nextProps) {
const {dispatcher} = nextProps
const prevDispatcher = this.state.dispatcher
if (dispatcher !== prevDispatcher) {
if (this.state.stop) {
this.state.stop()
}
const ffux = dispatcher(this.state.model.state)
this.setState(merge(this.state, {
ffux,
dispatcher,
stop: ffux.listen(model => this.setState(merge(this.state, {model})))
}))
}
}
render() {
return React.cloneElement(this.props.children, this.state.model)
}
}
|
Add a test for django model inheritance of the foreign key kind. | from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
class PositionedTag(Tag):
position = models.IntegerField()
| from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')
class Admin:
pass
def __unicode__(self):
return "<Poll '%s'>" % self.question
class Tag(models.Model):
name = models.CharField(max_length=200)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
tags = models.ManyToManyField(Tag)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
class Admin:
pass
def __unicode__(self):
return "<Choice '%s'>" % self.choice
class SelfRef(models.Model):
parent = models.ForeignKey('self',null=True)
name = models.CharField(max_length=50)
class MultiSelfRef(models.Model):
name = models.CharField(max_length=50)
ref = models.ManyToManyField('self')
|
Make root node able to execute itself | package org.hummingbirdlang.nodes;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.source.SourceSection;
import org.hummingbirdlang.HBLanguage;
import org.hummingbirdlang.types.realize.InferenceVisitor;
import org.hummingbirdlang.types.realize.Visitable;
public class HBSourceRootNode extends RootNode implements Visitable {
@Child private HBBlockNode bodyNode;
public HBSourceRootNode(SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) {
super(HBLanguage.class, sourceSection, frameDescriptor);
this.bodyNode = bodyNode;
}
public void accept(InferenceVisitor visitor) {
visitor.enter(this);
this.bodyNode.accept(visitor);
visitor.leave(this);
}
@Override
public Object execute(VirtualFrame frame) {
this.bodyNode.executeVoid(frame);
return null;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("HBSourceRootNode(");
result.append(bodyNode.toString());
result.append(")");
return result.toString();
}
}
| package org.hummingbirdlang.nodes;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.source.SourceSection;
import org.hummingbirdlang.HBLanguage;
import org.hummingbirdlang.types.realize.InferenceVisitor;
import org.hummingbirdlang.types.realize.Visitable;
public class HBSourceRootNode extends RootNode implements Visitable {
@Child private HBBlockNode bodyNode;
public HBSourceRootNode(SourceSection sourceSection, FrameDescriptor frameDescriptor, HBBlockNode bodyNode) {
super(HBLanguage.class, sourceSection, frameDescriptor);
this.bodyNode = bodyNode;
}
public void accept(InferenceVisitor visitor) {
visitor.enter(this);
this.bodyNode.accept(visitor);
visitor.leave(this);
}
@Override
public Object execute(VirtualFrame frame) {
return null;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("HBSourceRootNode(");
result.append(bodyNode.toString());
result.append(")");
return result.toString();
}
}
|
Remove vm. for local variable in function.
– SAAS-116 | 'use strict';
(function() {
angular.module('ncsaas')
.service('BodyClassService', [BodyClassService]);
function BodyClassService() {
var vm = this;
vm.getBodyClass = getBodyClass;
function getBodyClass(name) {
var bodyClass;
var stateWithProfile = [
'profile',
'profile-edit',
'project',
'project-edit',
'customer',
'customer-edit',
'customer-plans',
'user',
'home',
'login',
];
if (stateWithProfile.indexOf(name) > -1 ) {
if (name === 'login' || name === 'home') {
bodyClass = 'app-body site-body';
return bodyClass;
} else {
bodyClass = 'app-body obj-view';
return bodyClass;
}
} else {
bodyClass = 'app-body'
return bodyClass;
}
}
}
})();
| 'use strict';
(function() {
angular.module('ncsaas')
.service('BodyClassService', [BodyClassService]);
function BodyClassService() {
var vm = this;
vm.getBodyClass = getBodyClass;
function getBodyClass(name) {
var stateWithProfile = [
'profile',
'profile-edit',
'project',
'project-edit',
'customer',
'customer-edit',
'customer-plans',
'user',
'home',
'login',
];
if (stateWithProfile.indexOf(name) > -1 ) {
if (name === 'login' || name === 'home') {
vm.bodyClass = 'app-body site-body';
return vm.bodyClass;
} else {
vm.bodyClass = 'app-body obj-view';
return vm.bodyClass;
}
} else {
vm.bodyClass = 'app-body'
return vm.bodyClass;
}
}
}
})();
|
Add default description on client side | import { connect } from 'react-redux';
import Profile from '../components/Profile.jsx';
import { completeUpdate } from '../actions/index.js';
import request from 'then-request';
const mapStateToProps = (state) => ({
profile: state.profile,
});
const mapDispatchToProps = (dispatch) => ({
onUpdateClick: (profile) => {
// send put request to server
request('PUT', '/api/profile', {
json: {
id: profile.id,
languages: profile.languages,
description: profile.description || 'Click here to edit!',
},
})
.done(data => {
if (data.statusCode === 200) {
dispatch(completeUpdate());
}
});
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
| import { connect } from 'react-redux';
import Profile from '../components/Profile.jsx';
import { completeUpdate } from '../actions/index.js';
import request from 'then-request';
const mapStateToProps = (state) => ({
profile: state.profile,
});
const mapDispatchToProps = (dispatch) => ({
onUpdateClick: (profile) => {
// send put request to server
request('PUT', '/api/profile', {
json: {
id: profile.id,
languages: profile.languages,
description: profile.description,
},
})
.done(data => {
if (data.statusCode === 200) {
dispatch(completeUpdate());
}
});
},
});
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
|
Add height and width to adsense ads | <?php
namespace ATPAdvertising\View\Helper;
class Adsense extends \ATP\View\Helper
{
public function __invoke($id)
{
$ad = new \ATPAdvertising\Model\AdsenseAd();
$ad->loadByIdentifier($id);
return "
<script async src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script>
<ins class=\"adsbygoogle\"
style=\"display:inline-block;width:{$ad->width}px;height:{$ad->height}px\"
data-ad-client=\"{$ad->publisher}\"
data-ad-slot=\"{$ad->adId}\"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
";
}
}
| <?php
namespace ATPAdvertising\View\Helper;
class Adsense extends \ATP\View\Helper
{
public function __invoke($id)
{
$ad = new \ATPAdvertising\Model\AdsenseAd();
$ad->loadByIdentifier($id);
return "
<script async src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script>
<ins class=\"adsbygoogle\"
style=\"display:inline-block;width:728px;height:90px\"
data-ad-client=\"{$ad->publisher}\"
data-ad-slot=\"{$ad->adId}\"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
";
}
}
|
Add settings to svg sprite task | 'use strict';
if (!config.tasks.svgSprite) {
return false;
}
const svgstore = require('gulp-svgstore');
let paths = {
src: path.join(config.root.base, config.root.src, config.tasks.svgSprite.src, getExtensions(config.tasks.svgSprite.extensions)),
dest: path.join(config.root.base, config.root.dest, config.tasks.svgSprite.dest)
};
function svgSprite() {
return gulp.src(paths.src, {since: cache.lastMtime('svgSprite')})
.pipe(plumber(handleErrors))
.pipe(rename(path => {
path.basename = 'icon-' + path.basename.toLowerCase();
}))
.pipe(cache('svgSprite'))
.pipe(imagemin([imagemin.svgo({plugins:[config.tasks.svgSprite.svgo]})]))
.pipe(svgstore())
.pipe(gulp.dest(paths.dest))
.pipe(size({
title: 'SVG:',
showFiles: true
})
);
}
module.exports = svgSprite;
| 'use strict';
if (!config.tasks.svgSprite) {
return false;
}
const svgstore = require('gulp-svgstore');
let paths = {
src: path.join(config.root.base, config.root.src, config.tasks.svgSprite.src, getExtensions(config.tasks.svgSprite.extensions)),
dest: path.join(config.root.base, config.root.dest, config.tasks.svgSprite.dest)
};
function svgSprite() {
return gulp.src(paths.src, {since: cache.lastMtime('svgSprite')})
.pipe(plumber(handleErrors))
.pipe(rename(path => {
path.basename = 'icon-' + path.basename.toLowerCase();
}))
.pipe(cache('svgSprite'))
.pipe(imagemin())
.pipe(svgstore())
.pipe(gulp.dest(paths.dest))
.pipe(size({
title: 'SVG:',
showFiles: true
})
);
}
module.exports = svgSprite;
|
Remove a don't-know-why-it's-still-there parameter: login_url | from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone
from django.contrib import auth
from django.conf import settings
from onetime import utils
from onetime.models import Key
def cleanup(request):
utils.cleanup()
return HttpResponse('ok', content_type='text/plain')
def login(request, key):
next = request.GET.get('next', None)
if next is None:
next = settings.LOGIN_REDIRECT_URL
user = auth.authenticate(key=key)
if user is None:
url = settings.LOGIN_URL
if next is not None:
url = '%s?next=%s' % (url, next)
return HttpResponseRedirect(url)
auth.login(request, user)
data = Key.objects.get(key=key)
data.update_usage()
if data.next is not None:
next = data.next
return HttpResponseRedirect(next)
| from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone
from django.contrib import auth
from django.conf import settings
from onetime import utils
from onetime.models import Key
def cleanup(request):
utils.cleanup()
return HttpResponse('ok', content_type='text/plain')
def login(request, key, login_url=None):
next = request.GET.get('next', None)
if next is None:
next = settings.LOGIN_REDIRECT_URL
user = auth.authenticate(key=key)
if user is None:
url = settings.LOGIN_URL
if next is not None:
url = '%s?next=%s' % (url, next)
return HttpResponseRedirect(url)
auth.login(request, user)
data = Key.objects.get(key=key)
data.update_usage()
if data.next is not None:
next = data.next
return HttpResponseRedirect(next)
|
Use proper CSS class for pairing view | module.exports = Backbone.View.extend({
className: 'main_pairing main_wrap',
initialize: function(){
var self = this
self.$el.html(ss.tmpl['main-pairing'].render()).appendTo('.dash .main').addClass('animated fadeInUp')
self.display_qr();
},
clear: function(){
var self = this
self.$el.removeClass('animated fadeInUp')
self.$el.addClass('animatedQuick fadeOutUp')
setTimeout(function(){
self.$el.remove()
}, 500)
},
display_qr: function(){
var self = this
self.user.get_server_address(function(err, address){
if (err) return alert('Getting server address failed: ' + err.message)
self.user.create_pairing_token(function(err_, token){
if (err_) return alert('Pairing failed: ' + err_.message)
var qr = { // Compress the structure a bit.
a: {
h: address.host,
p: address.port,
f: address.fingerprint.replace(/:/g, '')
},
t: token
};
new QRCode(document.getElementById('qrcode'), JSON.stringify(qr))
})
})
}
})
| module.exports = Backbone.View.extend({
className: 'main_price main_wrap',
initialize: function(){
var self = this
self.$el.html(ss.tmpl['main-pairing'].render()).appendTo('.dash .main').addClass('animated fadeInUp')
self.display_qr();
},
clear: function(){
var self = this
self.$el.removeClass('animated fadeInUp')
self.$el.addClass('animatedQuick fadeOutUp')
setTimeout(function(){
self.$el.remove()
}, 500)
},
display_qr: function(){
var self = this
self.user.get_server_address(function(err, address){
if (err) return alert('Getting server address failed: ' + err.message)
self.user.create_pairing_token(function(err_, token){
if (err_) return alert('Pairing failed: ' + err_.message)
var qr = { // Compress the structure a bit.
a: {
h: address.host,
p: address.port,
f: address.fingerprint.replace(/:/g, '')
},
t: token
};
new QRCode(document.getElementById('qrcode'), JSON.stringify(qr))
})
})
}
})
|
Update version to 0.4.1 for release | """EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.4.1"
# Implement NullHandler because it was only added in Python 2.7+.
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Create a logger, but by default, have it do nothing
_log = logging.getLogger('evelink')
_log.addHandler(NullHandler())
# Update the version number used in the user-agent
api._user_agent = 'evelink v%s' % __version__
__all__ = [
"account",
"api",
"char",
"constants",
"corp",
"eve",
"map",
"parsing",
"server",
]
| """EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.4.0"
# Implement NullHandler because it was only added in Python 2.7+.
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Create a logger, but by default, have it do nothing
_log = logging.getLogger('evelink')
_log.addHandler(NullHandler())
# Update the version number used in the user-agent
api._user_agent = 'evelink v%s' % __version__
__all__ = [
"account",
"api",
"char",
"constants",
"corp",
"eve",
"map",
"parsing",
"server",
]
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/'))
print dbs
dbs = dbs.split('(')[0]
print dbs
# dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
#
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = AdminConfig.list('DataSource', AdminConfig.getid('/Cell:cnxwas1Cell01/'))
print dbs
# dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
#
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' ) |
DEVOPS-42: Fix webapp password reset link | from django.contrib.auth import views
from django.urls import path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
path(
r"account/reset/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
| from django.contrib.auth import views
from django.urls import path, re_path
from accounts.forms import LoginForm, PasswordResetForm, SetPasswordForm
urlpatterns = [
path(
"login/",
views.LoginView.as_view(
template_name="accounts/login.html", authentication_form=LoginForm
),
name="login",
),
path("logout/", views.LogoutView.as_view(), name="logout"),
# Password reset
path(
"account/password_reset/",
views.PasswordResetView.as_view(form_class=PasswordResetForm),
name="password_reset",
),
path(
"account/password_reset/done/",
views.PasswordResetDoneView.as_view(),
name="password_reset_done",
),
re_path(
r"^account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$",
views.PasswordResetConfirmView.as_view(form_class=SetPasswordForm),
name="password_reset_confirm",
),
path(
"account/reset/done/",
views.PasswordResetCompleteView.as_view(),
name="password_reset_complete",
),
]
|
Put dt in the wrong spot! | 'use strict';
var config = require('../config');
var Backbone = require('backbone');
var User = require('./user');
var World = module.exports = Backbone.Model.extend({
initialize: function () {
this.users = new User.Collection();
console.log(this.users);
},
// control flow
step: function () {
var now = Date.now();
var dt = (now - this.lastStep) / 1000;
this.lastStep = now;
this.users.invoke('step', dt);
// this.users.checkCollisions();
this.trigger('step', this.users.invoke('toFrame'));
},
start: function () {
if (this.running) {
console.error('game already running!');
} else {
this.lastStep = Date.now();
this.running = setInterval(this.step.bind(this), 1000 / config.world.fps);
console.log('game started!');
}
},
stop: function () {
if (!this.running) {
console.error('game not currently running!');
} else {
console.log('game stopped!');
clearInterval(this.running);
}
}
});
World.Collection = Backbone.Collection.extend({
model: World
});
| 'use strict';
var config = require('../config');
var Backbone = require('backbone');
var User = require('./user');
var World = module.exports = Backbone.Model.extend({
initialize: function () {
this.users = new User.Collection();
console.log(this.users);
},
// control flow
step: function () {
var now = Date.now();
var dt = (now - this.lastStep) / 1000;
this.lastStep = now;
this.users.invoke('step', this);
// this.users.checkCollisions();
this.trigger('step', this.users.invoke('toFrame', dt));
},
start: function () {
if (this.running) {
console.error('game already running!');
} else {
this.lastStep = Date.now();
this.running = setInterval(this.step.bind(this), 1000 / config.world.fps);
console.log('game started!');
}
},
stop: function () {
if (!this.running) {
console.error('game not currently running!');
} else {
console.log('game stopped!');
clearInterval(this.running);
}
}
});
World.Collection = Backbone.Collection.extend({
model: World
});
|
Rename argument, remove unusued one | <?php
/**
* @file
* Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginBlockGenerator extends Generator
{
/**
* Generator Plugin Block
* @param $module
* @param $class_name
* @param $plugin_label
* @param $plugin_id
* @param $services
*/
public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
{
$parameters = [
'module' => $module,
'class_name' => $class_name,
'plugin_label' => $plugin_label,
'plugin_id' => $plugin_id,
'services' => $services,
];
$this->renderFile(
'module/plugin-block.php.twig',
$this->getPluginPath($module, 'Block').'/'.$class_name.'.php',
$parameters
);
}
}
| <?php
/**
* @file
* Contains \Drupal\AppConsole\Generator\PluginBlockGenerator.
*/
namespace Drupal\AppConsole\Generator;
class PluginBlockGenerator extends Generator
{
/**
* Generator Plugin Block
* @param $module
* @param $class_name
* @param $plugin_label
* @param $plugin_id
* @param $services
*/
public function generate($module, $class_name, $plugin_label, $plugin_id, $services)
{
$parameters = [
'module' => $module,
'class' => [
'name' => $class_name,
'underscore' => $this->camelCaseToUnderscore($class_name)
],
'plugin_label' => $plugin_label,
'plugin_id' => $plugin_id,
'services' => $services,
];
$this->renderFile(
'module/plugin-block.php.twig',
$this->getPluginPath($module, 'Block').'/'.$class_name.'.php',
$parameters
);
}
}
|
Use preferred library.type for webpack | module.exports = {
mode: 'production',
output: {
filename: 'd3-funnel.js',
library: {
name: 'D3Funnel',
type: 'umd',
},
},
externals: {
// Do not compile d3 with the output
// In non-CommonJS, allows window.d3 to be used
// In CommonJS, this will use the included d3 package
d3: 'd3',
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
},
],
},
};
| module.exports = {
mode: 'production',
output: {
filename: 'd3-funnel.js',
libraryTarget: 'umd',
library: 'D3Funnel',
},
externals: {
// Do not compile d3 with the output
// In non-CommonJS, allows window.d3 to be used
// In CommonJS, this will use the included d3 package
d3: 'd3',
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
},
],
},
};
|
Update expected number of attributes in datasource test for WF10 | package org.wildfly.apigen.test.model;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.apigen.test.AbstractTestCase;
import org.wildfly.apigen.model.AddressTemplate;
import org.wildfly.apigen.model.DefaultStatementContext;
import org.wildfly.apigen.model.ResourceDescription;
import org.wildfly.apigen.operations.ReadDescription;
/**
* Verifies the Model API helper classes and it usage
*
* @author Heiko Braun
* @since 29/07/15
*/
public class ModelAPITestCase extends AbstractTestCase {
@Test
public void testResourceDescriptionParsing() throws Exception {
AddressTemplate address = AddressTemplate.of("/subsystem=datasources/data-source=*");
ReadDescription op = new ReadDescription(address);
ModelNode response = client.execute(op.resolve(new DefaultStatementContext()));
ResourceDescription description = ResourceDescription.from(response);
Assert.assertNotNull(description.getText());
Assert.assertEquals(59, description.getAttributes().size());
}
}
| package org.wildfly.apigen.test.model;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.apigen.test.AbstractTestCase;
import org.wildfly.apigen.model.AddressTemplate;
import org.wildfly.apigen.model.DefaultStatementContext;
import org.wildfly.apigen.model.ResourceDescription;
import org.wildfly.apigen.operations.ReadDescription;
/**
* Verifies the Model API helper classes and it usage
*
* @author Heiko Braun
* @since 29/07/15
*/
public class ModelAPITestCase extends AbstractTestCase {
@Test
public void testResourceDescriptionParsing() throws Exception {
AddressTemplate address = AddressTemplate.of("/subsystem=datasources/data-source=*");
ReadDescription op = new ReadDescription(address);
ModelNode response = client.execute(op.resolve(new DefaultStatementContext()));
ResourceDescription description = ResourceDescription.from(response);
Assert.assertNotNull(description.getText());
Assert.assertEquals(57, description.getAttributes().size());
}
}
|
Add error handling on individual websockets too | const WebSocket = require('ws');
const ConnectionPool = require('./connection-pool.js');
const port = 3000;
class Server {
constructor() {
this.conPool = new ConnectionPool();
}
start() {
const wss = new WebSocket.Server({ port: port });
log('Listening on port %d...', port);
try {
wss.on('connection', ws => {
ws.on('error', e => log('ws error:\n', e));
try {
log('New Connection');
this.conPool.newVisitor(ws);
} catch(e) {
log('ERROR handling new Visitor:\n',e);
}
});
} catch(e) {
log('ERROR listening for connections:\n', e);
}
wss.on('error', e => log('Wss error:\n', e));
}
}
module.exports = { Server };
| const WebSocket = require('ws');
const ConnectionPool = require('./connection-pool.js');
const port = 3000;
class Server {
constructor() {
this.conPool = new ConnectionPool();
}
start() {
const wss = new WebSocket.Server({ port: port });
log('Listening on port %d...', port);
try {
wss.on('connection', ws => {
try {
log('New Connection');
this.conPool.newVisitor(ws);
} catch(e) {
log('ERROR handling new Visitor:\n',e);
}
});
} catch(e) {
log('ERROR listening for connections:\n', e);
}
wss.on('error', e => log('Wss error:\n', e));
}
}
module.exports = { Server };
|
Fix checking using in_array instead | <?php
namespace Endroid\PredictionIO\Model;
/**
* Class EntityEvent
*
* @package Endroid\PredictionIO\Model
*/
class EntityEvent extends AbstractEvent
{
static $AVAILABLE_EVENTS = ['$set', '$unset', '$delete'];
/**
* @param string $event
* @param string $entityType
* @param string $entityId
*/
public function __construct($event, $entityType, $entityId)
{
$this->checkEvent($event);
parent::__construct($event, $entityType, $entityId);
$this->setEventType(self::EVENT_TYPE_ENTITY);
}
/**
* @inheritdoc
*/
public function supportsTargetEntity()
{
return false;
}
/**
* @param $event
*
* @throws \InvalidArgumentException
*/
public function checkEvent($event)
{
if (!in_array($event, self::$AVAILABLE_EVENTS)) {
throw new \InvalidArgumentException(sprintf("Unsupported event: `%s`, available events: `%s`",
$event,
implode(', ', self::$AVAILABLE_EVENTS)
)
);
}
}
} | <?php
namespace Endroid\PredictionIO\Model;
/**
* Class EntityEvent
*
* @package Endroid\PredictionIO\Model
*/
class EntityEvent extends AbstractEvent
{
static $AVAILABLE_EVENTS = ['$set', '$unset', '$delete'];
/**
* @param string $event
* @param string $entityType
* @param string $entityId
*/
public function __construct($event, $entityType, $entityId)
{
$this->checkEvent($event);
parent::__construct($event, $entityType, $entityId);
$this->setEventType(self::EVENT_TYPE_ENTITY);
}
/**
* @inheritdoc
*/
public function supportsTargetEntity()
{
return false;
}
/**
* @param $event
*
* @throws \InvalidArgumentException
*/
public function checkEvent($event)
{
if (!isset(self::$AVAILABLE_EVENTS[$event])) {
throw new \InvalidArgumentException(sprintf("Unsupported event: `%s`, available events: `%s`",
$event,
implode(', ', self::$AVAILABLE_EVENTS)
)
);
}
}
} |
Allow for inline-graphic in table cell. | import { XMLTextElement } from 'substance'
import { TEXT } from '../kit'
export default class TableCellNode extends XMLTextElement {
constructor (...args) {
super(...args)
this.rowIdx = -1
this.colIdx = -1
}
get rowspan () {
return _parseSpan(this.getAttribute('rowspan'))
}
get colspan () {
return _parseSpan(this.getAttribute('colspan'))
}
isShadowed () {
return this.shadowed
}
getMasterCell () {
return this.masterCell
}
}
TableCellNode.type = 'table-cell'
TableCellNode.schema = {
content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula', 'inline-graphic')
}
function _parseSpan (str) {
let span = parseInt(str, 10)
if (isFinite(span)) {
return Math.max(span, 1)
} else {
return 1
}
}
| import { XMLTextElement } from 'substance'
import { TEXT } from '../kit'
export default class TableCellNode extends XMLTextElement {
constructor (...args) {
super(...args)
this.rowIdx = -1
this.colIdx = -1
}
get rowspan () {
return _parseSpan(this.getAttribute('rowspan'))
}
get colspan () {
return _parseSpan(this.getAttribute('colspan'))
}
isShadowed () {
return this.shadowed
}
getMasterCell () {
return this.masterCell
}
}
TableCellNode.type = 'table-cell'
TableCellNode.schema = {
content: TEXT('bold', 'italic', 'sup', 'sub', 'monospace', 'ext-link', 'xref', 'inline-formula')
}
function _parseSpan (str) {
let span = parseInt(str, 10)
if (isFinite(span)) {
return Math.max(span, 1)
} else {
return 1
}
}
|
Update slicing so that array sizes match | #!/usr/bin/env python
"""
Test the MPS class
"""
import unittest
import numpy as np
import parafermions as pf
class Test(unittest.TestCase):
def test_pe_degeneracy(self):
# should initialise with all zeros
N, l = 8, 0.0
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
d, v = pe.Diagonalise(k=100)
# check that all eigenvalues are degenerate
assert(np.sum(d[1:10:2]-d[:10:2]) < 1e-10)
N, l = 8, 1.0
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
d, v = pe.Diagonalise(k=100)
# check only the ground state eigenvalues are degenerate
assert((d[1]-d[0]) < 1e-15)
assert(np.sum(d[1:10:2]-d[:10:2]) > 1e-2)
| #!/usr/bin/env python
"""
Test the MPS class
"""
import unittest
import numpy as np
import parafermions as pf
class Test(unittest.TestCase):
def test_pe_degeneracy(self):
# should initialise with all zeros
N, l = 8, 0.2
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
d, v = pe.Diagonalise(k=100)
assert(np.sum(d[1:11:2]-d[:11:2]) < 1e-10)
N, l = 8, 1.0
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
d, v = pe.Diagonalise(k=100)
assert((d[1]-d[0]) < 1e-15)
assert(np.sum(d[1:11:2]-d[:11:2]) > 1e-2)
|
Test high level public API instead of internal. | package markdown_test
import (
"log"
"os"
"github.com/shurcooL/go/markdown"
)
func Example() {
input := []byte(`Title
=
This is a new paragraph. I wonder if I have too many spaces.
What about new paragraph.
But the next one...
Is really new.
1. Item one.
1. Item TWO.
Final paragraph.
`)
output, err := markdown.Process("", input, nil)
if err != nil {
log.Fatalln(err)
}
os.Stdout.Write(output)
// Output:
//Title
//=====
//
//This is a new paragraph. I wonder if I have too many spaces. What about new paragraph. But the next one...
//
//Is really new.
//
//1. Item one.
//2. Item TWO.
//
//Final paragraph.
//
}
func Example2() {
input := []byte(`Title
==
Subtitle
---
How about ` + "`this`" + ` and other stuff like *italic*, **bold** and ***super extra***.
`)
output, err := markdown.Process("", input, nil)
if err != nil {
log.Fatalln(err)
}
os.Stdout.Write(output)
// Output:
//Title
//=====
//
//Subtitle
//--------
//
//How about `this` and other stuff like *italic*, **bold** and ***super extra***.
//
}
| package markdown_test
import (
"os"
"github.com/russross/blackfriday"
"github.com/shurcooL/go/markdown"
)
func Example() {
input := []byte(`Title
=
This is a new paragraph. I wonder if I have too many spaces.
What about new paragraph.
But the next one...
Is really new.
1. Item one.
1. Item TWO.
Final paragraph.
`)
output := blackfriday.Markdown(input, markdown.NewRenderer(), 0)
os.Stdout.Write(output)
// Output:
//Title
//=====
//
//This is a new paragraph. I wonder if I have too many spaces. What about new paragraph. But the next one...
//
//Is really new.
//
//1. Item one.
//2. Item TWO.
//
//Final paragraph.
//
}
func Example2() {
input := []byte(`Title
==
Subtitle
---
How about ` + "`this`" + ` and other stuff like *italic*, **bold** and ***super extra***.
`)
output := blackfriday.Markdown(input, markdown.NewRenderer(), 0)
os.Stdout.Write(output)
// Output:
//Title
//=====
//
//Subtitle
//--------
//
//How about `this` and other stuff like *italic*, **bold** and ***super extra***.
//
}
|
Revert "remove not null constraint"
This reverts commit 32f5c29a23341c4f1dd6c1241a751201ce286430. | package com.bazaarvoice.dropwizard.assets;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotNull;
import java.util.Map;
public class AssetsConfiguration {
@NotNull
@JsonProperty
private String cacheSpec = ConfiguredAssetsBundle.DEFAULT_CACHE_SPEC.toParsableString();
@NotNull
@JsonProperty
private Map<String, String> overrides = Maps.newHashMap();
@NotNull
@JsonProperty
private Map<String, String> mimeTypes = Maps.newHashMap();
/** The caching specification for how to memoize assets. */
public String getCacheSpec() {
return cacheSpec;
}
public Iterable<Map.Entry<String, String>> getOverrides() {
return Iterables.unmodifiableIterable(overrides.entrySet());
}
public Iterable<Map.Entry<String, String>> getMimeTypes() {
return Iterables.unmodifiableIterable(mimeTypes.entrySet());
}
}
| package com.bazaarvoice.dropwizard.assets;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotNull;
import java.util.Map;
public class AssetsConfiguration {
@NotNull
@JsonProperty
private String cacheSpec = ConfiguredAssetsBundle.DEFAULT_CACHE_SPEC.toParsableString();
@NotNull
@JsonProperty
private Map<String, String> overrides = Maps.newHashMap();
@JsonProperty
private Map<String, String> mimeTypes = Maps.newHashMap();
/** The caching specification for how to memoize assets. */
public String getCacheSpec() {
return cacheSpec;
}
public Iterable<Map.Entry<String, String>> getOverrides() {
return Iterables.unmodifiableIterable(overrides.entrySet());
}
public Iterable<Map.Entry<String, String>> getMimeTypes() {
return Iterables.unmodifiableIterable(mimeTypes.entrySet());
}
}
|
Use JUnit QuickCheck in ApiError test | package com.clxcommunications.xms;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.apache.commons.lang3.StringEscapeUtils;
import org.junit.runner.RunWith;
import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;
@RunWith(JUnitQuickcheck.class)
public class ApiErrorTest {
private final ApiObjectMapper json = new ApiObjectMapper();
@Property
public void canSerializeJson(String code, String text) throws Exception {
ApiError input = ImmutableApiError.of(code, text);
String expected = Utils.join("\n",
"{",
" \"code\" : \"" + StringEscapeUtils.escapeJson(code) + "\",",
" \"text\" : \"" + StringEscapeUtils.escapeJson(text) + "\"",
"}");
String actual = json.writeValueAsString(input);
assertThat(actual, is(TestUtils.jsonEqualTo(expected)));
}
@Property
public void canDeserializeJson(String code, String text) throws Exception {
ApiError expected = ImmutableApiError.of(code, text);
String input = json.writeValueAsString(expected);
ApiError actual = json.readValue(input, ApiError.class);
assertThat(actual, is(expected));
}
}
| package com.clxcommunications.xms;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.junit.Test;
public class ApiErrorTest {
private final ApiObjectMapper json = new ApiObjectMapper();
@Test
public void canSerializeJson() throws Exception {
String code = RandomStringUtils.randomPrint(1, 20);
String text = RandomStringUtils.randomPrint(1, 20);
ApiError input = ImmutableApiError.of(code, text);
String expected = Utils.join("\n",
"{",
" \"code\" : \"" + StringEscapeUtils.escapeJson(code) + "\",",
" \"text\" : \"" + StringEscapeUtils.escapeJson(text) + "\"",
"}");
String actual = json.writeValueAsString(input);
assertThat(actual, is(TestUtils.jsonEqualTo(expected)));
}
@Test
public void canDeserializeJson() throws Exception {
String code = RandomStringUtils.randomPrint(1, 20);
String text = RandomStringUtils.randomPrint(1, 20);
ApiError expected = ImmutableApiError.of(code, text);
String input = json.writeValueAsString(expected);
ApiError actual = json.readValue(input, ApiError.class);
assertThat(actual, is(expected));
}
}
|
Delete Property Setters for Custom Fields, and set them inside Custom Field | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import webnotes
def execute():
webnotes.reload_doc("core", "doctype", "custom_field")
cf_doclist = webnotes.get_doctype("Custom Field")
delete_list = []
for d in webnotes.conn.sql("""select cf.name as cf_name, ps.property,
ps.value, ps.name as ps_name
from `tabProperty Setter` ps, `tabCustom Field` cf
where ps.doctype_or_field = 'DocField' and ps.property != 'previous_field'
and ps.doc_type=cf.dt and ps.field_name=cf.fieldname""", as_dict=1):
if cf_doclist.get_field(d.property):
webnotes.conn.sql("""update `tabCustom Field`
set `%s`=%s where name=%s""" % (d.property, '%s', '%s'), (d.value, d.cf_name))
delete_list.append(d.ps_name)
if delete_list:
webnotes.conn.sql("""delete from `tabProperty Setter` where name in (%s)""" %
', '.join(['%s']*len(delete_list)), tuple(delete_list)) | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import webnotes
from webnotes.model.meta import get_field
def execute():
webnotes.reload_doc("core", "doctype", "custom_field")
custom_fields = {}
for cf in webnotes.conn.sql("""select dt, fieldname from `tabCustom Field`""", as_dict=1):
custom_fields.setdefault(cf.dt, []).append(cf.fieldname)
delete_list = []
for ps in webnotes.conn.sql("""select * from `tabProperty Setter`""", as_dict=1):
if ps.field_name in custom_fields.get(ps.doc_type, []):
if ps.property == "previous_field":
property_name = "insert_after"
field_meta = get_field(ps.doc_type, ps.value)
property_value = field_meta.label if field_meta else ""
else:
property_name = ps.property
property_value =ps.value
webnotes.conn.sql("""update `tabCustom Field`
set %s=%s where dt=%s and fieldname=%s""" % (property_name, '%s', '%s', '%s'),
(property_value, ps.doc_type, ps.field_name))
delete_list.append(ps.name)
if delete_list:
webnotes.conn.sql("""delete from `tabProperty Setter` where name in (%s)""" %
', '.join(['%s']*len(delete_list)), tuple(delete_list)) |
Reset user status when logging out | import update from 'immutability-helper'
import ActionTypes from '../actionTypes'
const initialState = {
isLoading: false,
lastRequestAt: undefined,
latestActivities: [],
unreadMessagesCount: 0,
}
export default (state = initialState, action) => {
switch (action.type) {
case ActionTypes.AUTH_TOKEN_EXPIRED_OR_INVALID:
case ActionTypes.AUTH_LOGOUT:
return update(state, {
lastRequestAt: { $set: undefined },
latestActivities: [],
unreadMessagesCount: 0,
})
case ActionTypes.USER_STATUS_REQUEST:
return update(state, {
isLoading: { $set: true },
})
case ActionTypes.USER_STATUS_SUCCESS:
return update(state, {
isLoading: { $set: false },
lastRequestAt: { $set: Date.now() },
latestActivities: { $set: action.payload.latestActivities },
unreadMessagesCount: { $set: action.payload.unreadMessagesCount },
})
case ActionTypes.USER_STATUS_FAILURE:
return update(state, {
isLoading: { $set: false },
})
default:
return state
}
}
| import update from 'immutability-helper'
import ActionTypes from '../actionTypes'
const initialState = {
isLoading: false,
lastRequestAt: undefined,
latestActivities: [],
unreadMessagesCount: 0,
}
export default (state = initialState, action) => {
switch (action.type) {
case ActionTypes.USER_STATUS_REQUEST:
return update(state, {
isLoading: { $set: true },
})
case ActionTypes.USER_STATUS_SUCCESS:
return update(state, {
isLoading: { $set: false },
lastRequestAt: { $set: Date.now() },
latestActivities: { $set: action.payload.latestActivities },
unreadMessagesCount: { $set: action.payload.unreadMessagesCount },
})
case ActionTypes.USER_STATUS_FAILURE:
return update(state, {
isLoading: { $set: false },
})
default:
return state
}
}
|
Set default input to UTF-8 to prevent breaking the working
installations. | <?php
/**
* The configuration file for RG2.
*
* This file should be modified to set up the details for a specific Routegadget installation.
*
*/
// Location of directory where Routegadget is installed.
// This should have /cgi-bin, /kartat and /rg2 sub-directories.
// Example define('RG_BASE_DIRECTORY', 'http://www.happyherts.routegadget.co.uk');
//define('RG_BASE_DIRECTORY', 'C:/xampp/htdocs/HHRoutegadget');
define('RG_BASE_DIRECTORY', 'http://www.happyherts.routegadget.co.uk');
//
// Set encoding for input data default UTF-8
define('RG_INPUT_ENCODING', 'UTF-8');
//
// Set encoding for output data returned throug API
define('RG_OUTPUT_ENCODING', 'UTF-8');
// User interface colour theme: see gallery at http://jqueryui.com/themeroller/
// Example define('UI_THEME', 'excite-bike');
define('UI_THEME', 'excite-bike');
// text to display in footer. Use '' to leave blank.
define('FOOTER_TEXT', '© Maprunner 2013. Maps published on this web site that contain OS data by permission of Ordnance Survey® Licence Number 100046745.');
?>
| <?php
/**
* The configuration file for RG2.
*
* This file should be modified to set up the details for a specific Routegadget installation.
*
*/
// Location of directory where Routegadget is installed.
// This should have /cgi-bin, /kartat and /rg2 sub-directories.
// Example define('RG_BASE_DIRECTORY', 'http://www.happyherts.routegadget.co.uk');
//define('RG_BASE_DIRECTORY', 'C:/xampp/htdocs/HHRoutegadget');
define('RG_BASE_DIRECTORY', 'http://www.happyherts.routegadget.co.uk');
//
// Set encoding for data
define('RG_INPUT_ENCODING', 'ISO-8859-1');
define('RG_OUTPUT_ENCODING', 'UTF-8');
// User interface colour theme: see gallery at http://jqueryui.com/themeroller/
// Example define('UI_THEME', 'excite-bike');
define('UI_THEME', 'excite-bike');
// text to display in footer. Use '' to leave blank.
define('FOOTER_TEXT', '© Maprunner 2013. Maps published on this web site that contain OS data by permission of Ordnance Survey® Licence Number 100046745.');
?>
|
Fix orientation flips for demo | package com.madisp.bad.demo;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
* Created with IntelliJ IDEA.
* User: madis
* Date: 3/20/13
* Time: 8:44 AM
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = new FrameLayout(this);
v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
v.setId(R.id.mainContainer);
setContentView(v);
if (savedInstanceState == null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.mainContainer, new ListFragment());
ft.commit();
}
}
}
| package com.madisp.bad.demo;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
* Created with IntelliJ IDEA.
* User: madis
* Date: 3/20/13
* Time: 8:44 AM
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v = new FrameLayout(this);
v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
v.setId(R.id.mainContainer);
setContentView(v);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.mainContainer, new ListFragment());
ft.commit();
}
}
|
Add version variable that can be set by the linker | /*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package version
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
var gitVersion string
type version struct {
*flags.EmptyFlag
}
func init() {
if gitVersion == "" {
gitVersion = "unknown"
}
cli.Register("version", &version{})
}
func (c *version) Run(f *flag.FlagSet) error {
fmt.Printf("govc %s\n", gitVersion)
return nil
}
| /*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package version
import (
"flag"
"fmt"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)
type version struct {
*flags.EmptyFlag
}
func init() {
cli.Register("version", &version{})
}
func (c *version) Run(f *flag.FlagSet) error {
fmt.Println("govc version 0.0.1-dev")
return nil
}
|
Make sure that repo has owner name and name in tests
In most tests we only set a slug for a repository. This works fine in
most cases, but has a drawback of not displaying a proper owner name and
name in the UI. This commit fixes the situation by setting owner name and
name based on slug if needed. | import V3Serializer from './v3';
export default V3Serializer.extend({
serializeSingle(repository) {
this.fixOwnerAndName(repository);
if (!repository.defaultBranch && repository.branches) {
let defaultBranch = repository.branches.models.find(branch => branch.default_branch);
repository.defaultBranch = defaultBranch;
}
if (!repository.currentBuild) {
let builds = repository._schema.builds.where((build) => {
let repoId = repository.id;
return build.repository_id === repoId || build.repositoryId == repoId;
});
if (builds.length) {
repository.currentBuild = builds.models[0];
}
}
return V3Serializer.prototype.serializeSingle.apply(this, arguments);
},
// In most tests we just set slug for the repo. This ensures that we return
// also name and owner data to make the payload more similar to what we get in
// production.
fixOwnerAndName(repository) {
let owner, name,
attrs = repository.attrs;
if (attrs.slug) {
[owner, name] = attrs.slug.split('/');
}
attrs.owner = attrs.owner || {};
if (owner && !attrs.owner.login) {
attrs.owner.login = owner;
}
if (name && !attrs.name) {
attrs.name = name;
}
}
});
| import V3Serializer from './v3';
export default V3Serializer.extend({
serializeSingle(repository) {
if (!repository.defaultBranch && repository.branches) {
let defaultBranch = repository.branches.models.find(branch => branch.default_branch);
repository.defaultBranch = defaultBranch;
}
if (!repository.currentBuild) {
let builds = repository._schema.builds.where((build) => {
let repoId = repository.id;
return build.repository_id === repoId || build.repositoryId == repoId;
});
if (builds.length) {
repository.currentBuild = builds.models[0];
}
}
return V3Serializer.prototype.serializeSingle.apply(this, arguments);
}
});
|
Remove useless & wrong code for CreateResultBox
* Copy & paste sucks. | 'use strict';
(function (module, undefined) {
function CreateResultBox(elem) {
// TODO: add property 'list' and 'details' for each UI state.
this.elem = elem;
this.list = new TimetableList(elem);
}
Object.defineProperties(CreateResultBox.prototype, {
'showingList': {
value: true
},
'showingDetails': {
value: false
}
});
module.exports = CreateResultBox;
function TimetableList(box) {
this.ttElems = box.$$('.item-timetable');
}
Object.defineProperties(TimetableList.prototype, {
'nTimetables': {
get: function () { return this.ttElems.count(); }
}
});
TimetableList.prototype.getItemAt = function (index) {
return new TimetableListItem(this.ttElems.get(index));
};
function TimetableListItem(elem) {
this.elem = elem;
}
Object.defineProperties(TimetableListItem.prototype, {
'credits': {
get: function () { return this.elem.$('.credits').getText(); }
},
'nClassDays': {
get: function () { return this.elem.$('.n-class-days').getText(); }
},
'nFreeHours': {
get: function () { return this.elem.$('.n-free-hours').getText(); }
}
});
})(module);
| 'use strict';
(function (module, undefined) {
function CreateResultBox(elem) {
// TODO: add property 'list' and 'details' for each UI state.
this.elem = elem;
this.list = new TimetableList(elem);
}
Object.defineProperties(CreateResultBox.prototype, {
'showingList': {
value: true
},
'showingDetails': {
value: false
}
});
CreateResultBox.prototype.clickGenerateButton = function () {
return this.elem.$('.btn-generate').click();
};
module.exports = CreateResultBox;
function TimetableList(box) {
this.ttElems = box.$$('.item-timetable');
}
Object.defineProperties(TimetableList.prototype, {
'nTimetables': {
get: function () { return this.ttElems.count(); }
}
});
TimetableList.prototype.getItemAt = function (index) {
return new TimetableListItem(this.ttElems.get(index));
};
function TimetableListItem(elem) {
this.elem = elem;
}
Object.defineProperties(TimetableListItem.prototype, {
'credits': {
get: function () { return this.elem.$('.credits').getText(); }
},
'nClassDays': {
get: function () { return this.elem.$('.n-class-days').getText(); }
},
'nFreeHours': {
get: function () { return this.elem.$('.n-free-hours').getText(); }
}
});
})(module);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.