text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Write deployment resources in tab format | package commands
import (
"fmt"
"os"
"text/tabwriter"
"github.com/evandbrown/dm/googlecloud"
"github.com/evandbrown/dm/util"
"github.com/spf13/cobra"
)
var statCmd = &cobra.Command{
Use: "stat",
Short: "Stat a deployment, listing its resources",
}
func init() {
statCmd.PreRun = func(cmd *cobra.Command, args []string) {
requireName()
}
statCmd.Run = func(cmd *cobra.Command, args []string) {
util.Check(stat(cmd, args))
}
}
func stat(cmd *cobra.Command, args []string) error {
service, err := googlecloud.GetService()
util.Check(err)
call := service.Resources.List(Project, Name)
resources, error := call.Do()
util.Check(error)
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 8, 2, '\t', 0)
fmt.Fprintln(w, "Resource Type\tName\t")
for _, r := range resources.Resources {
fmt.Fprintf(w, "%s\t%s\t\n", r.Type, r.Name)
}
w.Flush()
return nil
}
| package commands
import (
"fmt"
"github.com/evandbrown/dm/googlecloud"
"github.com/evandbrown/dm/util"
"github.com/spf13/cobra"
)
var statCmd = &cobra.Command{
Use: "stat",
Short: "Stat a deployment, listing its resources",
}
func init() {
statCmd.PreRun = func(cmd *cobra.Command, args []string) {
requireName()
}
statCmd.Run = func(cmd *cobra.Command, args []string) {
util.Check(stat(cmd, args))
}
}
func stat(cmd *cobra.Command, args []string) error {
service, err := googlecloud.GetService()
util.Check(err)
call := service.Resources.List(Project, Name)
resources, error := call.Do()
util.Check(error)
for _, r := range resources.Resources {
fmt.Printf("%s\t%s\n", r.Type, r.Name)
}
return nil
}
|
Add convenience method on test case. | """Base stuff for testing.
"""
import subprocess
assert not 'twill' in subprocess.__file__
from flask.ext.testing import TestCase
from abilian.application import Application
__all__ = ['TestConfig', 'BaseTestCase']
class TestConfig(object):
SQLALCHEMY_DATABASE_URI = "sqlite://"
SQLALCHEMY_ECHO = False
TESTING = True
SECRET_KEY = "SECRET"
class BaseTestCase(TestCase):
config_class = TestConfig
application_class = Application
def create_app(self):
config = self.config_class()
self.app = self.application_class(config)
return self.app
def setUp(self):
self.app.create_db()
self.session = self.db.session
def tearDown(self):
self.db.session.remove()
self.db.drop_all()
self.db.engine.dispose()
@property
def db(self):
return self.app.extensions['sqlalchemy'].db
# Useful for debugging
def dump_routes(self):
rules = list(self.app.url_map.iter_rules())
rules.sort(key=lambda x: x.rule)
for rule in rules:
print rule, rule.methods, rule.endpoint
| """Base stuff for testing.
"""
import subprocess
assert not 'twill' in subprocess.__file__
from flask.ext.testing import TestCase
from abilian.application import Application
from abilian.core.entities import db
__all__ = ['TestConfig', 'BaseTestCase']
class TestConfig(object):
SQLALCHEMY_DATABASE_URI = "sqlite://"
SQLALCHEMY_ECHO = False
TESTING = True
SECRET_KEY = "SECRET"
class BaseTestCase(TestCase):
config_class = TestConfig
application_class = Application
def create_app(self):
config = self.config_class()
self.app = self.application_class(config)
return self.app
def setUp(self):
self.app.create_db()
self.session = db.session
def tearDown(self):
db.session.remove()
db.drop_all()
db.engine.dispose()
# Useful for debugging
def dump_routes(self):
rules = list(self.app.url_map.iter_rules())
rules.sort(key=lambda x: x.rule)
for rule in rules:
print rule, rule.methods, rule.endpoint
|
Fix jest auto-mocks hoisting on Windows
Summary: ts-jest transformation was not applied on Windows because of wrong pattern in jest.config. Because of this jest.mock calls was not hoisted to the top and were applied after imports.
Reviewed By: mweststrate
Differential Revision: D21379004
fbshipit-source-id: ec52f98228c5d9e58c0832f2ad201a36d6c8534e | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
module.exports = {
transform: {
'^.*__tests__(/|\\\\).*\\.tsx?$': 'ts-jest',
'\\.(js|tsx?)$': '<rootDir>/scripts/jest-transform.js',
},
setupFiles: ['<rootDir>/scripts/jest-setup.js'],
moduleNameMapper: {
'^flipper$': '<rootDir>/app/src',
'^flipper-doctor$': '<rootDir>/doctor/src',
'^flipper-pkg$': '<rootDir>/pkg/src',
'^flipper-pkg-lib$': '<rootDir>/pkg-lib/src',
},
clearMocks: true,
coverageReporters: ['json-summary', 'lcov', 'html'],
testMatch: ['**/**.node.(js|jsx|ts|tsx)'],
testEnvironment: 'jest-environment-jsdom-sixteen',
};
| /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
module.exports = {
transform: {
'^.*__tests__/.*\\.tsx?$': 'ts-jest',
'\\.(js|tsx?)$': '<rootDir>/scripts/jest-transform.js',
},
setupFiles: ['<rootDir>/scripts/jest-setup.js'],
moduleNameMapper: {
'^flipper$': '<rootDir>/app/src',
'^flipper-doctor$': '<rootDir>/doctor/src',
'^flipper-pkg$': '<rootDir>/pkg/src',
'^flipper-pkg-lib$': '<rootDir>/pkg-lib/src',
},
clearMocks: true,
coverageReporters: ['json-summary', 'lcov', 'html'],
testMatch: ['**/**.node.(js|jsx|ts|tsx)'],
testEnvironment: 'jest-environment-jsdom-sixteen',
};
|
Fix usage of deprecated class | package nl.homeserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
} | package nl.homeserver.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
}
} |
Update renderer logger to log all arguments.
Closes #60. | import app from 'ampersand-app';
import electron from 'electron';
const mainLogger = electron.remote.require('app/main/utils/expose-app.js')().logger;
/**
* Get configured logger.
*
* @param {string} consoleMethod Name of `console` method
* @param {string} winstonMethod Name of Winston's logger method (selected from
* defaults)
* @returns {Function} logger
*/
function getLogger(consoleMethod, winstonMethod) {
return (...args) => {
console[consoleMethod].apply(console, args); // eslint-disable-line no-console
mainLogger[winstonMethod].apply(null, ['ui', ...args]);
};
}
module.exports = function configureLogger() {
app.logger = {
debug: getLogger('log', 'debug'),
error: getLogger('error', 'error'),
info: getLogger('log', 'info'),
log: getLogger('log', 'info'),
verbose: getLogger('log', 'verbose'),
warn: getLogger('warn', 'warn'),
};
};
| import app from 'ampersand-app';
import electron from 'electron';
import { partial } from 'lodash';
module.exports = function configureLogger() {
const colorMap = {
verbose: 'cyan',
info: 'green',
warn: 'orange',
debug: 'blue',
error: 'red',
};
const mainLogger = () => {
return electron.remote.require('app/main/utils/expose-app.js')().logger;
};
const proxyLog = (type, content) => {
if (type === 'log') {
type = 'info';
}
/* eslint-disable no-console */
console.log(`%c ${type}`, `color:${colorMap[type]};font-weight:bold`, content);
/* eslint-enable no-console */
mainLogger()[type]('[ui]', content);
};
app.logger = {
error: partial(proxyLog, 'error'),
warn: partial(proxyLog, 'warn'),
info: partial(proxyLog, 'info'),
verbose: partial(proxyLog, 'verbose'),
debug: partial(proxyLog, 'debug'),
log: partial(proxyLog, 'log'),
};
};
|
Fix PHP 5.3 closure bug in the captcha service provider | <?php namespace Larapress\Providers;
use Illuminate\Support\ServiceProvider;
use Larapress\Services\Captcha;
use Larapress\Services\Helpers;
class CaptchaServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$self = $this;
$this->app->bind('captcha', function() use ($self)
{
return new Captcha(
$self->app['view'],
$self->app['config'],
$self->app['session.store'],
new Helpers
);
});
}
}
| <?php namespace Larapress\Providers;
use Illuminate\Support\ServiceProvider;
use Larapress\Services\Captcha;
use Larapress\Services\Helpers;
class CaptchaServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->bind('captcha', function()
{
return new Captcha(
$this->app['view'],
$this->app['config'],
$this->app['session.store'],
new Helpers
);
});
}
}
|
Comment out filter that forbids development access | <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
//if (@$_SERVER['SERVER_ADDR'] != '127.0.0.1') {
// header('HTTP/1.0 403 Forbidden');
// exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
//}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
| <?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (@$_SERVER['SERVER_ADDR'] != '147.251.21.32') {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Fix tests on python 3 | import os
import sys
from nose.tools import *
try:
from importlib import reload
except ImportError:
pass
def setup_yamlmod():
import yamlmod
reload(yamlmod)
def teardown_yamlmod():
import yamlmod
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
sys.meta_path.remove(hook)
break
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_installs_hook():
import yamlmod
hooks = []
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
hooks.append(hook)
eq_(len(hooks), 1, 'did not find exactly one hook')
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_fixture():
import fixture
eq_(fixture.debug, True)
eq_(fixture.domain, 'example.com')
eq_(fixture.users, ['alice', 'bob', 'cathy'])
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_hidden_attributes():
import fixture
eq_(fixture.__name__, 'fixture')
eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))
| import os
import sys
from nose.tools import *
def setup_yamlmod():
import yamlmod
reload(yamlmod)
def teardown_yamlmod():
import yamlmod
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
sys.meta_path.remove(hook)
break
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_installs_hook():
import yamlmod
hooks = []
for hook in sys.meta_path:
if isinstance(hook, yamlmod.YamlImportHook):
hooks.append(hook)
eq_(len(hooks), 1, 'did not find exactly one hook')
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_import_fixture():
import fixture
eq_(fixture.debug, True)
eq_(fixture.domain, 'example.com')
eq_(fixture.users, ['alice', 'bob', 'cathy'])
@with_setup(setup_yamlmod, teardown_yamlmod)
def test_hidden_attributes():
import fixture
eq_(fixture.__name__, 'fixture')
eq_(fixture.__file__, os.path.join(os.path.dirname(__file__), 'fixture.yml'))
|
Change user agent for batch api client | 'use strict';
var qs = require('querystring');
var request = require('request');
var dot = require('dot');
var hostHeader = dot.template('{{=it.username}}.localhost.lan');
var debug = require('../util/debug')('batch-client');
function BatchClient(endpoint, username, apiKey) {
this.endpoint = endpoint;
this.username = username;
this.apiKey = apiKey;
}
module.exports = BatchClient;
BatchClient.prototype.enqueue = function(query, callback) {
var enqueueRequest = {
url: this.endpoint + '?' + qs.stringify({'api_key': this.apiKey}),
headers: {
'Content-Type': 'application/json',
'Host': hostHeader({username: this.username}),
'User-Agent': 'camshaft'
},
body: JSON.stringify({query: query})
};
request.post(enqueueRequest, function(err, response, body) {
response = response || {};
if (err || response.statusCode !== 201) {
return callback(new Error('Unable to enqueue SQL API batch job'));
}
var job = JSON.parse(body);
debug('Queued job: %j', job);
return callback(null, {status: 'ok'});
});
};
| 'use strict';
var qs = require('querystring');
var request = require('request');
var dot = require('dot');
var hostHeader = dot.template('{{=it.username}}.localhost.lan');
var debug = require('../util/debug')('batch-client');
function BatchClient(endpoint, username, apiKey) {
this.endpoint = endpoint;
this.username = username;
this.apiKey = apiKey;
}
module.exports = BatchClient;
BatchClient.prototype.enqueue = function(query, callback) {
var enqueueRequest = {
url: this.endpoint + '?' + qs.stringify({'api_key': this.apiKey}),
headers: {
'Content-Type': 'application/json',
'Host': hostHeader({username: this.username}),
'User-Agent': 'CartoDB-Analysis-API'
},
body: JSON.stringify({query: query})
};
request.post(enqueueRequest, function(err, response, body) {
response = response || {};
if (err || response.statusCode !== 201) {
return callback(new Error('Unable to enqueue SQL API batch job'));
}
var job = JSON.parse(body);
debug('Queued job: %j', job);
return callback(null, {status: 'ok'});
});
};
|
Fix ceiling in other file | function redistributeCollagePics()
{
var $pictures = jQuery('.carousel-panel-collage-wrapper').contents();
jQuery('.carousel-panel-collage-wrapper').parent().remove();
var $container = jQuery('#carousel-container');
var width = $container.innerWidth();
var height = $container.innerHeight();
// Calculate number of pictures per panel
var picsPerPanel = Math.floor(($pictures.length * 400 * 220) / (width * height));
var numPanels = Math.ceil($pictures.length / picsPerPanel);
var $panels = jQuery();
for (var i = 0; i < numPanels; ++i)
{
for (var j = i * picsPerPanel; j < (i * picsPerPanel) + picsPerPanel; ++j)
{
$wrapper = jQuery('<div class="carousel-panel-collage-wrapper"></div>');
$wrapper.html($pictures.eq(j));
$panel = jQuery('<div class="carousel-panel"></div>');
$panel.append($wrapper);
$panels.append($panel);
}
}
}
jQuery(document).ready(function()
{
jQuery(window).resize(redistributeCollagePics);
}
);
| function redistributeCollagePics()
{
var $pictures = jQuery('.carousel-panel-collage-wrapper').contents();
jQuery('.carousel-panel-collage-wrapper').parent().remove();
var $container = jQuery('#carousel-container');
var width = $container.innerWidth();
var height = $container.innerHeight();
// Calculate number of pictures per panel
var picsPerPanel = Math.floor(($pictures.length * 400 * 220) / (width * height));
var numPanels = Math.ceiling($pictures.length / picsPerPanel);
var $panels = jQuery();
for (var i = 0; i < numPanels; ++i)
{
for (var j = i * picsPerPanel; j < (i * picsPerPanel) + picsPerPanel; ++j)
{
$wrapper = jQuery('<div class="carousel-panel-collage-wrapper"></div>');
$wrapper.html($pictures.eq(j));
$panel = jQuery('<div class="carousel-panel"></div>');
$panel.append($wrapper);
$panels.append($panel);
}
}
}
jQuery(document).ready(function()
{
jQuery(window).resize(redistributeCollagePics);
}
);
|
Add refresh button (last night) | var ClassifierList = React.createClass({
getInitialState: function() {
return {
classifiers: null,
time: 0
}
},
getClassifierList: function(data) {
this.setState({classifiers: data.classifiers, time: data.time})
},
componentDidMount: function() {
this.refreshList();
},
refreshList: function() {
this.refs.ajax.sendNewRequest({});
},
render: function() {
var items = [];
items.push(<span>{"Classifier List"}</span>);
items.push(<input type={"button"} onClick={this.refreshList} value={"Refresh"} />);
items.push(<AjaxRequest ref={"ajax"} url={"/api/listClassifiers"} onNewResponse={this.getClassifierList} />);
if(this.state.classifiers) {
items.push(<ul>{_(this.state.classifiers).map(function(info, name) {
console.log(info);
return <div>{name}</div>
}, this).value()}</ul>);
}
return <div>{items}</div>;
}
}); | var ClassifierList = React.createClass({
getInitialState: function() {
return {
classifiers: null,
time: 0
}
},
getClassifierList: function(data) {
this.setState({classifiers: data.classifiers, time: data.time})
},
componentDidMount: function() {
this.refs.ajax.sendNewRequest({});
},
render: function() {
var items = [];
items.push(<div>{"Classifier List"}</div>);
items.push(<AjaxRequest ref={"ajax"} url={"/api/listClassifiers"} onNewResponse={this.getClassifierList} />);
if(this.state.classifiers) {
items.push(<ul>{_(this.state.classifiers).map(function(info, name) {
console.log(info);
return <div>{name}</div>
}, this).value()}</ul>);
}
return <div>{items}</div>;
}
}); |
Set code to Invalid argument for ValueErrors | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger
class GrpcExceptionWrapper(object):
def __init__(self, response_type, state_code=StatusCode.UNKNOWN):
self.response_type = response_type
self.state_code = state_code
def _set_context(self, context, exception):
if context is not None:
context.set_code(self.state_code)
context.set_details(str(exception))
def __call__(self, f):
def wrap_f(caller_self, request, context):
try:
return f(caller_self, request, context)
except ValueError as e:
context.set_code(StatusCode.INVALID_ARGUMENT)
self._set_context(context, e)
logger.info(str(e))
return self.response_type()
except Exception as e:
self._set_context(context, e)
logger.exception(e)
return self.response_type()
return wrap_f
| # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from grpc import StatusCode
from qrl.core.misc import logger
class GrpcExceptionWrapper(object):
def __init__(self, response_type, state_code=StatusCode.UNKNOWN):
self.response_type = response_type
self.state_code = state_code
def _set_context(self, context, exception):
if context is not None:
context.set_code(self.state_code)
context.set_details(str(exception))
def __call__(self, f):
def wrap_f(caller_self, request, context):
try:
return f(caller_self, request, context)
except ValueError as e:
self._set_context(context, e)
logger.info(str(e))
return self.response_type()
except Exception as e:
self._set_context(context, e)
logger.exception(e)
return self.response_type()
return wrap_f
|
Add copyright header to distributed CSS | import del from 'del';
import gulp from 'gulp';
import mergeStream from 'merge-stream';
import loadPlugins from 'gulp-load-plugins';
import cssnextPlugin from 'postcss-cssnext';
import {cssSrcFolder, cssBuildFolder, copyrightHeader} from './common';
const plugins = loadPlugins();
gulp.task('css-build-src', () => {
return gulp.src([`${cssSrcFolder}/**/*.scss`, `!${cssSrcFolder}/*.scss`])
.pipe(plugins.sass({outputStyle: 'compressed'}))
.pipe(plugins.postcss([cssnextPlugin()]))
.pipe(plugins.header(copyrightHeader))
.pipe(gulp.dest(cssBuildFolder));
});
gulp.task('css-build-assets', () => {
return gulp.src(`${cssSrcFolder}/*/**/!(package.json|*.md|*.scss)`)
.pipe(gulp.dest(cssBuildFolder));
});
gulp.task('css-build-variables-and-mixins-package', () => {
return mergeStream(
gulp.src([`${cssSrcFolder}/pui-variables.scss`, `${cssSrcFolder}/mixins.scss`]),
).pipe(gulp.dest(`${cssBuildFolder}/variables-and-mixins`));
});
gulp.task('css-clean', callback => del([cssBuildFolder], callback));
gulp.task('css-build', gulp.series('css-clean',
'css-build-src',
'css-build-assets',
'css-build-variables-and-mixins-package'
)); | import del from 'del';
import gulp from 'gulp';
import mergeStream from 'merge-stream';
import loadPlugins from 'gulp-load-plugins';
import cssnextPlugin from 'postcss-cssnext';
import {cssSrcFolder, cssBuildFolder} from './common';
const plugins = loadPlugins();
gulp.task('css-build-src', () => {
return gulp.src([`${cssSrcFolder}/**/*.scss`, `!${cssSrcFolder}/*.scss`])
.pipe(plugins.sass({outputStyle: 'compressed'}))
.pipe(plugins.postcss([cssnextPlugin()]))
.pipe(gulp.dest(cssBuildFolder));
});
gulp.task('css-build-assets', () => {
return gulp.src(`${cssSrcFolder}/*/**/!(package.json|*.md|*.scss)`)
.pipe(gulp.dest(cssBuildFolder));
});
gulp.task('css-build-variables-and-mixins-package', () => {
return mergeStream(
gulp.src([`${cssSrcFolder}/pui-variables.scss`, `${cssSrcFolder}/mixins.scss`]),
).pipe(gulp.dest(`${cssBuildFolder}/variables-and-mixins`));
});
gulp.task('css-clean', callback => del([cssBuildFolder], callback));
gulp.task('css-build', gulp.series('css-clean',
'css-build-src',
'css-build-assets',
'css-build-variables-and-mixins-package'
)); |
Save the user's data under the username key. | <?php
namespace User;
use Application\BaseDb;
class UserDb extends BaseDb
{
protected $keyName = 'users';
public function save($user)
{
$data = array(
'uri' => $user->getUri(),
'username' => $user->getUsername(),
'slug' => $user->getUsername(),
'verbose_uri' => $user->getVerboseUri()
);
$savedUser = $this->load('uri', $user->getUri());
if ($savedUser) {
// user is already known - update this record
$data = array_merge($savedUser, $data);
}
$this->cache->save($this->keyName, $data, 'uri', $user->getUri());
$this->cache->save($this->keyName, $data, 'username', $user->getUsername());
}
}
| <?php
namespace User;
use Application\BaseDb;
class UserDb extends BaseDb
{
protected $keyName = 'users';
public function save($user)
{
$data = array(
'uri' => $user->getUri(),
'username' => $user->getUsername(),
'slug' => $user->getUsername(),
'verbose_uri' => $user->getVerboseUri()
);
$savedUser = $this->load('uri', $user->getUri());
if ($savedUser) {
// user is already known - update this record
$data = array_merge($savedUser, $data);
}
$this->cache->save($this->keyName, $data, 'uri', $user->getUri());
}
}
|
Raise window to focus on Mac | from __future__ import print_function, division
from sys import argv, stderr
def run_gui():
'''Start the event loop to calucate spectra interactively'''
# Import Qt functions. Do so here to handle errors better
try:
from PyQt4.QtGui import QApplication
except ImportError:
print("Cannot find PyQt4", file=stderr)
print("You must install this to run the GUI", file=stderr)
return 1
# For good measure, try to find PyQwt5 now as a check
try:
import PyQt4.Qwt5
except ImportError:
print("Cannot find PyQwt5", file=stderr)
print("You must install this to run the GUI", file=stderr)
return 1
from mainwindow import MainWindow
# The actual event loop
app = QApplication(argv)
window = MainWindow()
window.show()
window.raise_()
return app.exec_()
| from __future__ import print_function, division
from sys import argv, stderr
def run_gui():
'''Start the event loop to calucate spectra interactively'''
# Import Qt functions. Do so here to handle errors better
try:
from PyQt4.QtGui import QApplication
except ImportError:
print("Cannot find PyQt4", file=stderr)
print("You must install this to run the GUI", file=stderr)
return 1
# For good measure, try to find PyQwt5 now as a check
try:
import PyQt4.Qwt5
except ImportError:
print("Cannot find PyQwt5", file=stderr)
print("You must install this to run the GUI", file=stderr)
return 1
from mainwindow import MainWindow
# The actual event loop
app = QApplication(argv)
window = MainWindow()
window.show()
return app.exec_()
|
Add subnet arg to AWS driver; remove unused code from main driver | from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Kozinaki',
description='OpenStack multi-cloud driver for AWS, Azure',
url='https://github.com/compunova/kozinaki.git',
author='Compunova',
author_email='kozinaki@compu-nova.com',
version='0.1.4',
long_description=readme(),
packages=find_packages(),
install_requires=[
'haikunator==2.1.0',
'azure==2.0.0rc6',
'boto3==1.4.0',
'google-cloud==0.21.0',
'cryptography==1.4'
]
)
| from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(
name='Kozinaki',
description='OpenStack multi-cloud driver for AWS, Azure',
url='https://github.com/compunova/kozinaki.git',
author='Compunova',
author_email='kozinaki@compu-nova.com',
version='0.1.3',
long_description=readme(),
packages=find_packages(),
install_requires=[
'haikunator==2.1.0',
'azure==2.0.0rc6',
'boto3==1.4.0',
'google-cloud==0.21.0',
'cryptography==1.4'
]
)
|
Test also line feeds in field names | package common
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_CSVDump(t *testing.T) {
type io struct {
Fields []string
Rows [][]string
Output string
}
tests := []io{
io{
Fields: []string{"f1", "f2"},
Rows: [][]string{
[]string{"11", "12"},
[]string{"21", "22"},
},
Output: "f1,f2\n11,12\n21,22\n",
},
io{
Fields: []string{"f1", "f2"},
Rows: [][]string{
[]string{"11"},
[]string{"21", "22", "23"},
},
Output: "f1,f2\n11\n21,22,23\n",
},
io{
Fields: []string{"f\n\n1", "f\n2"},
Rows: [][]string{
[]string{"11"},
[]string{"2\r\n1", "2\r\n2", "23"},
},
Output: "f\\n\\n1,f\\n2\n11\n2\\r\\n1,2\\r\\n2,23\n",
},
}
for _, test := range tests {
assert.Equal(t, test.Output, DumpInCSVFormat(test.Fields, test.Rows))
}
}
| package common
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_CSVDump(t *testing.T) {
type io struct {
Fields []string
Rows [][]string
Output string
}
tests := []io{
io{
Fields: []string{"f1", "f2"},
Rows: [][]string{
[]string{"11", "12"},
[]string{"21", "22"},
},
Output: "f1,f2\n11,12\n21,22\n",
},
io{
Fields: []string{"f1", "f2"},
Rows: [][]string{
[]string{"11"},
[]string{"21", "22", "23"},
},
Output: "f1,f2\n11\n21,22,23\n",
},
}
for _, test := range tests {
assert.Equal(t, test.Output, DumpInCSVFormat(test.Fields, test.Rows))
}
}
|
Update dsub version to 0.3.2.dev0
PiperOrigin-RevId: 243855458 | # Copyright 2017 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.2.dev0'
| # Copyright 2017 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1'
|
Add to start urls to contain all dataset pages | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items
class DatasetSpider(CrawlSpider):
pages = 9466
name = 'dataset'
allowed_domains = ['data.gc.ca']
start_urls = []
for i in range(1, pages + 1):
start_urls.append('http://data.gc.ca/data/en/dataset?page=' + str(i))
rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
'parse_dataset')]
def parse_dataset(self, response):
sel = Selector(response)
dataset = items.DatasetItem()
dataset['url'] = response.url
dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract()
return dataset
| from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from .. import items
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca']
start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']),
'parse_dataset')]
def parse_dataset(self, response):
sel = Selector(response)
dataset = items.DatasetItem()
dataset['url'] = response.url
dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract()
dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract()
return dataset
|
select_menu: Remove extraneous "?" when no queries.
Previously, when the last query parameter was removed, the URL was set
to "http://example.org/foo?" with a trailing "?" symbol.
This is visually displeasing. Make it so that the URL becomes a cleaner
"http://example.org/foo" instead.
Also remove unneeded blank lines. | // +build js
package select_menu
import (
"fmt"
"net/url"
"github.com/gopherjs/gopherjs/js"
"github.com/shurcooL/go/gopherjs_http/jsutil"
"honnef.co/go/js/dom"
)
func init() {
js.Global.Set("SelectMenuOnInput", jsutil.Wrap(SelectMenuOnInput))
}
func SelectMenuOnInput(event dom.Event, selElem dom.HTMLElement, defaultOption, queryParameter string) {
url, err := url.Parse(dom.GetWindow().Location().Href)
if err != nil {
// We don't expect this can ever happen, so treat it as an internal error if it does.
panic(fmt.Errorf("internal error: parsing window.location.href as URL failed: %v", err))
}
query := url.Query()
if selected := selElem.(*dom.HTMLSelectElement).SelectedOptions()[0].Text; selected == defaultOption {
query.Del(queryParameter)
} else {
query.Set(queryParameter, selected)
}
url.RawQuery = query.Encode()
dom.GetWindow().Location().Href = url.String()
}
| // +build js
package select_menu
import (
"net/url"
"strings"
"github.com/gopherjs/gopherjs/js"
"github.com/shurcooL/go/gopherjs_http/jsutil"
"honnef.co/go/js/dom"
)
func init() {
js.Global.Set("SelectMenuOnInput", jsutil.Wrap(SelectMenuOnInput))
}
func SelectMenuOnInput(event dom.Event, object dom.HTMLElement, defaultOption, queryParameter string) {
rawQuery := strings.TrimPrefix(dom.GetWindow().Location().Search, "?")
query, _ := url.ParseQuery(rawQuery)
selectElement := object.(*dom.HTMLSelectElement)
selected := selectElement.SelectedOptions()[0].Text
if selected == defaultOption {
query.Del(queryParameter)
} else {
query.Set(queryParameter, selected)
}
dom.GetWindow().Location().Search = "?" + query.Encode()
}
|
Update require signature for React and React Native | 'use strict';
var React = require('react');
var {
requireNativeComponent,
DeviceEventEmitter,
View
} = require('react-native');
var Component = requireNativeComponent('RSSignatureView', null);
var styles = {
signatureBox: {
flex: 1
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#F5FCFF',
}
};
var saveEvent, cancelEvent;
var SignatureCapture = React.createClass({
propTypes: {
pitchEnabled: React.PropTypes.bool
},
componentDidMount: function() {
saveEvent = DeviceEventEmitter.addListener('onSaveEvent', this.props.onSaveEvent);
cancelEvent = DeviceEventEmitter.addListener('onCancelEvent', this.props.onCancelEvent);
},
componentWillUnmount: function() {
saveEvent.remove();
cancelEvent.remove();
},
render: function() {
return (
<View style={styles.container}>
<Component style={styles.signatureBox} />
</View>
)
}
});
module.exports = SignatureCapture;
| 'use strict';
var React = require('react-native');
var {
requireNativeComponent,
DeviceEventEmitter,
View
} = React;
var Component = requireNativeComponent('RSSignatureView', null);
var styles = {
signatureBox: {
flex: 1
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#F5FCFF',
}
};
var saveEvent, cancelEvent;
var SignatureCapture = React.createClass({
propTypes: {
pitchEnabled: React.PropTypes.bool
},
componentDidMount: function() {
saveEvent = DeviceEventEmitter.addListener('onSaveEvent', this.props.onSaveEvent);
cancelEvent = DeviceEventEmitter.addListener('onCancelEvent', this.props.onCancelEvent);
},
componentWillUnmount: function() {
saveEvent.remove();
cancelEvent.remove();
},
render: function() {
return (
<View style={styles.container}>
<Component style={styles.signatureBox} />
</View>
)
}
});
module.exports = SignatureCapture;
|
Rename to pam2 as we're breaking the API, bump version | from setuptools import setup, find_packages
import sys, os
version = '1.0'
setup(name='pam2',
version=version,
description="PAM interface using ctypes",
long_description="""\
An interface to the Pluggable Authentication Modules (PAM) library on linux, written in pure python (using ctypes)""",
classifiers=["Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Systems Administration :: Authentication/Directory"
],
keywords='',
author='Grzegorz Nosek',
author_email='root@localdomain.pl',
url='http://github.com/gnosek/python-pam',
download_url = "http://github.com/gnosek/python-pam/archive/%s.zip" % version,
license='MIT',
py_modules=["pam"],
zip_safe=True,
install_requires=[],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import sys, os
version = '0.1.4'
setup(name='pam',
version=version,
description="PAM interface using ctypes",
long_description="""\
An interface to the Pluggable Authentication Modules (PAM) library on linux, written in pure python (using ctypes)""",
classifiers=["Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: MacOS X",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Systems Administration :: Authentication/Directory"
],
keywords='',
author='Chris AtLee',
author_email='chris@atlee.ca',
url='http://atlee.ca/software/pam',
download_url = "http://atlee.ca/software/pam/dist/%s" % version,
license='MIT',
py_modules=["pam"],
zip_safe=True,
install_requires=[],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Use dict interface to bunch.
I'm not sure why, but we got this error on the server::
Traceback (most recent call last):
File "fmn/consumer/util.py", line 33, in get_fas_email
if person.email:
AttributeError: 'dict' object has no attribute 'email'
This should fix that. | import fedora.client
import logging
log = logging.getLogger("fmn")
def new_packager(topic, msg):
""" Returns a username if the message is about a new packager in FAS. """
if '.fas.group.member.sponsor' in topic:
group = msg['msg']['group']
if group == 'packager':
return msg['msg']['user']
return None
def new_badges_user(topic, msg):
""" Returns a username if the message is about a new fedbadges user. """
if '.fedbadges.person.login.first' in topic:
return msg['msg']['user']['username']
return None
def get_fas_email(config, username):
""" Return FAS email associated with a username.
We use this to try and get the right email for new autocreated users.
We used to just use $USERNAME@fp.o, but when first created most users don't
have that alias available yet.
"""
try:
fas = fedora.client.AccountSystem(**config['fas_credentials'])
person = fas.person_by_username(username)
if person.get('email'):
return person['email']
raise ValueError("No email found: %r, %r" % (person.email, username))
except Exception:
log.exception("Failed to get FAS email for %r" % username)
return '%s@fedoraproject.org' % username
| import fedora.client
import logging
log = logging.getLogger("fmn")
def new_packager(topic, msg):
""" Returns a username if the message is about a new packager in FAS. """
if '.fas.group.member.sponsor' in topic:
group = msg['msg']['group']
if group == 'packager':
return msg['msg']['user']
return None
def new_badges_user(topic, msg):
""" Returns a username if the message is about a new fedbadges user. """
if '.fedbadges.person.login.first' in topic:
return msg['msg']['user']['username']
return None
def get_fas_email(config, username):
""" Return FAS email associated with a username.
We use this to try and get the right email for new autocreated users.
We used to just use $USERNAME@fp.o, but when first created most users don't
have that alias available yet.
"""
try:
fas = fedora.client.AccountSystem(**config['fas_credentials'])
person = fas.person_by_username(username)
if person.email:
return person.email
raise ValueError("No email found: %r, %r" % (person.email, username))
except Exception:
log.exception("Failed to get FAS email for %r" % username)
return '%s@fedoraproject.org' % username
|
Fix analytics wrapper for window.location.href | (function (root) {
"use strict";
root.GOVUK.GDM = root.GOVUK.GDM || {};
root.GOVUK.GDM.analytics = {
'register': function () {
GOVUK.Analytics.load();
var cookieDomain = (root.document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : root.document.domain;
var universalId = 'UA-49258698-1';
GOVUK.analytics = new GOVUK.Analytics({
universalId: universalId,
cookieDomain: cookieDomain
});
},
'location': {
'href': function () {
return root.location.href;
},
'pathname': function () {
return root.location.pathname;
},
'hostname': function () {
return root.location.hostname;
},
'search': function () {
return root.location.search;
}
}
};
})(window);
| (function (root) {
"use strict";
root.GOVUK.GDM = root.GOVUK.GDM || {};
root.GOVUK.GDM.analytics = {
'register': function () {
GOVUK.Analytics.load();
var cookieDomain = (root.document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : root.document.domain;
var universalId = 'UA-49258698-1';
GOVUK.analytics = new GOVUK.Analytics({
universalId: universalId,
cookieDomain: cookieDomain
});
},
'location': {
'href': function () {
return root.location.search;
},
'pathname': function () {
return root.location.pathname;
},
'hostname': function () {
return root.location.hostname;
},
'search': function () {
return root.location.search;
}
}
};
})(window);
|
Adjust padding on animated page wrapper | import React from 'react';
import styled from 'styled-components';
const ANIMATION_PERIOD = 500;
const AnimatedPageWrapper = styled.div`
align-items: center;
bottom: 0;
display: flex;
justify-content: center;
left: 0;
opacity: ${({ opacity }) => opacity};
padding: 2em;
position: fixed;
right: 0;
text-align: center;
top: 0;
transition: opacity ${ ANIMATION_PERIOD }ms ease-in-out;
width: 100%;
`;
class AnimatedPage extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false
};
}
componentWillAppear(callback) {
// Called on fresh load.
this.animateIn(callback);
}
componentWillEnter(callback) {
// Called during transition between routes.
this.animateIn(callback);
}
componentWillLeave(callback) {
this.animateOut(callback);
}
animateIn(callback) {
setTimeout(() => {
this.setState({ show: true }, callback);
}, ANIMATION_PERIOD);
}
animateOut(callback) {
this.setState({ show: false }, () => {
setTimeout(callback, ANIMATION_PERIOD)
});
}
render() {
return (
<AnimatedPageWrapper
opacity={this.state.show ? 1 : 0}
>
{this.props.children}
</AnimatedPageWrapper>
);
}
};
export default AnimatedPage;
| import React from 'react';
import styled from 'styled-components';
const ANIMATION_PERIOD = 500;
const AnimatedPageWrapper = styled.div`
align-items: center;
bottom: 0;
display: flex;
justify-content: center;
left: 0;
opacity: ${({ opacity }) => opacity};
padding: 1em;
position: fixed;
right: 0;
text-align: center;
top: 0;
transition: opacity ${ ANIMATION_PERIOD }ms ease-in-out;
width: 100%;
`;
class AnimatedPage extends React.Component {
constructor(props) {
super(props);
this.state = {
show: false
};
}
componentWillAppear(callback) {
// Called on fresh load.
this.animateIn(callback);
}
componentWillEnter(callback) {
// Called during transition between routes.
this.animateIn(callback);
}
componentWillLeave(callback) {
this.animateOut(callback);
}
animateIn(callback) {
setTimeout(() => {
this.setState({ show: true }, callback);
}, ANIMATION_PERIOD);
}
animateOut(callback) {
this.setState({ show: false }, () => {
setTimeout(callback, ANIMATION_PERIOD)
});
}
render() {
return (
<AnimatedPageWrapper
opacity={this.state.show ? 1 : 0}
>
{this.props.children}
</AnimatedPageWrapper>
);
}
};
export default AnimatedPage;
|
Fix bad error checking - caused name/image/thumbnail to be arrays | module.exports = {
"parseResults": function(result) {
var xmlItems = result.items && result.items.item;
var items = [];
if (xmlItems) {
for (var i = 0; i < xmlItems.length; i++) {
var game = xmlItems[i];
items.push({
"subtype": game.$.subtype,
"objectid": game.$.objectid,
"collid": game.$.collid,
"name": game.name && game.name[0]._,
"image": game.image && game.image[0],
"thumbnail": game.thumbnail && game.thumbnail[0]
});
}
}
return items;
}
};
| module.exports = {
"parseResults": function(result) {
var xmlItems = result.items && result.items.item;
var items = [];
if (xmlItems) {
for (var i = 0; i < xmlItems.length; i++) {
var game = xmlItems[i];
items.push({
"subtype": game.$.subtype,
"objectid": game.$.objectid,
"collid": game.$.collid,
"name": game.name || game.name[0]._,
"image": game.image || game.image[0],
"thumbnail": game.thumbnail || game.thumbnail[0]
});
}
}
return items;
}
};
|
Fix format string on Python 2.6 | import datetime
from .utc_timezone import UTC
FORMAT_NO_FRACTION = '%Y-%m-%dT%H:%M:%SZ'
FORMAT_WITH_FRACTION = '%Y-%m-%dT%H:%M:%S.%fZ'
class utcdatetime(object):
def __init__(self, year, month, day, hour=0, minute=0, second=0,
microsecond=0):
self.__dt = datetime.datetime(year, month, day, hour, minute, second,
microsecond, tzinfo=UTC)
def __str__(self):
return self.__dt.strftime(
FORMAT_WITH_FRACTION if self.__dt.microsecond > 0
else FORMAT_NO_FRACTION)
def __repr__(self):
parts = [self.__dt.year, self.__dt.month, self.__dt.day,
self.__dt.hour, self.__dt.minute]
if self.__dt.second > 0:
parts.append(self.__dt.second)
if self.__dt.microsecond > 0:
parts.append(self.__dt.microsecond)
return 'utcdatetime({0})'.format(', '.join(
['{0}'.format(part) for part in parts]))
| import datetime
from .utc_timezone import UTC
FORMAT_NO_FRACTION = '%Y-%m-%dT%H:%M:%SZ'
FORMAT_WITH_FRACTION = '%Y-%m-%dT%H:%M:%S.%fZ'
class utcdatetime(object):
def __init__(self, year, month, day, hour=0, minute=0, second=0,
microsecond=0):
self.__dt = datetime.datetime(year, month, day, hour, minute, second,
microsecond, tzinfo=UTC)
def __str__(self):
return self.__dt.strftime(
FORMAT_WITH_FRACTION if self.__dt.microsecond > 0
else FORMAT_NO_FRACTION)
def __repr__(self):
parts = [self.__dt.year, self.__dt.month, self.__dt.day,
self.__dt.hour, self.__dt.minute]
if self.__dt.second > 0:
parts.append(self.__dt.second)
if self.__dt.microsecond > 0:
parts.append(self.__dt.microsecond)
return 'utcdatetime({})'.format(', '.join(
['{0}'.format(part) for part in parts]))
|
Add test for random lastName | <?php
namespace Faker\Test\Provider\ru_RU;
use Faker\Generator;
use Faker\Provider\ru_RU\Person;
use PHPUnit\Framework\TestCase;
class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
public function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testLastNameFemale()
{
$this->assertEquals("a", substr($this->faker->lastName('female'), -1));
}
public function testLastNameMale()
{
$this->assertNotEquals("a", substr($this->faker->lastName('male'), -1));
}
public function testLastNameRandom()
{
$this->assertNotNull($this->faker->lastName());
}
}
| <?php
namespace Faker\Test\Provider\ru_RU;
use Faker\Generator;
use Faker\Provider\ru_RU\Person;
use PHPUnit\Framework\TestCase;
class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
public function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testLastNameFemale()
{
$this->assertEquals("a", substr($this->faker->lastName('female'), -1));
}
public function testLastNameMale()
{
$this->assertNotEquals("a", substr($this->faker->lastName('male'), -1));
}
}
|
Use normal function instead of lambda for this | import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
def error_stub():
raise RuntimeError("Simply failing")
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", error_stub)
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
| import asyncio
from pytest import mark, raises
from oshino.run import main
from mock import patch
def create_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return loop
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
def test_startup():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
@mark.integration
@patch("oshino.core.heart.forever", lambda: False)
@patch("oshino.core.heart.create_loop", create_loop)
@patch("dotenv.find_dotenv", lambda: raise RuntimeError("Simply failing"))
def test_dot_env_fail():
with raises(SystemExit):
main(("--config", "tests/data/test_config.yml", "--noop"))
|
Add email (required) and packages | """Millipede installation script
https://github.com/evadot/millipede
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="millipede",
version="0.1",
description="A millipede generator",
long_description=long_description,
url="https://github.com/evadot/millipede",
author="The millipede fan club",
author_email="millipede@bidouilliste.com",
license="MIT",
classifiers=[
'Development Status :: 4 - Alpha',
'Intended Audience :: Religion',
'Topic :: Religion'
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
keywords="millipede",
entry_points={
'console_scripts': [
'millipede=millipede:main',
],
},
)
| """Millipede installation script
https://github.com/evadot/millipede
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name="millipede",
version="0.1",
description="A millipede generator",
long_description=long_description,
url="https://github.com/evadot/millipede"
author="The millipede fan club"
license="MIT"
classifiers=[
'Development Status :: 4 - Alpha',
'Intended Audience :: Religion',
'Topic :: Religion'
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords="millipede",
entry_points={
'console_scripts': [
'millipede=millipede:main',
],
},
)
|
Remove the View stuff, FOSRest handles this via listeners. | <?php
namespace Trq\TodoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Trq\TodoBundle\Entity\Todo;
class TodoController extends Controller
{
/**
* getTodosAction
*
* @access public
* @return void
*/
public function getTodosAction()
{
$todos = $this->getDoctrine()
->getRepository('TrqTodoBundle:Todo')
->findAll();
return ['todos' => $todos];
}
/**
* getTodoAction
*
* @param mixed $todo
* @access public
* @return void
*/
public function getTodoAction(Todo $todo)
{
return ['todo' => $todo];
}
}
| <?php
namespace Trq\TodoBundle\Controller;
use FOS\RestBundle\View\View;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Trq\TodoBundle\Entity\Todo;
class TodoController extends Controller
{
/**
* getTodosAction
*
* @access public
* @return void
*/
public function getTodosAction()
{
$todos = $this->getDoctrine()
->getRepository('TrqTodoBundle:Todo')
->findAll();
$view = View::create();
$view->setData(['todos' => $todos]);
return $view;
}
/**
* getTodoAction
*
* @param mixed $todo
* @access public
* @return void
*/
public function getTodoAction(Todo $todo)
{
return ['todo' => $todo];
}
}
|
Fix if statement in logger config | var Good = require("good");
var goodConsole = require("good-console");
var moment = require("moment");
var LOG_PATH = process.env.LOG_PATH ||
"./logs/log-" + moment().format("YYYYMMDD");
// Log to file FALSE by default
var LOG_FILE = process.env.LOG_FILE || "false";
if (LOG_FILE !== "false" && LOG_FILE !== "true") {
throw new Error("LOG_FILE env variable must be \"true\" or \"false\"");
}
var reporters = [];
if (LOG_FILE === "true") {
reporters.push(new Good.GoodFile(LOG_PATH, {
ops: "*",
request: "*",
log: "*",
error: "*"
}));
}
// Setup console reporter
// Default args
var consoleArgs = [{
log: "*",
error: "*",
request: "*"
}];
// Set args for test env
if (process.env.NODE_ENV === "test") {
consoleArgs = [{
log: ["error"],
error: "*"
}];
}
reporters.push({
reporter: goodConsole,
args: consoleArgs
});
module.exports = reporters;
| var Good = require("good");
var goodConsole = require("good-console");
var moment = require("moment");
var LOG_PATH = process.env.LOG_PATH ||
"./logs/log-" + moment().format("YYYYMMDD");
// Log to file FALSE by default
var LOG_FILE = process.env.LOG_FILE || "false";
if (LOG_FILE !== "false" && LOG_FILE !== "true") {
throw new Error("LOG_FILE env variable must be \"true\" or \"false\"");
}
var reporters = [];
if (LOG_FILE) {
reporters.push(new Good.GoodFile(LOG_PATH, {
ops: "*",
request: "*",
log: "*",
error: "*"
}));
}
// Setup console reporter
// Default args
var consoleArgs = [{
log: "*",
error: "*",
request: "*"
}];
// Set args for test env
if (process.env.NODE_ENV === "test") {
consoleArgs = [{
log: ["error"],
error: "*"
}];
}
reporters.push({
reporter: goodConsole,
args: consoleArgs
});
module.exports = reporters;
|
Remove -y option from zip | import 'instapromise';
import fs from 'fs';
import logger from 'gulplog';
import path from 'path';
import spawnAsync from '@exponent/spawn-async';
const paths = {
template: path.resolve(__dirname, '../template'),
templateNodeModules: path.resolve(__dirname, '../template/node_modules'),
}
let tasks = {
async archiveTemplate() {
await verifyNodeModulesAsync();
await spawnAsync('zip', ['-rq9', 'template.zip', 'template'], {
stdio: 'inherit',
cwd: path.resolve(__dirname, '..'),
});
}
};
async function verifyNodeModulesAsync() {
let stats;
try {
stats = await fs.promise.stat(paths.templateNodeModules);
} catch (e) { }
if (stats) {
if (!stats.isDirectory()) {
throw new Error(
`${paths.templateNodeModules} is not a directory; be sure to run ` +
`"npm install" before releasing a new version of XDL`
);
}
} else {
logger.info(`Running "npm install" to set up ${paths.templateNodeModules}...`);
await spawnAsync('npm', ['install'], {
stdio: 'inherit',
cwd: paths.template,
});
}
}
export default tasks;
| import 'instapromise';
import fs from 'fs';
import logger from 'gulplog';
import path from 'path';
import spawnAsync from '@exponent/spawn-async';
const paths = {
template: path.resolve(__dirname, '../template'),
templateNodeModules: path.resolve(__dirname, '../template/node_modules'),
}
let tasks = {
async archiveTemplate() {
await verifyNodeModulesAsync();
await spawnAsync('zip', ['-rqy9', 'template.zip', 'template'], {
stdio: 'inherit',
cwd: path.resolve(__dirname, '..'),
});
}
};
async function verifyNodeModulesAsync() {
let stats;
try {
stats = await fs.promise.stat(paths.templateNodeModules);
} catch (e) { }
if (stats) {
if (!stats.isDirectory()) {
throw new Error(
`${paths.templateNodeModules} is not a directory; be sure to run ` +
`"npm install" before releasing a new version of XDL`
);
}
} else {
logger.info(`Running "npm install" to set up ${paths.templateNodeModules}...`);
await spawnAsync('npm', ['install'], {
stdio: 'inherit',
cwd: paths.template,
});
}
}
export default tasks;
|
Add UUID to the Volume Details section | define(function (require) {
var React = require('react/addons'),
Backbone = require('backbone'),
ResourceDetail = require('components/projects/common/ResourceDetail.react'),
Id = require('./details/Id.react'),
Status = require('./details/Status.react'),
Size = require('./details/Size.react'),
Identity = require('./details/Identity.react');
return React.createClass({
displayName: "VolumeDetailsSection",
propTypes: {
volume: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
var volume = this.props.volume;
return (
<div className="resource-details-section section">
<h4 className="title">Volume Details</h4>
<ul>
<Status volume={volume}/>
<Size volume={volume}/>
<Identity volume={volume}/>
<Id volume={volume}/>
<ResourceDetail label="Identifier">
{volume.get('uuid')}
</ResourceDetail>
</ul>
</div>
);
}
});
});
| define(function (require) {
var React = require('react/addons'),
Backbone = require('backbone'),
ResourceDetail = require('components/projects/common/ResourceDetail.react'),
Id = require('./details/Id.react'),
Status = require('./details/Status.react'),
Size = require('./details/Size.react'),
Identity = require('./details/Identity.react');
return React.createClass({
displayName: "VolumeDetailsSection",
propTypes: {
volume: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
var volume = this.props.volume;
return (
<div className="resource-details-section section">
<h4 className="title">Volume Details</h4>
<ul>
<Status volume={volume}/>
<Size volume={volume}/>
<Identity volume={volume}/>
<Id volume={volume}/>
</ul>
</div>
);
}
});
});
|
Add possibility to shuffle an associative array
Usage: `{{ myArray | shuffle }}` will shuffle as usual (initial behaviour of the plugin); `{{ myArray | shuffle(true) }}` will preserve the keys of an associative array. | <?php
/**
* This file is part of Twig.
*
* (c) 2009 Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Ricard Clau <ricard.clau@gmail.com>
*/
class Twig_Extensions_Extension_Array extends Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFilters()
{
$filters = array(
new Twig_SimpleFilter('shuffle', 'twig_shuffle_filter'),
);
return $filters;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'array';
}
}
/**
* Shuffles an array.
*
* @param array|Traversable $array An array
*
* @return array
*/
function twig_shuffle_filter($array, $associative = false)
{
if ($array instanceof Traversable) {
$array = iterator_to_array($array, false);
}
if($associative) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
}
else {
shuffle($array);
}
return $array;
}
| <?php
/**
* This file is part of Twig.
*
* (c) 2009 Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Ricard Clau <ricard.clau@gmail.com>
*/
class Twig_Extensions_Extension_Array extends Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFilters()
{
$filters = array(
new Twig_SimpleFilter('shuffle', 'twig_shuffle_filter'),
);
return $filters;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'array';
}
}
/**
* Shuffles an array.
*
* @param array|Traversable $array An array
*
* @return array
*/
function twig_shuffle_filter($array)
{
if ($array instanceof Traversable) {
$array = iterator_to_array($array, false);
}
shuffle($array);
return $array;
}
|
TASK: Remove flattern of font task
... to make sub-font-folders possible | 'use strict';
if (!config.tasks.fonts) {
return false;
}
let paths = {
src: path.join(config.root.base, config.root.src, config.tasks.fonts.src, '/**', getExtensions(config.tasks.fonts.extensions)),
dest: path.join(config.root.base, config.root.dest, config.tasks.fonts.dest)
};
function fonts() {
return gulp.src(paths.src, {since: cache.lastMtime('fonts')})
.pipe(plumber(handleErrors))
.pipe(cache('fonts'))
.pipe(changed(paths.dest)) // Ignore unchanged files
.pipe(chmod(config.chmod))
.pipe(gulp.dest(paths.dest))
.pipe(size({
title: 'Fonts:',
showFiles: false
})
);
}
module.exports = fonts;
| 'use strict';
if (!config.tasks.fonts) {
return false;
}
let paths = {
src: path.join(config.root.base, config.root.src, config.tasks.fonts.src, '/**', getExtensions(config.tasks.fonts.extensions)),
dest: path.join(config.root.base, config.root.dest, config.tasks.fonts.dest)
};
function fonts() {
return gulp.src(paths.src, {since: cache.lastMtime('fonts')})
.pipe(plumber(handleErrors))
.pipe(cache('fonts'))
.pipe(changed(paths.dest)) // Ignore unchanged files
.pipe(flatten())
.pipe(chmod(config.chmod))
.pipe(gulp.dest(paths.dest))
.pipe(size({
title: 'Fonts:',
showFiles: false
})
);
}
module.exports = fonts;
|
Fix PowersOf to return `count` items, not "numbers up to base**count". | import time
from prometheus_client import _INF
# TODO(korfuri): if python>3.3, use perf_counter() or monotonic().
def Time():
"""Returns some representation of the current time.
This wrapper is meant to take advantage of a higher time
resolution when available. Thus, its return value should be
treated as an opaque object. It can be compared to the current
time with TimeSince().
"""
return time.time()
def TimeSince(t):
"""Compares a value returned by Time() to the current time.
Returns:
the time since t, in fractional seconds.
"""
return time.time() - t
def PowersOf(logbase, count, lower=0, include_zero=True):
"""Returns a list of count powers of logbase (from logbase**lower)."""
if not include_zero:
return [logbase ** i for i in range(lower, count+lower)] + [_INF]
else:
return [0] + [logbase ** i for i in range(lower, count+lower)] + [_INF]
| import time
from prometheus_client import _INF
# TODO(korfuri): if python>3.3, use perf_counter() or monotonic().
def Time():
"""Returns some representation of the current time.
This wrapper is meant to take advantage of a higher time
resolution when available. Thus, its return value should be
treated as an opaque object. It can be compared to the current
time with TimeSince().
"""
return time.time()
def TimeSince(t):
"""Compares a value returned by Time() to the current time.
Returns:
the time since t, in fractional seconds.
"""
return time.time() - t
def PowersOf(logbase, count, lower=0, include_zero=True):
"""Returns a list of count powers of logbase (from logbase**lower)."""
if not include_zero:
return [logbase ** i for i in range(lower, count)] + [_INF]
else:
return [0] + [logbase ** i for i in range(lower, count)] + [_INF]
|
Add new Python versions to the supported languages
Now that tests are passing for Python 3.1 and 3.2, they should go into the list of supported versions of Python listed on PyPI. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
settings = dict()
# Publish
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
settings.update(
name='whenpy',
version='0.1.0',
description='Friendly Dates and Times',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/When.py',
packages=['when'],
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=['pytz'],
license=open('LICENSE').read(),
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
setup(**settings)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
settings = dict()
# Publish
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
settings.update(
name='whenpy',
version='0.1.0',
description='Friendly Dates and Times',
long_description=open('README.rst').read(),
author='Andy Dirnberger',
author_email='dirn@dirnonline.com',
url='https://github.com/dirn/When.py',
packages=['when'],
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=['pytz'],
license=open('LICENSE').read(),
classifiers=(
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules',
),
)
setup(**settings)
|
Correct an app name reference in an example test
Said test may or may not be removed in a future commit - haven't figured that out yet | /*
* Copyright 2016 Philip Cohn-Cort
*
* 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.fuzz.indicator;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.fuzz.emptyhusk", appContext.getPackageName());
}
}
| /*
* Copyright 2016 Philip Cohn-Cort
*
* 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.fuzz.indicator;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.cliabhach.emptyhusk", appContext.getPackageName());
}
}
|
Fix reading the host from the config file | import execute from './core';
import adminApi from './adminApi';
import colors from 'colors';
import configLoader from './configLoader';
import program from 'commander';
program
.version(require("../package.json").version)
.option('--path <value>', 'Path to the configuration file')
.option('--host <value>', 'Kong admin host (default: localhost:8001)')
.parse(process.argv);
if (!program.path) {
console.log('--path to the config file is required'.red);
process.exit(1);
}
let config = configLoader(program.path);
let host = program.host || config.host || 'localhost:8001';
if (!host) {
console.log('Kong admin host must be specified in config or --host'.red);
process.exit(1);
}
console.log(`Apply config to ${host}`.green);
execute(config, adminApi(host))
.catch(error => {
console.log(`${error}`.red, '\n', error.stack);
process.exit(1);
});
| import execute from './core';
import adminApi from './adminApi';
import colors from 'colors';
import configLoader from './configLoader';
import program from 'commander';
program
.version(require("../package.json").version)
.option('--path <value>', 'Path to the configuration file')
.option('--host <value>', 'Kong admin host (default: localhost:8001)', 'localhost:8001')
.parse(process.argv);
if (!program.path) {
console.log('--path to the config file is required'.red);
process.exit(1);
}
let config = configLoader(program.path);
let host = program.host || config.host;
if (!host) {
console.log('Kong admin host must be specified in config or --host'.red);
process.exit(1);
}
console.log(`Apply config to ${host}`.green);
execute(config, adminApi(host))
.catch(error => {
console.log(`${error}`.red, '\n', error.stack);
process.exit(1);
});
|
Remove duplicate assertion. We aren't the Department of Redundancy Department. | <?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
public function testFuncExists()
{
$this->assertTrue(function_exists('random_int'));
}
public function testOutput()
{
$integers = array(
random_int(0, 1000),
random_int(1001,2000),
random_int(-100, -10),
random_int(-1000, 1000),
random_int(~PHP_INT_MAX, PHP_INT_MAX)
);
$this->assertFalse($integers[0] === $integers[1]);
$this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
$this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
$this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[4] >= ~PHP_INT_MAX && $integers[4] <= PHP_INT_MAX);
}
}
| <?php
class RandomIntTest extends PHPUnit_Framework_TestCase
{
public function testFuncExists()
{
$this->assertTrue(function_exists('random_int'));
}
public function testOutput()
{
$integers = array(
random_int(0, 1000),
random_int(1001,2000),
random_int(-100, -10),
random_int(-1000, 1000),
random_int(~PHP_INT_MAX, PHP_INT_MAX)
);
$this->assertFalse($integers[0] === $integers[1]);
$this->assertTrue($integers[0] >= 0 && $integers[0] <= 1000);
$this->assertTrue($integers[1] >= 1001 && $integers[1] <= 2000);
$this->assertTrue($integers[2] >= -100 && $integers[2] <= -10);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[3] >= -1000 && $integers[3] <= 1000);
$this->assertTrue($integers[4] >= ~PHP_INT_MAX && $integers[4] <= PHP_INT_MAX);
}
}
|
Update my poor man’s JavaScript error event tracking code. | /* global ga */
var eventTracking = (function() {
'use strict';
// http://blog.gospodarets.com/track_javascript_angularjs_and_jquery_errors_with_google_analytics/
var _sendErrorsToGoogleAnalytics = function () {
window.addEventListener('error', function (err) {
var ie = window.event || {};
var errorMessage = err.message || ie.errorMessage;
var errorFilename = err.filename || ie.errorUrl;
var errorLineNumber = ', Line: ' + (err.lineno || ie.errorLine);
var errorColumnNumber = ', Column: ' + (err.colno || 'undefined'); // print undefined as a string if it doesn’t exist
var userAgent = ', User Agent: ' + navigator.userAgent;
var platform = ', Platform: ' + navigator.platform;
ga('send', 'event', 'JavaScript Errors', errorMessage, errorFilename + errorLineNumber + errorColumnNumber + userAgent + platform, 0, true);
});
};
var init = function () {
_sendErrorsToGoogleAnalytics();
};
return {
init: init
};
}()); | /* global ga */
var eventTracking = (function() {
'use strict';
// http://blog.gospodarets.com/track_javascript_angularjs_and_jquery_errors_with_google_analytics/
var _sendErrorsToGoogleAnalytics = function () {
window.addEventListener('error', function (err) {
var lineAndColumnInfo = err.colno ? ' line:' + err.lineno +', column:'+ err.colno : ' line:' + err.lineno;
ga(
'send',
'event',
'JavaScript Errors',
err.message,
err.filename + lineAndColumnInfo + ' -> ' + navigator.userAgent + navigator.platform + screen.width + screen.height,
0,
true
);
});
};
var init = function () {
_sendErrorsToGoogleAnalytics();
};
return {
init: init
};
}()); |
Set up release to mesh-tensorflow 0.0.4.
PiperOrigin-RevId: 221204704 | """Install Mesh TensorFlow."""
from setuptools import find_packages
from setuptools import setup
setup(
name='mesh-tensorflow',
version='0.0.4',
description='Mesh TensorFlow',
author='Google Inc.',
author_email='no-reply@google.com',
url='http://github.com/tensorflow/mesh',
license='Apache 2.0',
packages=find_packages(),
package_data={},
scripts=[],
install_requires=[
'future',
'six',
],
extras_require={
'tensorflow': ['tensorflow>=1.9.0'],
'tensorflow_gpu': ['tensorflow-gpu>=1.9.0'],
'tests': [
'absl-py',
'pytest',
'tensor2tensor>=1.9.0', # TODO(trandustin): rm dependence
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning',
)
| """Install Mesh TensorFlow."""
from setuptools import find_packages
from setuptools import setup
setup(
name='mesh-tensorflow',
version='0.0.3',
description='Mesh TensorFlow',
author='Google Inc.',
author_email='no-reply@google.com',
url='http://github.com/tensorflow/mesh',
license='Apache 2.0',
packages=find_packages(),
package_data={},
scripts=[],
install_requires=[
'future',
'six',
],
extras_require={
'tensorflow': ['tensorflow>=1.9.0'],
'tensorflow_gpu': ['tensorflow-gpu>=1.9.0'],
'tests': [
'absl-py',
'pytest',
'tensor2tensor>=1.9.0', # TODO(trandustin): rm dependence
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
],
keywords='tensorflow machine learning',
)
|
Add more useful display of the request data. | """
Models.
"""
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from pubsubpull.fields import JSONB
class Request(models.Model):
"""A web request.
"""
user = models.ForeignKey(User, null=True, blank=True, related_name='requests')
method = models.CharField(max_length=20)
path = models.TextField()
def __unicode__(self):
return "%s %s" % (self.method, self.path)
OPERATION_TYPE = dict(I="INSERT", U="UPDATE", D="DELETE", T="TRUNCATE")
class UpdateLog(models.Model):
"""Store a change to a single row in a table.
"""
table = models.CharField(max_length=200)
type = models.CharField(max_length=1, choices=OPERATION_TYPE.items())
when = models.DateTimeField(auto_now_add=True)
request = models.ForeignKey(Request, null=True, blank=True,
related_name='changes')
old = JSONB(null=True, blank=True)
new = JSONB(null=True, blank=True)
def save(self, **kw):
raise ValidationError("Instances of this class cannot be using Django")
def __unicode__(self):
return u"%s %s @ %s" % (OPERATION_TYPE[self.type], self.table, self.when)
| """
Models.
"""
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db import models
from pubsubpull.fields import JSONB
class Request(models.Model):
"""A web request.
"""
user = models.ForeignKey(User, null=True, blank=True, related_name='requests')
method = models.CharField(max_length=20)
path = models.TextField()
OPERATION_TYPE = dict(I="INSERT", U="UPDATE", D="DELETE", T="TRUNCATE")
class UpdateLog(models.Model):
"""Store a change to a single row in a table.
"""
table = models.CharField(max_length=200)
type = models.CharField(max_length=1, choices=OPERATION_TYPE.items())
when = models.DateTimeField(auto_now_add=True)
request = models.ForeignKey(Request, null=True, blank=True,
related_name='changes')
old = JSONB(null=True, blank=True)
new = JSONB(null=True, blank=True)
def save(self, **kw):
raise ValidationError("Instances of this class cannot be using Django")
def __unicode__(self):
return u"%s %s @ %s" % (OPERATION_TYPE[self.type], self.table, self.when)
|
Fix a bug in Firefox with scrolling half pages
In newer Firefox versions (around version 63), the window.scrollBy call
sometimes does not do anything at all, and later on will scroll the page
twice. This causes erratic behaviour when using half page scrolling with
Saka key.
I have not been able to determine when exactly, or why the scrollBy call
sometimes doesn't work, but changing the call to scrollTo does prevent
the bug from showing up.
Untested in other browsers, but behaviour should be mostly unchanged. | import { behavior, scroll, scrollStep } from './utils'
export function scrollDown (event) {
scroll(event.repeat, scrollStep, 'scrollTop')
}
export function scrollUp (event) {
scroll(event.repeat, -scrollStep, 'scrollTop')
}
export function scrollLeft (event) {
scroll(event.repeat, -scrollStep, 'scrollLeft')
}
export function scrollRight (event) {
scroll(event.repeat, scrollStep, 'scrollLeft')
}
export function scrollPageDown () {
scrollBy({
top: innerHeight * 0.9,
behavior
})
}
export function scrollPageUp () {
scrollBy({
top: -innerHeight * 0.9,
behavior
})
}
export function scrollHalfPageDown () {
scrollTo({
top: window.pageYOffset + window.innerHeight / 2,
left: 0,
behavior: behavior
})
}
export function scrollHalfPageUp () {
scrollTo({
top: window.pageYOffset - window.innerHeight / 2,
left: 0,
behavior: behavior
})
}
export function scrollToBottom () {
scrollTo({
top: document.documentElement.scrollHeight,
behavior
})
}
export function scrollToTop () {
scrollTo({
top: 0,
behavior
})
}
export function scrollToLeft () {
scrollTo({
left: 0,
behavior
})
}
export function scrollToRight () {
scrollTo({
left: document.documentElement.scrollWidth,
behavior
})
}
| import { behavior, scroll, scrollStep } from './utils'
export function scrollDown (event) {
scroll(event.repeat, scrollStep, 'scrollTop')
}
export function scrollUp (event) {
scroll(event.repeat, -scrollStep, 'scrollTop')
}
export function scrollLeft (event) {
scroll(event.repeat, -scrollStep, 'scrollLeft')
}
export function scrollRight (event) {
scroll(event.repeat, scrollStep, 'scrollLeft')
}
export function scrollPageDown () {
scrollBy({
top: innerHeight * 0.9,
behavior
})
}
export function scrollPageUp () {
scrollBy({
top: -innerHeight * 0.9,
behavior
})
}
export function scrollHalfPageDown () {
scrollBy({
top: innerHeight / 2,
behavior
})
}
export function scrollHalfPageUp () {
scrollBy({
top: -innerHeight / 2,
behavior
})
}
export function scrollToBottom () {
scrollTo({
top: document.documentElement.scrollHeight,
behavior
})
}
export function scrollToTop () {
scrollTo({
top: 0,
behavior
})
}
export function scrollToLeft () {
scrollTo({
left: 0,
behavior
})
}
export function scrollToRight () {
scrollTo({
left: document.documentElement.scrollWidth,
behavior
})
}
|
Fix support for multiple values for a single parameter. | package io.katharsis.rs.parameterProvider.provider;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import com.fasterxml.jackson.databind.ObjectMapper;
public class QueryParamProvider implements RequestContextParameterProvider {
@Override
public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
Object returnValue;
List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value());
if (value == null || value.isEmpty()) {
return null;
} else {
if (String.class.isAssignableFrom(parameter.getType())) {
// Given a query string: ?x=y&x=z, JAX-RS will return a value of y.
returnValue = value.get(0);
} else if (Iterable.class.isAssignableFrom(parameter.getType())) {
returnValue = value;
} else {
try {
returnValue = objectMapper.readValue(value.get(0), parameter.getType());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return returnValue;
}
@Override
public boolean provides(Parameter parameter) {
return parameter.isAnnotationPresent(QueryParam.class);
}
}
| package io.katharsis.rs.parameterProvider.provider;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import com.fasterxml.jackson.databind.ObjectMapper;
public class QueryParamProvider implements RequestContextParameterProvider {
@Override
public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
Object returnValue;
List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value());
if (value == null || value.isEmpty()) {
return null;
} else {
if (String.class.isAssignableFrom(parameter.getType())) {
// Given a query string: ?x=y&x=z, JAX-RS will return a value of y.
returnValue = value.get(0);
} else {
try {
returnValue = objectMapper.readValue(value.get(0), parameter.getType());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return returnValue;
}
@Override
public boolean provides(Parameter parameter) {
return parameter.isAnnotationPresent(QueryParam.class);
}
}
|
Make the regression test feel more welcome | <?php
declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Test;
use PHPUnit\Framework\TestCase;
use stdClass;
class Issue3156Test extends TestCase
{
public function testConstants(): stdClass
{
$this->assertStringEndsWith('/', '/');
return new stdClass();
}
public function dataSelectOperatorsProvider(): array
{
return [
['1'],
['2']
];
}
/**
* @depends testConstants
* @dataProvider dataSelectOperatorsProvider
*/
public function testDependsRequire(string $val, stdClass $obj): void
{
$this->assertStringEndsWith('/', '/');
}
}
| <?php
declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Test;
use PHPUnit\Framework\TestCase;
use stdClass;
class TestTest extends TestCase
{
public function testConstants(): stdClass
{
$this->assertStringEndsWith('/', '/');
return new stdClass();
}
public function dataSelectOperatorsProvider(): array
{
return [
['1'],
['2']
];
}
/**
* @depends testConstants
* @dataProvider dataSelectOperatorsProvider
*/
public function testDependsRequire(string $val, stdClass $obj): void
{
$this->assertStringEndsWith('/', '/');
}
}
|
Add Moxy StrategyType for showMessage | /*
* 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.sandrlab.listcase.presentation.repos_list.view;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import com.arellomobile.mvp.MvpView;
import com.arellomobile.mvp.viewstate.strategy.SkipStrategy;
import com.arellomobile.mvp.viewstate.strategy.StateStrategyType;
import com.sandrlab.listcase.models.GitRepoModel;
import java.util.List;
/**
* @author Alexander Bilchuk (a.bilchuk@sandrlab.com)
*/
public interface GitReposListView extends MvpView {
void addTopAndroidReposListItems(@NonNull List<GitRepoModel> gitRepoModelsToAdd);
void refreshListItems(@NonNull List<GitRepoModel> newGitRepoModels);
void enableSwipeToRefresh();
void disableSwipeToRefresh();
void hideSwipeToRefreshLoading();
void showLoading();
void hideLoading();
@StateStrategyType(SkipStrategy.class)
void showMessage(@StringRes int stringResId);
}
| /*
* 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.sandrlab.listcase.presentation.repos_list.view;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import com.arellomobile.mvp.MvpView;
import com.sandrlab.listcase.models.GitRepoModel;
import java.util.List;
/**
* @author Alexander Bilchuk (a.bilchuk@sandrlab.com)
*/
public interface GitReposListView extends MvpView {
void addTopAndroidReposListItems(@NonNull List<GitRepoModel> gitRepoModelsToAdd);
void refreshListItems(@NonNull List<GitRepoModel> newGitRepoModels);
void enableSwipeToRefresh();
void disableSwipeToRefresh();
void hideSwipeToRefreshLoading();
void showLoading();
void hideLoading();
void showMessage(@StringRes int stringResId);
}
|
Set `canRetransform` flag to `false` in instrumentation.
We do not need to retransform classes once they are loaded.
All instrumentation byte-code is pushed at loading time.
This fixes a problem with Java 7 that was failing to add
a transformer because we did not declare retransformation
capability in `MANIFEST.MF` file in Java agent jar.
Java 6 allowed to add transformer due to a bug. | /* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), false);
}
}
| /* NEST (New Scala Test)
* Copyright 2007-2013 LAMP/EPFL
* @author Grzegorz Kossakowski
*/
package scala.tools.partest.javaagent;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
/**
* Profiling agent that instruments byte-code to insert calls to
* {@link scala.tools.partest.instrumented.Profiler#methodCalled(String, String, String)}
* by using ASM library for byte-code manipulation.
*/
public class ProfilingAgent {
public static void premain(String args, Instrumentation inst) throws UnmodifiableClassException {
// NOTE: we are adding transformer that won't be applied to classes that are already loaded
// This should be ok because premain should be executed before main is executed so Scala library
// and the test-case itself won't be loaded yet. We rely here on the fact that ASMTransformer does
// not depend on Scala library. In case our assumptions are wrong we can always insert call to
// inst.retransformClasses.
inst.addTransformer(new ASMTransformer(), true);
}
}
|
Use host + port from config | var Express = require('express');
var webpack = require('webpack');
var config = require('../src/config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = config.host || 'localhost';
var port = (config.port + 1) || 3001;
var serverOptions = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true}
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> 🚧 Webpack development server listening on port %s', port);
}
});
| var Express = require('express');
var webpack = require('webpack');
var config = require('../src/config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = process.env.HOST || 'localhost';
var port = parseInt(config.port, 10) + 1 || 3001;
var serverOptions = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true}
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> 🚧 Webpack development server listening on port %s', port);
}
});
|
Read default cookie opt setting from body data tag | var componentEvent = require('kwf/component-event');
var cookies = require('js-cookie');
var $ = require('jQuery');
var CookieOpt = {};
CookieOpt.getDefaultOpt = function() {
var defaultOpt = $('body').data('cookieDefaultOpt');
if (defaultOpt != 'in' && defaultOpt != 'out') defaultOpt = 'in';
return defaultOpt;
};
CookieOpt.isSetOpt = function() {
return !!cookies.get('cookieOpt');
};
CookieOpt.getOpt = function() {
if (CookieOpt.isSetOpt()) {
return cookies.get('cookieOpt');
} else {
return CookieOpt.getDefaultOpt();
}
};
CookieOpt.setOpt = function(value) {
var opt = cookies.get('cookieOpt');
cookies.set('cookieOpt', value, { expires: 3*365 });
if (opt != value) {
componentEvent.trigger('cookieOptChanged', value);
}
};
CookieOpt.onOptChange = function(callback) {
componentEvent.on('cookieOptChanged', callback);
};
module.exports = CookieOpt;
| var componentEvent = require('kwf/component-event');
var cookies = require('js-cookie');
var CookieOpt = {};
CookieOpt.getDefaultOpt = function() {
return 'in'; // TODO get from baseProperty
};
CookieOpt.isSetOpt = function() {
return !!cookies.get('cookieOpt');
};
CookieOpt.getOpt = function() {
if (CookieOpt.isSetOpt()) {
return cookies.get('cookieOpt');
} else {
return CookieOpt.getDefaultOpt();
}
};
CookieOpt.setOpt = function(value) {
var opt = cookies.get('cookieOpt');
cookies.set('cookieOpt', value, { expires: 3*365 });
if (opt != value) {
componentEvent.trigger('cookieOptChanged', value);
}
};
CookieOpt.onOptChange = function(callback) {
componentEvent.on('cookieOptChanged', callback);
};
module.exports = CookieOpt;
|
Make facet selector JS slightly less horrific and error prone. | $(function($) {
$(".more-facets").each(function(i, elem) {
$(elem).modal({backdrop:true,
shown: function(e) { alert("show"); },
});
});
// add Ajax behaviour on pagination links
$(".ajax, .modal-body > .pagination ul li a").live("click", function(event) {
// MASSIVE HACK - extract the facet class from the fclass data attribute
// that is written into the modal-body div and alter the various
// links to point the the particular facet list page. This is deeply
// offensive to all that is good and pure...
var klass = $(".modal-body").data("fclass");
if (klass && this.href) {
event.preventDefault();
$("#modal-popup").load(this.href.replace(/search\?/, "search/" + klass + "/?"));
}
});
$(".facet-header").click(function(event) {
event.preventDefault();
$(this).parent().next("dl").toggle(200);
});
});
| $(function($) {
$(".more-facets").each(function(i, elem) {
$(elem).modal({backdrop:true,
shown: function(e) { alert("show"); },
});
});
// add Ajax behaviour on pagination links
$(".ajax, .modal-body > .pagination ul li a").live("click", function(event) {
event.preventDefault();
// MASSIVE HACK - extract the facet class from the fclass data attribute
// that is written into the modal-body div and alter the various
// links to point the the particular facet list page. This is deeply
// offensive to all that is good and pure...
if (this.href) {
var klass = $(".modal-body").data("fclass");
$("#modal-popup").load(this.href.replace(/search\?/, "search/" + klass + "/?"))
}
});
$(".facet-header").click(function(event) {
event.preventDefault();
$(this).parent().next("dl").toggle(200);
});
});
|
Handle missing accounts on HaveIBeenPwned properly. | import plumeria.util.http as http
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.command.parse import Text
from plumeria.message.mappings import build_mapping
from plumeria.util.collections import SafeStructure
from plumeria.util.ratelimit import rate_limit
@commands.register("haveibeenpwned", "pwned", category="Search", params=[Text('query')])
@rate_limit(burst_size=4)
async def have_i_been_pwned(message, query):
"""
Checks where an account (specified by account name or email address) exists
on sites that have experienced data breaches.
Example::
pwned email@example.com
"""
try:
r = await http.get("https://haveibeenpwned.com/api/v2/breachedaccount/" + query, headers=[
('User-Agent', 'Plumeria chat bot (+https://gitlab.com/sk89q/Plumeria)')
])
except http.BadStatusCodeError as e:
if e.http_code == 404:
raise CommandError("Account not found! (That's good.)")
else:
raise e
results = SafeStructure(r.json())
return build_mapping(
[(e.Title, "{} ({} breached) ({})".format(e.BreachDate, e.PwnCount, ", ".join(e.DataClasses))) for e in
results])
| import plumeria.util.http as http
from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.command.parse import Text
from plumeria.message.mappings import build_mapping
from plumeria.util.collections import SafeStructure
from plumeria.util.ratelimit import rate_limit
@commands.register("haveibeenpwned", "pwned", category="Search", params=[Text('query')])
@rate_limit(burst_size=4)
async def have_i_been_pwned(message, query):
"""
Checks where an account (specified by account name or email address) exists
on sites that have experienced data breaches.
Example::
pwned email@example.com
"""
r = await http.get("https://haveibeenpwned.com/api/v2/breachedaccount/" + query, headers=[
('User-Agent', 'Plumeria chat bot (+https://gitlab.com/sk89q/Plumeria)')
])
if not len(r.text().strip()):
raise CommandError("Account not found! (That's good.)")
results = SafeStructure(r.json())
return build_mapping(
[(e.Title, "{} ({} breached) ({})".format(e.BreachDate, e.PwnCount, ", ".join(e.DataClasses))) for e in
results])
|
Add test to verify it handles errors correctly | import createCredentialsAuthenticator from '../../src/authenticators/credentials'
beforeEach(() => {
fetch.resetMocks()
})
it('fetches from given endpoint using default config', () => {
fetch.mockResponse(JSON.stringify({ ok: true }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
credentials.authenticate(creds)
expect(fetch).toHaveBeenCalledWith('/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(creds)
})
})
it('resolves with returned data by default', async () => {
fetch.mockResponse(JSON.stringify({ token: '12345' }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
const promise = credentials.authenticate(creds)
await expect(promise).resolves.toEqual({ token: '12345' })
})
it('handles invalid responses', async () => {
const error = { error: 'Wrong email or password' }
fetch.mockResponse(JSON.stringify(error), { status: 401 })
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const promise = credentials.authenticate({
email: 'text@example.com',
password: 'password'
})
await expect(promise).rejects.toEqual(error)
})
| import createCredentialsAuthenticator from '../../src/authenticators/credentials'
beforeEach(() => {
fetch.resetMocks()
})
it('fetches from given endpoint using default config', () => {
fetch.mockResponse(JSON.stringify({ ok: true }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
credentials.authenticate(creds)
expect(fetch).toHaveBeenCalledWith('/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(creds)
})
})
it('resolves with returned data by default', async () => {
fetch.mockResponse(JSON.stringify({ token: '12345' }))
const credentials = createCredentialsAuthenticator({
endpoint: '/authenticate'
})
const creds = { email: 'text@example.com', password: 'password' }
const promise = credentials.authenticate(creds)
await expect(promise).resolves.toEqual({ token: '12345' })
})
|
Add additional failure checks on client. | package database_test
import (
"io/ioutil"
"os"
"testing"
"github.com/josephspurrier/gocleanarchitecture/database"
"github.com/josephspurrier/gocleanarchitecture/domain/user"
)
// TestClient ensures the client works properly.
func TestClient(t *testing.T) {
c := database.NewClient("db.json")
// Check the output.
AssertEqual(t, c.Path, "db.json")
AssertEqual(t, c.Write(), nil)
AssertEqual(t, c.Read(), nil)
AssertEqual(t, c.Write(), nil)
// Test adding a record and reading it.
u := new(user.Item)
u.Email = "jdoe@example.com"
u.Password = "Pa$$w0rd"
c.AddRecord(*u)
AssertEqual(t, len(c.Records()), 1)
// Cleanup
os.Remove("db.json")
}
// TestClient ensures the client fails properly.
func TestClientFail(t *testing.T) {
c := database.NewClient("")
// Check the output.
AssertEqual(t, c.Path, "")
AssertNotNil(t, c.Write())
AssertNotNil(t, c.Read())
}
// TestClientFailOpen ensures the client fails properly.
func TestClientFailOpen(t *testing.T) {
c := database.NewClient("dbbad.json")
// Write a bad file.
ioutil.WriteFile("dbbad.json", []byte("{"), 0644)
// Check the output.
AssertNotNil(t, c.Read())
// Cleanup
os.Remove("dbbad.json")
}
| package database_test
import (
"os"
"testing"
"github.com/josephspurrier/gocleanarchitecture/database"
"github.com/josephspurrier/gocleanarchitecture/domain/user"
)
// TestClient ensures the client works properly.
func TestClient(t *testing.T) {
c := database.NewClient("db.json")
// Check the output.
AssertEqual(t, c.Path, "db.json")
AssertEqual(t, c.Write(), nil)
AssertEqual(t, c.Read(), nil)
AssertEqual(t, c.Write(), nil)
// Test adding a record and reading it.
u := new(user.Item)
u.Email = "jdoe@example.com"
u.Password = "Pa$$w0rd"
c.AddRecord(*u)
AssertEqual(t, len(c.Records()), 1)
// Cleanup
os.Remove("db.json")
}
|
Fix scrollbar update with ref util | import GeminiScrollbar from 'react-gemini-scrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
// Use the containers gemini ref if present
if (containerRef.geminiRef != null) {
this.updateWithRef(containerRef.geminiRef);
return;
}
if (containerRef instanceof GeminiScrollbar) {
containerRef.scrollbar.update();
}
}
};
module.exports = ScrollbarUtil;
| import FluidGeminiScrollbar from '../components/FluidGeminiScrollbar';
let scrollbarWidth = null;
const ScrollbarUtil = {
/**
* Taken from Gemini's source code with some edits
* https://github.com/noeldelgado/gemini-scrollbar/blob/master/index.js#L22
* @param {Object} options
* @return {Number} The width of the native scrollbar
*/
getScrollbarWidth(options = {}) {
if (scrollbarWidth == null || options.forceUpdate) {
let element = global.document.createElement('div');
element.style.position = 'absolute';
element.style.top = '-9999px';
element.style.width = '100px';
element.style.height = '100px';
element.style.overflow = 'scroll';
element.style.msOverflowStyle = 'scrollbar';
global.document.body.appendChild(element);
scrollbarWidth = (element.offsetWidth - element.clientWidth);
global.document.body.removeChild(element);
}
return scrollbarWidth;
},
updateWithRef(containerRef) {
if (containerRef) {
if (containerRef instanceof FluidGeminiScrollbar.constructor
&& containerRef.geminiRef != null) {
containerRef.geminiRef.scrollbar.update();
} else {
containerRef.scrollbar.update();
}
}
}
};
module.exports = ScrollbarUtil;
|
Use insert_text instead of changed | #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__insert_text(self, entry, *args):
try:
temp = float(entry.get_text())
except ValueError:
temp = 0
celsius = (temp - 32) * 5/9.0
farenheit = (temp * 9/5.0) + 32
self.view.celsius.set_text("%.2f" % celsius)
self.view.farenheit.set_text("%.2f" % farenheit)
widgets = ["quitbutton", "temperature", "celsius", "farenheit"]
view = BaseView(gladefile="faren", delete_handler=quit_if_last,
widgets=widgets)
ctl = FarenControl(view)
view.show()
gtk.main()
| #!/usr/bin/env python
import gtk
from kiwi.controllers import BaseController
from kiwi.ui.views import BaseView
from kiwi.ui.gadgets import quit_if_last
class FarenControl(BaseController):
def on_quitbutton__clicked(self, *args):
self.view.hide_and_quit()
def after_temperature__changed(self, entry, *args):
try:
temp = float(entry.get_text())
except ValueError:
temp = 0
celsius = (temp - 32) * 5/9.0
farenheit = (temp * 9/5.0) + 32
self.view.celsius.set_text("%.2f" % celsius)
self.view.farenheit.set_text("%.2f" % farenheit)
widgets = ["quitbutton", "temperature", "celsius", "farenheit"]
view = BaseView(gladefile="faren", delete_handler=quit_if_last,
widgets=widgets)
ctl = FarenControl(view)
view.show()
gtk.main()
|
Make sure to cast to int as this does not work on old numpy versions | import afnumpy
import arrayfire
import numpy
from IPython.core.debugger import Tracer
from .. import private_utils as pu
def tile(A, reps):
try:
tup = tuple(reps)
except TypeError:
tup = (reps,)
if(len(tup) > 4):
raise NotImplementedError('Only up to 4 dimensions are supported')
d = len(tup)
shape = list(A.shape)
n = max(A.size, 1)
if (d < A.ndim):
tup = (1,)*(A.ndim-d) + tup
# Calculate final shape
while len(shape) < len(tup):
shape.insert(0,1)
shape = tuple(numpy.array(shape) * numpy.array(tup))
# Prepend ones to simplify calling
if (d < 4):
tup = (1,)*(4-d) + tup
tup = pu.c2f(tup)
s = arrayfire.tile(A.d_array, int(tup[0]), int(tup[1]), int(tup[2]), int(tup[3]))
return afnumpy.ndarray(shape, dtype=pu.typemap(s.type()), af_array=s)
| import afnumpy
import arrayfire
import numpy
from .. import private_utils as pu
def tile(A, reps):
try:
tup = tuple(reps)
except TypeError:
tup = (reps,)
if(len(tup) > 4):
raise NotImplementedError('Only up to 4 dimensions are supported')
d = len(tup)
shape = list(A.shape)
n = max(A.size, 1)
if (d < A.ndim):
tup = (1,)*(A.ndim-d) + tup
# Calculate final shape
while len(shape) < len(tup):
shape.insert(0,1)
shape = tuple(numpy.array(shape) * numpy.array(tup))
# Prepend ones to simplify calling
if (d < 4):
tup = (1,)*(4-d) + tup
tup = pu.c2f(tup)
s = arrayfire.tile(A.d_array, tup[0], tup[1], tup[2], tup[3])
return afnumpy.ndarray(shape, dtype=pu.typemap(s.type()), af_array=s)
|
Allow pip to decide which version of doit to install | # Always prefer setuptools over distutils
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='wrapit',
version='0.3.1',
description='A task loader for doit that supports argparse console scripts',
long_description=long_description,
url='https://github.com/rbeagrie/wrapit',
author='Rob Beagrie',
author_email='rob@beagrie.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='doit development console_scripts build_tools',
packages=['wrapit'],
install_requires=['doit'],
)
| # Always prefer setuptools over distutils
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='wrapit',
version='0.3.0',
description='A task loader for doit that supports argparse console scripts',
long_description=long_description,
url='https://github.com/rbeagrie/wrapit',
author='Rob Beagrie',
author_email='rob@beagrie.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
keywords='doit development console_scripts build_tools',
packages=['wrapit'],
extras_require={
':python_version<"3.0"': ['doit==0.29.0'],
':python_version>="3.0"': ['doit==0.30.0'],
},
)
|
Return deleted comments instead of throwing error | from modularodm import Q
from modularodm.exceptions import NoResultsFound
from rest_framework import generics
from rest_framework.exceptions import NotFound
from api.comments.serializers import CommentSerializer, CommentDetailSerializer
from website.project.model import Comment
class CommentMixin(object):
"""Mixin with convenience methods for retrieving the current comment based on the
current URL. By default, fetches the comment based on the comment_id kwarg.
"""
serializer_class = CommentSerializer
comment_lookup_url_kwarg = 'comment_id'
def get_comment(self, check_permissions=True):
pk = self.kwargs[self.comment_lookup_url_kwarg]
query = Q('_id', 'eq', pk)
try:
comment = Comment.find_one(query)
except NoResultsFound:
raise NotFound
if check_permissions:
# May raise a permission denied
self.check_object_permissions(self.request, comment)
return comment
class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin):
"""Details about a specific comment.
"""
# permission classes
# required scopes
serializer_class = CommentDetailSerializer
# overrides RetrieveAPIView
def get_object(self):
return self.get_comment()
| from rest_framework import generics
from api.comments.serializers import CommentSerializer, CommentDetailSerializer
from website.project.model import Comment
from api.base.utils import get_object_or_error
class CommentMixin(object):
"""Mixin with convenience methods for retrieving the current comment based on the
current URL. By default, fetches the comment based on the comment_id kwarg.
"""
serializer_class = CommentSerializer
comment_lookup_url_kwarg = 'comment_id'
def get_comment(self, check_permissions=True):
comment = get_object_or_error(Comment, self.kwargs[self.comment_lookup_url_kwarg])
if check_permissions:
# May raise a permission denied
self.check_object_permissions(self.request, comment)
return comment
class CommentDetail(generics.RetrieveUpdateAPIView, CommentMixin):
"""Details about a specific comment.
"""
# permission classes
# required scopes
serializer_class = CommentDetailSerializer
# overrides RetrieveAPIView
def get_object(self):
return self.get_comment()
|
Set a default value of false | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMenusTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('menus', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->tinyInteger('primary')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('menus');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMenusTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('menus', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->boolean('primary');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('menus');
}
}
|
Update to use new blog location. |
function yql_lookup(query, cb_function) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true';
//alert(url);
$.getJSON(url, cb_function);
}
function look_up_news() {
var feed_url = 'http://mediacloud.org/blog/feed/';
//alert(google_url);
yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) {
var results = response.query.results;
var news_items = $('#news_items');
//console.log(results);
news_items.children().remove();
news_items.html('');
$.each(results.item, function (index, element) {
var title = element.title;
var link = element.link;
news_items.append($('<a/>', {
'href': link
}).text(title)).append('<br/>');
});
});
}
|
function yql_lookup(query, cb_function) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true';
//alert(url);
$.getJSON(url, cb_function);
}
function look_up_news() {
var feed_url = 'http://www.mediacloud.org/feed/';
//alert(google_url);
yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) {
var results = response.query.results;
var news_items = $('#news_items');
//console.log(results);
news_items.children().remove();
news_items.html('');
$.each(results.item, function (index, element) {
var title = element.title;
var link = element.link;
news_items.append($('<a/>', {
'href': link
}).text(title)).append('<br/>');
});
});
}
|
Remove not-needed option.
The aurelia plugin already takes care of this. | const phantomjs = require('phantomjs-prebuilt')
exports.config = {
framework: 'mocha',
plugins: [{
package: 'aurelia-protractor-plugin'
}, {
package: 'protractor-console',
logLevels: ['debug', 'info', 'warning', 'severe']
}],
capabilities: {
'browserName': 'phantomjs',
'phantomjs.binary.path': phantomjs.path
},
seleniumServerJar: './node_modules/selenium-jar/bin/selenium-server-standalone-2.52.0.jar',
localSeleniumStandaloneOpts: {
args: ['-Djna.nosys=true']
},
baseUrl: 'http://localhost:3000',
specs: ['test/e2e*.spec.js'],
mochaOpts: {
reporter: 'spec',
timeout: 6000
}
}
| const protractor = require('protractor')
const phantomjs = require('phantomjs-prebuilt')
exports.config = {
framework: 'mocha',
plugins: [{
package: 'aurelia-protractor-plugin'
}, {
package: 'protractor-console',
logLevels: ['debug', 'info', 'warning', 'severe']
}],
capabilities: {
'browserName': 'phantomjs',
'phantomjs.binary.path': phantomjs.path
},
seleniumServerJar: './node_modules/selenium-jar/bin/selenium-server-standalone-2.52.0.jar',
localSeleniumStandaloneOpts: {
args: ['-Djna.nosys=true']
},
baseUrl: 'http://localhost:3000',
specs: ['test/e2e*.spec.js'],
onPrepare: () => {
protractor.ignoreSynchronization = true
},
mochaOpts: {
reporter: 'spec',
timeout: 6000
}
}
|
Add new status (unknown), and necessary build files. | # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# The default mongodb database name.
DB_NAME = 'kernel-ci'
# The default ID key for mongodb documents.
ID_KEY = '_id'
# Job and/or build status.
BUILDING_STATUS = 'BUILDING'
DONE_STATUS = 'DONE'
FAILED_STATUS = 'FAILED'
SUCCESS_STATUS = 'SUCCESS'
UNKNOWN_STATUS = 'UNKNOWN'
# Build file names.
DONE_FILE = '.done'
BUILD_META_FILE = 'build.meta'
BUILD_FAIL_FILE = 'build.FAIL'
BUILD_PASS_FILE = 'build.PASS'
| # Copyright (C) 2014 Linaro Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# The default mongodb database name.
DB_NAME = 'kernel-ci'
# The default ID key for mongodb documents.
ID_KEY = '_id'
# Job and/or build status.
BUILDING_STATUS = 'BUILDING'
DONE_STATUS = 'DONE'
FAILED_STATUS = 'FAILED'
SUCCESS_STATUS = 'SUCCESS'
|
Call NodeVisitor.begin() before visiting ast. | package jltools.frontend;
import jltools.ast.*;
import jltools.util.*;
/** A pass which runs a visitor. */
public class VisitorPass extends AbstractPass
{
Job job;
NodeVisitor v;
public VisitorPass(Job job) {
this(job, null);
}
public VisitorPass(Job job, NodeVisitor v) {
this.job = job;
this.v = v;
}
public void visitor(NodeVisitor v) {
this.v = v;
}
public NodeVisitor visitor() {
return v;
}
public boolean run() {
Node ast = job.ast();
if (ast == null) {
throw new InternalCompilerError("Null AST: did the parser run?");
}
if (v.begin()) {
ErrorQueue q = job.compiler().errorQueue();
int nErrsBefore = q.errorCount();
ast = ast.visit(v);
v.finish();
int nErrsAfter = q.errorCount();
job.ast(ast);
return (nErrsBefore == nErrsAfter);
// because, if they're equal, no new errors occured,
// so the run was successful.
}
return false;
}
public String toString() {
return v.getClass().getName() + "(" + job + ")";
}
}
| package jltools.frontend;
import jltools.ast.*;
import jltools.util.*;
/** A pass which runs a visitor. */
public class VisitorPass extends AbstractPass
{
Job job;
NodeVisitor v;
public VisitorPass(Job job) {
this(job, null);
}
public VisitorPass(Job job, NodeVisitor v) {
this.job = job;
this.v = v;
}
public void visitor(NodeVisitor v) {
this.v = v;
}
public NodeVisitor visitor() {
return v;
}
public boolean run() {
Node ast = job.ast();
if (ast == null) {
throw new InternalCompilerError("Null AST: did the parser run?");
}
ErrorQueue q = job.compiler().errorQueue();
int nErrsBefore = q.errorCount();
ast = ast.visit(v);
v.finish();
int nErrsAfter = q.errorCount();
job.ast(ast);
return (nErrsBefore == nErrsAfter);
// because, if they're equal, no new errors occured,
// so the run was successful.
}
public String toString() {
return v.getClass().getName() + "(" + job + ")";
}
}
|
Make user integration test more resilient to 409 errors. | package wl_integration_test
import (
"github.com/nu7hatch/gouuid"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/robdimsdale/wl"
)
var _ = Describe("basic user functionality", func() {
It("can update the user's name", func() {
By("Creating a new random user name")
uuid1, err := uuid.NewV4()
Expect(err).NotTo(HaveOccurred())
newUserName := uuid1.String()
By("Getting and updating user")
var user wl.User
var updatedUser wl.User
Eventually(func() error {
user, err = client.User()
user.Name = "test-" + newUserName
updatedUser, err = client.UpdateUser(user)
return err
}).Should(Succeed())
Expect(updatedUser.ID).To(Equal(user.ID))
})
})
| package wl_integration_test
import (
"github.com/nu7hatch/gouuid"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/robdimsdale/wl"
)
var _ = Describe("basic user functionality", func() {
It("can update the user's name", func() {
By("Creating a new random user name")
uuid1, err := uuid.NewV4()
Expect(err).NotTo(HaveOccurred())
newUserName := uuid1.String()
By("Getting user")
var user wl.User
Eventually(func() error {
user, err = client.User()
return err
}).Should(Succeed())
By("Updating user")
var updatedUser wl.User
user.Name = "test-" + newUserName
Eventually(func() error {
updatedUser, err = client.UpdateUser(user)
return err
}).Should(Succeed())
Expect(updatedUser.ID).To(Equal(user.ID))
})
})
|
Add a unicode method for the Nonces | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentials"
user = models.ForeignKey(User)
expiry = models.DateTimeField("Expires On", default=default_expiry_time)
identifier = models.CharField("MAC Key Identifier", max_length=16, default=random_string)
key = models.CharField("MAC Key", max_length=16, default=random_string)
def __unicode__(self):
return u"{0}:{1}".format(self.identifier, self.key)
@property
def expired(self):
"""Returns whether or not the credentials have expired"""
if self.expiry < datetime.datetime.now():
return True
return False
class Nonce(models.Model):
"""Keeps track of any NONCE combinations that we have used"""
nonce = models.CharField("NONCE", max_length=16, null=True, blank=True)
timestamp = models.DateTimeField("Timestamp", auto_now_add=True)
credentials = models.ForeignKey(Credentials)
def __unicode__(self):
timestamp = self.timestamp - datetime.datetime(1970,1,1)
timestamp = timestamp.days * 24 * 3600 + timestamp.seconds
return u"[{0}/{1}/{2}]".format(self.nonce, timestamp, self.credentials.identifier) | from django.db import models
from django.contrib.auth.models import User
import datetime
def default_expiry_time():
return datetime.datetime.now() + datetime.timedelta(days=1)
def random_string():
return User.objects.make_random_password(16)
class Credentials(models.Model):
"Keeps track of issued MAC credentials"
user = models.ForeignKey(User)
expiry = models.DateTimeField("Expires On", default=default_expiry_time)
identifier = models.CharField("MAC Key Identifier", max_length=16, default=random_string)
key = models.CharField("MAC Key", max_length=16, default=random_string)
def __unicode__(self):
return u"{0}:{1}".format(self.identifier, self.key)
@property
def expired(self):
"""Returns whether or not the credentials have expired"""
if self.expiry < datetime.datetime.now():
return True
return False
class Nonce(models.Model):
"""Keeps track of any NONCE combinations that we have used"""
nonce = models.CharField("NONCE", max_length=16, null=True, blank=True)
timestamp = models.DateTimeField("Timestamp", auto_now_add=True)
credentials = models.ForeignKey(Credentials) |
[webdriver] Add wiki note for test. | package to.etc.domui.test.binding;
import org.junit.Assert;
import org.junit.Test;
import to.etc.domui.test.binding.order1.TestBindingOrder1;
import to.etc.domui.webdriver.core.AbstractWebDriverTest;
/**
* @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
* Created on 15-3-17.
*/
public class TestBindingOrder extends AbstractWebDriverTest {
/**
* https://etc.to/confluence/display/DOM/Tests%3A+data+binding
* @throws Exception
*/
@Test
public void testBinding1() throws Exception {
wd().openScreen(TestBindingOrder1.class);
//-- Switching country should switch city
wd().select("country", "Netherlands");
String city = wd().selectGetSelectedLabel("city");
Assert.assertEquals("Amsterdam", city);
wd().select("country", "USA");
city = wd().selectGetSelectedLabel("city");
Assert.assertEquals("New York", city);
//-- Switching city to a city in another country should change country
wd().select("city", "Lelystad");
city = wd().selectGetSelectedLabel("country");
Assert.assertEquals("Netherlands", city);
//-- Switching city to another in the same country
wd().select("city", "Amsterdam");
city = wd().selectGetSelectedLabel("country");
Assert.assertEquals("Netherlands", city);
Thread.sleep(10000);
}
}
| package to.etc.domui.test.binding;
import org.junit.Assert;
import org.junit.Test;
import to.etc.domui.test.binding.order1.TestBindingOrder1;
import to.etc.domui.webdriver.core.AbstractWebDriverTest;
/**
* @author <a href="mailto:jal@etc.to">Frits Jalvingh</a>
* Created on 15-3-17.
*/
public class TestBindingOrder extends AbstractWebDriverTest {
@Test
public void testBinding1() throws Exception {
wd().openScreen(TestBindingOrder1.class);
//-- Switching country should switch city
wd().select("country", "Netherlands");
String city = wd().selectGetSelectedLabel("city");
Assert.assertEquals("Amsterdam", city);
wd().select("country", "USA");
city = wd().selectGetSelectedLabel("city");
Assert.assertEquals("New York", city);
//-- Switching city to a city in another country should change country
wd().select("city", "Lelystad");
city = wd().selectGetSelectedLabel("country");
Assert.assertEquals("Netherlands", city);
//-- Switching city to another in the same country
wd().select("city", "Amsterdam");
city = wd().selectGetSelectedLabel("country");
Assert.assertEquals("Netherlands", city);
Thread.sleep(10000);
}
}
|
Remove check for domain in DOI | import logging
import time
from website.app import init_app
from website.identifiers.utils import request_identifiers_from_ezid
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
for preprint in preprints_without_identifiers:
logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name))
ezid_response = request_identifiers_from_ezid(preprint)
preprint.set_preprint_identifiers(ezid_response)
preprint.save()
doi = preprint.get_identifier('doi')
assert preprint._id.upper() in doi.value
logger.info('Created DOI {} for Preprint with guid {} from service {}'.format(doi.value, preprint._id, preprint.provider.name))
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
if __name__ == '__main__':
init_app(routes=False)
add_identifiers_to_preprints()
| import logging
import time
from website.app import init_app
from website.identifiers.utils import get_top_level_domain, request_identifiers_from_ezid
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
for preprint in preprints_without_identifiers:
logger.info('Saving identifier for preprint {} from source {}'.format(preprint._id, preprint.provider.name))
ezid_response = request_identifiers_from_ezid(preprint)
preprint.set_preprint_identifiers(ezid_response)
preprint.save()
doi = preprint.get_identifier('doi')
subdomain = get_top_level_domain(preprint.provider.external_url)
assert subdomain.upper() in doi.value
assert preprint._id.upper() in doi.value
logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name))
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
if __name__ == '__main__':
init_app(routes=False)
add_identifiers_to_preprints()
|
Remove temporary file after upload | const db = require('../lib/db')
const mongoose = db.goose
const conn = db.rope
const fs = require('fs')
const router = require('koa-router')()
const File = require('../lib/models/file')
const grid = require('gridfs-stream')
const gfs = grid(conn.db, mongoose.mongo)
router.get('/', function *() {
try {
var results = yield File.find()
} catch (err) {
throw err
}
for (var file in results) {
results[file] = results[file].toObject()
}
yield this.render('media', {
pageTitle: 'Media',
list: true,
files: results
})
})
router.post('/upload', function *(next) {
const file = this.request.body.files.file
const writestream = gfs.createWriteStream({
filename: file.name,
root: 'media',
content_type: file.type
})
const content = fs.createReadStream(file.path)
content.pipe(writestream)
try {
yield new Promise(function (resolve) {
writestream.on('close', () => resolve())
})
} catch (err) {
throw err
}
this.body = file.name + ' was written to DB'
yield next
fs.unlink(file.path, function (err) {
if (err) throw err
})
})
module.exports = router
| const db = require('../lib/db')
const mongoose = db.goose
const conn = db.rope
const fs = require('fs')
const router = require('koa-router')()
const File = require('../lib/models/file')
const grid = require('gridfs-stream')
const gfs = grid(conn.db, mongoose.mongo)
router.get('/', function *() {
try {
var results = yield File.find()
} catch (err) {
throw err
}
for (var file in results) {
results[file] = results[file].toObject()
}
yield this.render('media', {
pageTitle: 'Media',
list: true,
files: results
})
})
router.post('/upload', function *(next) {
const file = this.request.body.files.file
const writestream = gfs.createWriteStream({
filename: file.name,
root: 'media',
content_type: file.type
})
const content = fs.createReadStream(file.path)
content.pipe(writestream)
try {
yield new Promise(function (resolve) {
writestream.on('close', () => resolve())
})
} catch (err) {
throw err
}
this.body = file.name + ' was written to DB'
yield next
})
module.exports = router
|
Fix back to top icon not appearing on webkit browsers | // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
app.views.BackToTop = Backbone.View.extend({
events: {
"click #back-to-top": "backToTop"
},
initialize: function() {
var throttledScroll = _.throttle(this.toggleVisibility, 250);
$(window).scroll(throttledScroll);
},
backToTop: function(evt) {
evt.preventDefault();
$("html, body").animate({scrollTop: 0});
},
toggleVisibility: function() {
if($(document).scrollTop() > 1000) {
$("#back-to-top").addClass("visible");
} else {
$("#back-to-top").removeClass("visible");
}
}
});
// @license-end
| // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-v3-or-Later
app.views.BackToTop = Backbone.View.extend({
events: {
"click #back-to-top": "backToTop"
},
initialize: function() {
var throttledScroll = _.throttle(this.toggleVisibility, 250);
$(window).scroll(throttledScroll);
},
backToTop: function(evt) {
evt.preventDefault();
$("html, body").animate({scrollTop: 0});
},
toggleVisibility: function() {
if($("html, body").scrollTop() > 1000) {
$("#back-to-top").addClass("visible");
} else {
$("#back-to-top").removeClass("visible");
}
}
});
// @license-end
|
Hide the selected state when already on it | // @flow
import type {Snapshot, SnapshotItem} from 'redux-ship';
export type State = {
logs: {action: mixed, snapshot: Snapshot<mixed, mixed>}[],
selectedLog: ?number,
selectedSnapshotItem: ?SnapshotItem<mixed, mixed>,
};
export const initialState: State = {
logs: [],
selectedLog: null,
selectedSnapshotItem: null,
};
export type Commit = {
type: 'AddLog',
action: mixed,
snapshot: Snapshot<mixed, mixed>,
} | {
type: 'SelectLog',
logIndex: number,
} | {
type: 'SelectSnapshotItem',
snapshotItem: SnapshotItem<mixed, mixed>,
};
export function reduce(state: State, commit: Commit): State {
switch (commit.type) {
case 'AddLog':
return {
...state,
logs: [
...state.logs,
{
action: commit.action,
snapshot: commit.snapshot,
}
],
};
case 'SelectLog':
return commit.logIndex === state.selectedLog ? state : {
...state,
selectedLog: commit.logIndex,
selectedSnapshotItem: null,
};
case 'SelectSnapshotItem':
return {
...state,
selectedSnapshotItem: commit.snapshotItem,
};
default:
return state;
}
}
| // @flow
import type {Snapshot, SnapshotItem} from 'redux-ship';
export type State = {
logs: {action: mixed, snapshot: Snapshot<mixed, mixed>}[],
selectedLog: ?number,
selectedSnapshotItem: ?SnapshotItem<mixed, mixed>,
};
export const initialState: State = {
logs: [],
selectedLog: null,
selectedSnapshotItem: null,
};
export type Commit = {
type: 'AddLog',
action: mixed,
snapshot: Snapshot<mixed, mixed>,
} | {
type: 'SelectLog',
logIndex: number,
} | {
type: 'SelectSnapshotItem',
snapshotItem: SnapshotItem<mixed, mixed>,
};
export function reduce(state: State, commit: Commit): State {
switch (commit.type) {
case 'AddLog':
return {
...state,
logs: [
...state.logs,
{
action: commit.action,
snapshot: commit.snapshot,
}
],
};
case 'SelectLog':
return {
...state,
selectedLog: commit.logIndex,
};
case 'SelectSnapshotItem':
return {
...state,
selectedSnapshotItem: commit.snapshotItem,
};
default:
return state;
}
}
|
Make `show_panel` a normal argument to `GitSavvyError` | import sublime
from ..common import util
MYPY = False
if MYPY:
from typing import Sequence
class GitSavvyError(Exception):
def __init__(self, msg, *args, cmd=None, stdout="", stderr="", show_panel=True, **kwargs):
# type: (str, object, Sequence[str], str, str, bool, object) -> None
super(GitSavvyError, self).__init__(msg, *args)
self.message = msg
self.cmd = cmd
self.stdout = stdout
self.stderr = stderr
if msg:
if show_panel:
util.log.display_panel(sublime.active_window(), msg)
util.debug.log_error(msg)
class FailedGithubRequest(GitSavvyError):
pass
class FailedGitLabRequest(GitSavvyError):
pass
| import sublime
from ..common import util
MYPY = False
if MYPY:
from typing import Sequence
class GitSavvyError(Exception):
def __init__(self, msg, *args, cmd=None, stdout="", stderr="", **kwargs):
# type: (str, object, Sequence[str], str, str, object) -> None
super(GitSavvyError, self).__init__(msg, *args)
self.message = msg
self.cmd = cmd
self.stdout = stdout
self.stderr = stderr
if msg:
if kwargs.get('show_panel', True):
util.log.display_panel(sublime.active_window(), msg)
util.debug.log_error(msg)
class FailedGithubRequest(GitSavvyError):
pass
class FailedGitLabRequest(GitSavvyError):
pass
|
Add delay to anchoring code | import { bodyLoader } from 'src/util/loader'
import { remoteFunction } from 'src/util/webextensionRPC'
import * as rendering from './rendering'
import * as interactions from './interactions'
export async function init() {
await bodyLoader()
setTimeout(() => {
remoteFunction('followAnnotationRequest')()
}, 500)
}
export function setupAnchorFallbackOverlay() {}
browser.runtime.onMessage.addListener(request => {
if (request.type !== 'direct-link') {
return
}
;(async () => {
const highlightSuccessful = await rendering.highlightAnnotation({
annotation: request.annotation,
})
if (highlightSuccessful) {
interactions.scrollToHighlight()
} else {
setupAnchorFallbackOverlay()
}
})()
})
init()
| import { bodyLoader } from 'src/util/loader'
import { remoteFunction } from 'src/util/webextensionRPC'
import * as rendering from './rendering'
import * as interactions from './interactions'
export async function init() {
await bodyLoader()
remoteFunction('followAnnotationRequest')()
}
export function setupAnchorFallbackOverlay() {}
browser.runtime.onMessage.addListener(request => {
if (request.type !== 'direct-link') {
return
}
;(async () => {
const highlightSuccessful = await rendering.highlightAnnotation({
annotation: request.annotation,
})
if (highlightSuccessful) {
interactions.scrollToHighlight()
} else {
setupAnchorFallbackOverlay()
}
})()
})
init()
|
Remove a duplicated label from the collection view | package com.intellij.debugger.streams.ui;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
super(project, value);
}
@Override
public String calcValueName() {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.calcValueName();
}
return value.type().name();
}
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.getDescriptorEvaluation(debuggerContext);
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
}
}
| package com.intellij.debugger.streams.ui;
import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.ContextUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.memory.utils.InstanceValueDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElementFactory;
import com.intellij.psi.PsiExpression;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class PrimitiveValueDescriptor extends InstanceValueDescriptor {
PrimitiveValueDescriptor(@NotNull Project project, @NotNull Value value) {
super(project, value);
}
@Override
public String calcValueName() {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.calcValueName();
}
return value.type().name();
}
@Override
public boolean isShowIdLabel() {
return true;
}
@Override
public PsiExpression getDescriptorEvaluation(DebuggerContext debuggerContext) throws EvaluateException {
final Value value = getValue();
if (value instanceof ObjectReference) {
return super.getDescriptorEvaluation(debuggerContext);
}
final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myProject).getElementFactory();
return elementFactory.createExpressionFromText("", ContextUtil.getContextElement(debuggerContext));
}
}
|
Resolve webpack-dev-server output filename error
```
ERROR in chunk [file] [entry]
Cannot use [chunkhash] or [contenthash] for chunk in 'js/[name]-[contenthash].js' (use [hash] instead)
```
Override the base config output filename and resolve the above error in chunk | const { environment } = require('@rails/webpacker')
const ConcatPlugin = require('webpack-concat-plugin')
environment.plugins.append('ConcatPlugin', new ConcatPlugin({
uglify: true,
sourceMap: true,
outputPath: 'js',
fileName: 'application.bundle.js',
filesToConcat: [
'jquery',
'jquery-ujs',
'jquery.iframe-transport',
'dropzone',
'govuk_frontend_toolkit/javascripts/govuk/stick-at-top-when-scrolling.js',
'govuk_frontend_toolkit/javascripts/govuk/stop-scrolling-at-footer.js',
'jquery-accessible-accordion-aria',
'jsrender',
'jquery-highlight',
'jquery-throttle-debounce',
'accessible-autocomplete',
'./app/webpack/javascripts/vendor/**/*',
'./app/webpack/javascripts/modules/**/*',
'./app/webpack/javascripts/plugins/**/*',
'./app/webpack/javascripts/application.js'
]
}))
environment.config.merge({
output: {
filename: 'js/[name]-[hash].js'
}
})
module.exports = environment
| const { environment } = require('@rails/webpacker')
const ConcatPlugin = require('webpack-concat-plugin')
environment.plugins.append('ConcatPlugin', new ConcatPlugin({
uglify: true,
sourceMap: true,
outputPath: 'js',
fileName: 'application.bundle.js',
filesToConcat: [
'jquery',
'jquery-ujs',
'jquery.iframe-transport',
'dropzone',
'govuk_frontend_toolkit/javascripts/govuk/stick-at-top-when-scrolling.js',
'govuk_frontend_toolkit/javascripts/govuk/stop-scrolling-at-footer.js',
'jquery-accessible-accordion-aria',
'jsrender',
'jquery-highlight',
'jquery-throttle-debounce',
'accessible-autocomplete',
'./app/webpack/javascripts/vendor/**/*',
'./app/webpack/javascripts/modules/**/*',
'./app/webpack/javascripts/plugins/**/*',
'./app/webpack/javascripts/application.js'
]
}))
module.exports = environment
|
Increase browser inactivity timeout for test runs. | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
browserNoActivityTimeout: 30000
});
};
| // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false, // leave Jasmine Spec Runner output visible in browser
jasmine: {
random: false
}
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
|
Use a dev api token | import os
class Config(object):
DEBUG = False
ASSETS_DEBUG = False
cache = False
manifest = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = False
SQLALCHEMY_RECORD_QUERIES = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/notifications_admin'
MAX_FAILED_LOGIN_COUNT = 10
PASS_SECRET_KEY = 'secret-key-unique-changeme'
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "dev-token")
WTF_CSRF_ENABLED = True
SECRET_KEY = 'secret-key'
HTTP_PROTOCOL = 'http'
DANGEROUS_SALT = 'itsdangeroussalt'
class Development(Config):
DEBUG = True
class Test(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_notifications_admin'
WTF_CSRF_ENABLED = False
class Live(Config):
DEBUG = False
HTTP_PROTOCOL = 'https'
configs = {
'development': Development,
'test': Test
}
| import os
class Config(object):
DEBUG = False
ASSETS_DEBUG = False
cache = False
manifest = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = False
SQLALCHEMY_RECORD_QUERIES = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/notifications_admin'
MAX_FAILED_LOGIN_COUNT = 10
PASS_SECRET_KEY = 'secret-key-unique-changeme'
SESSION_COOKIE_NAME = 'notify_admin_session'
SESSION_COOKIE_PATH = '/admin'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
NOTIFY_DATA_API_URL = os.getenv('NOTIFY_API_URL', "http://localhost:6001")
NOTIFY_DATA_API_AUTH_TOKEN = os.getenv('NOTIFY_API_TOKEN', "pLuj5kat5auC9Ve")
WTF_CSRF_ENABLED = True
SECRET_KEY = 'secret-key'
HTTP_PROTOCOL = 'http'
DANGEROUS_SALT = 'itsdangeroussalt'
class Development(Config):
DEBUG = True
class Test(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_notifications_admin'
WTF_CSRF_ENABLED = False
class Live(Config):
DEBUG = False
HTTP_PROTOCOL = 'https'
configs = {
'development': Development,
'test': Test
}
|
Implement `keys` and `values` of `Dictionary` | import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getitem__(self, key: K) -> Optional[V]:
return optional(self._entries.get(key))
def __setitem__(self, key: K, value: V) -> None:
self._entries[key] = value
@property
def keys(self) -> tp.Iterable[K]:
return self._entries.keys()
@property
def values(self) -> tp.Iterable[V]:
return self._entries.values()
def for_each(self, body: tp.Callable[[K, V], None]) -> None:
for key, value in self._entries.items():
body(key, value)
@property
def count(self) -> int:
return len(self._entries)
def remove_all(self) -> None:
self._entries.clear()
def __iter__(self) -> tp.Iterator[tp.Tuple[K, V]]:
return self._entries.items().__iter__()
| import typing as tp
import builtins as py
from .optional import Optional, optional
K = tp.TypeVar('K')
V = tp.TypeVar('V')
class Dictionary(tp.Generic[K, V], tp.Iterable[tp.Tuple[K, V]]):
def __init__(self, entries: tp.Dict[K, V]) -> None:
self._entries: tp.Dict[K, V] = py.dict(entries)
def __getitem__(self, key: K) -> Optional[V]:
return optional(self._entries.get(key))
def __setitem__(self, key: K, value: V) -> None:
self._entries[key] = value
def for_each(self, body: tp.Callable[[K, V], None]) -> None:
for key, value in self._entries.items():
body(key, value)
@property
def count(self) -> int:
return len(self._entries)
def remove_all(self) -> None:
self._entries.clear()
def __iter__(self) -> tp.Iterator[tp.Tuple[K, V]]:
return self._entries.items().__iter__()
|
III-666: Fix projector for the search readmodel of variations. | <?php
namespace CultuurNet\UDB3\Variations\ReadModel\Search;
use Broadway\EventHandling\EventListenerInterface;
use CultuurNet\UDB3\EventHandling\DelegateEventHandlingToSpecificMethodTrait;
use CultuurNet\UDB3\Variations\Model\Events\OfferVariationCreated;
use CultuurNet\UDB3\Variations\Model\Events\OfferVariationDeleted;
class Projector implements EventListenerInterface
{
use DelegateEventHandlingToSpecificMethodTrait;
/**
* @var RepositoryInterface
*/
protected $repository;
/**
* @param RepositoryInterface $repository
*/
public function __construct(RepositoryInterface $repository)
{
$this->repository = $repository;
}
protected function applyOfferVariationCreated(OfferVariationCreated $eventVariationCreated)
{
$this->repository->save(
$eventVariationCreated->getId(),
$eventVariationCreated->getEventUrl(),
$eventVariationCreated->getOwnerId(),
$eventVariationCreated->getPurpose(),
$eventVariationCreated->getOfferType()
);
}
protected function applyOfferVariationDeleted(OfferVariationDeleted $eventVariationDeleted)
{
$this->repository->remove($eventVariationDeleted->getId());
}
}
| <?php
namespace CultuurNet\UDB3\Variations\ReadModel\Search;
use Broadway\EventHandling\EventListenerInterface;
use CultuurNet\UDB3\EventHandling\DelegateEventHandlingToSpecificMethodTrait;
use CultuurNet\UDB3\Variations\Model\Events\OfferVariationCreated;
use CultuurNet\UDB3\Variations\Model\Events\OfferVariationDeleted;
class Projector implements EventListenerInterface
{
use DelegateEventHandlingToSpecificMethodTrait;
/**
* @var RepositoryInterface
*/
protected $repository;
/**
* @param RepositoryInterface $repository
*/
public function __construct(RepositoryInterface $repository)
{
$this->repository = $repository;
}
protected function applyOfferVariationCreated(OfferVariationCreated $eventVariationCreated)
{
$this->repository->save(
$eventVariationCreated->getId(),
$eventVariationCreated->getEventUrl(),
$eventVariationCreated->getOwnerId(),
$eventVariationCreated->getPurpose()
);
}
protected function applyOfferVariationDeleted(OfferVariationDeleted $eventVariationDeleted)
{
$this->repository->remove($eventVariationDeleted->getId());
}
}
|
Fix JS syntax error in variable declaration
Declarations in javascript should end with a semicolon. This
otherwise causes strange and hard to debug issues in minified
js assets.
Change-Id: I821a71b169b86e9f0318cbae4c6cc654cb97a4a7 | horizon.job_launching_warning = {
show_warning: function(cl_name_status_map, status_message_map) {
var cl_choice_elem = $('.cluster_choice').parent();
var current_cl_name = $('.cluster_choice option:selected').text();
var current_cl_status = cl_name_status_map[current_cl_name];
var warning_msg = status_message_map[current_cl_status];
var warning_elem = "<div class=\"not_active_state_warning alert alert-dismissable alert-warning\">" +
"<h4>" + gettext("Warning!") + "</h4>" +
"<p>" + warning_msg + "</p>" +
"</div>";
if ($.isEmptyObject(cl_name_status_map) || current_cl_status === 'Active') {
$('.not_active_state_warning').remove();
} else {
cl_choice_elem.append(warning_elem);
$('.not_active_state_warning').css('margin-top', '5px');
}
}
};
| horizon.job_launching_warning = {
show_warning: function(cl_name_status_map, status_message_map) {
var cl_choice_elem = $('.cluster_choice').parent();
var current_cl_name = $('.cluster_choice option:selected').text();
var current_cl_status = cl_name_status_map[current_cl_name];
var warning_msg = status_message_map[current_cl_status];
var warning_elem = "<div class=\"not_active_state_warning alert alert-dismissable alert-warning\">" +
"<h4>" + gettext("Warning!") + "</h4>" +
"<p>" + warning_msg + "</p>" +
"</div>";
if ($.isEmptyObject(cl_name_status_map) || current_cl_status === 'Active') {
$('.not_active_state_warning').remove();
} else {
cl_choice_elem.append(warning_elem);
$('.not_active_state_warning').css('margin-top', '5px');
}
}
}
|
Use new string formatting method | '''
Check your Facebook notifications on command line.
Author: Amit Chaudhary ( studenton.com@gmail.com )
'''
import json
# Configuration
notifications = 5 # Number of Notifications
profile_id = '1XXXXXXXXXXXXXX'
token = 'write token here'
base_url = 'https://www.facebook.com/feeds/notifications.php?id={0}&viewer={0}&key={1}&format=json'
url = base_url.format(profile_id, token)
def get_page(url):
try:
import urllib
return urllib.urlopen(url).read()
except:
return ''
def main():
try:
data = json.loads(get_page(url))
for i in range(notifications):
print data['entries'][i]['title'] + "\n"
except:
print """
Couldnot fetch the notifications. The possible causes are:
1. You are not connected to the internet.
2. You haven't entered the correct api token.
"""
if __name__ == "__main__":
main()
| '''
Check your Facebook notifications on command line.
Author: Amit Chaudhary ( studenton.com@gmail.com )
'''
import json
# Configuration
notifications = 5 # Number of Notifications
profile_id = '1XXXXXXXXXXXXXX'
token = 'write token here'
url = 'https://www.facebook.com/feeds/notifications.php?id=' + \
profile_id + '&viewer=' + profile_id + '&key=' + token + '&format=json'
def get_page(url):
try:
import urllib
return urllib.urlopen(url).read()
except:
return ''
def main():
try:
data = json.loads(get_page(url))
for i in range(notifications):
print data['entries'][i]['title'] + "\n"
except:
print """
Couldnot fetch the notifications. The possible causes are:
1. You are not connected to the internet.
2. You haven't entered the correct api token.
"""
if __name__ == "__main__":
main()
|
Add purchase functionality in back-end. | <?php
namespace App\Http\Controllers;
use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;
class Purchases extends Controller
{
/**
* Purchase book and generate invoice.
*
* @param Request $request
* @return Response
*/
public function index(Request $request) {
$invoice = null;
$purchaseService = new Purchase();
$purchaseQty = $request->input('qty');
$book = Book::find($request->input('book_id'));
$purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);
if($purchasePrice !== null) {
$book->quantity -= $purchaseQty;
$invoice = new Invoice();
$invoice->book_id = $book->id;
$invoice->amount = $purchasePrice;
$invoice->qty = $purchaseQty;
$invoice->created_at = date('Y-m-d H:i:s');
$invoice->updated_at = date('Y-m-d H:i:s');
$invoice->save();
$book->save();
}
return $invoice;
}
}
| <?php
namespace App\Http\Controllers;
use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;
class Purchases extends Controller
{
/**
* Purchase book and generate invoice.
*
* @param Request $request
* @return Response
*/
public function index(Request $request) {
$invoice = null;
$purchaseService = new Purchase();
$purchaseQty = $request->input('qty');
$book = Book::find($request->input('book_id'));
$purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);
if($purchasePrice !== null) {
$invoice = new Invoice();
$invoice->book_id = $book->id;
$invoice->amount = $purchasePrice;
$invoice->qty = $purchaseQty;
$invoice->created_at = date('Y-m-d H:i:s');
$invoice->updated_at = date('Y-m-d H:i:s');
$invoice->save();
}
return $invoice;
}
}
|
Change hunger values for toast | package net.shadowfacts.foodies.item;
import cpw.mods.fml.common.registry.GameRegistry;
/**
* Helper class for registering items.
* @author shadowfacts
*/
public class FItems {
// Foods
public static Food toast;
public static Food tomato;
public static Food beefPattie;
public static void preInit() {
// Create Items
toast = new Food(5, 0.3f).setUnlocalizedName("foodToast").setTextureName("foodToast");
tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato");
beefPattie = new Food(7, 0.4f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie");
// Register items
GameRegistry.registerItem(toast, "foodToast");
GameRegistry.registerItem(tomato, "fruitTomato");
GameRegistry.registerItem(beefPattie, "foodBeefPattie");
}
public static void load() {
}
public static void postInit() {
}
}
| package net.shadowfacts.foodies.item;
import cpw.mods.fml.common.registry.GameRegistry;
/**
* Helper class for registering items.
* @author shadowfacts
*/
public class FItems {
// Foods
public static Food toast;
public static Food tomato;
public static Food beefPattie;
public static void preInit() {
// Create Items
toast = new Food(7, 0.7f).setUnlocalizedName("foodToast").setTextureName("foodToast");
tomato = new Food(1, 0.1f).setUnlocalizedName("fruitTomato").setTextureName("fruitTomato");
beefPattie = new Food(7, 0.4f).setUnlocalizedName("foodBeefPattie").setTextureName("foodBeefPattie");
// Register items
GameRegistry.registerItem(toast, "foodToast");
GameRegistry.registerItem(tomato, "fruitTomato");
GameRegistry.registerItem(beefPattie, "foodBeefPattie");
}
public static void load() {
}
public static void postInit() {
}
}
|
Add framework status to API /_status
To figure out current framework statuses for the given environment
you either need access to the API token or you'd have to look through
a number of frontend pages to infer the status from.
Framework status is a part of almost every request to the API, so
it should always be available for a working API instance and it makes
sense to add it to the /_status page.
Adding it to the /_status page creates an easier way to get the list
of all framework statuses. | from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
from ..models import Framework
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
frameworks={f.slug: f.status for f in Framework.query.all()},
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
| import os
from flask import jsonify, current_app, request
from sqlalchemy.exc import SQLAlchemyError
from . import status
from . import utils
from dmutils.status import get_flags
@status.route('/_status')
def status_no_db():
if 'ignore-dependencies' in request.args:
return jsonify(
status="ok",
), 200
version = current_app.config['VERSION']
try:
return jsonify(
status="ok",
version=version,
db_version=utils.get_db_version(),
flags=get_flags(current_app)
)
except SQLAlchemyError:
current_app.logger.exception('Error connecting to database')
return jsonify(
status="error",
version=version,
message="Error connecting to database",
flags=get_flags(current_app)
), 500
|
Patch psycopg correctly in admin
[skip ci] | """
WSGI config for api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
from website import settings
if not settings.DEBUG_MODE:
from gevent import monkey
monkey.patch_all()
# PATCH: avoid deadlock on getaddrinfo, this patch is necessary while waiting for
# the final gevent 1.1 release (https://github.com/gevent/gevent/issues/349)
# unicode('foo').encode('idna') # noqa
from psycogreen.gevent import patch_psycopg # noqa
patch_psycopg()
import os # noqa
from django.core.wsgi import get_wsgi_application # noqa
from website.app import init_app # noqa
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'admin.base.settings')
init_app(set_backends=True, routes=False, attach_request_handlers=False)
application = get_wsgi_application()
| """
WSGI config for api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
from website import settings
if not settings.DEBUG_MODE:
from gevent import monkey
monkey.patch_all()
# PATCH: avoid deadlock on getaddrinfo, this patch is necessary while waiting for
# the final gevent 1.1 release (https://github.com/gevent/gevent/issues/349)
unicode('foo').encode('idna') # noqa
import os # noqa
from django.core.wsgi import get_wsgi_application # noqa
from website.app import init_app # noqa
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'admin.base.settings')
init_app(set_backends=True, routes=False, attach_request_handlers=False)
application = get_wsgi_application()
|
Return types in repositories & dataset | <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ProducerBundle\Repository;
use Doctrine\ORM\QueryBuilder;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;
/**
* Class ProducerRepository
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ProducerRepository extends AbstractEntityRepository implements ProducerRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function getDataSetQueryBuilder() : QueryBuilder
{
$queryBuilder = $this->getQueryBuilder();
$queryBuilder->groupBy('producer.id');
$queryBuilder->leftJoin('producer.translations', 'producer_translation');
$queryBuilder->leftJoin('producer.products', 'producer_products');
$queryBuilder->leftJoin('producer.shops', 'producer_shops');
return $queryBuilder;
}
}
| <?php
/*
* WellCommerce Open-Source E-Commerce Platform
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\ProducerBundle\Repository;
use WellCommerce\Bundle\DoctrineBundle\Repository\AbstractEntityRepository;
/**
* Class ProducerRepository
*
* @author Adam Piotrowski <adam@wellcommerce.org>
*/
class ProducerRepository extends AbstractEntityRepository implements ProducerRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function getDataSetQueryBuilder()
{
$queryBuilder = $this->getQueryBuilder();
$queryBuilder->groupBy('producer.id');
$queryBuilder->leftJoin('producer.translations', 'producer_translation');
$queryBuilder->leftJoin('producer.products', 'producer_products');
$queryBuilder->leftJoin('producer.shops', 'producer_shops');
return $queryBuilder;
}
}
|
Resolve promise in PR handler | 'use strict';
var R = require('ramda');
function onPrClose() {
return q.resolve();
}
function writeSuccess(res, result) {
res.send(':)');
}
function writeFailure(res, err) {
res.send(':(');
}
function pullRequestRouteHandler(req, res) {
var body = req.body;
var onSucess = R.curry(writeSuccess)(res);
var onFail = R.curry(writeFailure)(res);
var ghAction = body.action;
var ghEventType = req.header('X-Github-Event')
if(ghEventType !== 'pull_request') {
res.status(403)
.send('Pull requests only!');
}
if(ghAction === 'closed') {
onPrClose(body)
.then(onSuccess, onFail);
} else {
res.status(403)
.send('We only want "closed" PR events right now.');
}
}
module.exports = pullRequestRouteHandler;
| 'use strict';
var R = require('ramda');
function onPrClose() {
}
function writeSuccess(res, result) {
res.send(':)');
}
function writeFailure(res, err) {
res.send(':(');
}
function pullRequestRouteHandler(req, res) {
var body = req.body;
var onSucess = R.curry(writeSuccess)(res);
var onFail = R.curry(writeFailure)(res);
var ghAction = body.action;
var ghEventType = req.header('X-Github-Event')
if(ghEventType !== 'pull_request') {
res.status(403)
.send('Pull requests only!');
}
if(ghAction === 'closed') {
onPrClose(body)
.then(onSuccess, onFail);
} else {
res.status(403)
.send('We only want "closed" PR events right now.');
}
}
module.exports = pullRequestRouteHandler;
|
Allow admin store credit memo to be changed using rails-ujs
rails-ujs has a different api handling ajax events than jquery_ujs.
The former passes all the event information into the event.detail object
while the latter accept different parameters. For more details see:
- https://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers
- https://github.com/rails/jquery-ujs/wiki/ajax | Spree.ready(function() {
$('.store-credit-memo-row').each(function() {
var row = this;
var field = row.querySelector('[name="store_credit[memo]"]')
var textDisplay = row.querySelector('.store-credit-memo-text')
$(row).on('ajax:success', function(event, data) {
row.classList.remove('editing');
field.defaultValue = field.value;
textDisplay.textContent = field.value;
if (typeof data !== "undefined") {
// we are using jquery_ujs
message = data.message
} else {
// we are using rails-ujs
message = event.detail[0].message
}
show_flash('success', message);
}).on('ajax:error', function(event, xhr, status, error) {
if (typeof xhr !== "undefined") {
// we are using jquery_ujs
message = xhr.responseJSON.message
} else {
// we are using rails-ujs
message = event.detail[0].message
}
show_flash('error', message);
});
row.querySelector('.edit-memo').addEventListener('click', function() {
row.classList.add('editing');
});
row.querySelector('.cancel-memo').addEventListener('click', function() {
row.classList.remove('editing');
});
});
});
| Spree.ready(function() {
$('.store-credit-memo-row').each(function() {
var row = this;
var field = row.querySelector('[name="store_credit[memo]"]')
var textDisplay = row.querySelector('.store-credit-memo-text')
$(row).on('ajax:success', function(event, data) {
row.classList.remove('editing');
field.defaultValue = field.value;
textDisplay.textContent = field.value;
show_flash('success', data.message);
}).on('ajax:error', function(event, xhr, status, error) {
show_flash('error', xhr.responseJSON.message);
});
row.querySelector('.edit-memo').addEventListener('click', function() {
row.classList.add('editing');
});
row.querySelector('.cancel-memo').addEventListener('click', function() {
row.classList.remove('editing');
});
});
});
|
Remove 7 characters to get rid of ".models" | from sqjobs.utils import get_jobs_from_module
import logging
logger = logging.getLogger('sqjobs.contrib.django.utils')
def get_apps_names():
"""
copied from django-extensions compatibility sheam
"""
try:
# django >= 1.7, to support AppConfig
from django.apps import apps
return [app.name for app in apps.get_app_configs()]
except ImportError:
from django.db import models
return [app.__name__[:-7] for app in models.get_apps()]
def register_all_jobs(worker):
"""
Register all the jobs in a worker
"""
jobs = get_all_jobs()
for job in jobs:
worker.register_job(job)
return jobs
def get_all_jobs():
"""
Get all the jobs of the django INSTALLED_APPS
"""
jobs = []
for app_name in get_apps_names():
try:
module = app_name + '.jobs'
jobs.extend(get_jobs_from_module(module))
except ImportError:
pass
return jobs
| from sqjobs.utils import get_jobs_from_module
import logging
logger = logging.getLogger('sqjobs.contrib.django.utils')
def get_apps_names():
"""
copied from django-extensions compatibility sheam
"""
try:
# django >= 1.7, to support AppConfig
from django.apps import apps
return [app.name for app in apps.get_app_configs()]
except ImportError:
from django.db import models
return [app.__name__[:-6] for app in models.get_apps()]
def register_all_jobs(worker):
"""
Register all the jobs in a worker
"""
jobs = get_all_jobs()
for job in jobs:
worker.register_job(job)
return jobs
def get_all_jobs():
"""
Get all the jobs of the django INSTALLED_APPS
"""
jobs = []
for app_name in get_apps_names():
try:
module = app_name + '.jobs'
jobs.extend(get_jobs_from_module(module))
except ImportError:
pass
return jobs
|
[proberk] Disable test which is covered by an alert
TBR=borenet
Bug: skia:
Change-Id: I26d62f1c108f471a92b298c8bd37a2c845d80542
Reviewed-on: https://skia-review.googlesource.com/c/177910
Reviewed-by: Stephan Altmueller <43343ec95731c0e8daa7359daf7f2f3935582b24@google.com>
Commit-Queue: Stephan Altmueller <43343ec95731c0e8daa7359daf7f2f3935582b24@google.com> | package main
import (
"testing"
assert "github.com/stretchr/testify/require"
"go.skia.org/infra/go/testutils"
"go.skia.org/infra/proberk/go/types"
)
func TestProbeSSL(t *testing.T) {
t.Skip()
testutils.LargeTest(t)
probes := &types.Probe{
URLs: []string{
"https://skia.org",
"https://skia.org:443",
"https://35.201.76.220",
},
Method: "SSL",
}
// Verify the Certs are valid. This implies they are valid for 10 days.
for _, url := range probes.URLs {
assert.NoError(t, probeSSL(probes, url))
}
// Verify failure by expecting certs to be valid for 20 years.
probes.Expected = []int{7300}
for _, url := range probes.URLs {
assert.Error(t, probeSSL(probes, url))
}
}
| package main
import (
"testing"
assert "github.com/stretchr/testify/require"
"go.skia.org/infra/go/testutils"
"go.skia.org/infra/proberk/go/types"
)
func TestProbeSSL(t *testing.T) {
testutils.LargeTest(t)
probes := &types.Probe{
URLs: []string{
"https://skia.org",
"https://skia.org:443",
"https://35.201.76.220",
},
Method: "SSL",
}
// Verify the Certs are valid. This implies they are valid for 10 days.
for _, url := range probes.URLs {
assert.NoError(t, probeSSL(probes, url))
}
// Verify failure by expecting certs to be valid for 20 years.
probes.Expected = []int{7300}
for _, url := range probes.URLs {
assert.Error(t, probeSSL(probes, url))
}
}
|
Set buffer size to 10mb | var DEBUG_PORT = 8000;
var express = require('express');
var sys = require('sys');
var exec = require('child_process').exec;
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.send("Welcome to radiof.at! <form action='/' method='post' enctype='multipart/form-data'><input type='file' name='song' /><input type='submit' /></form>");
});
app.post('/', function(req, res) {
if (req.files.song.type == 'audio/mp3') {
// Convert an MP3
exec('./PROCESSMP3 ' + req.files.song.path, { timeout: 0, maxBuffer: 10485760 }, function(err, stdout, stderr) {
console.log("We're done!!!");
console.log(stdout);
res.sendfile(req.files.song.path + ".mp3");
});
}
});
app.listen(process.env.PORT || DEBUG_PORT);
| var DEBUG_PORT = 8000;
var express = require('express');
var sys = require('sys');
var exec = require('child_process').exec;
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.send("Welcome to radiof.at! <form action='/' method='post' enctype='multipart/form-data'><input type='file' name='song' /><input type='submit' /></form>");
});
app.post('/', function(req, res) {
if (req.files.song.type == 'audio/mp3') {
// Convert an MP3
exec('./PROCESSMP3 ' + req.files.song.path, { timeout: 0, maxBuffer: 0 }, function(err, stdout, stderr) {
console.log("We're done!!!");
console.log(stdout);
res.sendfile(req.files.song.path + ".mp3");
});
}
});
app.listen(process.env.PORT || DEBUG_PORT);
|
Create url from user input | const request = require('request');
const yargs = require('yargs');
// 68 Studencheskaya street Engels
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
describe: 'Address to fetch weather for.',
string: true
}
})
.help()
.alias('help', 'h')
.argv;
var url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(argv.address)}`;
request({
url: url,
json: true
}, (error, response, body) => {
console.log(body.results[0].formatted_address);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longitude: ${body.results[0].geometry.location.lng}`);
});
| const request = require('request');
const yargs = require('yargs');
// 68 Studencheskaya street Engels
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
describe: 'Address to fetch weather for.',
string: true
}
})
.help()
.alias('help', 'h')
.argv;
console.log(argv);
request({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address=68%20Studencheskaya%20street%20Engels',
json: true
}, (error, response, body) => {
console.log(body.results[0].formatted_address);
console.log(`Latitude: ${body.results[0].geometry.location.lat}`);
console.log(`Longitude: ${body.results[0].geometry.location.lng}`);
});
|
Change license to Apache 2 | # -*- coding: utf-8 -*-
# Needed to allow import
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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.
# -------------------------------------------------------------------------
"""
This is a doc string, will it be of use?
"""
# RELEASE: MH, MPS | # Needed to allow import
#
# Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser General Public License, V2.1
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://kamaelia.sourceforge.net/AUTHORS - please extend this file,
# not this notice.
# (2) Reproduced in the COPYING file, and at:
# http://kamaelia.sourceforge.net/COPYING
# Under section 3.5 of the MPL, we are using this text since we deem the MPL
# notice inappropriate for this file. As per MPL/GPL/LGPL removal of this
# notice is prohibited.
#
# Please contact us via: kamaelia-list-owner@lists.sourceforge.net
# to discuss alternative licensing.
# -------------------------------------------------------------------------
"""
This is a doc string, will it be of use?
"""
# RELEASE: MH, MPS |
Add click function for myAds link | function startApp() {
// sessionStorage.clear(); // Logout user after refresh web page
showMenuHideLinks();
listItems();
if (sessionStorage.getItem('username')) {
$('#loggedInUser').text('Welcome, ' + sessionStorage.getItem('username') + '!');
$('#loggedInUser').show();
}
$('#infoBox, #errorBox').click(function () {
$(this).fadeOut();
});
$(document).on({
ajaxStart: () => {$('#loadingBox').show()},
ajaxStop: () => {$('#loadingBox').hide()}
});
// Bind the navigation menu links
$('#linkHome').click(showHomeView);
$('#linkLogin').click(showLoginView);
$('#linkRegister').click(showRegisterView);
$('#linkListAds').click(function () {
listItems();
$('#viewHome').hide();
});
$('#linkCreateAd').click(showCreateAdView);
$('#linkMyAds').click(listMyAds);
$('#linkLogout').click(logoutUser);
// Bind the form submit buttons
$('#formLogin').submit(loginUser);
$('#formRegister').submit(registerUser);
$('#formCreateAd').submit(createAdvert);
$('#viewEditAd').submit(editAdvert);
} | function startApp() {
// sessionStorage.clear(); // Logout user after refresh web page
showMenuHideLinks();
listItems();
if (sessionStorage.getItem('username')) {
$('#loggedInUser').text('Welcome, ' + sessionStorage.getItem('username') + '!');
$('#loggedInUser').show();
}
$('#infoBox, #errorBox').click(function () {
$(this).fadeOut();
});
$(document).on({
ajaxStart: () => {$('#loadingBox').show()},
ajaxStop: () => {$('#loadingBox').hide()}
});
// Bind the navigation menu links
$('#linkHome').click(showHomeView);
$('#linkLogin').click(showLoginView);
$('#linkRegister').click(showRegisterView);
$('#linkListAds').click(function () {
listItems();
$('#viewHome').hide();
});
$('#linkCreateAd').click(showCreateAdView);
$('#linkLogout').click(logoutUser);
// Bind the form submit buttons
$('#formLogin').submit(loginUser);
$('#formRegister').submit(registerUser);
$('#formCreateAd').submit(createAdvert);
$('#viewEditAd').submit(editAdvert);
} |
Add last_updated field to RSSContent | from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
last_updated = models.DateTimeField(_('Last updated'), blank=True, null=True)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.last_updated = datetime.now()
self.save()
| from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_content = models.TextField(_('Pre-rendered content'), blank=True, editable=False)
class Meta:
abstract = True
def render(self, **kwargs):
return mark_safe(self.rendered_content)
#u'<div class="rsscontent"> RSS: <a href="'+self.link+'">'+self.link+'</a></div')
def cache_content(self):
print u"Getting RSS feed at %s" % (self.link,)
feed = feedparser.parse(self.link)
print u"Pre-rendering content"
self.rendered_content = render_to_string('rsscontent.html', {
'feed': feed})
self.save()
|
Write back ResponseWriterBinder into BindResponseWriter func | package coreutil
import (
"io"
"net/http"
"reflect"
"github.com/volatile/core"
)
type responseWriterBinder struct {
io.Writer
http.ResponseWriter
before []func([]byte)
}
func (w responseWriterBinder) Write(p []byte) (int, error) {
for _, f := range w.before {
f(p)
}
return w.Writer.Write(p)
}
// BindResponseWriter redirects the downstream response wrinting into a "w" writer that will take care to write back the original "ResponseWriter".
// "before" can be a set of functions that will be triggered juste before writing the repsonse.
func BindResponseWriter(w io.Writer, c *core.Context, before ...func([]byte)) {
c.ResponseWriter = responseWriterBinder{w, c.ResponseWriter, before}
}
// ResponseStatus returns the HTTP response status.
// Remember that the status is only set by the server after "ResponseWriter.WriteHeader()"" has been called.
func ResponseStatus(w http.ResponseWriter) int {
return int(httpResponseStruct(reflect.ValueOf(w)).FieldByName("status").Int())
}
// httpResponseStruct returns the response structure after going trough all the intermediary response writers.
func httpResponseStruct(v reflect.Value) reflect.Value {
switch v.Type().String() {
case "*http.response":
return v.Elem()
default:
return httpResponseStruct(v.FieldByName("ResponseWriter").Elem())
}
}
// SetDetectedContentType detects and sets and returns the response content type.
func SetDetectedContentType(w http.ResponseWriter, p []byte) string {
ct := w.Header().Get("Content-Type")
if ct == "" {
ct = http.DetectContentType(p)
w.Header().Set("Content-Type", ct)
}
return ct
}
| package coreutil
import (
"net/http"
"reflect"
)
// ResponseStatus returns the HTTP response status.
// Remember that the status is only set by the server after "ResponseWriter.WriteHeader()"" has been called.
func ResponseStatus(w http.ResponseWriter) int {
return int(httpResponseStruct(reflect.ValueOf(w)).FieldByName("status").Int())
}
// httpResponseStruct returns the response structure after going trough all the intermediary response writers.
func httpResponseStruct(v reflect.Value) reflect.Value {
switch v.Type().String() {
case "*http.response":
return v.Elem()
default:
return httpResponseStruct(v.FieldByName("ResponseWriter").Elem())
}
}
// SetDetectedContentType detects and sets and returns the response content type.
func SetDetectedContentType(w http.ResponseWriter, b []byte) string {
ct := w.Header().Get("Content-Type")
if ct == "" {
ct = http.DetectContentType(b)
w.Header().Set("Content-Type", ct)
}
return ct
}
|
Use fieldName while building query | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (config, fieldName, boundingBoxCoordinates) {
var geo_bounding_box = JSON.parse(`{"${fieldName}":` + JSON.stringify(boundingBoxCoordinates) + '}');
return ({
type: config.appbase.type,
body: {
"size": 1000,
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
geo_bounding_box
}
}
}
}
});
},
getAppbaseRef: function (config) {
return (
new Appbase({
url: 'https://scalr.api.appbase.io',
appname: config.appbase.appname,
username: config.appbase.username,
password: config.appbase.password
})
);
}
}; | var Appbase = require('appbase-js');
module.exports = {
getRequestObject: function (type, venue) {
return ({
type: type,
body: {
"size": 1000,
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"geo_bounding_box": {
"venue": venue
}
}
}
}
}
});
},
getAppbaseRef: function (config) {
return (
new Appbase({
url: 'https://scalr.api.appbase.io',
appname: config.appbase.appname,
username: config.appbase.username,
password: config.appbase.password
})
);
}
}; |
Add missing null check in GM_menuCommander.onPopupShowing.
This prevents the popup from showing all registered menu commands in windows with file://- and about:-URIs.
Fixes #1424 | Components.utils.import('resource://greasemonkey/util.js');
var GM_MenuCommander = {};
GM_MenuCommander.createMenuItem = function(command) {
var menuItem = document.createElement("menuitem");
menuItem.setAttribute("label", command.name);
if ('function' == typeof command.commandFunc) {
menuItem.addEventListener("command", command.commandFunc, true);
}
if (command.accessKey) {
menuItem.setAttribute("accesskey", command.accessKey);
}
return menuItem;
};
GM_MenuCommander.onPopupShowing = function(aMenuPopup) {
GM_util.emptyEl(aMenuPopup);
// Add menu items for commands for the active window.
var haveCommands = false;
var windowId = GM_util.windowId(gBrowser.contentWindow);
if(windowId) {
GM_BrowserUI.gmSvc.withAllMenuCommandsForWindowId(
windowId,
function(index, command) {
if (command.frozen) return;
aMenuPopup.insertBefore(
GM_MenuCommander.createMenuItem(command),
aMenuPopup.firstChild);
haveCommands = true;
});
}
aMenuPopup.parentNode.disabled = !haveCommands;
};
| Components.utils.import('resource://greasemonkey/util.js');
var GM_MenuCommander = {};
GM_MenuCommander.createMenuItem = function(command) {
var menuItem = document.createElement("menuitem");
menuItem.setAttribute("label", command.name);
if ('function' == typeof command.commandFunc) {
menuItem.addEventListener("command", command.commandFunc, true);
}
if (command.accessKey) {
menuItem.setAttribute("accesskey", command.accessKey);
}
return menuItem;
};
GM_MenuCommander.onPopupShowing = function(aMenuPopup) {
GM_util.emptyEl(aMenuPopup);
// Add menu items for commands for the active window.
var haveCommands = false;
GM_BrowserUI.gmSvc.withAllMenuCommandsForWindowId(
GM_util.windowId(gBrowser.contentWindow),
function(index, command) {
if (command.frozen) return;
aMenuPopup.insertBefore(
GM_MenuCommander.createMenuItem(command),
aMenuPopup.firstChild);
haveCommands = true;
});
aMenuPopup.parentNode.disabled = !haveCommands;
};
|
Fix popup for VPS reinstallation with PHP 5.3 | <?php
include('header.php');
$paquet = new Paquet();
$paquet -> add_action('vpsList');
$paquet -> add_action('vpsTemplate', array($_GET['vps']));
$paquet -> send_actions();
$vps = $paquet->getAnswer('vpsList')->$_GET['vps'];
$list = $paquet->getAnswer('vpsTemplate');
echo '<div class="center">';
printf(_('Reinstall %s, don\'t forget to redefine the root password.'), '<b>'.$vps->name.'</b>');
echo '</div>';
if(!empty($list)) {
echo '<select name="os" id="os" class="form-control">';
foreach ($list as $template) {
if($template == $vps->ostemplate) {
echo '<option value="'.$template.'" selected="selected">'.$template.'</option>';
}
else {
echo '<option value="'.$template.'">'.$template.'</option>';
}
}
echo '</select>';
}
echo '<div class="center">
<button onclick="popupclose()" type="button" class="btn btn-danger" data-toggle="dropdown">'._('Cancel').'</button> '.
'<button onclick="formVpsReinstall('.$_GET['vps'].')" type="button" class="btn btn-success" data-toggle="dropdown">'._('Confirm').'</button>'.
'</div>';
echo '<script type="text/javascript">'.
'$("#popupTitle").html("'._('Reinstall the Vps').'");'.
'</script>';
?>
| <?php
include('header.php');
$paquet = new Paquet();
$paquet -> add_action('vpsList');
$paquet -> add_action('vpsTemplate', array($_GET['vps']));
$paquet -> send_actions();
$vps = $paquet->getAnswer('vpsList')->$_GET['vps'];
echo '<div class="center">';
printf(_('Reinstall %s, don\'t forget to redefine the root password.'), '<b>'.$vps->name.'</b>');
echo '</div>';
if(!empty($paquet->getAnswer('vpsTemplate'))) {
echo '<select name="os" id="os" class="form-control">';
foreach ($paquet->getAnswer('vpsTemplate') as $template) {
if($template == $vps->ostemplate) {
echo '<option value="'.$template.'" selected="selected">'.$template.'</option>';
}
else {
echo '<option value="'.$template.'">'.$template.'</option>';
}
}
echo '</select>';
}
echo '<div class="center">
<button onclick="popupclose()" type="button" class="btn btn-danger" data-toggle="dropdown">'._('Cancel').'</button> '.
'<button onclick="formVpsReinstall('.$_GET['vps'].')" type="button" class="btn btn-success" data-toggle="dropdown">'._('Confirm').'</button>'.
'</div>';
echo '<script type="text/javascript">'.
'$("#popupTitle").html("'._('Reinstall the Vps').'");'.
'</script>';
?> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.