text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Fix className bug: should not be shorten | <?php
namespace PureBilling\Bundle\SDKBundle\Store\Base;
use Symfony\Component\Validator\Constraints as Assert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
use PureMachine\Bundle\SDKBundle\Store\Base\SymfonyBaseStore;
abstract class Element extends SymfonyBaseStore
{
public function __construct($data=null)
{
parent::__construct($data);
//Set Short type of class
// PureMachine\Bundle\SDKBundle\Store\Billing\CC become Billing\CC
$this->type = str_replace('PureBilling\Bundle\SDKBundle\Store\\', '',
get_class($this));
}
/**
* @Store\Property(description="type of the current answer")
* @Assert\Type("string")
* @Assert\NotBlank
*/
protected $type;
}
| <?php
namespace PureBilling\Bundle\SDKBundle\Store\Base;
use Symfony\Component\Validator\Constraints as Assert;
use PureMachine\Bundle\SDKBundle\Store\Annotation as Store;
use PureMachine\Bundle\SDKBundle\Store\Base\SymfonyBaseStore;
abstract class Element extends SymfonyBaseStore
{
public function __construct($data=null)
{
parent::__construct($data);
//Set Short type of class
// PureMachine\Bundle\SDKBundle\Store\Billing\CC become Billing\CC
$this->type = str_replace('PureBilling\Bundle\SDKBundle\Store\\', '',
get_class($this));
}
/**
* @Store\Property(description="type of the current answer")
* @Assert\Type("string")
* @Assert\NotBlank
*/
protected $type;
public function getClassName()
{
$class = explode('\\', get_called_class());
return end($class);
}
}
|
Remove __nav prefix due to conflicts with combineReducers function | const {PUSH, POP, REPLACE} = require('../constants/navigation');
module.exports = function navigate(state, {type, payload}) {
if (!state) {
return {};
}
const stack = state.stack;
const index = state.index;
switch (type) {
case PUSH:
return Object.assign({}, state, {
stack: stack.unshift(payload),
index: 0,
});
case POP:
const incremented = index + 1;
if (incremented === stack.count()) {
return state;
}
return Object.assign({}, state, {
stack: stack,
index: incremented,
});
case REPLACE:
if (!stack.count()) {
return state;
}
return Object.assign({}, state, {
stack: stack.splice(index, 1, payload),
index: index,
});
default:
return state;
}
};
| const {PUSH, POP, REPLACE} = require('../constants/navigation');
module.exports = function navigate(state, {type, payload}) {
if (!state) {
return {__nav: {}};
}
const stack = state.__nav.stack;
const index = state.__nav.index;
switch (type) {
case PUSH:
return Object.assign({}, state, {
__nav: {
stack: stack.unshift(payload),
index: 0,
},
});
case POP:
const incremented = index + 1;
if (incremented === stack.count()) {
return state;
}
return Object.assign({}, state, {
__nav: {
stack: stack,
index: incremented,
},
});
case REPLACE:
if (!stack.count()) {
return state;
}
return Object.assign({}, state, {
__nav: {
stack: stack.splice(index, 1, payload),
index: index,
},
});
default:
return state;
}
};
|
Fix Application module removing wrong type. | /**
* Copyright (C) 2015 android10.org. All rights reserved.
* @author Fernando Cejas (the android10 coder)
*/
package com.fernandocejas.android10.sample.presentation.internal.di.modules;
import android.content.Context;
import android.view.LayoutInflater;
import com.fernandocejas.android10.sample.data.executor.JobExecutor;
import com.fernandocejas.android10.sample.domain.executor.PostExecutionThread;
import com.fernandocejas.android10.sample.domain.executor.ThreadExecutor;
import com.fernandocejas.android10.sample.presentation.AndroidApplication;
import com.fernandocejas.android10.sample.presentation.UIThread;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/**
* Dagger module that provides objects which will live during the application lifecycle.
*/
@Module
public class ApplicationModule {
private final AndroidApplication application;
public ApplicationModule(AndroidApplication application) {
this.application = application;
}
@Provides @Singleton Context provideApplicationContext() {
return this.application;
}
@Provides @Singleton LayoutInflater provideLayoutInflater() {
return LayoutInflater.from(this.application);
}
@Provides @Singleton ThreadExecutor provideThreadExecutor(JobExecutor jobExecutor) {
return jobExecutor;
}
@Provides @Singleton PostExecutionThread providePostExecutionThread(UIThread uiThread) {
return uiThread;
}
}
| /**
* Copyright (C) 2015 android10.org. All rights reserved.
* @author Fernando Cejas (the android10 coder)
*/
package com.fernandocejas.android10.sample.presentation.internal.di.modules;
import android.app.Application;
import android.content.Context;
import android.view.LayoutInflater;
import com.fernandocejas.android10.sample.data.executor.JobExecutor;
import com.fernandocejas.android10.sample.domain.executor.PostExecutionThread;
import com.fernandocejas.android10.sample.domain.executor.ThreadExecutor;
import com.fernandocejas.android10.sample.presentation.UIThread;
import com.fernandocejas.android10.sample.presentation.internal.di.components.ForApplication;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/**
* Dagger module that provides objects which will live during the application lifecycle.
*/
@Module
public final class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides @Singleton @ForApplication Context provideApplicationContext() {
return this.application;
}
@Provides @Singleton LayoutInflater provideLayoutInflater() {
return LayoutInflater.from(this.application);
}
@Provides @Singleton ThreadExecutor provideThreadExecutor(JobExecutor jobExecutor) {
return jobExecutor;
}
@Provides @Singleton PostExecutionThread providePostExecutionThread(UIThread uiThread) {
return uiThread;
}
}
|
Include ember-data.js.map in S3 upload | module.exports = function(revision, tag, date){
return {
'ember-data.js': fileObject('ember-data.js', 'text/javascript', revision, tag, date),
'ember-data.js.map': fileObject('ember-data.js.map', 'application/json', revision, tag, date),
'ember-data.min.js': fileObject('ember-data.min.js', 'text/javascript', revision, tag, date),
'ember-data.prod.js': fileObject('ember-data.prod.js', 'text/javascript', revision, tag, date)
}
}
function fileObject(fileName, contentType, currentRevision, tag, date) {
return {
contentType: contentType,
destinations: {
canary: [
'canary' + fileName,
'canary/daily/' + date + fileName,
'canary/shas/' + currentRevision + fileName
],
stable: [
'stable' + fileName,
'stable/daily/' + date + fileName,
'stable/shas/' + currentRevision + fileName
],
beta: [
'beta' + fileName,
'beta/daily/' + date + fileName,
'beta/shas/' + currentRevision + fileName
]
}
}
}
| module.exports = function(revision, tag, date){
return {
'ember-data.js': fileObject('ember-data', '.js', 'text/javascript', revision, tag, date),
'ember-data.min.js': fileObject('ember-data.min', '.js', 'text/javascript', revision, tag, date),
'ember-data.prod.js': fileObject('ember-data.prod', '.js', 'text/javascript', revision, tag, date)
}
}
function fileObject(baseName, extension, contentType, currentRevision, tag, date) {
var fullName = "/" + baseName + extension;
return {
contentType: contentType,
destinations: {
canary: [
'canary' + fullName,
'canary/daily/' + date + fullName,
'canary/shas/' + currentRevision + fullName
],
stable: [
'stable' + fullName,
'stable/daily/' + date + fullName,
'stable/shas/' + currentRevision + fullName
],
beta: [
'beta' + fullName,
'beta/daily/' + date + fullName,
'beta/shas/' + currentRevision + fullName
]
}
}
}
|
Set token and fake liqen in redux middleware | import liqen from 'liqen'
import fakeLiqen from '../../server/local-liqen'
import cookies from 'cookies-js'
export const CALL_API = Symbol('call api')
export default store => next => action => {
const callAPI = action[CALL_API]
if (typeof callAPI === 'undefined') {
return next(action)
}
const token = cookies.get('access_token')
let core = liqen(token)
if (process.env.NODE_ENV === 'development') {
core = fakeLiqen(token)
}
const { ref, target, tag } = callAPI
// Send a pending
next({
type: 'CREATE_ANNOTATION_PENDING',
ref,
target,
tag
})
// Send to the server the update
core
.annotations
.create({
article_id: 1,
target: {
type: 'TextQuoteSelector',
prefix: target.prefix,
exact: target.exact,
suffix: target.suffix
},
tags: [tag]
})
.then(({id}) => next({
type: 'CREATE_ANNOTATION_SUCCESS',
ref,
id,
target,
tag
}))
.catch(() => next({
type: 'CREATE_ANNOTATION_FAILURE',
ref,
target,
tag
}))
}
| import liqen from 'liqen'
export const CALL_API = Symbol('call api')
export default store => next => action => {
const callAPI = action[CALL_API]
if (typeof callAPI === 'undefined') {
return next(action)
}
const { ref, target, tag } = callAPI
// Send a pending
next({
type: 'CREATE_ANNOTATION_PENDING',
ref,
target,
tag
})
// Send to the server the update
liqen()
.annotations
.create({
article_id: 1,
target: {
type: 'TextQuoteSelector',
prefix: target.prefix,
exact: target.exact,
suffix: target.suffix
},
tags: [tag]
})
.then(({id}) => next({
type: 'CREATE_ANNOTATION_SUCCESS',
ref,
id,
target,
tag
}))
.catch(() => next({
type: 'CREATE_ANNOTATION_FAILURE',
ref,
target,
tag
}))
}
|
Use higher pandas version for python 3.6.0 support | from setuptools import setup, find_packages
version = __import__('eemeter').get_version()
setup(
name='eemeter',
version=version,
description='Open Energy Efficiency Meter',
long_description=(
"Standard methods for calculating energy efficiency savings."
),
url='https://github.com/openeemeter/eemeter/',
author='Open Energy Efficiency',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
keywords='open energy efficiency meter',
packages=find_packages(),
install_requires=[
'holidays',
'lxml <= 3.6.1',
'numpy >= 1.10.2',
'scipy',
'pandas >= 0.19.2',
'patsy',
'pytz',
'requests',
'scikit-learn',
'statsmodels >= 0.8.0rc1',
'SQLAlchemy',
],
package_data={'': ['*.json', '*.gz']},
setup_requires=['pytest-runner'],
tests_require=['pytest'],
)
| from setuptools import setup, find_packages
version = __import__('eemeter').get_version()
setup(
name='eemeter',
version=version,
description='Open Energy Efficiency Meter',
long_description=(
"Standard methods for calculating energy efficiency savings."
),
url='https://github.com/openeemeter/eemeter/',
author='Open Energy Efficiency',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
keywords='open energy efficiency meter',
packages=find_packages(),
install_requires=[
'holidays',
'lxml <= 3.6.1',
'numpy >= 1.10.2',
'scipy',
'pandas >= 0.18,<0.19',
'patsy',
'pytz',
'requests',
'scikit-learn',
'statsmodels >= 0.8.0rc1',
'SQLAlchemy',
],
package_data={'': ['*.json', '*.gz']},
setup_requires=['pytest-runner'],
tests_require=['pytest'],
)
|
Fix for iframe in Safari | const styles = {
display: "grid",
gridTemplateRows: "1fr 1fr 7fr 1fr",
};
function Resume() {
return (
<section className="container" style={styles}>
<h3>Skills</h3>
<ul>
<li>JavaScript, Python, HTML, CSS, SQL, MongoDB</li>
<li>NodeJS, Express, React, jQuery, Bootstrap, GraphQL</li>
<li>AWS: Cloudfront, Route53, S3, Lambda, EC2, Cloudformation</li>
<li>
Meeting Facilitation, Story Mapping, Wireframing, Leading Continuous
Improvement
</li>
</ul>
<div>
<iframe
title="Resume"
src="./media/J. Michael Brown - Resume.pdf"
alt="Resume"
width="100%"
height="100%"
></iframe>
</div>
<p>
<a href="./media/J. Michael Brown - Resume.pdf" download>
Download Resume
</a>
</p>
</section>
);
}
export default Resume;
| const styles = {
display: "grid",
gridTemplateRows: "1fr 1fr 7fr 1fr",
};
function Resume() {
return (
<section className="container" style={styles}>
<h3>Skills</h3>
<ul>
<li>JavaScript, Python, HTML, CSS, SQL, MongoDB</li>
<li>NodeJS, Express, React, jQuery, Bootstrap, GraphQL</li>
<li>AWS: Cloudfront, Route53, S3, Lambda, EC2, Cloudformation</li>
<li>
Meeting Facilitation, Story Mapping, Wireframing, Leading Continuous
Improvement
</li>
</ul>
<iframe
title="Resume"
src="./media/J. Michael Brown - Resume.pdf"
alt="Resume"
width="100%"
height="100%"
></iframe>
<p>
<a href="./media/J. Michael Brown - Resume.pdf" download>
Download Resume
</a>
</p>
</section>
);
}
export default Resume;
|
TASK: Adjust test assertions to PHPUnit 8 | <?php
namespace Neos\Flow\Tests\Unit\Http\Helper;
use GuzzleHttp\Psr7\ServerRequest;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Tests\UnitTestCase;
/**
* Tests for the RequestInformationHelper
*/
class RequestInformationHelperTest extends UnitTestCase
{
/**
* @test
*/
public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
{
$request = ServerRequest::fromGlobals()
->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
->withAddedHeader('Authorization', 'Bearer SomeToken');
$renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
self::assertStringContainsString('SomePassword', $renderedHeaders);
self::assertStringContainsString('SomeToken', $renderedHeaders);
}
}
| <?php
namespace Neos\Flow\Tests\Unit\Http\Helper;
use GuzzleHttp\Psr7\ServerRequest;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Tests\UnitTestCase;
/**
* Tests for the RequestInformationHelper
*/
class RequestInformationHelperTest extends UnitTestCase
{
/**
* @test
*/
public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
{
$request = ServerRequest::fromGlobals()
->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
->withAddedHeader('Authorization', 'Bearer SomeToken');
$renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
self::assertNotContains('SomePassword', $renderedHeaders);
self::assertNotContains('SomeToken', $renderedHeaders);
}
}
|
Add error message when return codes don't match on the passthru | <?php
namespace Vanderbilt\EmailTriggerExternalModule;
use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;
require_once 'EmailTriggerExternalModule.php';
$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);
$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){
$surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
$link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
?>
<html>
<body>
<form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
<?=$link?>
<input type='hidden' value='1' name='__prefill' />
</form>
<script type='text/javascript'>
window.onload = function(){
document.passthruform.submit();
}
</script>
</body>
</html>
<?php }
else {
echo "Error: Incorrect return code specified";
}?>
| <?php
namespace Vanderbilt\EmailTriggerExternalModule;
use ExternalModules\AbstractExternalModule;
use ExternalModules\ExternalModules;
require_once 'EmailTriggerExternalModule.php';
$passthruData = $module->resetSurveyAndGetCodes($_REQUEST['pid'], $_REQUEST['record'], $_REQUEST['instrument'], $_REQUEST['event']);
$returnCode = $passthruData['return_code'];
$hash = $passthruData['hash'];
if($returnCode == $_REQUEST['returnCode']){
$surveyLink = APP_PATH_SURVEY_FULL."?s=".$hash;
$link = ($_REQUEST['returnCode'] == "NULL")? "":"<input type='hidden' value='".$returnCode."' name='__code'/>";
?>
<html>
<body>
<form id='passthruform' name='passthruform' action='<?=$surveyLink?>' method='post' enctype='multipart/form-data'>
<?=$link?>
<input type='hidden' value='1' name='__prefill' />
</form>
<script type='text/javascript'>
window.onload = function(){
document.passthruform.submit();
}
</script>
</body>
</html>
<?php } ?>
|
Make whole feat gene thumb clickable | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { primary } from '@artsy/reaction-force/dist/Assets/Fonts'
const propTypes = {
title: PropTypes.string,
href: PropTypes.string,
image: PropTypes.object
}
const Container = styled.div`
position: relative;
width: 95%;
overflow: hidden;
`
const GeneName = styled.span`
position: absolute;
left: 1em;
bottom: 1em;
text-decoration: none;
color: white;
text-shadow: 0 0 10px rgba(0, 0, 0, 0.7);
${primary.style} font-size: 13px;
line-height: 1.33em;
font-weight: bold;
`
const GeneImage = styled.img`width: 100%;`
const FeaturedGene = ({ title, href, image: { url: imageSrc } }) => {
return (
<a href={href}>
<Container>
<GeneName>{title}</GeneName>
<GeneImage src={imageSrc} />
</Container>
</a>
)
}
FeaturedGene.propTypes = propTypes
export default FeaturedGene
| import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { primary } from '@artsy/reaction-force/dist/Assets/Fonts'
const propTypes = {
title: PropTypes.string,
href: PropTypes.string,
image: PropTypes.object
}
const Container = styled.div`
position: relative;
width: 95%;
overflow: hidden;
`
const GeneLink = styled.a`
position: absolute;
left: 1em;
bottom: 1em;
text-decoration: none;
color: white;
text-shadow: 0 0 10px rgba(0, 0, 0, 0.7);
${primary.style} font-size: 13px;
line-height: 1.33em;
font-weight: bold;
`
const GeneImage = styled.img`width: 100%;`
const FeaturedGene = ({ title, href, image: { url: imageSrc } }) => {
return (
<Container>
<GeneLink href={href}>{title}</GeneLink>
<GeneImage src={imageSrc} />
</Container>
)
}
FeaturedGene.propTypes = propTypes
export default FeaturedGene
|
Fix bot failing to respond to command with it's username
Fix #5 | class CommandSource {
constructor(messageSource,botUsername){
this.botUsername = botUsername;
this.bindings = {};
messageSource.on("text",this.handle.bind(this));
}
addCommand(name,command){
if(name in this.bindings){
throw `Error: A command is already bound to ${name}`;
}
this.bindings[name] = command;
}
handle(message){
let text = message.text;
if(text.substr(0,1) !== "/"){
return;
}
text = text.substr(1);
let tokens = text.split(" ");
let commandName = tokens.shift();
let atAt = commandName.indexOf("@");
if(atAt !== -1){
if (commandName.substr(atAt+1) !== this.botUsername){
return;
}
commandName = commandName.substr(0,atAt);
}
commandName = commandName.toLowerCase();
if(!(commandName in this.bindings)){
throw `Error: ${commandName} is not a known command`;
}
this.bindings[commandName].execute(tokens,message);
}
}
module.exports = CommandSource;
| class CommandSource {
constructor(messageSource,botUsername){
this.botUsername = botUsername;
this.bindings = {};
messageSource.on("text",this.handle.bind(this));
}
addCommand(name,command){
if(name in this.bindings){
throw `Error: A command is already bound to ${name}`;
}
this.bindings[name] = command;
}
handle(message){
let text = message.text;
if(text.substr(0,1) !== "/"){
return;
}
text = text.substr(1);
let tokens = text.split(" ");
let commandName = tokens.shift();
let atAt = commandName.indexOf("@");
if(atAt !== -1){
let commandName = commandName.substr(0,atAt);
if (commanName.substr(atAt+1) !== this.botUsername){
return;
}
}
commandName = commandName.toLowerCase();
if(!(commandName in this.bindings)){
throw `Error: ${commandName} is not a known command`;
}
this.bindings[commandName].execute(tokens,message);
}
}
module.exports = CommandSource;
|
Fix assult api caching in sw
- caused by cors headers
- add exposed headers to assult api | const functions = require('firebase-functions');
const cors = require('cors');
const BASE = functions.config().legionassult.base;
const base = parseInt(+new Date(BASE) / 1000, 10);
const calcAssultTime = require('./utils/calcAssultTime')(base);
const corsOptions = {
origin: true,
methods: 'GET',
exposedHeaders: 'Date'
};
module.exports = function legionAssultTime() {
return functions.https.onRequest((req, res) => {
if (req.method !== 'GET') {
res.status(403).send('Forbidden!');
}
(cors(corsOptions))(req, res, () => {
/**
* api parameters
*
* start - starting time (any Date object formate)
* count - number of assult times returned
* callback - jsonp support callback function name
*/
const startFrom = (
req.query.start
? +new Date(req.query.start)
: +new Date()
) / 1000;
const count = Number(req.query.count || 5);
const assults = calcAssultTime(startFrom, count);
res
.status(200)
.set({
'Cache-Control': 'public, max-age=3600'
})
.jsonp({
start: startFrom,
count,
assults
});
});
});
};
| const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const BASE = functions.config().legionassult.base;
const base = parseInt(+new Date(BASE) / 1000, 10);
const calcAssultTime = require('./utils/calcAssultTime')(base);
module.exports = function legionAssultTime() {
return functions.https.onRequest((req, res) => {
if (req.method !== 'GET') {
res.status(403).send('Forbidden!');
}
cors(req, res, () => {
/**
* api parameters
*
* start - starting time (any Date object formate)
* count - number of assult times returned
* callback - jsonp support callback function name
*/
const startFrom = (
req.query.start
? +new Date(req.query.start)
: +new Date()
) / 1000;
const count = Number(req.query.count || 5);
const assults = calcAssultTime(startFrom, count);
res.status(200).jsonp({
start: startFrom,
count,
assults
});
});
});
};
|
Add support for Equipment CPT | <?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;
/**
* Add <body> classes
*/
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Setup\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/**
* Clean up the_excerpt()
*/
function excerpt_more() {
return ' … <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
add_filter('sage/wrap_base', __NAMESPACE__ . 'sage_wrap_base_cpts'); // Add our function to the sage/wrap_base filter
function sage_wrap_base_cpts($templates) {
$cpt = get_post_type(); // Get the current post type
if ($cpt) {
array_unshift($templates, 'base-' . $cpt . '.php'); // Shift the template to the front of the array
}
return $templates; // Return our modified array with base-$cpt.php at the front of the queue
}
| <?php
namespace Roots\Sage\Extras;
use Roots\Sage\Setup;
/**
* Add <body> classes
*/
function body_class($classes) {
// Add page slug if it doesn't exist
if (is_single() || is_page() && !is_front_page()) {
if (!in_array(basename(get_permalink()), $classes)) {
$classes[] = basename(get_permalink());
}
}
// Add class if sidebar is active
if (Setup\display_sidebar()) {
$classes[] = 'sidebar-primary';
}
return $classes;
}
add_filter('body_class', __NAMESPACE__ . '\\body_class');
/**
* Clean up the_excerpt()
*/
function excerpt_more() {
return ' … <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>';
}
add_filter('excerpt_more', __NAMESPACE__ . '\\excerpt_more');
|
:sparkles: Add in a modules option that defaults to false | 'use strict';
const path = require('path');
const pkg = require(path.resolve('./package.json'));
const semver = require('semver');
const versions = require('./versions.json');
const presetEnv = require.resolve('babel-preset-env');
const presetStage3 = require.resolve('babel-preset-stage-3');
module.exports = function(context, options) {
options = options || {};
const modules = options.modules || false;
const targets = {};
if (pkg.browserslist) {
targets.browsers = pkg.browserslist;
}
if (pkg.engines && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) {
targets.node = version;
} else if (semver.validRange(version)) {
targets.node = semver.minSatisfying(versions.node, version);
}
}
return {
presets: [
[presetEnv, {modules, targets}],
presetStage3,
],
};
};
| 'use strict';
const path = require('path');
const pkg = require(path.resolve('./package.json'));
const semver = require('semver');
const versions = require('./versions.json');
const presetEnv = require.resolve('babel-preset-env');
const presetStage3 = require.resolve('babel-preset-stage-3');
module.exports = function() {
const targets = {};
if (pkg.browserslist) {
targets.browsers = pkg.browserslist;
}
if (pkg.engines && pkg.engines.node) {
const version = pkg.engines.node;
if (semver.valid(version)) {
targets.node = version;
} else if (semver.validRange(version)) {
targets.node = semver.minSatisfying(versions.node, version);
}
}
return {
presets: [
[presetEnv, {targets}],
presetStage3,
],
};
};
|
Handle UTC formatting of covid newsfeed | // @flow
import * as React from 'react'
import moment from 'moment-timezone'
import {Alert} from 'react-native'
import {Column, Row} from '../components/layout'
import {ListRow, Detail, Title} from '../components/list'
import type {UpdateType} from './types'
type Props = {
onPress: string => any,
update: UpdateType,
}
export class UpdatesRow extends React.PureComponent<Props> {
_onPress = () => {
if (!this.props.update.link) {
Alert.alert('There is nowhere to go for this update')
return
}
this.props.onPress(this.props.update.link)
}
render() {
const {update} = this.props
const posted = moment
.utc(update.datePublished)
.utcOffset(-6)
.format('MMM Do YYYY')
return (
<ListRow arrowPosition="center" onPress={this._onPress}>
<Row alignItems="center">
<Column flex={1}>
<Title lines={2}>{posted}</Title>
<Detail lines={3}>{update.title}</Detail>
</Column>
</Row>
</ListRow>
)
}
}
| // @flow
import * as React from 'react'
import moment from 'moment-timezone'
import {Alert} from 'react-native'
import {Column, Row} from '../components/layout'
import {ListRow, Detail, Title} from '../components/list'
import type {UpdateType} from './types'
type Props = {
onPress: string => any,
update: UpdateType,
}
export class UpdatesRow extends React.PureComponent<Props> {
_onPress = () => {
if (!this.props.update.link) {
Alert.alert('There is nowhere to go for this update')
return
}
this.props.onPress(this.props.update.link)
}
render() {
const {update} = this.props
const posted = moment(update.datePublished).format('MMM Do YYYY')
return (
<ListRow arrowPosition="center" onPress={this._onPress}>
<Row alignItems="center">
<Column flex={1}>
<Title lines={2}>{posted}</Title>
<Detail lines={3}>{update.title}</Detail>
</Column>
</Row>
</ListRow>
)
}
}
|
Change string to English and remove absolute paths to work on installations not located under site root | (function() {
var saml = document.createElement('script');
saml.type = 'text/javascript';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(saml);
})();
$(document).ready(function(){
$('#password').parent().removeClass("infield groupbottom");
$('#password').parent().addClass("infield groupmiddle");
$('#password').attr( "autocomplete", "on" );
$('#password').parent().after(
'<p class="infield disclaimer">'+
'<input type="checkbox" id="disclaimer" placeholder="Disclaimer" value="" name="disclaimer"'+ 'original-title="" autocomplete="off" required />'+
'<a href="apps/disclaimer/pdf/disclaimer.pdf "><img src="core/img/filetypes/application-pdf.svg" /></a> I have read and agree to the Terms & Conditions.'+
'</p>'
);
$("#submit").removeAttr("disabled");
});
| (function() {
var saml = document.createElement('script');
saml.type = 'text/javascript';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(saml);
})();
$(document).ready(function(){
$('#password').parent().removeClass("infield groupbottom");
$('#password').parent().addClass("infield groupmiddle");
$('#password').attr( "autocomplete", "on" );
$('#password').parent().after(
'<p class="infield disclaimer">'+
'<input type="checkbox" id="disclaimer" placeholder="Disclaimer" value="" name="disclaimer"'+ 'original-title="" autocomplete="off" required />'+
'<a href="/apps/disclaimer/pdf/disclaimer.pdf "><img src="/core/img/filetypes/application-pdf.svg" /></a> Acepto los terminos y condiciones'+
'</p>'
);
$("#submit").removeAttr("disabled");
});
|
Send c/form email to address specified in env var | var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Mailgun',
auth: {
user: process.env.MAILGUN_USERNAME,
pass: process.env.MAILGUN_PASSWORD
}
});
/**
* GET /contact
*/
exports.contactGet = function(req, res) {
res.render('contact', {
title: 'Contact'
});
};
/**
* POST /contact
*/
exports.contactPost = function(req, res) {
req.assert('name', 'Name cannot be blank').notEmpty();
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('message', 'Message cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });
var errors = req.validationErrors();
if (errors) {
req.flash('error', errors);
return res.redirect('/contact');
}
var mailOptions = {
from: req.body.name + ' ' + '<'+ req.body.email + '>',
to: process.env.APP_EMAIL_ADDRESS,
subject: 'Contact Form',
text: req.body.message
};
transporter.sendMail(mailOptions, function(err) {
req.flash('success', { msg: 'Thank you! Your message has been submitted.' });
res.redirect('/contact');
});
};
| var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'Mailgun',
auth: {
user: process.env.MAILGUN_USERNAME,
pass: process.env.MAILGUN_PASSWORD
}
});
/**
* GET /contact
*/
exports.contactGet = function(req, res) {
res.render('contact', {
title: 'Contact'
});
};
/**
* POST /contact
*/
exports.contactPost = function(req, res) {
req.assert('name', 'Name cannot be blank').notEmpty();
req.assert('email', 'Email is not valid').isEmail();
req.assert('email', 'Email cannot be blank').notEmpty();
req.assert('message', 'Message cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ remove_dots: false });
var errors = req.validationErrors();
if (errors) {
req.flash('error', errors);
return res.redirect('/contact');
}
var mailOptions = {
from: req.body.name + ' ' + '<'+ req.body.email + '>',
to: 'your@email.com',
subject: 'Contact Form',
text: req.body.message
};
transporter.sendMail(mailOptions, function(err) {
req.flash('success', { msg: 'Thank you! Your message has been submitted.' });
res.redirect('/contact');
});
};
|
Remove document contents on injection | (function() {
window.stop();
document.documentElement.innerHTML = null;
const IS_LOCAL = false,
URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js",
URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE,
SCRIPT_OUT = "<script src='" + URL_OUT + "'></script>\n";
let loader = new XMLHttpRequest();
loader.open("GET", location.href, true);
loader.onreadystatechange = function() {
if (loader.readyState == 4) {
const res = loader.responseText;
document.open();
document.write(`${SCRIPT_OUT}${res}`);
document.close();
}
}
loader.send();
})(); | (function() {
window.stop();
const IS_LOCAL = false,
URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js",
URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE,
SCRIPT_OUT = "<script src='" + URL_OUT + "'></script>\n";
let loader = new XMLHttpRequest();
loader.open("GET", location.href, true);
loader.onreadystatechange = function() {
if (loader.readyState == 4) {
const res = loader.responseText;
document.open();
document.write(`${SCRIPT_OUT}${res}`);
document.close();
}
}
loader.send();
})(); |
Change double quotes to single quotes | #!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import messagebird
ACCESS_KEY = 'test_gshuPaZoeEG6ovbc8M79w0QyM'
try:
# Create a MessageBird client with the specified ACCESS_KEY.
client = messagebird.Client(ACCESS_KEY)
# Fetch the Balance object.
balance = client.balance()
# Print the object information.
print('\nThe following information was returned as a Balance object:\n')
print(' amount : %d' % balance.amount)
print(' type : %s' % balance.type)
print(' payment : %s\n' % balance.payment)
except messagebird.client.ErrorException as e:
print('\nAn error occured while requesting a Balance object:\n')
for error in e.errors:
print(' code : %d' % error.code)
print(' description : %s' % error.description)
print(' parameter : %s\n' % error.parameter)
| #!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import messagebird
ACCESS_KEY = 'test_gshuPaZoeEG6ovbc8M79w0QyM'
try:
# Create a MessageBird client with the specified ACCESS_KEY.
client = messagebird.Client(ACCESS_KEY)
# Fetch the Balance object.
balance = client.balance()
# Print the object information.
print('\nThe following information was returned as a Balance object:\n')
print(' amount : %d' % balance.amount)
print(' type : %s' % balance.type)
print(' payment : %s\n' % balance.payment)
except messagebird.client.ErrorException as e:
print('\nAn error occured while requesting a Balance object:\n')
for error in e.errors:
print(' code : %d' % error.code)
print(' description : %s' % error.description)
print(' parameter : %s\n' % error.parameter)
|
Use the latest Stream implementation. | /*******************************************************************************
* Copyright (C) 2016 Push Technology 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.pushtechnology.diffusion.transform.messaging;
import com.pushtechnology.diffusion.client.callbacks.Stream;
/**
* A stream of values received as messages.
*
* @param <V> the type of values
* @author Push Technology Limited
*/
public interface MessageStream<V> extends Stream {
/**
* Notified when a message is received.
*
* @param path the path to which the message was sent
* @param message the message
*/
void onMessageReceived(String path, V message);
}
| /*******************************************************************************
* Copyright (C) 2016 Push Technology 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.pushtechnology.diffusion.transform.messaging;
import com.pushtechnology.diffusion.client.features.Stream;
/**
* A stream of values received as messages.
*
* @param <V> the type of values
* @author Push Technology Limited
*/
public interface MessageStream<V> extends Stream {
/**
* Notified when a message is received.
*
* @param path the path to which the message was sent
* @param message the message
*/
void onMessageReceived(String path, V message);
}
|
Call cythsInit function after internationalization | //
// Author: CYOSP
// Created: 2016-10-21
// Version: 1.1.0
//
// 2016-10-22 V 1.1.0
// - Execute cythsInit function (if it exists)
// after internationalization
// 2016-10-21 V 1.0.0
// - Initial release
//
// i18next configuration
//
var i18nextOptions =
{
// evtl. use language-detector https://github.com/i18next/i18next-browser-languageDetector
lng: navigator.language || navigator.userLanguage,
fallbackLng: 'en',
load: 'currentOnly',
backend:
{
// i18nextLoadPath must be declared as a global variable
loadPath: i18nextLoadPath
}
}
//
// i18next initialization
//
i18next.use( i18nextXHRBackend ).init( i18nextOptions , function(err, t)
{
// For options see: https://github.com/i18next/jquery-i18next#initialize-the-plugin
jqueryI18next.init( i18next , $ );
// Start localizing, details: https://github.com/i18next/jquery-i18next#usage-of-selector-function
$( 'head, body' ).localize();
// Internationalization is performed
// Call CYTHS init function if defined
if( typeof cythsInit !== 'undefined' && $.isFunction( cythsInit ) )
{
cythsInit();
}
});
| // 2016-10-21 V 1.0.0
// - Initial release
//
// i18next configuration
//
var i18nextOptions =
{
// evtl. use language-detector https://github.com/i18next/i18next-browser-languageDetector
lng: navigator.language || navigator.userLanguage,
fallbackLng: 'en',
load: 'currentOnly',
backend:
{
// i18nextLoadPath must be declared as a global variable
loadPath: i18nextLoadPath
}
}
//
// i18next initialization
//
i18next.use( i18nextXHRBackend ).init( i18nextOptions , function(err, t)
{
// For options see: https://github.com/i18next/jquery-i18next#initialize-the-plugin
jqueryI18next.init( i18next , $ );
// Start localizing, details: https://github.com/i18next/jquery-i18next#usage-of-selector-function
$( 'head, body' ).localize();
}); |
Remove console.log about exit code | require('./patches/gherkin')
require('./keyboard/bindings')
const electron = require('electron')
const Cucumber = require('cucumber')
const Options = require('../cli/options')
const Output = require('./output')
const output = new Output()
const options = new Options(electron.remote.process.argv)
process.on('unhandledRejection', function(reason) {
output.write(reason.message + "\n" + reason.stack)
exitWithCode(3)
})
function exitWithCode(code) {
if (options.electronDebug) return
electron.remote.process.exit(code)
}
try {
const argv = options.cucumberArgv
const cwd = process.cwd()
const stdout = new Output()
new Cucumber.Cli({ argv, cwd, stdout }).run()
.then(pass => exitWithCode(pass ? 0 : 1))
} catch (err) {
log(err.stack)
exitWithCode(2)
}
| require('./patches/gherkin')
require('./keyboard/bindings')
const electron = require('electron')
const Cucumber = require('cucumber')
const Options = require('../cli/options')
const Output = require('./output')
const output = new Output()
const options = new Options(electron.remote.process.argv)
process.on('unhandledRejection', function(reason) {
output.write(reason.message + "\n" + reason.stack)
exitWithCode(3)
})
function exitWithCode(code) {
if (options.electronDebug) return
electron.remote.getGlobal('console').log("EXITING WITH CODE", code)
electron.remote.process.exit(code)
}
try {
const argv = options.cucumberArgv
const cwd = process.cwd()
const stdout = new Output()
new Cucumber.Cli({ argv, cwd, stdout }).run()
.then(pass => exitWithCode(pass ? 0 : 1))
} catch (err) {
log(err.stack)
exitWithCode(2)
}
|
Add :username param to PUT /v1/users/:username | package main
import (
"github.com/ricallinson/forgery"
"github.com/spacedock-io/index/common"
)
func Routes(server *f.Server) {
/*
Library repository routes
*/
server.Put("/v1/repositories/:repo/auth", LibraryAuth)
server.Put("/v1/repositories/:repo", CreateLibrary)
server.Delete("/v1/repositories/:repo", DeleteLibrary)
server.Put("/v1/repositories/:repo/images", UpdateLibraryImage)
server.Get("/v1/repositories/:repo/images", GetLibraryImage)
/*
User routes
*/
server.Get("/v1/users", common.CheckAuth, Login)
server.Post("/v1/users", CreateUser)
server.Put("/v1/users/:username", common.CheckAuth, UpdateUser)
/*
User repository routes
*/
server.Put("/v1/repositories/:namespace/:repo/auth", RepoAuth)
server.Put("/v1/repositories/:namespace/:repo", CreateRepo)
server.Delete("/v1/repositories/:namespace/:repo", DeleteRepo)
server.Put("/v1/repositories/:namespace/:repo/images", UpdateUserImage)
server.Get("/v1/repositories/:namespace/:repo/images", GetUserImage)
// Search route
server.Get("/v1/search", Search)
}
| package main
import (
"github.com/ricallinson/forgery"
"github.com/spacedock-io/index/common"
)
func Routes(server *f.Server) {
/*
Library repository routes
*/
server.Put("/v1/repositories/:repo/auth", LibraryAuth)
server.Put("/v1/repositories/:repo", CreateLibrary)
server.Delete("/v1/repositories/:repo", DeleteLibrary)
server.Put("/v1/repositories/:repo/images", UpdateLibraryImage)
server.Get("/v1/repositories/:repo/images", GetLibraryImage)
/*
User routes
*/
server.Get("/v1/users", common.CheckAuth, Login)
server.Post("/v1/users", CreateUser)
server.Put("/v1/users", common.CheckAuth, UpdateUser)
/*
User repository routes
*/
server.Put("/v1/repositories/:namespace/:repo/auth", RepoAuth)
server.Put("/v1/repositories/:namespace/:repo", CreateRepo)
server.Delete("/v1/repositories/:namespace/:repo", DeleteRepo)
server.Put("/v1/repositories/:namespace/:repo/images", UpdateUserImage)
server.Get("/v1/repositories/:namespace/:repo/images", GetUserImage)
// Search route
server.Get("/v1/search", Search)
}
|
:muscle: Resolve tick() after callbacks resolve | // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
module.exports = function() {
Ticker = {};
internal = {};
Ticker.tick = n => new Promise(function(resolve, reject) {
let promise = Promise.resolve();
if (typeof n === "undefined")
n = 1;
for (let i = 0; i < n; i += 1) {
internal.counter += 1;
if (internal.callbacks.has(internal.counter))
for (let callback of internal.callbacks.get(internal.counter))
promise = internal.appendPromise(promise, callback);
}
promise.then(resolve);
});
Ticker.at = function(n, callback) {
if (!internal.callbacks.has(n))
internal.callbacks.set(n, []);
internal.callbacks.get(n).push(callback);
};
internal.callbacks = new Map();
internal.counter = 0;
internal.appendPromise = function(promise, callback) {
return new Promise(function(done) {
promise.then(function() {
Promise.resolve(callback()).then(done);
});
});
};
return Ticker;
};
| // Copyright (c) 2017 The Regents of the University of Michigan.
// All Rights Reserved. Licensed according to the terms of the Revised
// BSD License. See LICENSE.txt for details.
module.exports = function() {
Ticker = {};
internal = {};
Ticker.tick = n => new Promise(function(resolve, reject) {
if (typeof n === "undefined")
n = 1;
for (let i = 0; i < n; i += 1) {
internal.counter += 1;
let promise = Promise.resolve();
if (internal.callbacks.has(internal.counter))
for (let callback of internal.callbacks.get(internal.counter))
promise = internal.appendPromise(promise, callback);
}
resolve();
});
Ticker.at = function(n, callback) {
if (!internal.callbacks.has(n))
internal.callbacks.set(n, []);
internal.callbacks.get(n).push(callback);
};
internal.callbacks = new Map();
internal.counter = 0;
internal.appendPromise = function(promise, callback) {
return new Promise(function(done) {
promise.then(function() {
Promise.resolve(callback()).then(done);
});
});
};
return Ticker;
};
|
Add details field to error | 'use strict';
var Mixin = require('../../utils/mixin'),
inherits = require('util').inherits;
var ErrorReportingMixinBase = module.exports = function (host, onParseError) {
Mixin.call(this, host);
this.posTracker = null;
this.onParseError = onParseError;
};
inherits(ErrorReportingMixinBase, Mixin);
ErrorReportingMixinBase.prototype._getOverriddenMethods = function (mxn) {
return {
_err: function (code, details) {
mxn.onParseError({
code: code,
line: mxn.posTracker.line,
col: mxn.posTracker.col,
offset: mxn.posTracker.offset,
details: details
});
}
};
};
| 'use strict';
var Mixin = require('../../utils/mixin'),
inherits = require('util').inherits;
var ErrorReportingMixinBase = module.exports = function (host, onParseError) {
Mixin.call(this, host);
this.posTracker = null;
this.onParseError = onParseError;
};
inherits(ErrorReportingMixinBase, Mixin);
ErrorReportingMixinBase.prototype._getOverriddenMethods = function (mxn) {
return {
_err: function (code) {
mxn.onParseError({
code: code,
line: mxn.posTracker.line,
col: mxn.posTracker.col,
offset: mxn.posTracker.offset
});
}
};
};
|
Fix applyF_filterG function to pass test case | # Problem 8
# 20.0 points possible (graded)
# Implement a function that meets the specifications below.
# For example, the following functions, f, g, and test code:
# def f(i):
# return i + 2
# def g(i):
# return i > 5
# L = [0, -10, 5, 6, -4]
# print(applyF_filterG(L, f, g))
# print(L)
# Should print:
# 6
# [5, 6]
def f(i):
return i + 2
def g(i):
return i > 5
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function, returns either True or False
Mutates L such that, for each element i originally in L, L contains i if g(f(i)) returns True, and no other elements
Returns the largest element in the mutated L or -1 if the list is empty
"""
l = L[:]
for i in l:
if not g(f(i)):
L.remove(i)
if len(L) == 0:
return -1
else:
return max(L)
L = [0, -10, 5, 6, -4]
print(applyF_filterG(L, f, g))
print(L) | # Problem 8
# 20.0 points possible (graded)
# Implement a function that meets the specifications below.
# For example, the following functions, f, g, and test code:
# def f(i):
# return i + 2
# def g(i):
# return i > 5
# L = [0, -10, 5, 6, -4]
# print(applyF_filterG(L, f, g))
# print(L)
# Should print:
# 6
# [5, 6]
def f(i):
return i + 2
def g(i):
return i > 5
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function, returns either True or False
Mutates L such that, for each element i originally in L, L contains i if g(f(i)) returns True, and no other elements
Returns the largest element in the mutated L or -1 if the list is empty
"""
l = L[:]
for i in l:
if g(f(i)) is False:
L.remove(i)
if len(L) == 0:
return -1
else:
return max(L)
L = [0, -10, 5, 6, -4]
print(applyF_filterG(L, f, g))
print(L) |
Delete existing urls before each run | import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
# remove existing values first as this allows us to remove bad urls from the csv file
Election.objects.update(modgov_url=None)
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
| import csv
import os
from django.core.management.base import BaseCommand
import resultsbot
from elections.models import Election
class Command(BaseCommand):
def handle(self, **options):
"""
Stores possible modgov urls stored in CSV file against the related election objects
"""
path = os.path.join(
os.path.dirname(resultsbot.__file__), "election_id_to_url.csv"
)
with open(path) as f:
csv_file = csv.reader(f)
for line in csv_file:
try:
election = Election.objects.get(slug=line[0])
election.modgov_url = line[1]
election.save()
except (IndexError, Election.DoesNotExist):
continue
|
Fix ScssFilter failing when sass is not installed in /usr/bin/sass. | <?php
App::uses('ScssFilter', 'AssetCompress.Filter');
class ScssFilterTest extends CakeTestCase {
public function setUp() {
parent::setUp();
$this->_pluginPath = App::pluginPath('AssetCompress');
$this->_cssDir = $this->_pluginPath . 'Test' . DS . 'test_files' . DS . 'css' . DS;
$this->filter = new ScssFilter();
}
public function testParsing() {
$this->skipIf(DS === '\\', 'Requires ruby and sass rubygem to be installed');
$hasSass = `which sass`;
$this->skipIf(empty($hasSass), 'Requires ruby and sass to be installed');
$this->filter->settings(array('sass' => trim($hasSass)));
$content = file_get_contents($this->_cssDir . 'test.scss');
$result = $this->filter->input($this->_cssDir . 'test.scss', $content);
$expected = file_get_contents($this->_cssDir . 'compiled_scss.css');
$this->assertEquals($expected, $result);
}
}
| <?php
App::uses('ScssFilter', 'AssetCompress.Filter');
class ScssFilterTest extends CakeTestCase {
public function setUp() {
parent::setUp();
$this->_pluginPath = App::pluginPath('AssetCompress');
$this->_cssDir = $this->_pluginPath . 'Test' . DS . 'test_files' . DS . 'css' . DS;
$this->filter = new ScssFilter();
}
public function testParsing() {
$this->skipIf(DS === '\\', 'Requires ruby and sass rubygem to be installed');
$hasSass = `which sass`;
$this->skipIf(empty($hasSass), 'Requires ruby and sass to be installed');
$content = file_get_contents($this->_cssDir . 'test.scss');
$result = $this->filter->input($this->_cssDir . 'test.scss', $content);
$expected = file_get_contents($this->_cssDir . 'compiled_scss.css');
$this->assertEquals($expected, $result);
}
}
|
Add backwards compatibility to Android lib | package com.reactnativenavigation.bridge;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.reactnativenavigation.views.managers.SharedElementTransitionManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NavigationReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new NavigationReactModule(reactContext)
);
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new SharedElementTransitionManager()
);
}
}
| package com.reactnativenavigation.bridge;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.reactnativenavigation.views.managers.SharedElementTransitionManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NavigationReactPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(
new NavigationReactModule(reactContext)
);
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new SharedElementTransitionManager()
);
}
}
|
Use the correct class name. | /*
* Copyright (c) 1998-2014 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* version 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/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as defined
* by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.app;
import com.trollworks.toolkit.utility.Launcher;
/**
* This class is to be compiled with Java 1.1 to allow it to be loaded and executed even on very old
* JVM's.
*/
public class GCS {
public static void main(String[] args) {
Launcher.launch("1.8", "com.trollworks.gcs.app.GCSMain", args); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| /*
* Copyright (c) 1998-2014 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* version 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/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as defined
* by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.app;
import com.trollworks.toolkit.utility.Launcher;
/**
* This class is to be compiled with Java 1.1 to allow it to be loaded and executed even on very old
* JVM's.
*/
public class GCS {
public static void main(String[] args) {
Launcher.launch("1.8", "com.trollworks.gcs.app.GCS", args); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
Add debug case for serialize sources | <?php
function dump ($o) {
$o = serialize($o);
echo json_encode($o), "\n";
}
class Foo {
public $bar = 1;
protected $baz = 2;
private $xyzzy = array(1,2,3,4,5,6,7,8,9);
protected $self;
public function __construct () {
$this->self = $this;
}
}
$f = new Foo();
dump($f);
class Bar {
}
$f = new Bar();
$f->self = $f;
dump($f);
class Child extends Foo {
public $lorem = 42;
protected $ipsum = 37;
private $dolor = 13;
}
$f = new Child();
dump($f);
$f = new stdClass;
$f->obj1->obj2->obj3->arr = array();
$f->obj1->obj2->obj3->arr[] = 1;
$f->obj1->obj2->obj3->arr[] = 2;
$f->obj1->obj2->obj3->arr[] = 3;
$f->obj1->obj2->obj3->arr['ref1'] = $f->obj1->obj2;
$f->obj1->obj2->obj3->arr['ref2'] = &$f->obj1->obj2->obj3->arr;
dump($f);
| <?php
function dump ($o) {
$o = serialize($o);
echo json_encode($o), "\n";
}
class Foo {
public $bar = 1;
protected $baz = 2;
private $xyzzy = array(1,2,3,4,5,6,7,8,9);
protected $self;
public function __construct () {
$this->self = $this;
}
}
$f = new Foo();
dump($f);
class Bar {
}
$f = new Bar();
$f->self = $f;
dump($f);
$f = new stdClass;
$f->obj1->obj2->obj3->arr = array();
$f->obj1->obj2->obj3->arr[] = 1;
$f->obj1->obj2->obj3->arr[] = 2;
$f->obj1->obj2->obj3->arr[] = 3;
$f->obj1->obj2->obj3->arr['ref1'] = $f->obj1->obj2;
$f->obj1->obj2->obj3->arr['ref2'] = &$f->obj1->obj2->obj3->arr;
dump($f);
|
Use os independent line seperator | import requests
from os import path, linesep
project_gutenberg_bible_url = 'http://www.gutenberg.org/cache/epub/10/pg10.txt'
bible_filename = 'bible.txt'
bible_path = path.join('..', 'data', bible_filename)
def bible_text(url=project_gutenberg_bible_url):
"""Get the bible text"""
return requests.get(url).text
def process_gutenberg_bible(url=project_gutenberg_bible_url):
"""Remove header and footer info"""
gutenberg_header_footer_sep = linesep*8
header, body, footer = bible_text(url).split(gutenberg_header_footer_sep)
return body
def save_internet_bible(url=project_gutenberg_bible_url):
"""Save bible as a text file"""
bible = process_gutenberg_bible(url)
with open(bible_path, 'w') as file:
file.write(bible)
| import requests
from os import path
project_gutenberg_bible_url = 'http://www.gutenberg.org/cache/epub/10/pg10.txt'
bible_filename = 'bible.txt'
bible_path = path.join('..', 'data', bible_filename)
def bible_text(url=project_gutenberg_bible_url):
"""Get the bible text"""
return requests.get(url).text
def process_gutenberg_bible(url=project_gutenberg_bible_url):
"""Remove header and footer info"""
gutenberg_header_footer_sep = '\n\r'*8
header, body, footer = bible_text(url).split(gutenberg_header_footer_sep)
return body
def save_internet_bible(url=project_gutenberg_bible_url):
"""Save bible as a text file"""
bible = process_gutenberg_bible(url)
with open(bible_path, 'w') as file:
file.write(bible)
|
Fix bug in method helpers not calling userId function | import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
export function requireAdmin() {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error(400, 'You must be logged in');
}
const user = Meteor.users.findOne(userId);
if (!user || user.roles.indexOf('admin') < 0) {
throw new Meteor.Error(400, 'You do not have permission to do that!');
}
return true;
}
export function isAdmin() {
const userId = Meteor.userId();
if (!userId) {
return false;
}
const user = Meteor.users.findOne(userId);
return user && user.hasRole('admin');
}
export function checkMinLength(length) {
return Match.Where((x) => {
check(x, String);
return x.length >= length;
});
};
export function requireUser() {
if (!Meteor.userId()) {
throw new Meteor.Error(403, 'You must be logged in');
}
return true;
}
| import { Meteor } from 'meteor/meteor';
import { Match, check } from 'meteor/check';
export function requireAdmin() {
const userId = Meteor.userId;
if (!userId) {
throw new Meteor.Error(400, 'You must be logged in');
}
const user = Meteor.users.findOne(userId);
if (!user || user.roles.indexOf('admin') < 0) {
throw new Meteor.Error(400, 'You do not have permission to do that!');
}
return true;
}
export function isAdmin() {
const userId = Meteor.userId;
if (!userId) {
return false;
}
const user = Meteor.users.findOne(userId);
return user && user.hasRole('admin');
}
export function checkMinLength(length) {
return Match.Where((x) => {
check(x, String);
return x.length >= length;
});
};
|
Clarify API doc a smidge. | <?php
/**
* @file
* This file documents all available hook functions to manipulate data.
*/
/**
* Define custom queries to be used when batching through "children" of objects.
*
* @param FedoraObject $object
* A FedoraObject.
*
* @return array
* An array of queries to be returned to the islandora_xacml_editor module.
* Each entry in the array is an associate array itself with the following
* structure:
* - type: The type of query to be executed either itql or sparql.
* - query: The defined query string. The field we expect returned is that of
* "object". I.e select ?object.
* - description: Human-readable description used in populating the options
* dropdown.
*/
function hook_islandora_xacml_editor_child_query($object) {
return array(
'sample_query' => array(
'type' => 'itql',
'query' => 'select $object from <#ri> where $object <fedora-rels-ext:isMemberOfCollection> <info:fedora/islandora:root>',
'description' => t('Sweet query bro.'),
),
);
}
| <?php
/**
* @file
* This file documents all available hook functions to manipulate data.
*/
/**
* Define custom queries to be used when batching through "children" of objects.
*
* @param FedoraObject $object
* A FedoraObject.
*
* @return array
* An array of queries to be returned to the islandora_xacml_editor module.
* Each entry in the array is an associate array itself with the following
* structure:
* - type: The type of query to be executed either itql or sparql.
* - query: The defined query string.
* - description: Human-readable description used in populating the options
* dropdown.
*/
function hook_islandora_xacml_editor_child_query($object) {
return array(
'sample_query' => array(
'type' => 'itql',
'query' => 'select $object from <#ri> where $object <fedora-rels-ext:isMemberOfCollection> <info:fedora/islandora:root>',
'description' => t('Sweet query bro.'),
),
);
}
|
Update in outputs and fix spaces and names.
Signed-off-by: messiasthi <8562fc1efba9a3c99753c749fdfb1b6932b70fbf@gmail.com> | # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def get_paths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
processed_files = []
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
processed_files = commands.detect(get_paths(params))
elif "delete" in params:
processed_files = commands.delete(commands.detect(get_paths(params)))
elif "link" in params:
processed_files = commands.link(commands.detect(get_paths(params)))
else:
commands.help()
if len(processed_files) > 0:
print(processed_files)
else:
print("No duplicates found")
print("Great! Bye!")
exit(0)
| # The client of DDuplicated tool.
from os import path as opath, getcwd
from sys import argv
from dduplicated import commands
def getPaths(params):
paths = []
for param in params:
path = opath.join(getcwd(), param)
if opath.exists(path) and opath.isdir(path) and not opath.islink(path):
paths.append(path)
return paths
def main():
params = argv
# Remove the command name
del params[0]
if len(params) == 0 or "help" in params:
commands.help()
elif "detect" in params:
duplicates = commands.detect(getPaths(params))
if len(duplicates) < 1:
print("No duplicates found")
print("Great! Bye!")
exit(0)
for (key, values) in duplicates.items():
print(key + " -> ")
for value in values:
print("\t\t\t\t\t" + value)
elif "delete" in params:
commands.delete(commands.detect(getPaths(params)))
elif "link" in params:
commands.link(commands.detect(getPaths(params)))
else:
commands.help()
exit(0)
|
Improve runtime by using an array of diffs | #!/bin/python3
import math
import os
import random
import re
import sys
def arrayManipulation(n, queries):
# An array used to capture the difference of an element
# compared to the previous element.
# Therefore the value of diffs[n] after all array manipulations is
# the cumulative sum of values from diffs[0] to diffs[n - 1]
diffs = [0] * n
for a, b, k in queries:
# Adds "k" to all subsequent elements in the array
diffs[a - 1] += k
# Ignore if b is out of range
if (b < n):
# Subtracts "k" from all subsequent elements in the array
diffs[b] -= k
sumSoFar = 0
maxSoFar = 0
for diff in diffs:
sumSoFar += diff
if sumSoFar > maxSoFar:
maxSoFar = sumSoFar
return maxSoFar
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)
fptr.write(str(result) + '\n')
fptr.close()
| #!/bin/python3
import math
import os
import random
import re
import sys
def arrayManipulation(n, queries):
array = [0] * n
for a, b, k in queries:
# Start is a - 1 because this is a one indexed array
for i in range(a - 1, b):
array[i] += k
print(array)
return max(array)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = arrayManipulation(n, queries)
fptr.write(str(result) + '\n')
fptr.close()
|
Add url to pypi package | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
url='https://github.com/openfisca/openfisca-country-template',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
'nose',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='OpenFisca-Country-Template',
version='0.1.0',
author='OpenFisca Team',
author_email='contact@openfisca.fr',
description=u'Template of a tax and benefit system for OpenFisca',
keywords='benefit microsimulation social tax',
license='http://www.fsf.org/licensing/licenses/agpl-3.0.html',
include_package_data = True, # Will read MANIFEST.in
install_requires=[
'OpenFisca-Core >= 6.1.0, < 11.0',
],
extras_require = {
'api': [
'OpenFisca-Web-API >= 4.0.0, < 6.0',
],
'test': [
'flake8',
'flake8-print',
'nose',
]
},
packages=find_packages(),
test_suite='nose.collector',
)
|
Add api calls to manager | <?php
namespace DarthSoup\Rundeck;
use DarthSoup\Rundeck\Adapter\AdapterInterface;
use DarthSoup\Rundeck\Api\Execution;
use DarthSoup\Rundeck\Api\Job;
use DarthSoup\Rundeck\Api\Project;
use DarthSoup\Rundeck\Api\System;
class Rundeck
{
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* @var string
*/
protected $api;
/**
* @param AdapterInterface $adapter
* @param string $api
*/
public function __construct(AdapterInterface $adapter, string $api)
{
$this->adapter = $adapter;
$this->api = $api;
}
/**
* @return System
*/
public function system()
{
return new System($this->adapter, $this->api);
}
/**
* @return Job
*/
public function job()
{
return new Job($this->adapter, $this->api);
}
/**
* @return Execution
*/
public function execution()
{
return new Execution($this->adapter, $this->api);
}
/*
* @return Project
*/
public function project()
{
return new Project($this->adapter, $this->api);
}
}
| <?php
namespace DarthSoup\Rundeck;
use DarthSoup\Rundeck\Adapter\AdapterInterface;
use DarthSoup\Rundeck\Api\System;
class Rundeck
{
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* @var string
*/
protected $api;
/**
* @param AdapterInterface $adapter
* @param string $api
*/
public function __construct(AdapterInterface $adapter, string $api)
{
$this->adapter = $adapter;
$this->api = $api;
}
/**
* @return System
*/
public function system()
{
return new System($this->adapter, $this->api);
}
}
|
Fix redis syntax error if third argument is undefined | const Redis = require('ioredis');
module.exports = url => {
const redis = new Redis(url);
redis.setJSON = async (...arguments) => {
arguments[1] = JSON.stringify(arguments[1]);
if (typeof arguments[2] === 'object' && arguments[2].asSeconds) {
arguments[2] = parseInt(arguments[2].asSeconds());
}
if (typeof arguments[2] === 'number') {
arguments[3] = parseInt(arguments[2]);
arguments[2] = 'EX';
}
if (typeof arguments[2] === 'undefined') {
arguments = [arguments[0], arguments[1]];
}
return await redis.set.apply(redis, arguments);
}
redis.getJSON = async key => {
const value = await redis.get(key);
if (value) {
return JSON.parse(value);
}
return value;
}
return redis;
};
| const Redis = require('ioredis');
module.exports = url => {
const redis = new Redis(url);
redis.setJSON = async (...arguments) => {
arguments[1] = JSON.stringify(arguments[1]);
if (typeof arguments[2] === 'object' && arguments[2].asSeconds) {
arguments[2] = parseInt(arguments[2].asSeconds());
}
if (typeof arguments[2] === 'number') {
arguments[3] = parseInt(arguments[2]);
arguments[2] = 'EX';
}
return await redis.set.apply(redis, arguments);
}
redis.getJSON = async key => {
const value = await redis.get(key);
if (value) {
return JSON.parse(value);
}
return value;
}
return redis;
};
|
Remove unneeded coverage lines from tests bundler | // ---------------------------------------
// Test Environment Setup
// ---------------------------------------
import sinon from 'sinon'
import chai from 'chai'
import sinonChai from 'sinon-chai'
import chaiAsPromised from 'chai-as-promised'
import chaiEnzyme from 'chai-enzyme'
chai.use(sinonChai)
chai.use(chaiAsPromised)
chai.use(chaiEnzyme())
global.chai = chai
global.sinon = sinon
global.expect = chai.expect
global.should = chai.should()
// ---------------------------------------
// Require Tests
// ---------------------------------------
// for use with karma-webpack-with-fast-source-maps
const __karmaWebpackManifest__ = []; // eslint-disable-line
const inManifest = (path) => ~__karmaWebpackManifest__.indexOf(path)
// require all `tests/**/*.spec.js`
const testsContext = require.context('./', true, /\.spec\.js$/)
// only run tests that have changed after the first pass.
const testsToRun = testsContext.keys().filter(inManifest)
;(testsToRun.length ? testsToRun : testsContext.keys()).forEach(testsContext)
| // ---------------------------------------
// Test Environment Setup
// ---------------------------------------
import sinon from 'sinon'
import chai from 'chai'
import sinonChai from 'sinon-chai'
import chaiAsPromised from 'chai-as-promised'
import chaiEnzyme from 'chai-enzyme'
chai.use(sinonChai)
chai.use(chaiAsPromised)
chai.use(chaiEnzyme())
global.chai = chai
global.sinon = sinon
global.expect = chai.expect
global.should = chai.should()
// ---------------------------------------
// Require Tests
// ---------------------------------------
// for use with karma-webpack-with-fast-source-maps
const __karmaWebpackManifest__ = []; // eslint-disable-line
const inManifest = (path) => ~__karmaWebpackManifest__.indexOf(path)
// require all `tests/**/*.spec.js`
const testsContext = require.context('./', true, /\.spec\.js$/)
// only run tests that have changed after the first pass.
const testsToRun = testsContext.keys().filter(inManifest)
;(testsToRun.length ? testsToRun : testsContext.keys()).forEach(testsContext)
// require all `src/**/*.js` except for `main.js` (for isparta coverage reporting)
if (__COVERAGE__) {
const componentsContext = require.context('../src/', true, /^((?!main|reducers).)*\.js$/)
componentsContext.keys().forEach(componentsContext)
}
|
Fix mix of tabs and spaces for indentation | L.CRS.proj4js = (function () {
var createProjection = function (code, def, /*L.Transformation*/ transformation) {
if (typeof(def) !== 'undefined') {
Proj4js.defs[code] = def;
}
var proj = new Proj4js.Proj(code);
return {
project: function (latlng) {
var point = new L.Point(latlng.lng, latlng.lat);
return Proj4js.transform(Proj4js.WGS84, proj, point);
},
unproject: function (point, unbounded) {
var point2 = Proj4js.transform(proj, Proj4js.WGS84, point.clone());
return new L.LatLng(point2.y, point2.x, unbounded);
}
};
};
return function (code, def, transformation) {
return L.Util.extend({}, L.CRS, {
code: code,
transformation: transformation ? transformation: new L.Transformation(1, 0, -1, 0),
projection: createProjection(code, def)
});
};
}());
| L.CRS.proj4js = (function () {
var createProjection = function (code, def, /*L.Transformation*/ transformation) {
if (typeof(def) !== 'undefined') {
Proj4js.defs[code] = def;
}
var proj = new Proj4js.Proj(code);
return {
project: function (latlng) {
var point = new L.Point(latlng.lng, latlng.lat);
return Proj4js.transform(Proj4js.WGS84, proj, point);
},
unproject: function (point, unbounded) {
var point2 = Proj4js.transform(proj, Proj4js.WGS84, point.clone());
return new L.LatLng(point2.y, point2.x, unbounded);
}
};
};
return function (code, def, transformation) {
return L.Util.extend({}, L.CRS, {
code: code,
transformation: transformation ? transformation: new L.Transformation(1, 0, -1, 0),
projection: createProjection(code, def)
});
};
}());
|
Test edit - to check svn email hook | import os, glob, string, shutil
from distutils.core import setup
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
| from distutils.core import setup
import os, glob, string, shutil
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
|
Make onUnhandled safe for undefined errors
Summary:
This pull request fixes cases where the `error` argument of the `onUnhandled` method in `Libraries/Promise.js` is undefined. Previously this would result in a redbox with the helpful message: `Cannot read property message of undefined`. With this pull request, unhandled promise rejections result in the desired yellowbox saying that a promise rejection went unhandled.
I still do not know what would cause the error argument to be undefined, but this change makes the module behave as expected in an app I am building.
cc bestander
Relevant issue: #8452
Closes https://github.com/facebook/react-native/pull/9119
Differential Revision: D3655589
Pulled By: bestander
fbshipit-source-id: a975a0ab58701240ba06574c04521cd542700ff7 | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Promise
* @flow
*/
'use strict';
const Promise = require('fbjs/lib/Promise.native');
if (__DEV__) {
require('promise/setimmediate/rejection-tracking').enable({
allRejections: true,
onUnhandled: (id, error = {}) => {
const {message = null, stack = null} = error;
const warning =
`Possible Unhandled Promise Rejection (id: ${id}):\n` +
(message == null ? '' : `${message}\n`) +
(stack == null ? '' : stack);
console.warn(warning);
},
onHandled: (id) => {
const warning =
`Promise Rejection Handled (id: ${id})\n` +
'This means you can ignore any previous messages of the form ' +
`"Possible Unhandled Promise Rejection (id: ${id}):"`;
console.warn(warning);
},
});
}
module.exports = Promise;
| /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Promise
* @flow
*/
'use strict';
const Promise = require('fbjs/lib/Promise.native');
if (__DEV__) {
require('promise/setimmediate/rejection-tracking').enable({
allRejections: true,
onUnhandled: (id, error) => {
const {message, stack} = error;
const warning =
`Possible Unhandled Promise Rejection (id: ${id}):\n` +
(message == null ? '' : `${message}\n`) +
(stack == null ? '' : stack);
console.warn(warning);
},
onHandled: (id) => {
const warning =
`Promise Rejection Handled (id: ${id})\n` +
'This means you can ignore any previous messages of the form ' +
`"Possible Unhandled Promise Rejection (id: ${id}):"`;
console.warn(warning);
},
});
}
module.exports = Promise;
|
Update email username to use the right variable name. | # Production settings for us_ignite
import os
from us_ignite.settings import *
# Sensitive values are saved as env variables:
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SITE_URL = 'http://us-ignite.herokuapp.com'
# Make this unique, and don't share it with anybody.
SECRET_KEY = env('SECRET_KEY')
# Basic authentication for Heroku
BASIC_WWW_AUTHENTICATION_USERNAME = env('WWW_USERNAME')
BASIC_WWW_AUTHENTICATION_PASSWORD = env('WWW_PASSWORD')
BASIC_WWW_AUTHENTICATION = False
# Email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = env('EMAIL_HOST')
EMAIL_PORT = env('EMAIL_PORT')
EMAIL_HOST_USER = env('HOST_USER')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
# Settings to use the filesystem
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
| # Production settings for us_ignite
import os
from us_ignite.settings import *
# Sensitive values are saved as env variables:
env = os.getenv
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
# settings is one directory up now
here = lambda *x: os.path.join(PROJECT_ROOT, '..', *x)
SITE_URL = 'http://us-ignite.herokuapp.com'
# Make this unique, and don't share it with anybody.
SECRET_KEY = env('SECRET_KEY')
# Basic authentication for Heroku
BASIC_WWW_AUTHENTICATION_USERNAME = env('WWW_USERNAME')
BASIC_WWW_AUTHENTICATION_PASSWORD = env('WWW_PASSWORD')
BASIC_WWW_AUTHENTICATION = False
# Email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = env('EMAIL_HOST')
EMAIL_PORT = env('EMAIL_PORT')
EMAIL_HOST_USER = env('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
# Settings to use the filesystem
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
|
Add csrf token protection to jQuery initiated requests | import Rails from 'rails-ujs';
import jQuery from 'jquery';
// We use `jQuery.active` in our capybara suit to wait for ajax requests.
// Newer jQuery-less version of rails-ujs is breaking it.
// We have to set `ajax:complete` listener on the same element as the one
// we catch ajax:send on as by the end of the request
// the old element may be removed from DOM.
Rails.delegate(document, '[data-remote]', 'ajax:send', ({ target }) => {
let callback = () => {
jQuery.active--;
target.removeEventListener('ajax:complete', callback);
};
target.addEventListener('ajax:complete', callback);
jQuery.active++;
});
// `smart_listing` gem is overriding `$.rails.href` method. When using newer
// jQuery-less version of rails-ujs it breaks.
// https://github.com/Sology/smart_listing/blob/master/app/assets/javascripts/smart_listing.coffee.erb#L9
addEventListener('load', () => {
const { href } = Rails;
Rails.href = function(element) {
return element.href || href(element);
};
});
// rails-ujs installs CSRFProtection for its own ajax implementation. We might need
// CSRFProtection for jQuery initiated requests. This code is from jquery-ujs.
jQuery.ajaxPrefilter((options, originalOptions, xhr) => {
if (!options.crossDomain) {
CSRFProtection(xhr);
}
});
function csrfToken() {
return jQuery('meta[name=csrf-token]').attr('content');
}
function CSRFProtection(xhr) {
let token = csrfToken();
if (token) {
xhr.setRequestHeader('X-CSRF-Token', token);
}
}
| import Rails from 'rails-ujs';
import jQuery from 'jquery';
// We use `jQuery.active` in our capybara suit to wait for ajax requests.
// Newer jQuery-less version of rails-ujs is breaking it.
// We have to set `ajax:complete` listener on the same element as the one
// we catch ajax:send on as by the end of the request
// the old element may be removed from DOM.
Rails.delegate(document, '[data-remote]', 'ajax:send', ({ target }) => {
let callback = () => {
jQuery.active--;
target.removeEventListener('ajax:complete', callback);
};
target.addEventListener('ajax:complete', callback);
jQuery.active++;
});
// `smart_listing` gem is overriding `$.rails.href` method. When using newer
// jQuery-less version of rails-ujs it breaks.
// https://github.com/Sology/smart_listing/blob/master/app/assets/javascripts/smart_listing.coffee.erb#L9
addEventListener('load', () => {
const { href } = Rails;
Rails.href = function(element) {
return element.href || href(element);
};
});
|
Update dependencies for Meteor 1.6.1 | //jshint esversion: 6
Package.describe({
name: 'elmarti:video-chat',
version: '2.1.1',
summary: 'Simple WebRTC Video Chat for your app.',
git: 'https://github.com/elmarti/meteor-video-chat',
documentation: 'README.md'
});
Package.onUse(api => {
Npm.depends({
"rtcfly": "0.1.5"
});
api.versionsFrom('1.5');
api.use('ecmascript');
api.use("rocketchat:streamer@0.6.1");
api.use("mizzao:user-status@0.6.7");
api.addFiles(['lib/index.js'], "client");
api.addFiles(['lib/publish.js'], "server");
api.addFiles(['lib/index.server.js'], 'server');
api.mainModule('lib/index.js', 'client');
});
| //jshint esversion: 6
Package.describe({
name: 'elmarti:video-chat',
version: '2.1.1',
summary: 'Simple WebRTC Video Chat for your app.',
git: 'https://github.com/elmarti/meteor-video-chat',
documentation: 'README.md'
});
Package.onUse(api => {
Npm.depends({
"rtcfly": "0.1.5"
});
api.versionsFrom('1.5');
api.use('ecmascript');
api.use("rocketchat:streamer@0.5.0");
api.use("mizzao:user-status@0.6.6");
api.addFiles(['lib/index.js'], "client");
api.addFiles(['lib/publish.js'], "server");
api.addFiles(['lib/index.server.js'], 'server');
api.mainModule('lib/index.js', 'client');
});
|
Modify the dummy image link | <?php
namespace Bex\Behat\ScreenshotExtension\Driver;
use Bex\Behat\ScreenshotExtension\Driver\ImageDriverInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class Dummy implements ImageDriverInterface
{
/**
* @param ArrayNodeDefinition $builder
*/
public function configure(ArrayNodeDefinition $builder)
{
// driver configuration tree should be built here
}
/**
* @param ContainerBuilder $container
* @param array $config
*/
public function load(ContainerBuilder $container, array $config)
{
// store the given configuration here
}
/**
* @param string $binaryImage
* @param string $filename
*
* @return string URL to the image
*/
public function upload($binaryImage, $filename)
{
// upload the image here and return the image url
return 'http://docs.behat.org/en/v2.5/_static/img/logo.png';
}
} | <?php
namespace Bex\Behat\ScreenshotExtension\Driver;
use Bex\Behat\ScreenshotExtension\Driver\ImageDriverInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class Dummy implements ImageDriverInterface
{
/**
* @param ArrayNodeDefinition $builder
*/
public function configure(ArrayNodeDefinition $builder)
{
// driver configuration tree should be built here
}
/**
* @param ContainerBuilder $container
* @param array $config
*/
public function load(ContainerBuilder $container, array $config)
{
// store the given configuration here
}
/**
* @param string $binaryImage
* @param string $filename
*
* @return string URL to the image
*/
public function upload($binaryImage, $filename)
{
// upload the image here and return the image url
return 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
}
} |
Add support for storing site preferences within the model. | package model
type Site struct {
ID string `json:"id,omitempty" redis:"id"`
Name *string `json:"name,omitempty" redis:"name"`
Type *string `json:"type,omitempty" redis:"type"`
Latitude *float64 `json:"latitude,omitempty" redis:"latitude"`
Longitude *float64 `json:"longitude,omitempty" redis:"longitude"`
TimeZoneID *string `json:"timeZoneId,omitempty" redis:"timeZoneId"`
TimeZoneName *string `json:"timeZoneName,omitempty" redis:"timeZoneName"`
TimeZoneOffset *int `json:"timeZoneOffset,omitempty" redis:"timeZoneOffset"`
SitePreferences interface{} `json:"site-preferences,omitempty" redis:"site-preferences,json"`
}
//https://maps.googleapis.com/maps/api/timezone/json?location=-33.86,151.20×tamp=1414645501
/*{
id: "whatever",
name: "Home",
type: "home",
latitude: -33.86,
longitude: 151.20,
timeZoneID: "Australia/Sydney",
timeZoneName: "Australian Eastern Daylight Time",
timeZoneOffset: 36000
}*/
| package model
type Site struct {
ID string `json:"id,omitempty" redis:"id"`
Name *string `json:"name,omitempty" redis:"name"`
Type *string `json:"type,omitempty" redis:"type"`
Latitude *float64 `json:"latitude,omitempty" redis:"latitude"`
Longitude *float64 `json:"longitude,omitempty" redis:"longitude"`
TimeZoneID *string `json:"timeZoneId,omitempty" redis:"timeZoneId"`
TimeZoneName *string `json:"timeZoneName,omitempty" redis:"timeZoneName"`
TimeZoneOffset *int `json:"timeZoneOffset,omitempty" redis:"timeZoneOffset"`
}
//https://maps.googleapis.com/maps/api/timezone/json?location=-33.86,151.20×tamp=1414645501
/*{
id: "whatever",
name: "Home",
type: "home",
latitude: -33.86,
longitude: 151.20,
timeZoneID: "Australia/Sydney",
timeZoneName: "Australian Eastern Daylight Time",
timeZoneOffset: 36000
}*/
|
Cut stable release for 0.1.0 | // Copyright 2016 Google 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
var (
// Major is the current major version of master branch..
Major = 0
// Minor is the current minor version of master branch.
Minor = 1
// Patch is the curernt patched version of the master branch.
Patch = 0
// Release is the current release level of the master branch. Valid values
// are dev (developement unreleased), rcX (release candidate with current
// iteration), stable (indicates a final released version).
Release = "stable"
)
| // Copyright 2016 Google 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
var (
// Major is the current major version of master branch..
Major = 0
// Minor is the current minor version of master branch.
Minor = 1
// Patch is the curernt patched version of the master branch.
Patch = 0
// Release is the current release level of the master branch. Valid values
// are dev (developement unreleased), rcX (release candidate with current
// iteration), stable (indicates a final released version).
Release = "rc2"
)
|
Fix migration that adds custom annotation permissions | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('annotations', '0002_add_volume_uri'),
]
operations = [
migrations.CreateModel(
name='AnnotationGroup',
fields=[
('group_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='auth.Group')),
('notes', models.TextField(blank=True)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
bases=('auth.group',),
),
migrations.AlterModelOptions(
name='annotation',
options={'permissions': (('view_annotation', 'View annotation'), ('admin_annotation', 'Manage annotation'))},
),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('annotations', '0002_add_volume_uri'),
]
operations = [
migrations.CreateModel(
name='AnnotationGroup',
fields=[
('group_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='auth.Group')),
('notes', models.TextField(blank=True)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
bases=('auth.group',),
),
migrations.AlterModelOptions(
name='annotation',
options={'permissions': (('view_annotation', 'View annotation'),)},
),
migrations.AlterModelOptions(
name='annotation',
options={'permissions': (('view_annotation', 'View annotation'), ('admin_annotation', 'Manage annotation'))},
),
]
|
Hide burger menu in VR mode | import 'aframe';
import 'aframe-extras';
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import SpaceScene from './components/SpaceScene';
import Sidebar from './components/Sidebar';
ReactDOM.render(<Sidebar/>, document.querySelector('.sidebar-container'));
ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container'));
const scene = document.getElementsByTagName('a-scene')[0];
const xButton = document.getElementById('close-sidebar');
const hamburgerIcon = document.getElementById('drawer-toggle-label');
function hideDrawer() {
document.getElementById('drawer-toggle').checked = false;
}
function hideBurger() {
hamburgerIcon.style.visibility = 'hidden';
}
function showBurger() {
hamburgerIcon.style.visibility = 'visible';
}
scene.onmousedown = hideDrawer;
scene.addEventListener('enter-vr', hideBurger, false);
scene.addEventListener('exit-vr', showBurger, false);
xButton.onmousedown = hideDrawer;
xButton.onmouseover = () => { xButton.src = 'assets/x-icon-white.png' };
xButton.onmouseout = () => { xButton.src = 'assets/x-icon-grey.png' };
| import 'aframe';
import 'aframe-extras';
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import SpaceScene from './components/SpaceScene';
import Sidebar from './components/Sidebar';
ReactDOM.render(<Sidebar/>, document.querySelector('.sidebar-container'));
ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container'));
function hideDrawer() {
document.getElementById('drawer-toggle').checked = false;
}
document.getElementsByTagName('a-scene')[0].onmousedown = hideDrawer;
const closeSidebar = document.getElementById('close-sidebar')
closeSidebar.onmousedown = hideDrawer;
closeSidebar.onmouseover = () => { closeSidebar.src = 'assets/x-icon-white.png' };
closeSidebar.onmouseout = () => { closeSidebar.src = 'assets/x-icon-grey.png' };
|
Test the 404 error handler | require('./test_helper');
describe('app', function () {
before(seeds);
describe('GET /', function () {
it('responds with success', function (done) {
request(app)
.get('/')
.expect(200)
.end(done);
});
});
describe('GET /index.json', function () {
it('responds with features', function (done) {
request(app)
.get('/index.json')
.expect(200)
.expect('Content-Type', /json/)
.expect(function (res) {
expect(res.body).to.have.length.above(0);
})
.end(done);
});
});
describe('GET /404', function () {
it('responds with a 404 error', function (done) {
request(app)
.get('/404')
.expect(404)
.end(done);
});
});
});
| require('./test_helper');
describe('app', function () {
before(seeds);
describe('GET /', function () {
it('responds with success', function (done) {
request(app)
.get('/')
.expect(200)
.end(done);
});
});
describe('GET /index.json', function () {
it('responds with features', function (done) {
request(app)
.get('/index.json')
.expect(200)
.expect('Content-Type', /json/)
.expect(function (res) {
expect(res.body).to.have.length.above(0);
})
.end(done);
});
});
});
|
Fix additional fullstop on accepted upload formatter
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk> |
from DebianChangesBot import Formatter
from DebianChangesBot.datasources import NewQueue
class UploadAcceptedFormatter(Formatter):
FIELDS = ('package', 'version', 'distribution', 'urgency', 'by')
OPTIONAL = ('closes',)
def format(self):
msg = "[green]%s[reset] "
if NewQueue().is_new(self.package):
msg += "[red](NEW)[reset] "
msg += "[yellow]%s[reset]) uploaded " % self.version
if self.distribution != 'unstable':
msg += "to [blue]%s[reset] "
if self.urgency != 'low':
msg += "with urgency [red]%s[reset]" % self.urgency
msg += "by [cyan]%s[reset]" % self.format_email_address(self.by)
if self.closes and '-backports' not in self.distribution:
bug_list = ', '.join(["[b]#%s[/b]" % x for x in self.closes.split(' ')])
msg += " (Closes: %s)" % bug_list
msg += ". http://packages.qa.debian.org/%s" % self.package
return msg
|
from DebianChangesBot import Formatter
from DebianChangesBot.datasources import NewQueue
class UploadAcceptedFormatter(Formatter):
FIELDS = ('package', 'version', 'distribution', 'urgency', 'by')
OPTIONAL = ('closes',)
def format(self):
msg = "[green]%s[reset] "
if NewQueue().is_new(self.package):
msg += "[red](NEW)[reset] "
msg += "[yellow]%s[reset]) uploaded " % self.version
if self.distribution != 'unstable':
msg += "to [blue]%s[reset] "
if self.urgency != 'low':
msg += "with urgency [red]%s[reset]" % self.urgency
msg += "by [cyan]%s[reset] " % self.format_email_address(self.by)
if self.closes and '-backports' not in self.distribution:
bug_list = ', '.join(["[b]#%s[/b]" % x for x in self.closes.split(' ')])
msg += "(Closes: %s) " % bug_list
msg += "http://packages.qa.debian.org/%s" % self.package
return msg
|
Use crypto/rand instead of math/rand
to satisfy the linter
Relates to #284 | package codecs
import (
"bytes"
"crypto/rand"
"math"
"testing"
)
func TestG722Payloader(t *testing.T) {
p := G722Payloader{}
const (
testlen = 10000
testmtu = 1500
)
//generate random 8-bit g722 samples
samples := make([]byte, testlen)
_, err := rand.Read(samples)
if err != nil {
t.Fatal("RNG Error: ", err)
}
//make a copy, for payloader input
samplesIn := make([]byte, testlen)
copy(samplesIn, samples)
//split our samples into payloads
payloads := p.Payload(testmtu, samplesIn)
outcnt := int(math.Ceil(float64(testlen) / testmtu))
if len(payloads) != outcnt {
t.Fatalf("Generated %d payloads instead of %d", len(payloads), outcnt)
}
if !bytes.Equal(samplesIn, samples) {
t.Fatal("Modified input samples")
}
samplesOut := bytes.Join(payloads, []byte{})
if !bytes.Equal(samplesIn, samplesOut) {
t.Fatal("Output samples don't match")
}
}
| package codecs
import (
"bytes"
"math"
"math/rand"
"testing"
)
func TestG722Payloader(t *testing.T) {
p := G722Payloader{}
const (
testlen = 10000
testmtu = 1500
)
//generate random 8-bit g722 samples
samples := make([]byte, testlen)
_, err := rand.Read(samples)
if err != nil {
//according to go docs, this should never ever happen
t.Fatal("RNG Error!")
}
//make a copy, for payloader input
samplesIn := make([]byte, testlen)
copy(samplesIn, samples)
//split our samples into payloads
payloads := p.Payload(testmtu, samplesIn)
outcnt := int(math.Ceil(float64(testlen) / testmtu))
if len(payloads) != outcnt {
t.Fatalf("Generated %d payloads instead of %d", len(payloads), outcnt)
}
if !bytes.Equal(samplesIn, samples) {
t.Fatal("Modified input samples")
}
samplesOut := bytes.Join(payloads, []byte{})
if !bytes.Equal(samplesIn, samplesOut) {
t.Fatal("Output samples don't match")
}
}
|
Use buzz.toTimer() method for time filter | (function() {
function timecode() {
return function(seconds) {
/**
var seconds = Number.parseFloat(seconds);
if (Number.isNaN(seconds)) {
return '-:--';
}
var wholeSeconds = Math.floor(seconds);
var minutes = Math.floor(wholeSeconds / 60);
var remainingSeconds = wholeSeconds % 60;
var output = minutes + ':';
if (remainingSeconds < 10) {
output += '0';
}
output += remainingSeconds;
return output;
*/
var output = buzz.toTimer(seconds);
return output;
};
}
angular
.module('blocJams')
.filter('timecode', timecode);
})(); | (function() {
function timecode() {
return function(seconds) {
var seconds = Number.parseFloat(seconds);
if (Number.isNaN(seconds)) {
return '-:--';
}
var wholeSeconds = Math.floor(seconds);
var minutes = Math.floor(wholeSeconds / 60);
var remainingSeconds = wholeSeconds % 60;
var output = minutes + ':';
if (remainingSeconds < 10) {
output += '0';
}
output += remainingSeconds;
return output;
};
}
angular
.module('blocJams')
.filter('timecode', timecode);
})(); |
Refactor to load to/from from .env values. | <?php
namespace Tests\Integration\Email;
use Dotenv\Dotenv;
use ElasticEmail\Client;
use ElasticEmail\Email\Send;
use Tests\Integration\IntegrationTestCase;
class SendTest extends IntegrationTestCase
{
/** @test */
public function send_an_email()
{
$this->loadEnv();
$client = new Client($_ENV['ELASTIC_EMAIL_API_KEY']);
$send = new Send($client);
$subject = "elasticemail-php: Integration test ensuring email send.";
$response = $send->handle([
'to' => $_ENV['INTEGRATION_TEST_EMAIL_TO'],
'from' => $_ENV['INTEGRATION_TEST_EMAIL_FROM'],
'subject' => $subject,
]);
$this->assertTrue($response->wasSuccessful());
$this->assertEquals(200, $response->getStatusCode());
}
}
| <?php
namespace Tests\Integration;
use Dotenv\Dotenv;
use ElasticEmail\Client;
use ElasticEmail\Email\Send;
use Tests\TestCase;
class SendTest extends TestCase
{
/** @test */
public function send_an_email()
{
$dotenv = Dotenv::createImmutable(__DIR__ . '../../');
$dotenv->load();
$apiKey = getenv('ELASTIC_EMAIL_API_KEY');
$from = getenv('INTEGRATION_TEST_EMAIL_FROM');
$to = getenv('INTEGRATION_TEST_EMAIL_TO');
$client = new Client($apiKey);
$send = new Send($client);
$response = $send->handle([
'to' => $to,
'from' => $from,
'subject' => $this->subject(__FUNCTION__),
]);
$this->assertTrue($response->wasSuccessful());
$this->assertEquals(200, $response->getStatusCode());
}
}
|
Change a report data format | #!/usr/bin/env python
import time
import thread
import string
import Adafruit_DHT as dht
import config
import gpio_lock
h = 0.0
t = 0.0
def get_ht_thread():
global h
global t
while True:
gpio_lock.acquire()
ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM)
gpio_lock.release()
h = '{0:0.1f}'.format(ht[0])
t = '{0:0.1f}'.format(ht[1])
h = string.atof(h)
t = string.atof(t)
time.sleep(2)
def get_ht():
return (h, t)
thread.start_new_thread(get_ht_thread, ())
if __name__ == '__main__':
ht = get_ht()
print('The humidity and temperature:')
print(ht)
| #!/usr/bin/env python
import time
import thread
import Adafruit_DHT as dht
import config
import gpio_lock
h = 0.0
t = 0.0
def get_ht_thread():
global h
global t
while True:
gpio_lock.acquire()
ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM)
gpio_lock.release()
h = '{0:0.1f}'.format(ht[0])
t = '{0:0.1f}'.format(ht[1])
time.sleep(2)
def get_ht():
return (h, t)
thread.start_new_thread(get_ht_thread, ())
if __name__ == '__main__':
ht = get_ht()
print('The humidity and temperature:')
print(ht)
|
Update Component split lazy loading | import Vue from './Vue'
import App from './App'
import store from './store'
import VueRouter from 'vue-router'
// Component split lazy loading
const About = resolve => {
// require.ensure is Webpack's special syntax for a code-split point.
require.ensure(['./components/Aboutme.vue'], () => {
resolve(require('./components/Aboutme.vue'))
})
}
const Profile = resolve => require(['./components/Profile.vue'], resolve)
const Contact = resolve => require(['./components/Contact.vue'], resolve)
const Products = resolve => require(['./components/ProductList.vue'], resolve)
const NotFound = resolve => require(['./NotFound.vue'], resolve)
const router = new VueRouter({
mode: 'history',
root: '/',
routes: [
{path: '/contact', component: Contact},
{path: '/about', component: About},
{path: '/profile/:username', component: Profile},
{path: '/products', component: Products},
{path: '/', redirect: '/about'},
{path: '*', component: NotFound}
]
})
Vue.use(VueRouter)
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
render: h => h(App),
router
})
| import Vue from './Vue'
import App from './App'
import About from './components/Aboutme'
import Profile from './components/Profile'
import Contact from './components/Contact'
import Products from './components/ProductList'
import NotFoundComponent from './NotFound'
import store from './store'
import VueRouter from 'vue-router'
const router = new VueRouter({
mode: 'history',
root: '/',
routes: [
{path: '/contact', component: Contact},
{path: '/about', component: About},
{path: '/profile/:username', component: Profile},
{path: '/products', component: Products},
{path: '/', redirect: '/about'},
{path: '*', component: NotFoundComponent}
]
})
Vue.use(VueRouter)
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
render: h => h(App),
router
})
|
Set function to work with negative numbers as well | export function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
export function shortenNumber (number, decimals, abbreviate) {
decimals = (decimals === undefined) ? 0 : decimals
abbreviate = (abbreviate === undefined) ? true : abbreviate
let k = 'K'
let m = 'M'
let b = 'B'
if (!abbreviate) {
k = 'Thousand'
m = 'Million'
b = 'Billion'
}
if (Math.abs(number) >= 1000000000) {
return `${Number((number / 1000000000).toFixed(decimals))} ${b}`
} else if (Math.abs(number) >= 1000000) {
return `${Number((number / 1000000).toFixed(decimals))} ${m}`
} else if (Math.abs(number) >= 1000) {
return `${Number((number / 1000).toFixed(decimals))} ${k}`
} else {
return number
}
}
| export function capitalizeFirstLetter (string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
export function shortenNumber (number, decimals, abbreviate) {
decimals = (decimals === undefined) ? 0 : decimals
abbreviate = (abbreviate === undefined) ? true : abbreviate
let k = 'K'
let m = 'M'
let b = 'B'
if (!abbreviate) {
k = 'Thousand'
m = 'Million'
b = 'Billion'
}
if (number >= 1000000000) {
return `${Number((number / 1000000000).toFixed(decimals))} ${b}`
} else if (number >= 1000000) {
return `${Number((number / 1000000).toFixed(decimals))} ${m}`
} else if (number >= 1000) {
return `${Number((number / 1000).toFixed(decimals))} ${k}`
} else {
return number
}
}
|
Update with reference to global nav partial | var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-background-size/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-background-size/tachyons-background-size.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_background-size.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/background-size/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/themes/background-size/index.html', html)
| var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-background-size/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-background-size/tachyons-background-size.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_background-size.css', 'utf8')
var template = fs.readFileSync('./templates/docs/background-size/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/themes/background-size/index.html', html)
|
BB-4476: Apply menu item position
- fixed unit tests | <?php
namespace Oro\Bundle\NavigationBundle\Tests\Unit\Entity;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
use Oro\Bundle\NavigationBundle\Entity\MenuUpdate;
class MenuUpdateTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
public function testProperties()
{
$properties = [
['title', 'test title'],
];
$this->assertPropertyAccessors(new MenuUpdate(), $properties);
}
public function testGetExtras()
{
$title = 'test title';
$priority = 10;
$update = new MenuUpdate();
$update->setTitle($title);
$update->setPriority($priority);
$this->assertEquals(['title' => $title, 'position' => $priority], $update->getExtras());
}
}
| <?php
namespace Oro\Bundle\NavigationBundle\Tests\Unit\Entity;
use Oro\Component\Testing\Unit\EntityTestCaseTrait;
use Oro\Bundle\NavigationBundle\Entity\MenuUpdate;
class MenuUpdateTest extends \PHPUnit_Framework_TestCase
{
use EntityTestCaseTrait;
public function testProperties()
{
$properties = [
['title', 'test title'],
];
$this->assertPropertyAccessors(new MenuUpdate(), $properties);
}
public function testGetExtras()
{
$title = 'test title';
$update = new MenuUpdate();
$update->setTitle($title);
$this->assertEquals(['title' => $title], $update->getExtras());
}
}
|
Remove unnecessary check for `n == 0`
The `while` loop below handles this case anyway. The only ‘overhead’ the check avoided was a single `n--` and a `ToBoolean(0)` — so this was definitely a micro-optimization.
Closes #3. | /*! http://mths.be/repeat v0.1.0 by @mathias */
if (!String.prototype.repeat) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var repeat = function(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
// `ToInteger`
var n = count ? Number(count) : 0;
if (n != n) { // better `isNaN`
n = 0;
}
// Account for out-of-bounds indices
if (n < 0 || n == Infinity) {
throw RangeError();
}
var result = '';
while (n--) {
result += string;
}
return result;
};
if (Object.defineProperty) {
Object.defineProperty(String.prototype, 'repeat', {
'value': repeat,
'configurable': true,
'writable': true
});
} else {
String.prototype.repeat = repeat;
}
}());
}
| /*! http://mths.be/repeat v0.1.0 by @mathias */
if (!String.prototype.repeat) {
(function() {
'use strict'; // needed to support `apply`/`call` with `undefined`/`null`
var repeat = function(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
// `ToInteger`
var n = count ? Number(count) : 0;
if (n != n) { // better `isNaN`
n = 0;
}
// Account for out-of-bounds indices
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
};
if (Object.defineProperty) {
Object.defineProperty(String.prototype, 'repeat', {
'value': repeat,
'configurable': true,
'writable': true
});
} else {
String.prototype.repeat = repeat;
}
}());
}
|
Change webpack merge strategy to override HtmlWebpackPlugin | 'use strict';
/* globals __dirname process module console */
/* eslint no-process-env: 0
no-console: 0
*/
const fs = require('fs');
const merge = require('webpack-merge');
const configs = {
// global section
global: require(__dirname + '/config/webpack/global'),
overrides: fs.existsSync(__dirname + '/config/webpack/overrides.js') ?
require(__dirname + '/config/webpack/overrides') : null,
// config by enviroments
production: require(__dirname + '/config/webpack/environments/production'),
development: require(__dirname + '/config/webpack/environments/development'),
test: require(__dirname + '/config/webpack/environments/test')
};
let load = function () {
let ENV = process.env.NODE_ENV
? process.env.NODE_ENV
: 'production';
console.log('Current Environment: ', ENV);
// load config file by environment
return configs && merge({
customizeArray: merge.unique(
'plugins',
['HtmlWebpackPlugin'],
plugin => plugin.constructor && plugin.constructor.name
)}
)(
configs.overrides ? configs.overrides(__dirname) : null,
configs.global(__dirname),
configs[ENV](__dirname)
);
};
module.exports = load();
| 'use strict';
/* globals __dirname process module console */
/* eslint no-process-env: 0
no-console: 0
*/
const fs = require('fs');
const merge = require('webpack-merge');
const configs = {
// global section
global: require(__dirname + '/config/webpack/global'),
overrides: fs.existsSync(__dirname + '/config/webpack/overrides.js') ?
require(__dirname + '/config/webpack/overrides') : null,
// config by enviroments
production: require(__dirname + '/config/webpack/environments/production'),
development: require(__dirname + '/config/webpack/environments/development'),
test: require(__dirname + '/config/webpack/environments/test')
};
let load = function () {
let ENV = process.env.NODE_ENV
? process.env.NODE_ENV
: 'production';
console.log('Current Environment: ', ENV);
// load config file by environment
return configs && merge(
configs.overrides ? configs.overrides(__dirname) : null,
configs.global(__dirname),
configs[ENV](__dirname)
);
};
module.exports = load();
|
Update jvanbruegge additions according to XO rules |
import h from 'snabbdom/h'
import extend from 'extend'
const sanitizeProps = (props) => {
props = props === null ? {} : props
Object.keys(props).map((prop) => {
const keysRiver = prop.split('-').reverse()
if (keysRiver.length > 1) {
let newObject = keysRiver.reduce(
(object, key) => ({ [key]: object }),
props[prop]
)
extend(true, props, newObject)
delete props[prop]
} else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) {
extend(true, props, { props: { [prop]: props[prop] } })
delete props[prop]
}
return { toto: true }
})
return props
}
const sanitizeChilds = (children) => {
if (children.length === 1 && typeof children[0] === 'string') {
return children[0]
}
if (children.reduce((acc, curr) => acc || Array.isArray(curr), false)) {
return children
.reduce((acc, curr) => Array.isArray(curr) ? [...acc, ...curr] : [...acc, curr], [])
}
return children
}
export const createElement = (type, props, ...children) => {
return (typeof type === 'function') ?
type(props, children) :
h(type, sanitizeProps(props), sanitizeChilds(children))
}
export default {
createElement
}
|
import h from 'snabbdom/h'
import extend from 'extend'
const sanitizeProps = (props) => {
props = props === null ? {} : props
Object.keys(props).map((prop) => {
const keysRiver = prop.split('-').reverse()
if (keysRiver.length > 1) {
let newObject = keysRiver.reduce(
(object, key) => ({ [key]: object }),
props[prop]
)
extend(true, props, newObject)
delete props[prop]
} else if (!(['class', 'props', 'attrs', 'style', 'on', 'hook', 'key'].indexOf(prop) > -1)) {
extend(true, props, { props: { [prop]: props[prop] } })
delete props[prop]
}
return { toto: true }
})
return props
}
const sanitizeChilds = (children) => {
if(children.length === 1 && typeof children[0] === 'string') {
return children[0]
}
if(children.reduce((acc, curr) => acc || Array.isArray(curr), false))
{
return children
.reduce((acc, curr) => Array.isArray(curr) ? [...acc, ...curr] : [...acc, curr], []);
}
return children;
}
export const createElement = (type, props, ...children) => {
return (typeof type === 'function') ?
type(props, children) :
h(type, sanitizeProps(props), sanitizeChilds(children))
}
export default {
createElement
}
|
Make JS compiler happy about OAUTH2_USE_OFFICEIAL_CLIENT_ID.
Review URL: https://chromiumcodereview.appspot.com/10206007
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@133634 0039d316-1c4b-4281-b951-d872f2087c98 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains various hacks needed to inform JSCompiler of various
// WebKit-specific properties and methods. It is used only with JSCompiler
// to verify the type-correctness of our code.
/** @type Array.<HTMLElement> */
Document.prototype.all;
/** @type {function(string): void} */
Document.prototype.execCommand = function(command) {};
/** @return {void} Nothing. */
Document.prototype.webkitCancelFullScreen = function() {};
/** @type {boolean} */
Document.prototype.webkitIsFullScreen;
/** @type {number} */
Element.ALLOW_KEYBOARD_INPUT;
/** @param {number} flags
/** @return {void} Nothing. */
Element.prototype.webkitRequestFullScreen = function(flags) {};
/** @type {{getRandomValues: function(Uint16Array):void}} */
Window.prototype.crypto;
// This string is replaced with the actual value in build-webapp.py.
var OAUTH2_USE_OFFICIAL_CLIENT_ID = false;
| // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file contains various hacks needed to inform JSCompiler of various
// WebKit-specific properties and methods. It is used only with JSCompiler
// to verify the type-correctness of our code.
/** @type Array.<HTMLElement> */
Document.prototype.all;
/** @type {function(string): void} */
Document.prototype.execCommand = function(command) {};
/** @return {void} Nothing. */
Document.prototype.webkitCancelFullScreen = function() {};
/** @type {boolean} */
Document.prototype.webkitIsFullScreen;
/** @type {number} */
Element.ALLOW_KEYBOARD_INPUT;
/** @param {number} flags
/** @return {void} Nothing. */
Element.prototype.webkitRequestFullScreen = function(flags) {};
/** @type {{getRandomValues: function(Uint16Array):void}} */
Window.prototype.crypto;
|
Update plugin to use new interface | <?php
namespace Rocketeer\Plugins\Laravel;
use Illuminate\Contracts\Container\Container;
use Rocketeer\Abstracts\AbstractPlugin;
class LaravelPlugin extends AbstractPlugin
{
/**
* Additional lookups to
* add to Rocketeer
*
* @type array
*/
protected $lookups = array(
'binaries' => array(
'Rocketeer\Plugins\Laravel\Binaries\%s',
),
'strategies' => array(
'Rocketeer\Plugins\Laravel\Strategies\%sStrategy',
),
);
/**
* @param Container $app
*
* @return Container
*/
public function register(Container $app)
{
$app->singleton('rocketeer.strategies.framework', 'Rocketeer\Plugins\Laravel\Strategies\Framework\LaravelStrategy');
return $app;
}
}
| <?php
namespace Rocketeer\Plugins\Laravel;
use Illuminate\Container\Container;
use Rocketeer\Abstracts\AbstractPlugin;
class LaravelPlugin extends AbstractPlugin
{
/**
* Additional lookups to
* add to Rocketeer
*
* @type array
*/
protected $lookups = array(
'binaries' => array(
'Rocketeer\Plugins\Laravel\Binaries\%s',
),
'strategies' => array(
'Rocketeer\Plugins\Laravel\Strategies\%sStrategy',
),
);
/**
* @param Container $app
*
* @return Container
*/
public function register(Container $app)
{
$app->singleton('rocketeer.strategies.framework', 'Rocketeer\Plugins\Laravel\Strategies\Framework\LaravelStrategy');
return $app;
}
}
|
Add fine tuning to silent helper | # coding=utf-8
from contextlib import contextmanager
from fabric.context_managers import settings, hide, prefix
from fabric.state import env
__all__ = ['get_sudo_context', 'sudo', 'only_messages', 'prefix']
@contextmanager
def sudo(user=None):
with settings(sudo_user=user or env.sudo_user or env.user, use_sudo=True):
yield
silent = lambda *h: settings(hide('commands', *h), warn_only=True)
hide_prefix = lambda: settings(output_prefix=False)
abort_on_error = lambda: settings(warn_only=False)
@contextmanager
def shell_env(**env_vars):
orig_shell = env['shell']
env_vars_str = ' '.join('{0}={1}'.format(key, value)
for key, value in env_vars.items())
env['shell'] = '{0} {1}'.format(env_vars_str, orig_shell)
yield
env['shell'] = orig_shell
| # coding=utf-8
from contextlib import contextmanager
from fabric.context_managers import settings, hide, prefix
from fabric.state import env
__all__ = ['get_sudo_context', 'sudo', 'only_messages', 'prefix']
@contextmanager
def sudo(user=None):
with settings(sudo_user=user or env.sudo_user or env.user, use_sudo=True):
yield
silent = lambda: settings(hide('commands'), warn_only=True)
hide_prefix = lambda: settings(output_prefix=False)
abort_on_error = lambda: settings(warn_only=False)
@contextmanager
def shell_env(**env_vars):
orig_shell = env['shell']
env_vars_str = ' '.join('{0}={1}'.format(key, value)
for key, value in env_vars.items())
env['shell'] = '{0} {1}'.format(env_vars_str, orig_shell)
yield
env['shell'] = orig_shell
|
Use new
util function for getting current people | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = get_current_people(position='senator')
representatives = get_current_people(position='representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
) | from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = Person.objects.filter(memberships__organization__name='Florida Senate')
representatives = Person.objects.filter(memberships__organization__name='Florida House of Representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
) |
Set bytes_per_inode to 8KB for data disk of unionfs
Change-Id: I52be8f573cb85b886a1ecccd044fc004ea78103f | package aliyunecs
const autoFdiskScript = `#/bin/bash
#fdisk ,formating and create the file system on /dev/xvdb or /dev/vdb
DISK_ATTACH_POINT="/dev/xvdb"
fdisk_fun()
{
fdisk -S 56 \$DISK_ATTACH_POINT << EOF
n
p
1
wq
EOF
sleep 5
mkfs.ext4 -i 8192 \${DISK_ATTACH_POINT}1
}
#config /etc/fstab and mount device
main()
{
if [ -b "/dev/vdb" ]; then
DISK_ATTACH_POINT="/dev/vdb"
fi
fdisk_fun
flag=0
if [ -d "/var/lib/docker" ];then
flag=1
service docker stop
rm -fr /var/lib/docker
fi
mkdir /var/lib/docker
echo "\${DISK_ATTACH_POINT}1 /var/lib/docker ext4 defaults 0 0" >>/etc/fstab
mount -a
if [ \$flag==1 ]; then
service docker start
fi
}
main
df -h
`
| package aliyunecs
const autoFdiskScript = `#/bin/bash
#fdisk ,formating and create the file system on /dev/xvdb or /dev/vdb
DISK_ATTACH_POINT="/dev/xvdb"
fdisk_fun()
{
fdisk -S 56 \$DISK_ATTACH_POINT << EOF
n
p
1
wq
EOF
sleep 5
mkfs.ext4 \${DISK_ATTACH_POINT}1
}
#config /etc/fstab and mount device
main()
{
if [ -b "/dev/vdb" ]; then
DISK_ATTACH_POINT="/dev/vdb"
fi
fdisk_fun
flag=0
if [ -d "/var/lib/docker" ];then
flag=1
service docker stop
rm -fr /var/lib/docker
fi
mkdir /var/lib/docker
echo "\${DISK_ATTACH_POINT}1 /var/lib/docker ext4 defaults 0 0" >>/etc/fstab
mount -a
if [ \$flag==1 ]; then
service docker start
fi
}
main
df -h
`
|
Make it more obvious that TRANSLATIONS is global | (function(global) {
"use strict";
var default_i18n = new Jed({
locale_data: global.TRANSLATIONS,
domain: "indico"
});
global.i18n = default_i18n;
global.$T = _.bind(default_i18n.gettext, default_i18n);
['gettext', 'ngettext', 'pgettext', 'npgettext', 'translate'].forEach(function(method_name) {
global.$T[method_name] = _.bind(default_i18n[method_name], default_i18n);
});
global.$T.domain = _.memoize(function(domain) {
return new Jed({
locale_data: global.TRANSLATIONS,
domain: domain
});
});
}(window));
| (function(global) {
"use strict";
var default_i18n = new Jed({
locale_data: TRANSLATIONS,
domain: "indico"
});
global.i18n = default_i18n;
global.$T = _.bind(default_i18n.gettext, default_i18n);
['gettext', 'ngettext', 'pgettext', 'npgettext', 'translate'].forEach(function(method_name) {
global.$T[method_name] = _.bind(default_i18n[method_name], default_i18n);
});
global.$T.domain = _.memoize(function(domain) {
return new Jed({
locale_data: TRANSLATIONS,
domain: domain
});
});
}(window));
|
Add explanatory comment for why an object lookup is used vs a string lookup. | // This appears to be redundant, but a object lookup call will perform better than
// a character lookup in a string.
const integerToChar = Array.prototype.reduce.call(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
(memo, char, idx) => {
memo[idx] = char;
return memo;
},
Object.create(null)
);
/* eslint-disable no-bitwise */
function encodeInteger (int, collection) {
if (int < 0) {
int = -int << 1 | 1;
} else {
int <<= 1;
}
let clamped;
do {
clamped = int & 31;
int >>= 5;
if (int > 0) { clamped |= 32; }
collection.push(integerToChar[clamped]);
} while (int > 0);
}
// eslint-disable-next-line max-params
exports.encode = function encode (collection, a, b, c, d, e) {
encodeInteger(a, collection);
encodeInteger(b, collection);
encodeInteger(c, collection);
encodeInteger(d, collection);
if (e) { encodeInteger(e, collection); }
};
| const integerToChar = Array.prototype.reduce.call(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
(memo, char, idx) => {
memo[idx] = char;
return memo;
},
Object.create(null)
);
/* eslint-disable no-bitwise */
function encodeInteger (int, collection) {
if (int < 0) {
int = -int << 1 | 1;
} else {
int <<= 1;
}
let clamped;
do {
clamped = int & 31;
int >>= 5;
if (int > 0) { clamped |= 32; }
collection.push(integerToChar[clamped]);
} while (int > 0);
}
// eslint-disable-next-line max-params
exports.encode = function encode (collection, a, b, c, d, e) {
encodeInteger(a, collection);
encodeInteger(b, collection);
encodeInteger(c, collection);
encodeInteger(d, collection);
if (e) { encodeInteger(e, collection); }
};
|
Add bit more out in test | package org.ethereum.solidity;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
/**
* Created by Anton Nashatyrev on 03.03.2016.
*/
public class CompilerTest {
@Test
public void simpleTest() throws IOException {
String contract =
"contract a {" +
" int i1;" +
" function i() returns (int) {" +
" return i1;" +
" }" +
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println("Out: '" + res.output + "'");
System.out.println("Err: '" + res.errors + "'");
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
public static void main(String[] args) throws Exception {
new CompilerTest().simpleTest();
}
}
| package org.ethereum.solidity;
import org.ethereum.solidity.compiler.CompilationResult;
import org.ethereum.solidity.compiler.SolidityCompiler;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
/**
* Created by Anton Nashatyrev on 03.03.2016.
*/
public class CompilerTest {
@Test
public void simpleTest() throws IOException {
String contract =
"contract a {" +
" int i1;" +
" function i() returns (int) {" +
" return i1;" +
" }" +
"}";
SolidityCompiler.Result res = SolidityCompiler.compile(
contract.getBytes(), true, SolidityCompiler.Options.ABI, SolidityCompiler.Options.BIN, SolidityCompiler.Options.INTERFACE);
System.out.println(res.output);
System.out.println(res.errors);
CompilationResult result = CompilationResult.parse(res.output);
System.out.println(result.contracts.get("a").bin);
}
public static void main(String[] args) throws Exception {
new CompilerTest().simpleTest();
}
}
|
Update helper to set auth type. | /**
* setupSiteKit utility.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* WordPress dependencies
*/
import { activatePlugin } from '@wordpress/e2e-test-utils';
/**
* Internal depedencies
*/
import {
setSiteVerification,
setSearchConsoleProperty,
} from '.';
export const setupSiteKit = async ( { verified, property, auth = 'proxy' } = {} ) => {
if ( auth !== 'proxy' && auth !== 'gcp' ) {
throw new Error( 'Auth type must be either proxy or gcp' );
}
await activatePlugin( `e2e-tests-${ auth }-auth-plugin` );
await setSiteVerification( verified );
await setSearchConsoleProperty( property );
};
| /**
* setupSiteKit utility.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* WordPress dependencies
*/
import { activatePlugin } from '@wordpress/e2e-test-utils';
/**
* Internal depedencies
*/
import {
setSiteVerification,
setSearchConsoleProperty,
} from '.';
export const setupSiteKit = async ( { verified, property } = {} ) => {
await activatePlugin( 'e2e-tests-auth-plugin' );
await setSiteVerification( verified );
await setSearchConsoleProperty( property );
};
|
Fix for blogger vanityUrl in API | var BloggerController = require('./controllers/blogger');
exports.serveRoutes = function(app) {
app.get('/api/v0.1/bloggers', function(req, res) {
BloggerController.getAllProfiles(true, function (profiles, error) {
if(error) {
res.send(error);
}
else {
res.json(profiles);
}
});
});
app.get('/api/v0.1/bloggers/:vanityurl', function(req, res) {
var vanityUrl = req.params.vanityurl;
BloggerController.getProfileByVanityUrl(vanityUrl, function (profile, error) {
if(error) {
res.send(error);
}
else {
res.json(profile);
}
});
});
}; | var BloggerController = require('./controllers/blogger');
exports.serveRoutes = function(app) {
app.get('/api/v0.1/bloggers', function(req, res) {
BloggerController.getAllProfiles(true, function (profiles, error) {
if(error) {
res.send(error);
}
else {
res.json(profiles);
}
});
});
app.get('/api/v0.1/bloggers/:vanityUrl', function(req, res) {
var vanityUrl = req.params.vanityurl;
BloggerController.getProfileByVanityUrl(vanityUrl, function (profile, error) {
if(error) {
res.send(error);
}
else {
res.json(profile);
}
});
});
}; |
Fix for python 2.6 compatibility | import logging
logger = logging.getLogger(__name__)
# Set of known preferences and default values:
KNOWN_PREFS = {
'popups': 'true',
'daysahead': '90',
}
def get_preferences(session):
edit_prefs = dict(
(pref, session.get('editpref_' + pref, default))
for pref, default in KNOWN_PREFS.iteritems()
)
return edit_prefs
def get_preference(session, name):
value = None
if name in KNOWN_PREFS:
value = session.get('editpref_' + name, KNOWN_PREFS[name])
return value
def set_preferences(session, prefs_requested):
for name, value in prefs_requested.iteritems():
set_preference(session, name, value)
def set_preference(session, name, value):
if name in KNOWN_PREFS:
logger.debug("Set pref {} to '{}'".format(name, value))
value = str(value)[:10] # limit length of stored value
session['editpref_' + name] = value
| import logging
logger = logging.getLogger(__name__)
# Set of known preferences and default values:
KNOWN_PREFS = {
'popups': 'true',
'daysahead': '90',
}
def get_preferences(session):
edit_prefs = {
pref: session.get('editpref_' + pref, default)
for pref, default in KNOWN_PREFS.iteritems()
}
return edit_prefs
def get_preference(session, name):
value = None
if name in KNOWN_PREFS:
value = session.get('editpref_' + name, KNOWN_PREFS[name])
return value
def set_preferences(session, prefs_requested):
for name, value in prefs_requested.iteritems():
set_preference(session, name, value)
def set_preference(session, name, value):
if name in KNOWN_PREFS:
logger.debug("Set pref {} to '{}'".format(name, value))
value = str(value)[:10] # limit length of stored value
session['editpref_' + name] = value
|
Use the whole body of POST request as the json event in precaching | import logging
from flask import request
from . import scores
from ... import preprocessors, responses, util
logger = logging.getLogger(__name__)
def configure(config, bp, scoring_system):
precache_map = util.build_precache_map(config)
@bp.route("/v3/precache/", methods=["POST"])
@preprocessors.nocache
@preprocessors.minifiable
def precache_v3():
event = request.get_json()
if event is None:
return responses.bad_request(
"Must provide a POST'ed json as an event")
try:
score_request = util.build_score_request_from_event(
precache_map, event)
except KeyError as e:
return responses.bad_request(
"Must provide the '{key}' parameter".format(key=e.args[0]))
if not score_request:
return responses.no_content()
else:
return scores.process_score_request(score_request)
return bp
| import json
import logging
from urllib.parse import unquote
from flask import request
from . import scores
from ... import preprocessors, responses, util
logger = logging.getLogger(__name__)
def configure(config, bp, scoring_system):
precache_map = util.build_precache_map(config)
@bp.route("/v3/precache/", methods=["POST"])
@preprocessors.nocache
@preprocessors.minifiable
def precache_v3():
if 'event' not in request.form:
return responses.bad_request(
"Must provide an 'event' parameter")
try:
event = json.loads(unquote(request.form['event']).strip())
except json.JSONDecodeError:
return responses.bad_request(
"Can not parse event argument as JSON blob")
score_request = util.build_score_request_from_event(precache_map, event)
if not score_request:
return responses.no_content()
else:
return scores.process_score_request(score_request)
return bp
|
Resolve also .jsx modules by default
see: http://webpack.github.io/docs/configuration.html#resolve-extensions | import reactTransform from 'babel-plugin-react-transform'
export default {
name: 'webpack-babel',
configure ({ buildTarget }) {
const hmrEnv = {
development: {
plugins: [reactTransform],
extra: {
'react-transform': {
transforms: [{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module']
}]
}
}
}
}
return {
babel: {
optional: ['runtime'],
stage: 0,
env: buildTarget === 'develop' ? hmrEnv : {}
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
}
}
}
}
| import reactTransform from 'babel-plugin-react-transform'
export default {
name: 'webpack-babel',
configure ({ buildTarget }) {
const hmrEnv = {
development: {
plugins: [reactTransform],
extra: {
'react-transform': {
transforms: [{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module']
}]
}
}
}
}
return {
babel: {
optional: ['runtime'],
stage: 0,
env: buildTarget === 'develop' ? hmrEnv : {}
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}
]
}
}
}
}
|
Add better definition for validate function. | $(window).ready(
function () {
$("#json-input").linedtextarea();
$("#json-input").bind('paste', function() {
// Need a timeout since paste event does not give the content
// of the clipboard.
setTimeout(function(){
validate_job_data($("#json-input").val());
},100);
});
$("#json-input").blur(function() {
validate_job_data($("#json-input").val());
});
});
validate_job_data = function(json_input) {
$.post(window.location.pathname,
{"json-input": json_input,
"csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()},
function(data) {
});
}
| $(window).ready(
function () {
$("#json-input").linedtextarea();
$("#json-input").bind('paste', function() {
// Need a timeout since paste event does not give the content
// of the clipboard.
setTimeout(function(){
validate_job_data($("#json-input").val());
},100);
});
$("#json-input").blur(function() {
validate_job_data($("#json-input").val());
});
});
validate_job_data = function() {
$.post(window.location.pathname,
{"json-input": json_input,
"csrfmiddlewaretoken": $("[name='csrfmiddlewaretoken']").val()},
function(data) {
});
}
|
Use smart text editor in tej.SubmitShellJob | from __future__ import division
from vistrails.gui.modules.source_configure import SourceConfigurationWidget
from vistrails.gui.modules.string_configure import TextEditor
class ShellSourceConfigurationWidget(SourceConfigurationWidget):
"""Configuration widget for SubmitShellJob.
Allows the user to edit a shell script that will be run on the server.
"""
def __init__(self, module, controller, parent=None):
SourceConfigurationWidget.__init__(self, module, controller,
TextEditor,
has_inputs=False, has_outputs=False,
parent=parent)
| from __future__ import division
from PyQt4 import QtGui
from vistrails.gui.modules.source_configure import SourceConfigurationWidget
class ShellSourceConfigurationWidget(SourceConfigurationWidget):
"""Configuration widget for SubmitShellJob.
Allows the user to edit a shell script that will be run on the server.
"""
def __init__(self, module, controller, parent=None):
SourceConfigurationWidget.__init__(self, module, controller,
QtGui.QTextEdit,
has_inputs=False, has_outputs=False,
parent=parent)
|
Change the implementation string to "Path" | package authoring.data;
import com.syntacticsugar.vooga.util.ResourceManager;
public class TileData {
private static final String PATH = ResourceManager.getString("Path_name");
private static final String SCENERY = ResourceManager.getString("Scenery_name");
private String myImagePath;
private String myImplementation;
private boolean isDestination;
public TileData(String imagePath) {
setImagePath(imagePath);
setImplementation("Path");
setDestination(false);
}
public void setImagePath(String path) {
this.myImagePath = path;
}
public void setImplementation(String impl) {
this.myImplementation = (impl.equals("Path")) ? PATH : SCENERY;
}
public void setDestination(boolean isDestination) {
this.isDestination = isDestination;
}
public String getImagePath() {
return this.myImagePath;
}
public String getImplementation() {
return this.myImplementation;
}
public boolean isDestination() {
return this.isDestination;
}
}
| package authoring.data;
import com.syntacticsugar.vooga.util.ResourceManager;
public class TileData {
private static final String PATH = ResourceManager.getString("Path_name");
private static final String SCENERY = ResourceManager.getString("Scenery_name");
private String myImagePath;
private String myImplementation;
private boolean isDestination;
public TileData(String imagePath) {
setImagePath(imagePath);
setImplementation(PATH);
setDestination(false);
}
public void setImagePath(String path) {
this.myImagePath = path;
}
public void setImplementation(String impl) {
this.myImplementation = (impl.equals("Path")) ? PATH : SCENERY;
}
public void setDestination(boolean isDestination) {
this.isDestination = isDestination;
}
public String getImagePath() {
return this.myImagePath;
}
public String getImplementation() {
return this.myImplementation;
}
public boolean isDestination() {
return this.isDestination;
}
}
|
BB-3348: Create validator for System Allowed Currencies restriction | <?php
namespace Oro\Bundle\LocaleBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Intl\Intl;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CurrencyType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
array(
'choices' => Intl::getCurrencyBundle()->getCurrencyNames('en'),
'restrict' => false
)
);
$resolver->setDefined('restrict');
$resolver->setAllowedTypes('restrict', 'bool');
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'currency';
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'oro_currency';
}
}
| <?php
namespace Oro\Bundle\LocaleBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Intl\Intl;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CurrencyType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'choices' => Intl::getCurrencyBundle()->getCurrencyNames('en'),
)
);
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'currency';
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'oro_currency';
}
}
|
Drop gratuitous relevance from Tagger Script | /*
Language: Tagger Script
Author: Philipp Wolfer <ph.wolfer@gmail.com>
Description: Syntax Highlighting for the Tagger Script as used by MusicBrainz Picard.
*/
function(hljs) {
var COMMENT = {
className: 'comment',
begin: /\$noop\(/,
end: /\)/,
contains: [{
begin: /\(/,
end: /\)/,
contains: ['self', {
begin: /\\./
}]
}],
relevance: 10
};
var FUNCTION = {
className: 'keyword',
begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/,
end: /\(/,
excludeEnd: true
};
var VARIABLE = {
className: 'variable',
begin: /%[_a-zA-Z0-9:]*/,
end: '%'
};
var ESCAPE_SEQUENCE = {
className: 'symbol',
begin: /\\./
};
return {
contains: [
COMMENT,
FUNCTION,
VARIABLE,
ESCAPE_SEQUENCE
]
};
}
| /*
Language: Tagger Script
Author: Philipp Wolfer <ph.wolfer@gmail.com>
Description: Syntax Highlighting for the Tagger Script as used by MusicBrainz Picard.
*/
function(hljs) {
var COMMENT = {
className: 'comment',
begin: /\$noop\(/,
end: /\)/,
contains: [{
begin: /\(/,
end: /\)/,
contains: ['self', {
begin: /\\./
}]
}],
relevance: 10
};
var FUNCTION = {
className: 'keyword',
begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/,
end: /\(/,
excludeEnd: true,
relevance: 5
};
var VARIABLE = {
className: 'variable',
begin: /%[_a-zA-Z0-9:]*/,
end: '%'
};
var ESCAPE_SEQUENCE = {
className: 'symbol',
begin: /\\./
};
return {
contains: [
COMMENT,
FUNCTION,
VARIABLE,
ESCAPE_SEQUENCE
]
};
}
|
Add one-line summary to docstring. |
from rest_framework.negotiation import DefaultContentNegotiation
class JSONAPIContentNegotiation(DefaultContentNegotiation):
def select_renderer(self, request, renderers, format_suffix=None):
"""
Returns appropriate tuple (renderer, media type).
If 'application/json' in acceptable media types, use the first renderer in
DEFAULT_RENDERER_CLASSES which should be 'api.base.renderers.JSONAPIRenderer'.
Media_type "application/vnd.api+json". Otherwise, use default select_renderer.
"""
accepts = self.get_accept_list(request)
if 'application/json' in accepts:
return (renderers[0], renderers[0].media_type)
return super(JSONAPIContentNegotiation, self).select_renderer(request, renderers)
|
from rest_framework.negotiation import DefaultContentNegotiation
class JSONAPIContentNegotiation(DefaultContentNegotiation):
def select_renderer(self, request, renderers, format_suffix=None):
"""
If 'application/json' in acceptable media types, use the first renderer in
DEFAULT_RENDERER_CLASSES which should be 'api.base.renderers.JSONAPIRenderer'.
Media_type "application/vnd.api+json". Otherwise, use default select_renderer.
Returns a tuple (renderer, media_type).
"""
accepts = self.get_accept_list(request)
if 'application/json' in accepts:
return (renderers[0], renderers[0].media_type)
return super(JSONAPIContentNegotiation, self).select_renderer(request, renderers)
|
Fix for accidental string continuation. | #!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha',
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
README = 'README.md'
def long_desc():
try:
import pypandoc
except ImportError:
with open(README) as f:
return f.read()
else:
return pypandoc.convert(README, 'rst')
setup(
name='cellulario',
version='1',
description='Cellular IO',
author='Justin Mayfield',
author_email='tooker@gmail.com',
url='https://github.com/mayfield/cellulario/',
license='MIT',
long_description=long_desc(),
packages=find_packages(),
test_suite='test',
classifiers=[
'Development Status :: 3 - Alpha'
#'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Add 'common_name' to company's form | from django import forms
from . import models
from pola.forms import (CommitDescriptionMixin,
FormHorizontalMixin, SaveButtonMixin,
ReadOnlyFieldsMixin)
class CompanyForm(ReadOnlyFieldsMixin, SaveButtonMixin, FormHorizontalMixin,
CommitDescriptionMixin, forms.ModelForm):
readonly_fields = [
'name'
]
class Meta:
model = models.Company
fields = [
'nip',
'name',
'official_name',
'common_name',
'address',
'plCapital',
'plCapital_notes',
'plTaxes',
'plTaxes_notes',
'plRnD',
'plRnD_notes',
'plWorkers',
'plWorkers_notes',
'plBrand',
'plBrand_notes',
'verified',
]
| from django import forms
from . import models
from pola.forms import (CommitDescriptionMixin,
FormHorizontalMixin, SaveButtonMixin,
ReadOnlyFieldsMixin)
class CompanyForm(ReadOnlyFieldsMixin, SaveButtonMixin, FormHorizontalMixin,
CommitDescriptionMixin, forms.ModelForm):
readonly_fields = [
'name'
]
class Meta:
model = models.Company
fields = [
'nip',
'name',
'official_name',
'address',
'plCapital',
'plCapital_notes',
'plTaxes',
'plTaxes_notes',
'plRnD',
'plRnD_notes',
'plWorkers',
'plWorkers_notes',
'plBrand',
'plBrand_notes',
'verified',
]
|
Fix storage migration to process all storages | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-26 04:08
from __future__ import unicode_literals
from django.db import migrations, models
def set_data_relation(apps, schema_editor):
Storage = apps.get_model('flow', 'Storage')
for storage in Storage.objects.all():
storage.data.add(storage.data_migration_temporary)
class Migration(migrations.Migration):
dependencies = [
('flow', '0028_add_data_location'),
]
operations = [
migrations.RenameField(
model_name='storage',
old_name='data',
new_name='data_migration_temporary',
),
migrations.AddField(
model_name='storage',
name='data',
field=models.ManyToManyField(related_name='storages', to='flow.Data'),
),
migrations.RunPython(set_data_relation),
migrations.RemoveField(
model_name='storage',
name='data_migration_temporary',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-26 04:08
from __future__ import unicode_literals
from django.db import migrations, models
def set_data_relation(apps, schema_editor):
Data = apps.get_model('flow', 'Data')
Storage = apps.get_model('flow', 'Storage')
for data in Data.objects.all():
storage = Storage.objects.filter(data_migration_temporary=data).first()
if storage:
storage.data.add(data)
class Migration(migrations.Migration):
dependencies = [
('flow', '0028_add_data_location'),
]
operations = [
migrations.RenameField(
model_name='storage',
old_name='data',
new_name='data_migration_temporary',
),
migrations.AddField(
model_name='storage',
name='data',
field=models.ManyToManyField(related_name='storages', to='flow.Data'),
),
migrations.RunPython(set_data_relation),
migrations.RemoveField(
model_name='storage',
name='data_migration_temporary',
),
]
|
Revert "add debug line for travis bc this is passing locally"
This reverts commit c930369362fa9c68e8f44296617695fc804e141d. | 'use strict'
const t = require('tap')
const spawn = require('child_process').spawn
const split = require('split2')
const autocannon = require.resolve('../autocannon')
const target = require.resolve('./targetProcess')
const lines = [
/Running 1s test @ .*$/,
/10 connections.*$/,
/$/,
/Stat.*Avg.*Stdev.*Max.*$/,
/Latency \(ms\).*$/,
/Req\/Sec.*$/,
/Bytes\/Sec.*$/,
/$/,
// Ensure that there are more than 0 successful requests
/[1-9]\d+.* requests in \d+s, .* read/
]
t.plan(lines.length * 2)
const child = spawn(autocannon, [
'-c', '10',
'-d', '1',
'--on-port', '/',
'--', 'node', target
], {
cwd: __dirname,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false
})
t.tearDown(() => {
child.kill()
})
child
.stderr
.pipe(split())
.on('data', (line) => {
const regexp = lines.shift()
t.ok(regexp, 'we are expecting this line')
t.ok(regexp.test(line), 'line matches ' + regexp)
})
| 'use strict'
const t = require('tap')
const spawn = require('child_process').spawn
const split = require('split2')
const autocannon = require.resolve('../autocannon')
const target = require.resolve('./targetProcess')
const lines = [
/Running 1s test @ .*$/,
/10 connections.*$/,
/$/,
/Stat.*Avg.*Stdev.*Max.*$/,
/Latency \(ms\).*$/,
/Req\/Sec.*$/,
/Bytes\/Sec.*$/,
/$/,
// Ensure that there are more than 0 successful requests
/[1-9]\d+.* requests in \d+s, .* read/
]
t.plan(lines.length * 2)
const child = spawn(autocannon, [
'-c', '10',
'-d', '1',
'--on-port', '/',
'--', 'node', target
], {
cwd: __dirname,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: false
})
t.tearDown(() => {
child.kill()
})
child
.stderr
.pipe(split())
.on('data', (line) => {
const regexp = lines.shift()
t.ok(regexp, 'we are expecting this line')
console.error(line)
t.ok(regexp.test(line), 'line matches ' + regexp)
})
|
UPDATE remove hit counts + FIX hit ratio was wrongly calculated | package com.github.atorr0.predictor.statistics;
import java.util.ArrayList;
import java.util.List;
/**
* Simple stats. for hits & misses.
*
* @author https://github.com/atorr0
*/
public class Statistics {
protected final List<Long> missesList = new ArrayList<>();
protected long misses = 0;
public float getHitRatio() {
long total = 0;
for (final Long misses : missesList)
total += misses;
return 1f - Float.parseFloat("" + total) / missesList.size();
}
public long incrementMisses() {
return ++misses;
}
public void next() {
missesList.add(misses);
misses = 0;
}
@Override
public String toString() {
return "Statistics [" //
+ "hitRatio=" + getHitRatio() //
+ ", missesList=" + missesList //
+ ", misses=" + misses //
+ "]";
}
} | package com.github.atorr0.predictor.statistics;
import java.util.ArrayList;
import java.util.List;
/**
* Simple stats. for hits & misses.
*
* @author https://github.com/atorr0
*/
public class Statistics {
protected final List<Long> missesList = new ArrayList<>();
protected long hits = 0, misses = 0;
public long incrementHits() {
return ++hits;
}
public long incrementMisses() {
return ++misses;
}
public void next() {
missesList.add(misses);
hits = 0;
misses = 0;
}
@Override
public String toString() {
long total = 0;
for (Long misses : missesList)
total += misses;
final float hitRatio = Float.parseFloat("" + total) / missesList.size();
return "Statistics [" //
+ "hitRatio=" + hitRatio //
+ ", missesList=" + missesList //
+ ", hits=" + hits + ", misses=" + misses //
+ "]";
}
} |
Return the instance from jss.use() | 'use strict'
var StyleSheet = require('./StyleSheet')
var Rule = require('./Rule')
var PluginsRegistry = require('./PluginsRegistry')
/**
* Jss constructor.
*
* @api public
*/
function Jss() {
this.plugins = new PluginsRegistry()
}
module.exports = Jss
/**
* Creates a new instance of Jss.
*
* @see Jss
* @api public
*/
Jss.prototype.create = function () {
return new Jss()
}
/**
* Create a stylesheet.
*
* @see StyleSheet
* @api public
*/
Jss.prototype.createStyleSheet = function (rules, options) {
if (!options) options = {}
options.jss = this
var sheet = new StyleSheet(rules, options)
return sheet
}
/**
* Create a rule.
*
* @see Rule
* @return {Rule}
* @api public
*/
Jss.prototype.createRule = function (selector, style, options) {
if (typeof selector == 'object') {
options = style
style = selector
selector = null
}
if (!options) options = {}
options.jss = this
var rule = new Rule(selector, style, options)
this.plugins.run(rule)
return rule
}
/**
* Register plugin. Passed function will be invoked with a rule instance.
*
* @param {Function} fn
* @api public
*/
Jss.prototype.use = function (fn) {
this.plugins.use(fn)
return this
}
| 'use strict'
var StyleSheet = require('./StyleSheet')
var Rule = require('./Rule')
var PluginsRegistry = require('./PluginsRegistry')
/**
* Jss constructor.
*
* @api public
*/
function Jss() {
this.plugins = new PluginsRegistry()
}
module.exports = Jss
/**
* Creates a new instance of Jss.
*
* @see Jss
* @api public
*/
Jss.prototype.create = function () {
return new Jss()
}
/**
* Create a stylesheet.
*
* @see StyleSheet
* @api public
*/
Jss.prototype.createStyleSheet = function (rules, options) {
if (!options) options = {}
options.jss = this
var sheet = new StyleSheet(rules, options)
return sheet
}
/**
* Create a rule.
*
* @see Rule
* @return {Rule}
* @api public
*/
Jss.prototype.createRule = function (selector, style, options) {
if (typeof selector == 'object') {
options = style
style = selector
selector = null
}
if (!options) options = {}
options.jss = this
var rule = new Rule(selector, style, options)
this.plugins.run(rule)
return rule
}
/**
* Register plugin. Passed function will be invoked with a rule instance.
*
* @param {Function} fn
* @api public
*/
Jss.prototype.use = function (fn) {
this.plugins.use(fn)
}
|
Add Backbone to MapView module dependencies. | define(['jquery', 'backbone', 'async!http://maps.googleapis.com/maps/api/js?sensor=true' + (window.location.host === 'localhost' ? '' : '&key=AIzaSyDZj9_A4WUDGph6cKf2A7VsFbDz6Pb7QBk')], function ($, Backbone) {
return Backbone.View.extend({
el: $('#map'),
render: function () {
this.map = new google.maps.Map(this.el, {
center: new google.maps.LatLng(60.171, 24.941), // Rautatieasema
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER
}
});
this.centerOnCurrentLocation();
return this;
},
centerOnCurrentLocation: function () {
if (navigator.geolocation) {
var that = this;
navigator.geolocation.getCurrentPosition(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
that.map.setCenter(latLng);
});
}
}
});
});
| define(['jquery', 'async!http://maps.googleapis.com/maps/api/js?sensor=true' + (window.location.host === 'localhost' ? '' : '&key=AIzaSyDZj9_A4WUDGph6cKf2A7VsFbDz6Pb7QBk')], function($) {
return Backbone.View.extend({
el: $('#map'),
render: function() {
this.map = new google.maps.Map(this.el, {
center: new google.maps.LatLng(60.200833, 24.9375), // Helsinki
zoom: 12,
center: new google.maps.LatLng(60.171, 24.941), // Rautatieasema
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER
}
});
this.centerOnCurrentLocation();
return this;
},
centerOnCurrentLocation: function () {
if (navigator.geolocation) {
var that = this;
navigator.geolocation.getCurrentPosition(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
that.map.setCenter(latLng);
});
}
}
});
});
|
Exclude env definition from server bundle
* Exclude webpack environment variables injection from server bundle. It
also prevents node from reading the actual values | /* eslint-disable import/no-extraneous-dependencies */
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import nodeExternals from 'webpack-node-externals';
import path from 'path';
import webpack from 'webpack';
import { loaders, globalOptions, serverEntry, frontendPlugins, optimizePlugins } from './common';
export default {
...globalOptions,
entry: serverEntry,
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, '../dist'),
filename: 'server.js',
},
target: 'node',
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader'),
},
...loaders,
],
},
plugins: [
...frontendPlugins,
new webpack.IgnorePlugin(/webpack-assets\.json$/),
new ExtractTextPlugin('[name].css'),
...optimizePlugins,
],
};
| /* eslint-disable import/no-extraneous-dependencies */
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import nodeExternals from 'webpack-node-externals';
import path from 'path';
import webpack from 'webpack';
import { loaders, globalOptions, serverEntry, frontendPlugins, optimizePlugins } from './common';
export default {
...globalOptions,
entry: serverEntry,
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, '../dist'),
filename: 'server.js',
},
target: 'node',
module: {
loaders: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader!postcss-loader'),
},
...loaders,
],
},
plugins: [
...frontendPlugins,
new webpack.IgnorePlugin(/webpack-assets\.json$/),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
}),
new ExtractTextPlugin('[name].css'),
...optimizePlugins,
],
};
|
Add UKRDC_PATIENT_SEARCH_URL to test app config | import string
import random
import pytest
from radar_api.app import create_app
from radar.database import db
@pytest.fixture(scope='session')
def app():
return create_app({
'TESTING': True,
'SQLALCHEMY_DATABASE_URI': 'postgres://postgres@localhost/radar_test',
'SECRET_KEY': ''.join(random.sample(string.printable, 32)),
'BASE_URL': 'http://localhost',
'UKRDC_PATIENT_SEARCH_URL': 'http://localhost:5101/search',
})
@pytest.yield_fixture(scope='session')
def app_context(app):
with app.app_context() as app_context:
yield app_context
@pytest.fixture(scope='session')
def test_db(request, app_context):
db.drop_all()
db.create_all()
def teardown():
db.drop_all()
request.addfinalizer(teardown)
return db
@pytest.fixture
def transaction(request, app_context, test_db):
db.session.begin_nested()
def teardown():
db.session.rollback()
request.addfinalizer(teardown)
return db
@pytest.yield_fixture
def client(app, app_context):
with app.test_client() as client:
yield client
| import string
import random
import pytest
from radar_api.app import create_app
from radar.database import db
@pytest.fixture(scope='session')
def app():
return create_app({
'TESTING': True,
'SQLALCHEMY_DATABASE_URI': 'postgres://postgres@localhost/radar_test',
'SECRET_KEY': ''.join(random.sample(string.printable, 32)),
'BASE_URL': 'http://localhost'
})
@pytest.yield_fixture(scope='session')
def app_context(app):
with app.app_context() as app_context:
yield app_context
@pytest.fixture(scope='session')
def test_db(request, app_context):
db.drop_all()
db.create_all()
def teardown():
db.drop_all()
request.addfinalizer(teardown)
return db
@pytest.fixture
def transaction(request, app_context, test_db):
db.session.begin_nested()
def teardown():
db.session.rollback()
request.addfinalizer(teardown)
return db
@pytest.yield_fixture
def client(app, app_context):
with app.test_client() as client:
yield client
|
Fix error when activating on empty editor | 'use babel'
import { dirname, basename } from 'path'
function getPath (path) {
let [projectPath, filePath] = atom.project.relativizePath(path)
if (!projectPath) {
projectPath = filePath ? dirname(filePath) : null
filePath = filePath ? basename(filePath) : null
}
return { projectPath, filePath }
}
function getActiveFile () {
let editor = atom.workspace.getActivePaneItem()
if (editor) {
if (editor.file) {
return editor.file.path
} else if (editor.buffer && editor.buffer.file) {
return editor.buffer.file.path
}
}
}
function getUserConfig (projectPath) {
try {
return require(projectPath + '/bs-config.js')
} catch(err) {
return {}
}
}
function onlineConfig (value) {
switch (value) {
case 0:
return false
break;
case 1:
return undefined
break;
case 2:
return true
break;
}
}
export { getPath, getActiveFile, getUserConfig, onlineConfig }
| 'use babel'
import { dirname, basename } from 'path'
function getPath (path) {
let [projectPath, filePath] = atom.project.relativizePath(path)
if (!projectPath) {
projectPath = dirname(filePath.toString())
filePath = basename(filePath.toString())
}
return { projectPath, filePath }
}
function getActiveFile () {
let editor = atom.workspace.getActivePaneItem()
if (editor) {
if (editor.file) {
return editor.file.path
} else if (editor.buffer && editor.buffer.file) {
return editor.buffer.file.path
}
}
}
function getUserConfig (projectPath) {
try {
return require(projectPath + '/bs-config.js')
} catch(err) {
return {}
}
}
function onlineConfig (value) {
switch (value) {
case 0:
return false
break;
case 1:
return undefined
break;
case 2:
return true
break;
}
}
export { getPath, getActiveFile, getUserConfig, onlineConfig }
|
Fix getting type, fix publish favicon | <?php
/**
* AdminLte Theme for Yii2 projects
*
* @link https://github.com/hiqdev/yii2-theme-adminlte
* @package yii2-theme-adminlte
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
namespace hiqdev\themes\adminlte;
use hiqdev\yii\compat\yii;
use yii\helpers\FileHelper;
use yii\helpers\Html;
/**
* Class for this theme.
* It's almost empty cause inheritance does all the tricks.
*/
class AdminLteTheme extends \hiqdev\thememanager\Theme
{
public $label = 'AdminLte';
public function favicon(): string
{
$path = yii::getAlias(yii::getApp()->params['favicon.ico']);
$mimeType = FileHelper::getMimeTypeByExtension($path);
$publishedPath = yii::getApp()->assetManager->publish($path);
$url = $publishedPath[1];
return Html::tag('link', null, ['rel' => 'shortcut icon', 'type' => $mimeType, 'href' => $url]);
}
}
| <?php
/**
* AdminLte Theme for Yii2 projects
*
* @link https://github.com/hiqdev/yii2-theme-adminlte
* @package yii2-theme-adminlte
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/
namespace hiqdev\themes\adminlte;
use Yii;
use yii\helpers\FileHelper;
use yii\helpers\Html;
/**
* Class for this theme.
* It's almost empty cause inheritance does all the tricks.
*/
class AdminLteTheme extends \hiqdev\thememanager\Theme
{
public $label = 'AdminLte';
public function favicon(): string
{
$icon = Yii::getAlias(Yii::$app->params['favicon.ico']);
$mimeType = FileHelper::getMimeType($icon);
return Html::tag('link', null, ['rel' => 'shortcut icon', 'type' => $mimeType, 'href' => Yii::$app->assetManager->getPublishedUrl($icon)]);
}
}
|
Rename matrix receiver for General to m
I'll try to keep names consistent. | // Copyright 2015 Jonathan J Lawlor. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package matrixexp
import (
"github.com/gonum/blas/blas64"
)
// General is a typical matrix literal
type General struct {
blas64.General
}
// Dims returns the matrix dimensions.
func (m *General) Dims() (r, c int) {
r, c = m.Rows, m.Cols
return
}
// At returns the value at a given row, column index.
func (m *General) At(r, c int) float64 {
return m.Data[r*m.Stride+c]
}
// Set changes the value at a given row, column index.
func (m *General) Set(r, c int, v float64) {
m.Data[r*m.Stride+c] = v
}
// Vector returns all of the values in the matrix as a []float64, in row order.
func (m *General) Vector() []float64 {
v := make([]float64, len(m.Data))
copy(v, m.Data)
return v
}
| // Copyright 2015 Jonathan J Lawlor. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package matrixexp
import (
"github.com/gonum/blas/blas64"
)
// General is a typical matrix literal
type General struct {
blas64.General
}
// Dims returns the matrix dimensions.
func (g *General) Dims() (r, c int) {
r, c = g.Rows, g.Cols
return
}
// At returns the value at a given row, column index.
func (g *General) At(r, c int) float64 {
return g.Data[r*g.Stride+c]
}
// Set changes the value at a given row, column index.
func (g *General) Set(r, c int, v float64) {
g.Data[r*g.Stride+c] = v
}
// Vector returns all of the values in the matrix as a []float64, in row order.
func (g *General) Vector() []float64 {
v := make([]float64, len(g.Data))
copy(v, g.Data)
return v
}
|
Improve config loader init function | import configparser
import os
class ConfigLoader(object):
def __init__(self, location="../engine.conf"):
config_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), location)
self.parser = configparser.ConfigParser()
self.parser.read(config_location)
self.web_debug = self.parser['WEB']['debug'].lower() == 'true'
self.checks_location = self.parser['GENERAL']['checks_location']
self.check_timeout = int(self.parser['GENERAL']['check_timeout'])
self.round_time_sleep = int(self.parser['GENERAL']['round_time_sleep'])
self.worker_refresh_time = int(self.parser['GENERAL']['worker_refresh_time'])
self.timezone = self.parser['GENERAL']['timezone']
self.db_uri = self.parser['DB']['uri']
self.redis_host = self.parser['REDIS']['host']
self.redis_port = int(self.parser['REDIS']['port'])
self.redis_password = self.parser['REDIS']['password']
| import configparser
import os
class ConfigLoader(object):
def __init__(self, location=None):
if location is None:
location = "../engine.conf"
config_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), location)
self.parser = configparser.ConfigParser()
self.parser.read(config_location)
self.web_debug = self.parser['WEB']['debug'].lower() == 'true'
self.checks_location = self.parser['GENERAL']['checks_location']
self.check_timeout = int(self.parser['GENERAL']['check_timeout'])
self.round_time_sleep = int(self.parser['GENERAL']['round_time_sleep'])
self.worker_refresh_time = int(self.parser['GENERAL']['worker_refresh_time'])
self.timezone = self.parser['GENERAL']['timezone']
self.db_uri = self.parser['DB']['uri']
self.redis_host = self.parser['REDIS']['host']
self.redis_port = int(self.parser['REDIS']['port'])
self.redis_password = self.parser['REDIS']['password']
|
Add line to not translate the lyche datepicker | /* Datepicker for lyche reservation form */
$(function() {
$('#lyche-datepicker').datepicker( {
monthNames: [ "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December" ],
dateFormat: 'dd-mm-yy',
onSelect: function(dateText) {
var path = window.location.href
if(path.indexOf("?") > -1){
path = path.substr(0, path.indexOf("?"))
}
window.location.href = path + "?date=" + dateText;
}
});
$("#ui-datepicker-div").addClass("notranslate");
}); | /* Datepicker for lyche reservation form */
$(function() {
$('#lyche-datepicker').datepicker( {
monthNames: [ "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December" ],
dateFormat: 'dd-mm-yy',
onSelect: function(dateText) {
var path = window.location.href
if(path.indexOf("?") > -1){
path = path.substr(0, path.indexOf("?"))
}
window.location.href = path + "?date=" + dateText;
}
});
});
|
Remove loop parameter from scheduler.start() | # -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import signal
import asyncio
from aiohttp import web
from foglamp.core import routes
from foglamp.core import middleware
from foglamp.core import scheduler
__author__ = "Praveen Garg"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
def _make_app():
"""create the server"""
# https://aiohttp.readthedocs.io/en/stable/_modules/aiohttp/web.html#run_app
app = web.Application(middlewares=[middleware.error_middleware])
routes.setup(app)
return app
def _shutdown(loop):
scheduler.shutdown()
for task in asyncio.Task.all_tasks():
task.cancel()
loop.stop()
def start():
"""starts the server"""
loop = asyncio.get_event_loop()
scheduler.start()
for signal_name in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
loop.add_signal_handler(signal_name, _shutdown, loop)
web.run_app(_make_app(), host='0.0.0.0', port=8082)
| # -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import signal
import asyncio
from aiohttp import web
from foglamp.core import routes
from foglamp.core import middleware
from foglamp.core import scheduler
__author__ = "Praveen Garg"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
def _make_app():
"""create the server"""
# https://aiohttp.readthedocs.io/en/stable/_modules/aiohttp/web.html#run_app
app = web.Application(middlewares=[middleware.error_middleware])
routes.setup(app)
return app
def _shutdown(loop):
scheduler.shutdown()
for task in asyncio.Task.all_tasks():
task.cancel()
loop.stop()
def start():
"""starts the server"""
loop = asyncio.get_event_loop()
scheduler.start(loop)
for signal_name in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
loop.add_signal_handler(signal_name, _shutdown, loop)
web.run_app(_make_app(), host='0.0.0.0', port=8082)
|
Refactor mixin with a $watch | "use strict";
/* Directives */
angular.module( "TrelloBlogDirectives", ["ngSanitize"] )
.directive( "markdown", ["$sanitize", function ( $sanitize ) {
var converter = new Showdown.converter();
return {
restrict: "AE",
link: function ( scope, element, attributes ) {
if (attributes.markdown) {
scope.$watch(attributes.markdown, function( input ) {
input = input || "";
var output = input.replace( /:([a-z0-1-+]+):/g, function ( match, text ) {
return "<i class=\"emoji--" + text + "\" title=\" " + text + "\">" + text + "</i>"
} );
element.html( $sanitize(converter.makeHtml( output )) );
} );
} else {
var input = element.html() || "";
var output = input.replace( /:([a-z0-1-+]+):/g, function ( match, text ) {
return "<i class=\"emoji--" + text + "\" title=\" " + text + "\">" + text + "</i>"
} );
element.html( $sanitize(converter.makeHtml( output )) );
}
}
}
}] );
| "use strict";
/* Directives */
angular.module( "TrelloBlogDirectives", ["ngSanitize"] )
.directive( "markdown", ["$sanitize", function ( $sanitize ) {
var converter = new Showdown.converter();
return {
restrict: "AE",
scope: {
source: "=markdown"
},
link: function ( scope, element, attributes ) {
var input = scope.source || element.html();
var output = input.replace( /:([a-z0-1-+]+):/g, function ( match, text ) {
return "<i class=\"emoji--" + text + "\" title=\" " + text + "\">" + text + "</i>"
} );
element.html( $sanitize(converter.makeHtml( output )) );
}
}
}] );
|
Remove devDependencies and scripts from distribution package.json | const fs = require('fs');
const path = require('path');
const pkg = require('../package.json');
const copyFileSync = (source, dest) => {
const content = fs.readFileSync(source, 'utf-8');
fs.writeFileSync(dest, content);
};
delete pkg.private;
delete pkg.scripts;
delete pkg.devDependencies;
pkg.main = 'cjs/index.js'
pkg.module = 'esm/index.js'
fs.writeFileSync('dist/package.json', JSON.stringify(pkg, null, 2));
copyFileSync('README.md', 'dist/README.md');
copyFileSync('LICENSE.md', 'dist/LICENSE.md');
const files = fs.readdirSync('src')
.filter(file => !file.includes('common') && !file.includes('index'))
.forEach(file => {
const name = file.endsWith('.js') ? file.slice(0, -3) : file;
const filePkg = {
name: `gl-matrix/${name}`,
main: `../cjs/${file}`,
module: `../esm/${file}`,
};
if(!fs.existsSync(`dist/${name}`)) {
fs.mkdirSync(`dist/${name}`);
}
fs.writeFileSync(
`dist/${name}/package.json`,
JSON.stringify(filePkg, null, 2)
);
});
| const fs = require('fs');
const path = require('path');
const pkg = require('../package.json');
const copyFileSync = (source, dest) => {
const content = fs.readFileSync(source, 'utf-8');
fs.writeFileSync(dest, content);
};
delete pkg.private;
pkg.main = 'cjs/index.js'
pkg.module = 'esm/index.js'
fs.writeFileSync('dist/package.json', JSON.stringify(pkg, null, 2));
copyFileSync('README.md', 'dist/README.md');
copyFileSync('LICENSE.md', 'dist/LICENSE.md');
const files = fs.readdirSync('src')
.filter(file => !file.includes('common') && !file.includes('index'))
.forEach(file => {
const name = file.endsWith('.js') ? file.slice(0, -3) : file;
const filePkg = {
name: `gl-matrix/${name}`,
main: `../cjs/${file}`,
module: `../esm/${file}`,
};
if(!fs.existsSync(`dist/${name}`)) {
fs.mkdirSync(`dist/${name}`);
}
fs.writeFileSync(
`dist/${name}/package.json`,
JSON.stringify(filePkg, null, 2)
);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.