text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add cormapy test suite to e2e test suite
|
#!/usr/bin/env python
# coding: utf-8
"""Run the end to end tests of the project."""
__author__ = "Martha Brennich"
__license__ = "MIT"
__copyright__ = "2020"
__date__ = "11/07/2020"
import sys
import unittest
import e2etest_freesas, e2etest_guinier_apps, e2etest_bift, e2etest_cormap
def suite():
"""Creates suite for e2e tests"""
test_suite = unittest.TestSuite()
test_suite.addTest(e2etest_freesas.suite())
test_suite.addTest(e2etest_guinier_apps.suite())
test_suite.addTest(e2etest_bift.suite())
test_suite.addTest(e2etest_cormap.suite())
return test_suite
if __name__ == "__main__":
runner = unittest.TextTestRunner()
result = runner.run(suite())
if result.wasSuccessful():
EXIT_STATUS = 0
else:
EXIT_STATUS = 1
sys.exit(EXIT_STATUS)
|
#!/usr/bin/env python
# coding: utf-8
"""Run the end to end tests of the project."""
__author__ = "Martha Brennich"
__license__ = "MIT"
__copyright__ = "2020"
__date__ = "11/07/2020"
import sys
import unittest
import e2etest_freesas, e2etest_guinier_apps, e2etest_bift
def suite():
"""Creates suite for e2e tests"""
test_suite = unittest.TestSuite()
test_suite.addTest(e2etest_freesas.suite())
test_suite.addTest(e2etest_guinier_apps.suite())
test_suite.addTest(e2etest_bift.suite())
return test_suite
if __name__ == "__main__":
runner = unittest.TextTestRunner()
result = runner.run(suite())
if result.wasSuccessful():
EXIT_STATUS = 0
else:
EXIT_STATUS = 1
sys.exit(EXIT_STATUS)
|
Remove import of old routes
|
// We only need to import the modules necessary for initial render
import CoreLayout from '../layouts/CoreLayout/CoreLayout'
import TogglRoute from './Toggl'
/* Note: Instead of using JSX, we recommend using react-router
PlainRoute objects to build route definitions. */
export const createRoutes = (store) => ({
path: '/',
component: CoreLayout,
indexRoute: TogglRoute(store),
childRoutes: [ ]
})
/* Note: childRoutes can be chunked or otherwise loaded programmatically
using getChildRoutes with the following signature:
getChildRoutes (location, cb) {
require.ensure([], (require) => {
cb(null, [
// Remove imports!
require('./Counter').default(store)
])
})
}
However, this is not necessary for code-splitting! It simply provides
an API for async route definitions. Your code splitting should occur
inside the route `getComponent` function, since it is only invoked
when the route exists and matches.
*/
export default createRoutes
|
// We only need to import the modules necessary for initial render
import CoreLayout from '../layouts/CoreLayout/CoreLayout'
import Home from './Home'
import CounterRoute from './Counter'
import TogglRoute from './Toggl'
/* Note: Instead of using JSX, we recommend using react-router
PlainRoute objects to build route definitions. */
export const createRoutes = (store) => ({
path: '/',
component: CoreLayout,
indexRoute: TogglRoute(store),
childRoutes: [ ]
})
/* Note: childRoutes can be chunked or otherwise loaded programmatically
using getChildRoutes with the following signature:
getChildRoutes (location, cb) {
require.ensure([], (require) => {
cb(null, [
// Remove imports!
require('./Counter').default(store)
])
})
}
However, this is not necessary for code-splitting! It simply provides
an API for async route definitions. Your code splitting should occur
inside the route `getComponent` function, since it is only invoked
when the route exists and matches.
*/
export default createRoutes
|
TODO: ADD FUNCTIONS AND ARGUMENTS. YOU'LL PROBABLY NEED TO DEBUG
|
#!/ usr/bin/python
#Black Hat Python SSH with Paramiko pg 26
#TODO: ADD FUNCTIONS AND ARGUMENTS, AND DONT FORGET TO DEBUG.
import threading, paramiko, subprocess
def ssh_command(ip, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/justin/.ssh/known_hosts')
client.set_missing_host_key_policy(paramoko.AutoAddPolicy())
client.connect(ip, usernmae= user, password= passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(1024) #read banner
while True:
command = ssh_session.recv(1024) #get the command from the SSH server
try:
cmd_output = subprocess.check_output(command, shell=True)
ssh_session.send(cmd_output)
excelpt: Exceptoin,e:
ssh_session.send(str(e))
client.close()
return
ssh_command('192.168.100.131', 'justin', 'lovesthepython','id')
#End of Program
|
#!/ usr/bin/python
#Black Hat Python
#SSH with Paramiko
#pg 26
import threading, paramiko, subprocess
def ssh_command(ip, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/justin/.ssh/known_hosts')
client.set_missing_host_key_policy(paramoko.AutoAddPolicy())
client.connect(ip, usernmae= user, password= passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(1024) #read banner
while True:
command = ssh_session.recv(1024) #get the command from the SSH server
try:
cmd_output = subprocess.check_output(command, shell=True)
ssh_session.send(cmd_output)
excelpt: Exceptoin,e:
ssh_session.send(str(e))
client.close()
return
ssh_command('192.168.100.131', 'justin', 'lovesthepython','id')
#End of Program
|
Add charset to HTML5 doc (and make more XHTML friendly)
git-svn-id: e52e7dec99011c9686d89c3d3c01e7ff0d333eee@2609 eee81c28-f429-11dd-99c0-75d572ba1ddd
|
<!DOCTYPE html>
<?php
/*
* fileopen.php
* To be used with ext-server_opensave.js for SVG-edit
*
* Licensed under the MIT License
*
* Copyright(c) 2010 Alexis Deveria
*
*/
// Very minimal PHP file, all we do is Base64 encode the uploaded file and
// return it to the editor
$file = $_FILES['svg_file']['tmp_name'];
$output = file_get_contents($file);
$type = $_REQUEST['type'];
$prefix = '';
// Make Data URL prefix for import image
if($type == 'import_img') {
$info = getimagesize($file);
$prefix = 'data:' . $info['mime'] . ';base64,';
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>
</head><body></body>
</html>
|
<!doctype html>
<?php
/*
* fileopen.php
* To be used with ext-server_opensave.js for SVG-edit
*
* Licensed under the MIT License
*
* Copyright(c) 2010 Alexis Deveria
*
*/
// Very minimal PHP file, all we do is Base64 encode the uploaded file and
// return it to the editor
$file = $_FILES['svg_file']['tmp_name'];
$output = file_get_contents($file);
$type = $_REQUEST['type'];
$prefix = '';
// Make Data URL prefix for import image
if($type == 'import_img') {
$info = getimagesize($file);
$prefix = 'data:' . $info['mime'] . ';base64,';
}
?>
<script>
window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>");
</script>
|
Test change for retina branch
|
package main.powercalc;
public class DataTuple {
private double lat;
private double lon;
private double data;
DataTuple() {
this.lat = 0.0;
this.lon = 0.0;
this.data = 0.0;
}
DataTuple(double lat, double lon, double data) {
this.lat = lat;
this.lon = lon;
this.data = data;
}
DataTuple(DataTuple dt) {
this.lat = dt.getLat();
this.lon = dt.getLon();
this.data = dt.getData();
}
/**
* @return the lat
*/
public double getLat() {
return lat;
}
/**
* @param lat the lat to set
*/
public void setLat(double lat) {
this.lat = lat;
}
/**
* @return the lon
*/
public double getLon() {
return lon;
}
/**
* @param lon the lon to set
*/
public void setLon(double lon) {
this.lon = lon;
}
/**
* @return the data
*/
public double getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(double data) {
this.data = data;
}
}
|
package main.powercalc;
public class DataTuple {
private double lat;
private double lon;
private double data;
DataTuple() {
this.lat = 0.0;
this.lon = 0.0;
this.data = 0.0;
}
DataTuple(double lat, double lon, double data) {
this.lat = lat;
this.lon = lon;
this.data = data;
}
DataTuple(DataTuple dt) {
this.lat = dt.getLat();
this.lon = dt.getLon();
this.data = dt.getData();
}
/**
* @return the lat
*/
public double getLat() {
return lat;
}
/**
* @param lat the lat to set
*/
public void setLat(double lat) {
this.lat = lat;
}
/**
* @return the lon
*/
public double getLon() {
return lon;
}
/**
* @param lon the lon to set
*/
public void setLon(double lon) {
this.lon = lon;
}
/**
* @return the data
*/
public double getData() {
return data;
}
/**
* @param data the data to set
*/
public void setData(double data) {
this.data = data;
}
}
|
Move comments to public javadocs
|
/*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache 2.0 License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.squidb.processor.data;
import com.yahoo.aptutils.model.DeclaredTypeName;
/**
* Tuple class to hold logged error info, to be written by the
* {@link com.yahoo.squidb.processor.plugins.defaults.ErrorLoggingPlugin}.
*/
public final class ErrorInfo {
/**
* The class on which to log the error
*/
public final DeclaredTypeName errorClass;
/**
* The specific element on which to log the error (or null/empty to log on the class)
*/
public final String element;
/**
* The error message to log
*/
public final String message;
public ErrorInfo(DeclaredTypeName errorClass, String element, String message) {
this.errorClass = errorClass;
this.element = element;
this.message = message;
}
}
|
/*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache 2.0 License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.squidb.processor.data;
import com.yahoo.aptutils.model.DeclaredTypeName;
/**
* Tuple class to hold logged error info, to be written by the
* {@link com.yahoo.squidb.processor.plugins.defaults.ErrorLoggingPlugin}.
*/
public final class ErrorInfo {
public final DeclaredTypeName errorClass; // The class on which to log the error
public final String element; // The specific element on which to log the error (or null/empty to log on the class)
public final String message; // The error message to log
public ErrorInfo(DeclaredTypeName errorClass, String element, String message) {
this.errorClass = errorClass;
this.element = element;
this.message = message;
}
}
|
Add a harder test example.
|
import numpy as np
import matplotlib.pyplot as pl
import pygp as pg
import pybo.models as pbm
import pybo.policies as pbp
def run_model(Model, sn, ell, sf, T):
model = Model(0.2)
gp = pg.BasicGP(sn, ell, sf)
policy = pbp.GPUCB(gp, model.bounds)
xmin = model.bounds[0][0]
xmax = model.bounds[0][1]
X = np.linspace(xmin, xmax, 200)[:, None]
x = (xmax-xmin) / 2
for i in xrange(T):
pg.gpplot(policy.gp, xmin=xmin, xmax=xmax)
pl.plot(X, policy.get_index(X), lw=2)
pl.axvline(x, color='r')
pl.axis('tight')
pl.axis(xmin=xmin, xmax=xmax)
pl.draw()
y = model.get_data(x)
policy.add_data(x, y)
x = policy.get_next()
if __name__ == '__main__':
# run_model(pbm.Sinusoidal, 0.2, 0.70, 1.25, 100)
run_model(pbm.Gramacy, 0.2, 0.05, 1.25, 100)
|
import numpy as np
import matplotlib.pyplot as pl
import pygp as pg
import pybo.models as pbm
import pybo.policies as pbp
if __name__ == '__main__':
sn = 0.2
ell = 0.670104947766
sf = 1.25415619045
model = pbm.Sinusoidal(0.2)
gp = pg.BasicGP(sn, ell, sf)
policy = pbp.GPUCB(gp, model.bounds)
xmin = model.bounds[0][0]
xmax = model.bounds[0][1]
X = np.linspace(xmin, xmax, 200)[:, None]
x = (xmax-xmin) / 2
for i in xrange(40):
pg.gpplot(policy.gp, xmin=xmin, xmax=xmax)
pl.plot(X, policy.get_index(X), lw=2)
pl.axvline(x, color='r')
pl.axis('tight')
pl.axis(xmin=xmin, xmax=xmax)
pl.draw()
y = model.get_data(x)
policy.add_data(x, y)
x = policy.get_next()
|
Correct documented event names for VectorSourceEvent
|
/**
* @module ol/source/VectorEventType
*/
/**
* @enum {string}
*/
export default {
/**
* Triggered when a feature is added to the source.
* @event module:ol/source/Vector.VectorSourceEvent#addfeature
* @api
*/
ADDFEATURE: 'addfeature',
/**
* Triggered when a feature is updated.
* @event module:ol/source/Vector.VectorSourceEvent#changefeature
* @api
*/
CHANGEFEATURE: 'changefeature',
/**
* Triggered when the clear method is called on the source.
* @event module:ol/source/Vector.VectorSourceEvent#clear
* @api
*/
CLEAR: 'clear',
/**
* Triggered when a feature is removed from the source.
* See {@link module:ol/source/Vector#clear source.clear()} for exceptions.
* @event module:ol/source/Vector.VectorSourceEvent#removefeature
* @api
*/
REMOVEFEATURE: 'removefeature',
/**
* Triggered when features starts loading.
* @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart
* @api
*/
FEATURESLOADSTART: 'featuresloadstart',
/**
* Triggered when features finishes loading.
* @event module:ol/source/Vector.VectorSourceEvent#featuresloadend
* @api
*/
FEATURESLOADEND: 'featuresloadend',
/**
* Triggered if feature loading results in an error.
* @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror
* @api
*/
FEATURESLOADERROR: 'featuresloaderror',
};
|
/**
* @module ol/source/VectorEventType
*/
/**
* @enum {string}
*/
export default {
/**
* Triggered when a feature is added to the source.
* @event module:ol/source/Vector.VectorSourceEvent#addfeature
* @api
*/
ADDFEATURE: 'addfeature',
/**
* Triggered when a feature is updated.
* @event module:ol/source/Vector.VectorSourceEvent#changefeature
* @api
*/
CHANGEFEATURE: 'changefeature',
/**
* Triggered when the clear method is called on the source.
* @event module:ol/source/Vector.VectorSourceEvent#clear
* @api
*/
CLEAR: 'clear',
/**
* Triggered when a feature is removed from the source.
* See {@link module:ol/source/Vector#clear source.clear()} for exceptions.
* @event module:ol/source/Vector.VectorSourceEvent#removefeature
* @api
*/
REMOVEFEATURE: 'removefeature',
/**
* Triggered when features starts loading.
* @event module:ol/source/Vector.VectorSourceEvent#featureloadstart
* @api
*/
FEATURESLOADSTART: 'featuresloadstart',
/**
* Triggered when features finishes loading.
* @event module:ol/source/Vector.VectorSourceEvent#featureloadend
* @api
*/
FEATURESLOADEND: 'featuresloadend',
/**
* Triggered if feature loading results in an error.
* @event module:ol/source/Vector.VectorSourceEvent#featureloaderror
* @api
*/
FEATURESLOADERROR: 'featuresloaderror',
};
|
Add playlist folder and playlist index in title if there is one
|
import { getBaseDestination } from '../storage/storage';
const youtubedl = require('youtube-dl');
const path = require('path');
const fs = require('fs');
const { remote } = require('electron');
export var init = function () { };
export var downloadVideo = function (link, onInfo, onError, onEnd) {
let filePath;
const baseDestination = getBaseDestination();
if (! fs.existsSync(baseDestination)) {
fs.mkdirSync(baseDestination);
}
const video = youtubedl(
link,
['--format=18'],
{ cwd: baseDestination }
);
video.on('info', function (info) {
onInfo(info);
const destination = getDestination(baseDestination, info);
if (! fs.existsSync(destination)) {
fs.mkdirSync(destination);
}
filePath = getFilePath(destination, info);
video.pipe(fs.createWriteStream(filePath));
});
video.on('error', onError);
video.on('end', () => {
console.log('finished downloading!');
onEnd(filePath);
});
};
function getDestination(baseDestination, info) {
if (info.playlist === null || info.playlist === 'NA') {
return path.join(baseDestination, info.uploader);
}
return path.join(baseDestination, info.uploader, info.playlist);
}
function getFilePath(destination, info) {
if (info.playlist_index === null || info.playlist_index === 'NA') {
return path.join(destination, info._filename);
}
return path.join(destination, info.playlist_index + ' - ' + info._filename);
}
|
import { getBaseDestination } from '../storage/storage';
const youtubedl = require('youtube-dl');
const path = require('path');
const fs = require('fs');
const { remote } = require('electron');
export var init = function () { };
export var downloadVideo = function (link, onInfo, onError, onEnd) {
let filePath;
const baseDestination = getBaseDestination();
if (! fs.existsSync(baseDestination)) {
fs.mkdirSync(baseDestination);
}
const video = youtubedl(
link,
['--format=18'],
{ cwd: baseDestination }
);
video.on('info', function (info) {
onInfo(info);
const destination = getDestination(baseDestination, info);
if (! fs.existsSync(destination)) {
fs.mkdirSync(destination);
}
filePath = path.join(destination, info._filename);
video.pipe(fs.createWriteStream(filePath));
});
video.on('error', onError);
video.on('end', () => {
console.log('finished downloading!');
onEnd(filePath);
});
};
function getDestination(baseDestination, info) {
return path.join(baseDestination, info.uploader);
}
|
Use global form of 'use strict' in gruntfile template file
|
'use strict';
const {join} = require('path');
const config = require('config').grunt;
module.exports = function(grunt) {
grunt.initConfig({
package: grunt.file.readJSON('package.json'),
ports: config.ports,
folders: config.folders,
files: config.files,
deployed: {
assets: config.folders.assets.split('/')[1],
images: config.files.images.split('/')[0],
fonts: config.files.fonts.split('/')[0]
}
});
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
/* -- load tasks placeholder -- */
};
|
const {join} = require('path');
const config = require('config').grunt;
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
package: grunt.file.readJSON('package.json'),
ports: config.ports,
folders: config.folders,
files: config.files,
deployed: {
assets: config.folders.assets.split('/')[1],
images: config.files.images.split('/')[0],
fonts: config.files.fonts.split('/')[0]
}
});
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
/* -- load tasks placeholder -- */
};
|
Exclude app dir from package
|
#!/usr/bin/env python
from __future__ import unicode_literals
from wagtail_mvc import __version__
from setuptools import setup, find_packages
setup(
name='wagtail_mvc',
version=__version__,
description='Allows better separation between '
'models and views in Wagtail CMS',
author='Dan Stringer',
author_email='dan.stringer1983@googlemail.com',
url='https://github.com/fatboystring/Wagtail-MVC/',
download_url='https://github.com/fatboystring/Wagtail-MVC/tarball/0.1.0',
packages=find_packages(exclude=['app']),
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
include_package_data=True,
keywords=['wagtail', 'django', 'mvc'],
install_requires=[]
)
|
#!/usr/bin/env python
from __future__ import unicode_literals
from wagtail_mvc import __version__
from setuptools import setup, find_packages
setup(
name='wagtail_mvc',
version=__version__,
description='Allows better separation between '
'models and views in Wagtail CMS',
author='Dan Stringer',
author_email='dan.stringer1983@googlemail.com',
url='https://github.com/fatboystring/Wagtail-MVC/',
download_url='https://github.com/fatboystring/Wagtail-MVC/tarball/0.1.0',
packages=find_packages(),
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
include_package_data=True,
keywords=['wagtail', 'django', 'mvc'],
install_requires=[]
)
|
Add lint to the default task
|
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var bs = require('browser-sync').create();
var del = require('del');
gulp.task('lint', function () {
return gulp.src('app/js/**/*.js')
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failAfterError());
});
gulp.task('serve', function () {
bs.init({
notify: false,
port: 9000,
open: true,
server: {
baseDir: ['app']
}
});
gulp.watch([
'app/**/*.html',
'app/js/**/*.js'
]).on('change', bs.reload);
gulp.watch('app/js/**/*.js', ['lint']);
});
gulp.task('clean', del.bind(null, ['dist']));
gulp.task('scripts', function () {
return gulp.src('app/js/**/*.js')
.pipe($.uglify())
.pipe(gulp.dest('dist/js'));
});
gulp.task('html', function () {
return gulp.src('app/**/*.html')
.pipe($.htmlmin({
collapseWhitespace: true
}))
.pipe(gulp.dest('dist'));
});
gulp.task('build', ['clean'], function (callback) {
runSequence(['scripts', 'html'], callback);
});
gulp.task('default', function (callback) {
runSequence('lint', 'build', callback);
});
|
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var runSequence = require('run-sequence');
var bs = require('browser-sync').create();
var del = require('del');
gulp.task('lint', function () {
return gulp.src('app/js/**/*.js')
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failAfterError());
});
gulp.task('serve', function () {
bs.init({
notify: false,
port: 9000,
open: true,
server: {
baseDir: ['app']
}
});
gulp.watch([
'app/**/*.html',
'app/js/**/*.js'
]).on('change', bs.reload);
gulp.watch('app/js/**/*.js', ['lint']);
});
gulp.task('clean', del.bind(null, ['dist']));
gulp.task('scripts', function () {
return gulp.src('app/js/**/*.js')
.pipe($.uglify())
.pipe(gulp.dest('dist/js'));
});
gulp.task('html', function () {
return gulp.src('app/**/*.html')
.pipe($.htmlmin({
collapseWhitespace: true
}))
.pipe(gulp.dest('dist'));
});
gulp.task('build', ['clean'], function (callback) {
runSequence(['scripts', 'html'], callback);
});
gulp.task('default', ['build']);
|
Move Flickr over to its newly-secured API domain
|
import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/oauth/request_token'
authorize_url = 'http://www.flickr.com/services/oauth/authorize'
access_token_url = 'http://www.flickr.com/services/oauth/access_token'
api_domain = 'api.flickr.com'
available_permissions = [
(None, 'access your public and private photos'),
('write', 'upload, edit and replace your photos'),
('delete', 'upload, edit, replace and delete your photos'),
]
permissions_widget = 'radio'
def get_authorize_params(self, redirect_uri, scopes):
params = super(Flickr, self).get_authorize_params(redirect_uri, scopes)
params['perms'] = scopes[0] or 'read'
return params
def get_user_id(self, key):
url = u'/services/rest/?method=flickr.people.getLimits'
url += u'&format=json&nojsoncallback=1'
r = self.api(key, self.api_domain, url)
return r.json()[u'person'][u'nsid']
|
import foauth.providers
class Flickr(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'http://www.flickr.com/'
docs_url = 'http://www.flickr.com/services/api/'
category = 'Pictures'
# URLs to interact with the API
request_token_url = 'http://www.flickr.com/services/oauth/request_token'
authorize_url = 'http://www.flickr.com/services/oauth/authorize'
access_token_url = 'http://www.flickr.com/services/oauth/access_token'
api_domain = 'secure.flickr.com'
available_permissions = [
(None, 'access your public and private photos'),
('write', 'upload, edit and replace your photos'),
('delete', 'upload, edit, replace and delete your photos'),
]
permissions_widget = 'radio'
def get_authorize_params(self, redirect_uri, scopes):
params = super(Flickr, self).get_authorize_params(redirect_uri, scopes)
params['perms'] = scopes[0] or 'read'
return params
def get_user_id(self, key):
url = u'/services/rest/?method=flickr.people.getLimits'
url += u'&format=json&nojsoncallback=1'
r = self.api(key, self.api_domain, url)
return r.json()[u'person'][u'nsid']
|
Call back a simpler Error object if a package was not found on Bower
|
/**
* @module bowerPackageURL
* @author Matthew Hasbach
* @copyright Matthew Hasbach 2015
* @license MIT
*/
/**
* The bowerPackageURL callback
* @callback bowerPackageURLCallback
* @param {Object} err - An error object if an error occurred
* @param {string} url - The repository URL associated with the provided bower package name
*/
/**
* Get the repository URL associated with a bower package name
* @alias module:bowerPackageURL
* @param {string} packageName - A bower package name
* @param {bowerPackageURLCallback} cb - A callback to be executed after the repository URL is collected
* @example
bowerPackageURL('lodash', function(err, url) {
if (err) { console.error(err); }
console.log(url);
});
*/
function bowerPackageURL(packageName, cb) {
if (typeof cb !== 'function') {
throw new TypeError('cb must be a function');
}
if (typeof packageName !== 'string') {
cb(new TypeError('packageName must be a string'));
return;
}
http.get('https://bower.herokuapp.com/packages/' + packageName)
.end(function(err, res) {
if (err && err.status === 404) {
err = new Error('Package ' + packageName + ' not found on Bower');
}
cb(err, res.body.url);
});
}
|
/**
* @module bowerPackageURL
* @author Matthew Hasbach
* @copyright Matthew Hasbach 2015
* @license MIT
*/
/**
* The bowerPackageURL callback
* @callback bowerPackageURLCallback
* @param {Object} err - An error object if an error occurred
* @param {string} url - The repository URL associated with the provided bower package name
*/
/**
* Get the repository URL associated with a bower package name
* @alias module:bowerPackageURL
* @param {string} packageName - A bower package name
* @param {bowerPackageURLCallback} cb - A callback to be executed after the repository URL is collected
* @example
bowerPackageURL('lodash', function(err, url) {
if (err) { console.error(err); }
console.log(url);
});
*/
function bowerPackageURL(packageName, cb) {
if (typeof cb !== 'function') {
throw new TypeError('cb must be a function');
}
if (typeof packageName !== 'string') {
cb(new TypeError('packageName must be a string'));
return;
}
http.get('https://bower.herokuapp.com/packages/' + packageName)
.end(function(err, res) {
cb(err, res.body.url);
});
}
|
Add format string to debug message.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: %s", source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip %s", source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: ", self, source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip ", self, source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
|
Set a connection timeout for DevTools methods
Close #194
|
'use strict';
const REQUEST_TIMEOUT = 10000;
// callback(err, data)
function externalRequest(transport, options, callback) {
const request = transport.get(options, function (response) {
let data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
if (response.statusCode === 200) {
callback(null, data);
} else {
callback(new Error(data));
}
});
});
request.setTimeout(REQUEST_TIMEOUT, function () {
this.abort();
});
request.on('error', function (err) {
callback(err);
});
}
module.exports = externalRequest;
|
'use strict';
// callback(err, data)
function externalRequest(transport, options, callback) {
const request = transport.get(options, function (response) {
let data = '';
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
if (response.statusCode === 200) {
callback(null, data);
} else {
callback(new Error(data));
}
});
});
request.on('error', function (err) {
callback(err);
});
}
module.exports = externalRequest;
|
Call celery task directly from management command instead of calling the signal
AA-461
|
"""
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
class Command(BaseCommand):
"""
Export course metadata for all courses
"""
help = 'Export course metadata for all courses'
def handle(self, *args, **options):
"""
Execute the command
"""
export_course_metadata_for_all_courses()
def export_course_metadata_for_all_courses():
"""
Export course metadata for all courses
"""
module_store = modulestore()
courses = module_store.get_courses()
for course in courses:
export_course_metadata_task.delay(str(course.id))
|
"""
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
class Command(BaseCommand):
"""
Export course metadata for all courses
"""
help = 'Export course metadata for all courses'
def handle(self, *args, **options):
"""
Execute the command
"""
export_course_metadata_for_all_courses()
def export_course_metadata_for_all_courses():
"""
Export course metadata for all courses
"""
module_store = modulestore()
courses = module_store.get_courses()
for course in courses:
export_course_metadata(None, course.id)
|
Fix git locator behavior in worktree environment
|
<?php
declare(strict_types=1);
namespace GrumPHP\Locator;
use GrumPHP\Util\Filesystem;
class GitRepositoryDirLocator
{
/**
* @var Filesystem
*/
private $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* Resolves the path to the git repository directory (aka as .git).
* For submodules, it parses the .git file and resolves to the .git/modules/[submodules] directory
*/
public function locate(string $gitDir): string
{
if (!$this->filesystem->isFile($gitDir)) {
return $gitDir;
}
$content = $this->filesystem->readPath($gitDir);
if (!preg_match('/gitdir:\s+(\S+)/', $content, $matches)) {
return $gitDir;
}
$gitRepositoryDir = $matches[1];
if ($this->filesystem->isAbsolutePath($gitRepositoryDir)) {
return $gitRepositoryDir;
}
return $this->filesystem->buildPath(
dirname($gitDir),
$gitRepositoryDir
);
}
}
|
<?php
declare(strict_types=1);
namespace GrumPHP\Locator;
use GrumPHP\Util\Filesystem;
class GitRepositoryDirLocator
{
/**
* @var Filesystem
*/
private $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* Resolves the path to the git repository directory (aka as .git).
* For submodules, it parses the .git file and resolves to the .git/modules/[submodules] directory
*/
public function locate(string $gitDir): string
{
if (!$this->filesystem->isFile($gitDir)) {
return $gitDir;
}
$content = $this->filesystem->readPath($gitDir);
if (!preg_match('/gitdir:\s+(\S+)/', $content, $matches)) {
return $gitDir;
}
$gitRepositoryDir = $matches[1];
return $this->filesystem->buildPath(
dirname($gitDir),
$gitRepositoryDir
);
}
}
|
Change default format to ics instead of ical
|
from rest_framework import renderers
from icalendar import Calendar, Event
class ICalRenderer(renderers.BaseRenderer):
media_type = 'text/calendar'
format = 'ics'
def render(self, data, media_type=None, renderer_context=None):
cal = Calendar()
cal.add('prodid', 'talks.ox.ac.uk')
cal.add('version', '2.0')
for e in data:
cal.add_component(self._event_to_ics(e))
return cal.to_ical()
@staticmethod
def _event_to_ics(e):
event = Event()
if 'title' in e:
event.add('summary', e['title'])
if 'description' in e:
event.add('description', e['description'])
if 'start' in e:
event.add('dtstart', e['start'])
if 'url' in e:
event.add('url', e['url'])
event.add('uid', e['url'])
# TODO add location field
return event
|
from rest_framework import renderers
from icalendar import Calendar, Event
class ICalRenderer(renderers.BaseRenderer):
media_type = 'text/calendar'
format = 'ical'
def render(self, data, media_type=None, renderer_context=None):
cal = Calendar()
cal.add('prodid', 'talks.ox.ac.uk')
cal.add('version', '2.0')
for e in data:
cal.add_component(self._event_to_ics(e))
return cal.to_ical()
@staticmethod
def _event_to_ics(e):
event = Event()
if 'title' in e:
event.add('summary', e['title'])
if 'description' in e:
event.add('description', e['description'])
if 'start' in e:
event.add('dtstart', e['start'])
if 'url' in e:
event.add('url', e['url'])
event.add('uid', e['url'])
# TODO add location field
return event
|
Implement localization and fix existing localization to match changes
|
/* This file is part of MusicalRegions for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.bukkit.musical;
import com.jcwhatever.bukkit.generic.language.Localized;
public class Lang {
private Lang() {}
@Localized
public static String get(String text, Object... params) {
return MusicalRegions.getInstance().getLanguageManager().get(text, params);
}
}
|
/* This file is part of MusicalRegions for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.bukkit.musical;
import com.jcwhatever.bukkit.generic.language.LanguageManager;
import com.jcwhatever.bukkit.generic.language.Localized;
public class Lang {
private Lang() {}
private static LanguageManager _languageManager = new LanguageManager();
@Localized
public static String get(String text, Object... params) {
return _languageManager.get(MusicalRegions.getInstance(), text, params);
}
}
|
Handle PY3 default data conversion vagaries in unit test
|
from django.core.urlresolvers import reverse_lazy, reverse
from django import forms
from .models import Author
from popupcrud.views import PopupCrudViewSet
# Create your views here.
class AuthorForm(forms.ModelForm):
sex = forms.ChoiceField(label="Sex", choices=(('M', 'Male'), ('F', 'Female')))
class Meta:
model = Author
fields = ('name', 'age')
class AuthorCrudViewset(PopupCrudViewSet):
model = Author
fields = ('name', 'age')
list_display = ('name', 'age', 'half_age', 'double_age')
list_url = reverse_lazy("authors")
new_url = reverse_lazy("new-author")
"""
form_class = AuthorForm
list_permission_required = ('tests.add_author',)
create_permission_required = ('tests.add_author',)
update_permission_required = ('tests.change_author',)
delete_permission_required = ('tests.delete_author',)
"""
def half_age(self, author):
return int(author.age/2)
half_age.label = "Half Age"
def get_edit_url(self, obj):
return reverse("edit-author", kwargs={'pk': obj.pk})
def get_delete_url(self, obj):
return reverse("delete-author", kwargs={'pk': obj.pk})
|
from django.core.urlresolvers import reverse_lazy, reverse
from django import forms
from .models import Author
from popupcrud.views import PopupCrudViewSet
# Create your views here.
class AuthorForm(forms.ModelForm):
sex = forms.ChoiceField(label="Sex", choices=(('M', 'Male'), ('F', 'Female')))
class Meta:
model = Author
fields = ('name', 'age')
class AuthorCrudViewset(PopupCrudViewSet):
model = Author
fields = ('name', 'age')
list_display = ('name', 'age', 'half_age', 'double_age')
list_url = reverse_lazy("authors")
new_url = reverse_lazy("new-author")
"""
form_class = AuthorForm
list_permission_required = ('tests.add_author',)
create_permission_required = ('tests.add_author',)
update_permission_required = ('tests.change_author',)
delete_permission_required = ('tests.delete_author',)
"""
def half_age(self, author):
return author.age/2
half_age.label = "Half Age"
def get_edit_url(self, obj):
return reverse("edit-author", kwargs={'pk': obj.pk})
def get_delete_url(self, obj):
return reverse("delete-author", kwargs={'pk': obj.pk})
|
Use const in place of var
|
import test from 'ava'
import gutil from 'gulp-util'
import gulpCssScss from './'
test('converts CSS to Scss', t => {
t.plan(2)
const cssScssStream = gulpCssScss();
const actual = ':root {\n --blue: blue;\n}\n\n.some-class {\n color: var(--blue);\n}\n\n';
const expected = '\n// Converted Variables\n\n$blue: blue !default;\n\n// Custom Media Query Variables\n\n\n.some-class {\n color: $blue;\n}\n\n';
cssScssStream.once('data', file => {
t.same(file.relative, 'default.scss');
t.same(file.contents.toString(), expected);
});
cssScssStream.write(new gutil.File({
path: 'default.css',
contents: new Buffer(actual)
}));
cssScssStream.end();
});
|
import test from 'ava'
import gutil from 'gulp-util'
import gulpCssScss from './'
test('converts CSS to Scss', t => {
t.plan(2)
var cssScssStream = gulpCssScss();
var actual = ':root {\n --blue: blue;\n}\n\n.some-class {\n color: var(--blue);\n}\n\n';
var expected = '\n// Converted Variables\n\n$blue: blue !default;\n\n// Custom Media Query Variables\n\n\n.some-class {\n color: $blue;\n}\n\n';
cssScssStream.once('data', file => {
t.same(file.relative, 'default.scss');
t.same(file.contents.toString(), expected);
});
cssScssStream.write(new gutil.File({
path: 'default.css',
contents: new Buffer(actual)
}));
cssScssStream.end();
});
|
Correct the --omit parameter for coverage.py
Despite what some things on the web suggest, you seem to need
to have a wildcard at the end of a path in the --omit list.
|
#!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')/*"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search \
tasks \
user_profile
coverage run --omit=$OMIT ./manage.py test --selenium-only \
core \
feedback \
user_profile
coverage html -d mzalendo-coverage
|
#!/bin/bash
find . -name '*.pyc' -delete
coverage erase
OMIT="$(python -c 'import sys; print sys.prefix')"
coverage run --omit=$OMIT ./manage.py test \
core \
feedback \
hansard \
helpers \
images \
info \
scorecards \
search \
tasks \
user_profile
coverage run --omit=$OMIT ./manage.py test --selenium-only \
core \
feedback \
user_profile
coverage html -d mzalendo-coverage
|
Remove currently shown card when all results are filtered out.
|
function addRowListeners(tableIdentifier) {
$(tableIdentifier + ' tr').click(function() {
selectDetailCard(this);
});
}
function selectFirstCard(tableIdentifier) {
if ($(tableIdentifier + ' tr:visible').length) {
selectDetailCard($(tableIdentifier + ' tr:visible').first(), true);
} else {
var type = $(tableIdentifier).attr('id');
$('#' + type + '-card').html('');
}
}
function selectDetailCard(me, initializing) {
$(me).parent().children('tr.active').removeClass('active');
$(me).addClass('active');
var rowId = $(me).attr('id');
$('#' + rowId + '-card').show();
var arrayIndex = parseInt(rowId.split('-')[1]);
var type = $(me).parents('table').attr('id');
var element = results[type][arrayIndex];
$.ajax({
url: '/search/renderCard',
method: 'POST',
data: {
json: JSON.stringify(element),
type: type
},
success: function(data) {
$('#' + type + '-card').html(data);
$('#' + type + '-card [data-content]').popup({
position: 'top center'
});
}
});
}
function jump(h) {
var top = document.getElementById(h).offsetTop;
window.scrollTo(0, top);
}
|
function addRowListeners(tableIdentifier) {
$(tableIdentifier + ' tr').click(function() {
selectDetailCard(this);
});
}
function selectFirstCard(tableIdentifier) {
if ($(tableIdentifier + ' tr:visible').length) {
selectDetailCard($(tableIdentifier + ' tr:visible').first(), true);
}
}
function selectDetailCard(me, initializing) {
$(me).parent().children('tr.active').removeClass('active');
$(me).addClass('active');
var rowId = $(me).attr('id');
$('#' + rowId + '-card').show();
var arrayIndex = parseInt(rowId.split('-')[1]);
var type = $(me).parents('table').attr('id');
var element = results[type][arrayIndex];
$.ajax({
url: '/search/renderCard',
method: 'POST',
data: {
json: JSON.stringify(element),
type: type
},
success: function(data) {
$('#' + type + '-card').html(data);
$('#' + type + '-card [data-content]').popup({
position: 'top center'
});
}
});
}
function jump(h) {
var top = document.getElementById(h).offsetTop;
window.scrollTo(0, top);
}
|
Update server site for osmlive reports
|
<?php
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
$c = new Memcached();
$c->addServer("localhost", 11211);
foreach($c->getAllKeys() as $key) {
if(startsWith($key, "qreport_")) {
$time_start = microtime(true);
$query = substr($key, strlen("qreport_")) ;
echo "====== QUERY $query ======\n";
echo file_get_contents("http://builder.osmand.net/reports/query_report?".$query."&force=true");
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "\n====== DONE $time seconds ======\n";
}
}
// var_dump( $c->getAllKeys() );
?>
|
<?php
function startsWith($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
$c = new Memcached();
$c->addServer("localhost", 11211);
foreach($c->getAllKeys() as $key) {
if(startsWith($key, "qreport_")) {
$time_start = microtime(true);
$query = substr($key, strlen("qreport_")) ;
echo "====== QUERY $query ======\n";
echo file_get_contents("http://builder.osmand.net/reports/query_report?".$query."&force=true";
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "\n====== DONE $time seconds ======\n";
}
}
// var_dump( $c->getAllKeys() );
?>
|
Fix tests under Django >= 1.10.3
See "DNS rebinding vulnerability when DEBUG=True"
in Django 1.10.3 release notes:
https://docs.djangoproject.com/en/1.10/releases/1.10.3/
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'ALLOWED_HOSTS': ['testserver'],
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
from os.path import dirname, join
import sys
import django
import django.conf
def pytest_configure():
example_path = join(dirname(dirname(__file__)), 'example')
if example_path not in sys.path:
sys.path.insert(0, example_path)
settings = {
'DEBUG': True,
'MIDDLEWARE_CLASSES': [
'django_httpolice.HTTPoliceMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
],
'ROOT_URLCONF': 'example_project.urls',
'LANGUAGE_CODE': 'en-us',
'USE_I18N': False,
'HTTPOLICE_ENABLE': True,
'HTTPOLICE_SILENCE': [1070, 1110],
}
if django.VERSION >= (1, 10): # pragma: no cover
settings['MIDDLEWARE'] = settings.pop('MIDDLEWARE_CLASSES')
django.conf.settings.configure(**settings)
|
Fix element not having an image
|
const React = require("react");
const ReactDOM = require("react-dom");
const e = React.createElement;
class Component extends React.Component {
render() {
const { enabled, status } = this.props.offlineSupport;
return e("span", null, [
"Offline support:",
e("img", {
key: "image",
className: "enabled",
// TODO Use build ID in the URL
src: `images/bullet_${enabled ? "green" : "red"}.png`,
alt: enabled ? "Enabled" : "Disabled"
}),
status && ` (${status})`
]);
}
}
module.exports = Component;
Component.render = (offlineSupport, domElement) => {
// Avoid the Inferno warning "(...) or Initial render target is not empty"
// TODO Is there simply a way to tell Inferno to not warn?
domElement.innerHTML = "";
render(offlineSupport, domElement);
offlineSupport.events.on("change", () => {
render(offlineSupport, domElement);
});
};
const render = (offlineSupport, domElement) => {
ReactDOM.render(e(Component, { offlineSupport }), domElement);
};
|
const React = require("react");
const ReactDOM = require("react-dom");
const e = React.createElement;
class Component extends React.Component {
render() {
const { enabled, status } = this.props.offlineSupport;
return e("span", null, [
"Offline support:",
e("img", {
className: "enabled",
// TODO Use build ID in the URL
src: `images/bullet_${enabled ? "green" : "red"}.png`,
alt: enabled ? "Enabled" : "Disabled"
}),
status && ` (${status})`
]);
}
}
module.exports = Component;
Component.render = (offlineSupport, domElement) => {
// Avoid the Inferno warning "(...) or Initial render target is not empty"
// TODO Is there simply a way to tell Inferno to not warn?
domElement.innerHTML = "";
render(offlineSupport, domElement);
offlineSupport.events.on("change", () => {
render(offlineSupport, domElement);
});
};
const render = (offlineSupport, domElement) => {
ReactDOM.render(e(Component, { offlineSupport }), domElement);
};
|
[Statie] Return missing layout to file params
|
<?php declare(strict_types=1);
namespace Symplify\Statie\Templating;
use Symplify\Statie\Configuration\Configuration;
use Symplify\Statie\Renderable\File\AbstractFile;
abstract class AbstractTemplatingFileDecorator
{
/**
* @var Configuration
*/
protected $configuration;
/**
* @required
*/
public function addConfiguration(Configuration $configuration): void
{
$this->configuration = $configuration;
}
/**
* @return mixed[]
*/
protected function createParameters(AbstractFile $file, string $fileKey): array
{
$parameters = $file->getConfiguration();
$parameters += $this->configuration->getOptions();
$parameters[$fileKey] = $file;
$parameters['layout'] = $file->getLayout();
return $parameters;
}
}
|
<?php declare(strict_types=1);
namespace Symplify\Statie\Templating;
use Symplify\Statie\Configuration\Configuration;
use Symplify\Statie\Renderable\File\AbstractFile;
abstract class AbstractTemplatingFileDecorator
{
/**
* @var Configuration
*/
protected $configuration;
/**
* @required
*/
public function addConfiguration(Configuration $configuration): void
{
$this->configuration = $configuration;
}
/**
* @return mixed[]
*/
protected function createParameters(AbstractFile $file, string $fileKey): array
{
$parameters = $file->getConfiguration();
$parameters += $this->configuration->getOptions();
$parameters[$fileKey] = $file;
return $parameters;
}
}
|
Convert md to rst readme specially for PyPi
|
from distutils.core import setup
with open('README.md') as readme:
with open('HISTORY.md') as history:
long_description = readme.read() + '\n\n' + history.read()
try:
import pypandoc
long_description = pypandoc.convert(long_description, 'rst', 'markdown')
except(IOError, ImportError):
long_description = long_description
VERSION = '1.0.1'
setup(
name='argparse-autogen',
py_modules=['argparse_autogen'],
version=VERSION,
url='https://github.com/sashgorokhov/argparse-autogen',
download_url='https://github.com/sashgorokhov/argparse-autogen/archive/v%s.zip' % VERSION,
keywords=['python', 'argparse', 'generate'],
classifiers=[],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description="Parser with automatic creation of parsers and subparsers for paths.",
)
|
from distutils.core import setup
with open('README.md') as readme:
with open('HISTORY.md') as history:
long_description = readme.read() + '\n\n' + history.read()
try:
import pypandoc
long_description = pypandoc.convert(long_description, 'rst')
except(IOError, ImportError):
long_description = long_description
VERSION = '1.0.1'
setup(
name='argparse-autogen',
py_modules=['argparse_autogen'],
version=VERSION,
url='https://github.com/sashgorokhov/argparse-autogen',
download_url='https://github.com/sashgorokhov/argparse-autogen/archive/v%s.zip' % VERSION,
keywords=['python', 'argparse', 'generate'],
classifiers=[],
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='sashgorokhov@gmail.com',
description="Parser with automatic creation of parsers and subparsers for paths.",
)
|
Put numpy namespace in scipy for backward compatibility...
|
"""\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is also available in the docstrings.
Available subpackages
---------------------
"""
try:
import pkg_resources as _pr # activate namespace packages (manipulates __path__)
del _pr
except ImportError:
pass
from numpy import show_config as show_numpy_config
if show_numpy_config is None:
raise ImportError,"Cannot import scipy when running from numpy source directory."
from numpy import __version__ as __numpy_version__
from __config__ import show as show_config
from version import version as __version__
import numpy._import_tools as _ni
pkgload = _ni.PackageLoader()
del _ni
import os as _os
SCIPY_IMPORT_VERBOSE = int(_os.environ.get('SCIPY_IMPORT_VERBOSE','0'))
pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
del _os
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test')
import numpy as _num
from numpy import *
__all__ += _num.__all__
del _num
__doc__ += pkgload.get_pkgdocs()
|
"""\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is also available in the docstrings.
Available subpackages
---------------------
"""
try:
import pkg_resources as _pr # activate namespace packages (manipulates __path__)
del _pr
except ImportError:
pass
from numpy import show_config as show_numpy_config
if show_numpy_config is None:
raise ImportError,"Cannot import scipy when running from numpy source directory."
from numpy import __version__ as __numpy_version__
from __config__ import show as show_config
from version import version as __version__
import numpy._import_tools as _ni
pkgload = _ni.PackageLoader()
del _ni
import os as _os
SCIPY_IMPORT_VERBOSE = int(_os.environ.get('SCIPY_IMPORT_VERBOSE','0'))
pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
del _os
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test')
__doc__ += pkgload.get_pkgdocs()
|
Tracks: Remove useless field descs, increase rows
|
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from wtforms.fields import StringField, TextAreaField
from wtforms.validators import DataRequired
from indico.util.i18n import _
from indico.web.forms.base import IndicoForm
class TrackForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()])
code = StringField(_('Code'))
description = TextAreaField(_('Description'), render_kw={'rows': 10})
|
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico 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
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from wtforms.fields import StringField, TextAreaField
from wtforms.validators import DataRequired
from indico.util.i18n import _
from indico.web.forms.base import IndicoForm
class TrackForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()], description=_('Title of the track'))
code = StringField(_('Code'), description=_('Code for the track'))
description = TextAreaField(_('Description'), description=_('Text describing the track'))
|
Add the validation of setter methods
|
<?php
/**
* 面向对象-属性设置器
*/
class Person
{
private $age;
/**
* Sets the value of age.
*
* @param mixed $age the age
*
* @return self
*/
public function setAge($age)
{
if ($age > 100) {
throw new Exception('You are too old!');
}
$this->age = $age;
return $this;
}
/**
* Gets the value of age.
*
* @return mixed
*/
public function getAge()
{
return $this->age;
}
}
$hackingangle = new Person();
var_dump($hackingangle->setAge(26));
var_dump($hackingangle->setAge(120)->getAge());
|
<?php
/**
* 面向对象-属性设置器
*/
class Person
{
private $age;
/**
* Sets the value of age.
*
* @param mixed $age the age
*
* @return self
*/
public function setAge($age)
{
$this->age = $age;
return $this;
}
/**
* Gets the value of age.
*
* @return mixed
*/
public function getAge()
{
return $this->age;
}
}
$hackingangle = new Person();
var_dump($hackingangle->setAge(26));
var_dump($hackingangle->setAge(120)->getAge());
|
Make Config GUIs easier to work with
|
package ljfa.tntutils.gui;
import java.util.ArrayList;
import java.util.List;
import ljfa.tntutils.Config;
import ljfa.tntutils.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
public class TntuConfigGui extends GuiConfig {
public TntuConfigGui(GuiScreen parent) {
super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration");
}
/** Compiles a list of config elements
* Borrowed from EnderIO's implementation
*/
private static List<IConfigElement> getConfigElements() {
List<IConfigElement> list = new ArrayList<IConfigElement>();
for(String name: Config.conf.getCategoryNames())
list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(name)));
return list;
}
}
|
package ljfa.tntutils.gui;
import java.util.ArrayList;
import java.util.List;
import ljfa.tntutils.Config;
import ljfa.tntutils.Reference;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.ConfigElement;
import cpw.mods.fml.client.config.DummyConfigElement;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
public class TntuConfigGui extends GuiConfig {
public TntuConfigGui(GuiScreen parent) {
super(parent, getConfigElements(), Reference.MODID, false, false, "TNTUtils configuration");
}
/** Compiles a list of config elements */
private static List<IConfigElement> getConfigElements() {
List<IConfigElement> list = new ArrayList<IConfigElement>();
//Add categories to config GUI
list.add(new ConfigElement<ConfigCategory>(Config.conf.getCategory(Config.CATEGORY_GENERAL)));
return list;
}
}
|
Break bucle cuando encuentra una coincidencia
|
<?php
namespace Aluc\Tools;
class Urls {
private static function get_url() {
$base_url = static::get_current_uri();
return $base_url;
// $routes = array();
// $routes = explode('/', $base_url);
}
private static function get_current_uri() {
// Copy & paste, no tocar!
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
$uri = '/' . trim($uri, '/');
return $uri;
}
public static function serve_request($urls) {
$base_url = static::get_url();
foreach ($urls as $url => $func) {
if (preg_match($url, $base_url)) {
$func();
break;
}
}
}
}
|
<?php
namespace Aluc\Tools;
class Urls {
private static function get_url() {
$base_url = static::get_current_uri();
return $base_url;
// $routes = array();
// $routes = explode('/', $base_url);
}
private static function get_current_uri() {
// Copy & paste, no tocar!
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
$uri = '/' . trim($uri, '/');
return $uri;
}
public static function serve_request($urls) {
$base_url = static::get_url();
foreach ($urls as $url => $func) {
if (preg_match($url, $base_url)) {
$func();
}
}
}
}
|
Add Bridge of flic framework.
It is a sort of plugin register.
|
"use strict";
var util = require("util"),
express = require("express"),
Bridge = require("flic").bridge,
routes = require("./routes");
var app = express(),
port = routes.config.port,
staticFiles = express.static,
apiUrl = routes.config.apiUrl;
process.on("uncaughtException", function (err) {
console.log(err);
});
app.use(staticFiles(routes.config.staticFiles));
app.use(apiUrl, routes.apis);
app.listen(port, function () {
util.log("Argo listening on http://localhost:" + port);
util.log("Argo listening apis on http://localhost:" + port + apiUrl);
}).on("upgrade", function (request, socket, body) {
routes.stream.run(request, socket, body);
util.log("Argo streaming prices and events on ws://localhost:" +
port + routes.config.streamUrl);
});
/*eslint-disable no-new */
new Bridge();
/*eslint-enable no-new */
|
"use strict";
var util = require("util"),
express = require("express"),
seneca = require("seneca"),
routes = require("./routes");
var app = express(),
port = routes.config.port,
staticFiles = express.static,
apiUrl = routes.config.apiUrl;
process.on("uncaughtException", function (err) {
console.log(err);
});
app.use(staticFiles(routes.config.staticFiles));
app.use(apiUrl, routes.apis);
app.listen(port, function () {
util.log("Argo listening on http://localhost:" + port);
util.log("Argo listening apis on http://localhost:" + port + apiUrl);
}).on("upgrade", function (request, socket, body) {
routes.stream.run(request, socket, body);
util.log("Argo streaming prices and events on ws://localhost:" +
port + routes.config.streamUrl);
});
seneca = seneca();
seneca.use("plugin/register.js");
seneca.listen();
seneca.ready(function (error) {
if (!error) {
seneca.act("role:plugin", {
cmd: "register",
name: "ready"
}, function (err, result) {
if (!err) {
util.log("Argo plugin:", result.value);
}
});
}
});
|
Test line numbers in lexer tests.
|
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, text, tp, line = None, col = None ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
if line is not None:
assert_equal( token.getLine(), line )
if col is not None:
assert_equal( token.getColumn(), col )
def test_hello_world():
tokens = _lex( """print( "Hello, world!" )""" )
_assert_token( tokens[0], "print", EeyoreLexer.SYMBOL, 1, 1 )
_assert_token( tokens[1], "(", EeyoreLexer.LPAREN, 1, 6 )
_assert_token( tokens[2], "Hello, world!", EeyoreLexer.STRING, 1, 8 )
_assert_token( tokens[3], ")", EeyoreLexer.RPAREN, 1, 24 )
assert_equal( len( tokens ), 4 )
|
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, ( text, tp ) ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
def test_hello_world():
tokens = _lex( """print( "Hello, world!" )""" )
_assert_token( tokens[0], ( "print", EeyoreLexer.SYMBOL ) )
_assert_token( tokens[1], ( "(", EeyoreLexer.LPAREN ) )
_assert_token( tokens[2], ( "Hello, world!", EeyoreLexer.STRING ) )
_assert_token( tokens[3], ( ")", EeyoreLexer.RPAREN ) )
# TODO: test line numbers
|
Fix undefined name and scope variables
|
function calcWidth(name) {
return 250 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
if(request.url.split('/')[1] != ''){
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
HTTP.get(url, {headers: {'Accept': 'application/json'}}, function(err, res) {
var name = '';
var f = "MMM Do YYYY";
var payload = res.data[0];
if (res.data.length != 0) {
var name = payload.name;
var version = payload.latestVersion.version;
var pubdate = moment(payload.latestVersion.published.$date).format(f);
var starCount = payload.starCount.toLocaleString();
var installyear = payload['installs-per-year'].toLocaleString();
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var params = {w: width, totalW: width+2, n: name, v: version, p: pubdate,
s: starCount, i: installyear};
var icon = SSR.render('icon', params);
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
}
});
|
var f = "MMM Do YYYY";
function calcWidth(name) {
return 250 + name.length * 6.305555555555555;
}
WebApp.connectHandlers.use("/package", function(request, response) {
if(request.url.split('/')[1] != ''){
var url = `https://atmospherejs.com/a/packages/findByNames\
?names=${request.url.split('/')[1]}`;
HTTP.get(url, {headers: {'Accept': 'application/json'}}, function(err, res) {
var name,version,pubdate,starCount,installyear = '';
if (res.data.length != 0) {
name = res.data[0].name;
version = res.data[0].latestVersion.version;
pubdate = moment(res.data[0].latestVersion.published.$date).format(f);
starCount = res.data[0].starCount.toLocaleString();
installyear = res.data[0]['installs-per-year'].toLocaleString();
}
SSR.compileTemplate('icon', Assets.getText('icon.svg'));
var width = calcWidth(name);
var params = {w: width, totalW: width+2, n: name, v: version, p: pubdate,
s: starCount, i: installyear};
var icon = SSR.render('icon', params);
response.writeHead(200, {"Content-Type": "image/svg+xml"});
response.end(icon);
});
}
});
|
Convert number value to string
|
import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../FormBuilderPropTypes'
import DefaultTextField from 'component:@sanity/components/textfields/default'
export default class Num extends React.Component {
static displayName = 'Number';
static propTypes = {
field: FormBuilderPropTypes.field,
value: PropTypes.number,
onChange: PropTypes.func,
focus: PropTypes.bool
};
static defaultProps = {
onChange() {}
};
constructor(props, context) {
super(props, context)
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
const val = e.target.value.trim()
this.props.onChange({patch: {$set: val === '' ? undefined : Number(e.target.value)}})
}
render() {
const {value, field, focus} = this.props
return (
<DefaultTextField
label={field.title}
type="number"
placeholder={field.placeholder || 'Must be a number. Ex 1234'}
onChange={this.handleChange}
onKeyPress={this.handleKeyPress}
value={String(value)}
focus={focus}
ref={this.setInputElement}
/>
)
}
}
|
import React, {PropTypes} from 'react'
import FormBuilderPropTypes from '../FormBuilderPropTypes'
import DefaultTextField from 'component:@sanity/components/textfields/default'
export default class Num extends React.Component {
static displayName = 'Number';
static propTypes = {
field: FormBuilderPropTypes.field,
value: PropTypes.number,
onChange: PropTypes.func,
focus: PropTypes.bool
};
static defaultProps = {
onChange() {}
};
constructor(props, context) {
super(props, context)
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
const val = e.target.value.trim()
this.props.onChange({patch: {$set: val === '' ? undefined : Number(e.target.value)}})
}
render() {
const {value, field, focus} = this.props
return (
<DefaultTextField
label={field.title}
type="number"
placeholder={field.placeholder || 'Must be a number. Ex 1234'}
onChange={this.handleChange}
onKeyPress={this.handleKeyPress}
value={value}
focus={focus}
ref={this.setInputElement}
/>
)
}
}
|
Trivial: Make vertical white space after license header consistent
Vertical white space between license header and the actual code is not consistent
across files. It looks like majority of the files leaves a single blank line
after license header. So make it consistent except for those exceptional cases
where the actual code starts with a function or class definition.
Change-Id: If6679ab19dc2d7a9df93e076db3019abc1e5b86b
|
# Copyright 2012 Intel Inc, OpenStack Foundation.
# 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.
"""
Fakes For filter and weight tests.
"""
from openstack.common.scheduler import weights
class FakeWeigher1(weights.BaseHostWeigher):
def __init__(self):
pass
class FakeWeigher2(weights.BaseHostWeigher):
def __init__(self):
pass
class FakeClass(object):
def __init__(self):
pass
|
# Copyright 2012 Intel Inc, OpenStack Foundation.
# 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.
"""
Fakes For filter and weight tests.
"""
from openstack.common.scheduler import weights
class FakeWeigher1(weights.BaseHostWeigher):
def __init__(self):
pass
class FakeWeigher2(weights.BaseHostWeigher):
def __init__(self):
pass
class FakeClass(object):
def __init__(self):
pass
|
Support emulation of 'option' tag with MenuItem
|
/*
This file is a part of libertysoil.org website
Copyright (C) 2015 Loki Education (Social Enterprise)
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/>.
*/
import React from 'react';
import classNames from 'classnames';
const MenuItem = ({ className, isOption, ...props }) => {
const cn = classNames('menu__item action', className);
if (isOption) {
return <option className={cn} {...props} />;
}
return <div className={cn} {...props} />;
};
export default MenuItem;
|
/*
This file is a part of libertysoil.org website
Copyright (C) 2015 Loki Education (Social Enterprise)
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/>.
*/
import React from 'react';
import classNames from 'classnames';
const MenuItem = ({
children,
className,
...props
}) => (
<div className={classNames('menu__item action', className)} {...props}>
{children}
</div>
);
export default MenuItem;
|
Add adapter option number sorting
|
package com.sometrik.framework;
import java.util.ArrayList;
import java.util.TreeMap;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class FWPicker extends Spinner implements NativeMessageHandler {
ArrayAdapter<String> adapter;
ArrayList<Integer> numberList;
TreeMap<Integer, String> valueMap;
public FWPicker(Context context) {
super(context);
adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
valueMap = new TreeMap<Integer, String>();
numberList = new ArrayList<Integer>();
}
@Override
public void handleMessage(NativeMessage message) {
switch (message.getMessage()) {
case ADD_OPTION:
valueMap.put(message.getValue(), message.getTextValue());
numberList.add(message.getValue());
for (int i = 0; i < numberList.size(); i++) {
adapter.add(valueMap.get(numberList.get(i)));
}
setAdapter(adapter);
break;
default:
System.out.println("Message couldn't be handled by Picker");
break;
}
}
@Override
public void showView() {
}
@Override
public int getElementId() {
return getId();
}
}
|
package com.sometrik.framework;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class FWPicker extends Spinner implements NativeMessageHandler {
ArrayAdapter<String> adapter;
public FWPicker(Context context) {
super(context);
adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
}
@Override
public void handleMessage(NativeMessage message) {
switch(message.getMessage()){
case ADD_OPTION:
adapter.add(message.getTextValue());
setAdapter(adapter);
break;
}
}
@Override
public void showView() {
}
@Override
public int getElementId() {
return getId();
}
}
|
Fix regex example, the model must not be a unicode string.
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from parser_base import RegexParser
import model
class RegexSemantics(object):
def __init__(self):
super(RegexSemantics, self).__init__()
self._count = 0
def START(self, ast):
return model.Regex(ast)
def CHOICE(self, ast):
return model.Choice(ast.opts)
def SEQUENCE(self, ast):
if not ast.terms:
return model.Empty()
elif len(ast.terms) < 2:
return ast.terms[0]
else:
return model.Sequence(ast.terms)
def CLOSURE(self, ast):
return model.Closure(ast)
def SUBEXP(self, ast):
return ast
def LITERAL(self, ast):
return model.Literal(ast)
def translate(regex, trace=False):
parser = RegexParser(trace=trace, semantics=RegexSemantics())
model = parser.parse(regex, 'START')
model.set_rule_numbers()
return model.render().encode("ascii")
|
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from parser_base import RegexParser
import model
class RegexSemantics(object):
def __init__(self):
super(RegexSemantics, self).__init__()
self._count = 0
def START(self, ast):
return model.Regex(ast)
def CHOICE(self, ast):
return model.Choice(ast.opts)
def SEQUENCE(self, ast):
if not ast.terms:
return model.Empty()
elif len(ast.terms) < 2:
return ast.terms[0]
else:
return model.Sequence(ast.terms)
def CLOSURE(self, ast):
return model.Closure(ast)
def SUBEXP(self, ast):
return ast
def LITERAL(self, ast):
return model.Literal(ast)
def translate(regex, trace=False):
parser = RegexParser(trace=trace, semantics=RegexSemantics())
model = parser.parse(regex, 'START')
model.set_rule_numbers()
return model.render()
|
Add access_token, expires_in to RedirectHandler valid keys
|
/**
* RedirectHandler will attempt to find
* these keys in the URL. If found,
* this is an indication to Torii that
* the Ember app has loaded inside a popup
* and should postMessage this data to window.opener
*/
var authorizationKeys = [
'code', // oauth2 authorization code flow
'access_token', // used by facebook-bearer and other oauth2 providers
'expires_in' // used by facebook-bearer
];
import ParseQueryString from 'torii/lib/parse-query-string';
var RedirectHandler = Ember.Object.extend({
init: function(url){
this.url = url;
},
run: function(){
var data = this.parseUrl();
return new Ember.RSVP.Promise(function(resolve, reject){
if (!window.opener) {
reject('No window.opener');
} else if (Ember.keys(data).get('length') < 1) {
reject("No data found");
} else {
data.__torii_message = true;
window.opener.postMessage(data, '*');
resolve(data);
}
});
},
parseUrl: function(){
var parser = new ParseQueryString(this.url,
authorizationKeys);
return parser.parse();
}
});
RedirectHandler.reopenClass({
// untested
handle: function(url){
var handler = new RedirectHandler(url);
return handler.run();
}
});
export default RedirectHandler;
|
/**
* RedirectHandler will attempt to find
* these keys in the URL. If found,
* this is an indication to Torii that
* the Ember app has loaded inside a popup
* and should postMessage this data to window.opener
*/
var authorizationKeys = [
'code'
];
import ParseQueryString from 'torii/lib/parse-query-string';
var RedirectHandler = Ember.Object.extend({
init: function(url){
this.url = url;
},
run: function(){
var data = this.parseUrl();
return new Ember.RSVP.Promise(function(resolve, reject){
if (!window.opener) {
reject('No window.opener');
} else if (Ember.keys(data).get('length') < 1) {
reject("No data found");
} else {
data.__torii_message = true;
window.opener.postMessage(data, '*');
resolve(data);
}
});
},
parseUrl: function(){
var parser = new ParseQueryString(this.url,
authorizationKeys);
return parser.parse();
}
});
RedirectHandler.reopenClass({
// untested
handle: function(url){
var handler = new RedirectHandler(url);
return handler.run();
}
});
export default RedirectHandler;
|
Optimize loop by caching lowercase version of comparison.
|
var _ = require('underscore');
/**
* Represents an ActiveDirectory user account.
*
* @private
* @param {Object} [properties] The properties to assign to the newly created item.
* @returns {User}
*/
var User = function(properties) {
for (var property in (properties || {})) {
if (Array.prototype.hasOwnProperty.call(properties, property)) {
this[property] = properties[property];
}
}
};
/**
* Checks to see if the user is the member of the specified group.
*
* @param {String} group The name of the group to check for membership.
* @returns {Boolean}
*/
User.prototype.isMemberOf = function isMemberOf(group) {
if (! group) return(false);
group = (group || '').toLowerCase();
return(_.any(this.groups || [], function(item) {
return (((item || {}).cn || '').toLowerCase() === group);
}));
};
module.exports = User;
|
var _ = require('underscore');
/**
* Represents an ActiveDirectory user account.
*
* @private
* @param {Object} [properties] The properties to assign to the newly created item.
* @returns {User}
*/
var User = function(properties) {
for (var property in (properties || {})) {
if (Array.prototype.hasOwnProperty.call(properties, property)) {
this[property] = properties[property];
}
}
};
/**
* Checks to see if the user is the member of the specified group.
*
* @param {String} group The name of the group to check for membership.
* @returns {Boolean}
*/
User.prototype.isMemberOf = function isMemberOf(group) {
if (! group) return(false);
return(_.any(this.groups || [], function(item) {
return (((item || {}).cn || '').toLowerCase() === (group || '').toLowerCase());
}));
};
module.exports = User;
|
Set meta-name for sheet as "styled-jss"
|
import styled from './styled'
import type {
BaseStylesType,
ComponentStyleType,
StyledType,
StyledElementAttrsType,
StyledElementType,
TagNameOrStyledElementType
} from './types'
const getStyledArgs = (
tagNameOrStyledElement: TagNameOrStyledElementType
): StyledElementAttrsType => {
if (typeof tagNameOrStyledElement === 'string') {
return {tagName: tagNameOrStyledElement, style: {}}
}
const {tagName, style} = tagNameOrStyledElement
return {tagName, style}
}
const createStyled = (jss: Function) => (baseStyles: BaseStylesType = {}): StyledType => {
let sheet
const mountSheet = () => {
if (!sheet) {
sheet = jss.createStyleSheet(baseStyles, {
link: true,
meta: 'styled-jss',
}).attach()
}
return sheet
}
return Object.assign((
tagNameOrStyledElement: TagNameOrStyledElementType
) => (
ownStyle: ComponentStyleType
): StyledElementType => {
const {tagName, style} = getStyledArgs(tagNameOrStyledElement)
const elementStyle = {...style, ...ownStyle}
return styled({tagName, baseStyles, elementStyle, mountSheet})
}, {mountSheet, sheet, styles: baseStyles})
}
export default createStyled
|
import styled from './styled'
import type {
BaseStylesType,
ComponentStyleType,
StyledType,
StyledElementAttrsType,
StyledElementType,
TagNameOrStyledElementType
} from './types'
const getStyledArgs = (
tagNameOrStyledElement: TagNameOrStyledElementType
): StyledElementAttrsType => {
if (typeof tagNameOrStyledElement === 'string') {
return {tagName: tagNameOrStyledElement, style: {}}
}
const {tagName, style} = tagNameOrStyledElement
return {tagName, style}
}
const createStyled = (jss: Function) => (baseStyles: BaseStylesType = {}): StyledType => {
let sheet
const mountSheet = () => {
if (!sheet) {
sheet = jss.createStyleSheet(baseStyles, {
link: true,
meta: 'sheet',
}).attach()
}
return sheet
}
return Object.assign((
tagNameOrStyledElement: TagNameOrStyledElementType
) => (
ownStyle: ComponentStyleType
): StyledElementType => {
const {tagName, style} = getStyledArgs(tagNameOrStyledElement)
const elementStyle = {...style, ...ownStyle}
return styled({tagName, baseStyles, elementStyle, mountSheet})
}, {mountSheet, sheet, styles: baseStyles})
}
export default createStyled
|
Update the React setState checks to avoid version-based syntax errors
|
module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/no-danger": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/require-extension": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2
}
};
|
module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/no-danger": 2,
"react/no-did-mount-set-state": [2, "allow-in-func"],
"react/no-did-update-set-state": [2, "allow-in-func"],
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/require-extension": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2
}
};
|
Revert "Fix the location path of OpenIPSL"
This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.
|
import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}
# Instance of CITests
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL
sys.exit(1)
else:
# Run Check on App Examples
passAppEx = 1
for package in appExamples.keys():
passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])
# The tests are failing if the number of failed check > 0
if passAppEx:
# Everything is fine
sys.exit(0)
else:
# Exit with error
sys.exit(1)
|
import sys
from CITests import CITests
# Libs in Application Examples
appExamples = {
#"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo",
#"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo",
#"SevenBus":"/ApplicationExamples/SevenBus/package.mo",
#"IEEE9":"/ApplicationExamples/IEEE9/package.mo",
#"IEEE14":"/ApplicationExamples/IEEE14/package.mo",
#"AKD":"/ApplicationExamples/AKD/package.mo",
#"N44":"/ApplicationExamples/N44/package.mo",
#"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo",
#"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo"
}
# Instance of CITests
ci = CITests("/OpenIPSL")
# Run Check on OpenIPSL
passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo")
if not passLib:
# Error in OpenIPSL
sys.exit(1)
else:
# Run Check on App Examples
passAppEx = 1
for package in appExamples.keys():
passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package])
# The tests are failing if the number of failed check > 0
if passAppEx:
# Everything is fine
sys.exit(0)
else:
# Exit with error
sys.exit(1)
|
Add a test for running tasks
|
import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3)
def test_coroutines(self):
print(self.client)
assert len(self.client.tasks._children) == (1 + self.client.total_connections)
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
|
import hashlib
from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection
class Tests(object):
def setup(self):
self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1)
def teardown(self):
pass
class TestConnectedWebsocketConnection:
def setup(self):
self.token = hashlib.sha256(b'derp').hexdigest()
self.socket = ConnectedWebsocketConnection(None, self.token)
def test_message_increment(self):
assert self.socket.message_count == 0
self.socket.increment_message_counter()
assert self.socket.message_count == 1
self.socket.increment_message_counter()
assert self.socket.message_count == 2
def test_socket_as_string(self):
assert str(self.socket) == "<Websocket {}>".format(self.socket.id)
|
Allow the external webpack bundles to be specified with the global file list.
|
// Default karma configuration
var _ = require('lodash');
var sharedConfig = require('./shared.config');
var webpackPreprocessorLibrary = 'webpack';
module.exports = function (karma, testFiles, globalFiles, externals) {
globalFiles = arrayify(globalFiles);
testFiles = arrayify(testFiles);
var options = sharedConfig(karma);
options.files = globalFiles.concat(testFiles);
_.each(testFiles, function(file) { addPreprocessor(options, file); });
options.webpack.externals = externals;
karma.set(options);
return options;
};
function arrayify(maybeArray) {
if (_.isArray(maybeArray)) {
return maybeArray;
} else if (maybeArray) {
return [maybeArray];
} else {
return [];
}
}
function addPreprocessor(options, path) {
options.preprocessors = options.preprocessors || {};
options.preprocessors[path] = [webpackPreprocessorLibrary];
}
|
// Default karma configuration
var _ = require('lodash');
var sharedConfig = require('./shared.config');
var webpackPreprocessorLibrary = 'webpack';
module.exports = function (karma, globalFiles, testFiles) {
globalFiles = arrayify(globalFiles);
testFiles = arrayify(testFiles);
var options = sharedConfig(karma);
options.files = globalFiles.concat(testFiles);
_.each(testFiles, function(file) { addPreprocessor(options, file); });
karma.set(options);
return options;
};
function arrayify(maybeArray) {
if (_.isArray(maybeArray)) {
return maybeArray;
} else if (maybeArray) {
return [maybeArray];
} else {
return [];
}
}
function addPreprocessor(options, path) {
options.preprocessors = options.preprocessors || {};
options.preprocessors[path] = [webpackPreprocessorLibrary];
}
|
Create PHP wrapper for assertArrayHasKey
|
//Re-implement PHPUnit's TestCase
class PHPUnit_Framework_TestCase
{
//Setup a static constructor so that our Test Cases can inherit
static function __construct() {
}
//Override the PHP Twig Extension with the JavaScript implementation
public function setJavaScriptExtension($ext) {
$this->ext = $ext;
}
//Set the JavaScript assertion implementation
public function setAsserter($asserter) {
$this->asserter = $asserter;
}
//Set the Javascript test name setter
public function setNameSetter($nameSetter) {
$this->nameSetter = $nameSetter;
}
//Run the tests
public function run($tests) {
//$tests is an array of strings; the names of the test functions
for($i = 0; $i < count($tests); $i++) {
$testToRun = $tests[$i];
//Set the test name (calls it() in JavaScript)
$this->nameSetter->setTestName($testToRun);
//Run the test
$this->$testToRun();
}
}
//Actual assertions happen in JavaScript
private function assertEquals($a, $b) {
return $this->asserter->equal($a, $b);
}
private function assertContains($a, $b) {
return $this->asserter->contains($a, $b);
}
private function assertArrayHasKey($key, $array) {
return $this->asserter->contains($key, $array);
}
}
|
//Re-implement PHPUnit's TestCase
class PHPUnit_Framework_TestCase
{
//Setup a static constructor so that our Test Cases can inherit
static function __construct() {
}
//Override the PHP Twig Extension with the JavaScript implementation
public function setJavaScriptExtension($ext) {
$this->ext = $ext;
}
//Set the JavaScript assertion implementation
public function setAsserter($asserter) {
$this->asserter = $asserter;
}
//Set the Javascript test name setter
public function setNameSetter($nameSetter) {
$this->nameSetter = $nameSetter;
}
//Run the tests
public function run($tests) {
//$tests is an array of strings; the names of the test functions
for($i = 0; $i < count($tests); $i++) {
$testToRun = $tests[$i];
//Set the test name (calls it() in JavaScript)
$this->nameSetter->setTestName($testToRun);
//Run the test
$this->$testToRun();
}
}
//Actual assertions happen in JavaScript
private function assertEquals($a, $b) {
return $this->asserter->equal($a, $b);
}
private function assertContains($a, $b) {
return $this->asserter->contains($a, $b);
}
}
|
Check jQuery version only if jQuery is available
|
import Alert from './alert'
import Button from './button'
import Carousel from './carousel'
import Collapse from './collapse'
import Dropdown from './dropdown'
import Modal from './modal'
import Popover from './popover'
import Scrollspy from './scrollspy'
import Tab from './tab'
import Toast from './toast'
import Tooltip from './tooltip'
import Util from './util'
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.3.1): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(() => {
// only check jQuery version if jQuery is available
if (typeof window.$ !== 'undefined' || typeof window.jQuery !== 'undefined') {
const version = window.$.fn.jquery.split(' ')[0].split('.')
const minMajor = 1
const ltMajor = 2
const minMinor = 9
const minPatch = 1
const maxMajor = 4
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
}
})()
export {
Util,
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
Scrollspy,
Tab,
Toast,
Tooltip
}
|
import $ from 'jquery'
import Alert from './alert'
import Button from './button'
import Carousel from './carousel'
import Collapse from './collapse'
import Dropdown from './dropdown'
import Modal from './modal'
import Popover from './popover'
import Scrollspy from './scrollspy'
import Tab from './tab'
import Toast from './toast'
import Tooltip from './tooltip'
import Util from './util'
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.3.1): index.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
(() => {
if (typeof $ === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.')
}
const version = $.fn.jquery.split(' ')[0].split('.')
const minMajor = 1
const ltMajor = 2
const minMinor = 9
const minPatch = 1
const maxMajor = 4
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0')
}
})()
export {
Util,
Alert,
Button,
Carousel,
Collapse,
Dropdown,
Modal,
Popover,
Scrollspy,
Tab,
Toast,
Tooltip
}
|
Change num of planned tests.
|
const numberOfPlannedTests = 5
casper.test.begin('test-simple-image-resize', numberOfPlannedTests, (test) => {
casper.start(`http://${testhost}`, function () {
})
casper.then(function () {
const curr = this.getCurrentUrl()
const fixturePath = this.fetchText('#fixture_path')
this.fill('#entryForm', {
my_file : `${fixturePath}/1.jpg`,
width_field : '400',
height_field: '400',
})
this.evaluate(function () { $('#entryForm').submit() })
this.waitFor(function () {
return curr !== this.getCurrentUrl()
})
})
casper.then(function () {
this.test.assertTextExists('ASSEMBLY_COMPLETED')
})
casper.run(function () {
this.test.done()
})
})
|
const numberOfPlannedTests = 6
casper.test.begin('test-simple-image-resize', numberOfPlannedTests, (test) => {
casper.start(`http://${testhost}`, function () {
})
casper.then(function () {
const curr = this.getCurrentUrl()
const fixturePath = this.fetchText('#fixture_path')
this.fill('#entryForm', {
my_file : `${fixturePath}/1.jpg`,
width_field : '400',
height_field: '400',
})
this.evaluate(function () { $('#entryForm').submit() })
this.waitFor(function () {
return curr !== this.getCurrentUrl()
})
})
casper.then(function () {
this.test.assertTextExists('ASSEMBLY_COMPLETED')
})
casper.run(function () {
this.test.done()
})
})
|
Add quotes to cron information page, for the example crontab file
|
<?php
$this->data['header'] = 'Cron information page';
$this->includeAtTemplateBase('includes/header.php');
?>
<div id="content">
<p>Cron is a way to run things regularly on unix systems.</p>
<p>Here is a suggestion for a crontab file:</p>
<pre style="font-size: x-small; color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code><?php
foreach ($this->data['urls'] AS $url ) {
echo "# " . $url['title'] . "\n";
echo "" . $url['int'] . " curl --silent \"" . $url['href'] . "\" > /dev/null 2>&1\n";
}
?>
</code></pre>
<p>Click here to run the cron jobs:
<ul>
<?php
foreach ($this->data['urls'] AS $url ) {
echo '<li><a href="' . $url['href'] . '">' . $url['title'] . '</a></li>';
}
?>
</ul>
</div>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
<?php
$this->data['header'] = 'Cron information page';
$this->includeAtTemplateBase('includes/header.php');
?>
<div id="content">
<p>Cron is a way to run things regularly on unix systems.</p>
<p>Here is a suggestion for a crontab file:</p>
<pre style="font-size: x-small; color: #444; padding: 1em; border: 1px solid #eee; margin: .4em "><code><?php
foreach ($this->data['urls'] AS $url ) {
echo "# " . $url['title'] . "\n";
echo "" . $url['int'] . " curl --silent --compressed " . $url['href'] . " > /dev/null 2>&1\n";
}
?>
</code></pre>
<p>Click here to run the cron jobs:
<ul>
<?php
foreach ($this->data['urls'] AS $url ) {
echo '<li><a href="' . $url['href'] . '">' . $url['title'] . '</a></li>';
}
?>
</ul>
</div>
<?php
$this->includeAtTemplateBase('includes/footer.php');
?>
|
Add ADD_INSTALLED_APPS to 'enabled' file
Django looks for translation catalogs from directories in
INSTALLED_APPS. To display translations for designate-dashboard,
'designatedashboard' needs to be registered to INSTALLED_APPS.
(cherry picked from commit 1ed7893eb2ae10172a2f664fc05428c28c29099e)
Change-Id: Id5f0f0cb9cba455fededa622da04ed7bee313218
Closes-Bug: #1561202
|
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from designatedashboard import exceptions
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'domains'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'project'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'dns'
ADD_INSTALLED_APPS = ['designatedashboard']
ADD_EXCEPTIONS = {
'recoverable': exceptions.RECOVERABLE,
'not_found': exceptions.NOT_FOUND,
'unauthorized': exceptions.UNAUTHORIZED,
}
# Python panel class of the PANEL to be added.
ADD_PANEL = (
'designatedashboard.dashboards.project.dns_domains.panel.DNSDomains')
|
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from designatedashboard import exceptions
# The name of the panel to be added to HORIZON_CONFIG. Required.
PANEL = 'domains'
# The name of the dashboard the PANEL associated with. Required.
PANEL_DASHBOARD = 'project'
# The name of the panel group the PANEL is associated with.
PANEL_GROUP = 'dns'
ADD_EXCEPTIONS = {
'recoverable': exceptions.RECOVERABLE,
'not_found': exceptions.NOT_FOUND,
'unauthorized': exceptions.UNAUTHORIZED,
}
# Python panel class of the PANEL to be added.
ADD_PANEL = (
'designatedashboard.dashboards.project.dns_domains.panel.DNSDomains')
|
Remove unecessary initialization of case insensitive instance variable,
already handled in parent class
|
<?php
namespace Stringizer\Transformers;
use Stringizer\Transformers\TransformerCaseInsensitive;
/**
* StringFirstOccurrence
*
* @link https://github.com/jasonlam604/Stringizer
* @copyright Copyright (c) 2016 Jason Lam
* @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE (MIT License)
*/
class StringFirstOccurrence extends TransformerCaseInsensitive implements TransformerInterface
{
private $needle;
private $beforeNeedle;
public function __construct($value, $needle, $beforeNeedle = false)
{
parent::__construct($value);
$this->needle = $needle;
$this->beforeNeedle = $beforeNeedle;
}
/**
* StringFirstOccurrence
*/
public function execute()
{
if ($this->isCaseInsensitive())
return mb_stristr($this->getValue(), $this->needle, $this->beforeNeedle);
else
return mb_strstr($this->getValue(), $this->needle, $this->beforeNeedle);
}
}
|
<?php
namespace Stringizer\Transformers;
use Stringizer\Transformers\TransformerCaseInsensitive;
/**
* StringFirstOccurrence
*
* @link https://github.com/jasonlam604/Stringizer
* @copyright Copyright (c) 2016 Jason Lam
* @license https://github.com/jasonlam604/Stringizer/blob/master/LICENSE (MIT License)
*/
class StringFirstOccurrence extends TransformerCaseInsensitive implements TransformerInterface
{
private $needle;
private $beforeNeedle;
public function __construct($value, $needle, $beforeNeedle = false)
{
parent::__construct($value);
$this->needle = $needle;
$this->beforeNeedle = $beforeNeedle;
$this->caseInsensitive = false;
}
/**
* StringFirstOccurrence
*/
public function execute()
{
if ($this->isCaseInsensitive())
return mb_stristr($this->getValue(), $this->needle, $this->beforeNeedle);
else
return mb_strstr($this->getValue(), $this->needle, $this->beforeNeedle);
}
}
|
Fix a bug, forgot to import logging
|
from bitHopper.Website import app, flask
import btcnet_info
import bitHopper.Configuration.Workers
import logging
@app.route("/worker", methods=['POST', 'GET'])
def worker():
#Check if this is a form submission
handle_worker_post(flask.request.form)
#Get a list of currently configured workers
pools_workers = {}
for pool in btcnet_info.get_pools():
if pool.name is None:
logging.debug('Ignoring %s', pool)
continue
pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name)
return flask.render_template('worker.html', pools = pools_workers)
def handle_worker_post(post):
for item in ['method','username','password', 'pool']:
if item not in post:
return
if post['method'] == 'remove':
bitHopper.Configuration.Workers.remove(
post['pool'], post['username'], post['password'])
elif post['method'] == 'add':
bitHopper.Configuration.Workers.add(
post['pool'], post['username'], post['password'])
|
from bitHopper.Website import app, flask
import btcnet_info
import bitHopper.Configuration.Workers
@app.route("/worker", methods=['POST', 'GET'])
def worker():
#Check if this is a form submission
handle_worker_post(flask.request.form)
#Get a list of currently configured workers
pools_workers = {}
for pool in btcnet_info.get_pools():
if pool.name is None:
logging.debug('Ignoring %s', pool)
continue
pools_workers[pool.name] = bitHopper.Configuration.Workers.get_worker_from(pool.name)
return flask.render_template('worker.html', pools = pools_workers)
def handle_worker_post(post):
for item in ['method','username','password', 'pool']:
if item not in post:
return
if post['method'] == 'remove':
bitHopper.Configuration.Workers.remove(
post['pool'], post['username'], post['password'])
elif post['method'] == 'add':
bitHopper.Configuration.Workers.add(
post['pool'], post['username'], post['password'])
|
Bump version number for adding !antighost command
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.2.5',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0'],
dependency_links=['git+https://github.com/jedevc/EuPy.git@7b48c35e96a1775ee37c4e5da8d3de46e99e609c#egg=eupy-1.0'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
#!/usr/bin/env python3
from setuptools import setup
setup(
name='botbot',
version='0.2.4',
description='A meta-bot for Euphoria.',
author='Rishov Sarkar',
url='https://github.com/ArkaneMoose/BotBot',
license='MIT',
packages=['botbot'],
package_dir={'botbot': 'source'},
install_requires=['eupy >=1.0, <2.0'],
dependency_links=['git+https://github.com/jedevc/EuPy.git@7b48c35e96a1775ee37c4e5da8d3de46e99e609c#egg=eupy-1.0'],
entry_points={
'console_scripts': [
'botbot = botbot.__main__:main'
]
}
)
|
Add support for array properties rendering
|
<?php
namespace Nayjest\Grids;
use Exception;
use RuntimeException;
class ObjectDataRow extends DataRow
{
/**
* @param string $fieldName
* @return mixed
* @throws Exception
*/
protected function extractCellValue($fieldName)
{
if (strpos($fieldName, '.') !== false) {
$parts = explode('.', $fieldName);
$res = $this->src;
foreach ($parts as $part) {
$res = is_object($res) ? $res->{$part} : $res[$part];
if ($res === null) {
return $res;
}
}
return $res;
} else {
try {
return $this->src->{$fieldName};
} catch(Exception $e) {
throw new RuntimeException(
"Can't read '$fieldName' property from DataRow"
);
}
}
}
}
|
<?php
namespace Nayjest\Grids;
use Exception;
use RuntimeException;
class ObjectDataRow extends DataRow
{
/**
* @param string $fieldName
* @return mixed
* @throws Exception
*/
protected function extractCellValue($fieldName)
{
if (strpos($fieldName, '.') !== false) {
$parts = explode('.', $fieldName);
$res = $this->src;
foreach ($parts as $part) {
$res = $res->{$part};
if ($res === null) {
return $res;
}
}
return $res;
} else {
try {
return $this->src->{$fieldName};
} catch(Exception $e) {
throw new RuntimeException(
"Can't read '$fieldName' property from DataRow"
);
}
}
}
}
|
[MIG] medical_prescription_us: Upgrade test namespace
* Change openerp namespace to odoo in test imports
|
# -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError
class TestMedicalPrescriptionOrderLine(TransactionCase):
def setUp(self):
super(TestMedicalPrescriptionOrderLine, self).setUp()
self.order_line_1 = self.env.ref(
'medical_prescription.' +
'medical_prescription_order_line_patient_1_order_1_line_1'
)
def test_check_refill_qty_original(self):
""" Test refill_qty_original cannot be less than 0 """
with self.assertRaises(ValidationError):
self.order_line_1.refill_qty_original = -1
|
# -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp.tests.common import TransactionCase
from openerp.exceptions import ValidationError
class TestMedicalPrescriptionOrderLine(TransactionCase):
def setUp(self):
super(TestMedicalPrescriptionOrderLine, self).setUp()
self.order_line_1 = self.env.ref(
'medical_prescription.' +
'medical_prescription_order_line_patient_1_order_1_line_1'
)
def test_check_refill_qty_original(self):
""" Test refill_qty_original cannot be less than 0 """
with self.assertRaises(ValidationError):
self.order_line_1.refill_qty_original = -1
|
Use fixed constant values for cursorMvmt
|
// package core contains the core data structures and functionality
// leveraged y the other other Goed packages.
package core
import "os"
const Version = "0.0.3"
const ApiVersion = "v1"
var Trace = true
// Ed is thew editor singleton
var Ed Editable
// Colors is the number of colors to use in the terminal
var Colors int
// Home represent the goed "home" folder.
var Home string
// testing : whether we are in "unit test" mode.
var Testing bool
// ConfigFile holds the path to the config file currently in use.
var ConfFile string
// LogFile holds the path of the log file currently in use.
var LogFile *os.File
// terminal as defined by $SHELL
var Terminal string
var Bus ActionDispatcher
var ApiPort int
var Socket string // instance RPC socket
var InstanceId int64 // instance ID
type CursorMvmt byte
const (
CursorMvmtRight CursorMvmt = 0
CursorMvmtLeft = 1
CursorMvmtUp = 2
CursorMvmtDown = 3
CursorMvmtPgDown = 4
CursorMvmtPgUp = 5
CursorMvmtHome = 6
CursorMvmtEnd = 7
CursorMvmtTop = 8
CursorMvmtBottom = 9
)
type ViewType int
const (
ViewTypeStandard ViewType = iota
ViewTypeInteractive
)
|
// package core contains the core data structures and functionality
// leveraged y the other other Goed packages.
package core
import "os"
const Version = "0.0.3"
const ApiVersion = "v1"
var Trace = false
// Ed is thew editor singleton
var Ed Editable
// Colors is the number of colors to use in the terminal
var Colors int
// Home represent the goed "home" folder.
var Home string
// testing : whether we are in "unit test" mode.
var Testing bool
// ConfigFile holds the path to the config file currently in use.
var ConfFile string
// LogFile holds the path of the log file currently in use.
var LogFile *os.File
// terminal as defined by $SHELL
var Terminal string
var Bus ActionDispatcher
var ApiPort int
var Socket string // instance RPC socket
var InstanceId int64 // instance ID
type CursorMvmt byte
const (
CursorMvmtRight CursorMvmt = iota
CursorMvmtLeft
CursorMvmtUp
CursorMvmtDown
CursorMvmtPgDown
CursorMvmtPgUp
CursorMvmtHome
CursorMvmtEnd
CursorMvmtTop
CursorMvmtBottom
)
type ViewType int
const (
ViewTypeStandard ViewType = iota
ViewTypeInteractive
)
|
Fix syntax error in query from request builder
|
'use strict'
class API {
static createQueryFromRequest (request) {
delete request.rats
delete request.CMDRs
let limit = parseInt(request.limit) || 25
delete request.limit
let offset = (parseInt(request.page) - 1) * limit || parseInt(request.offset) || 0
delete request.offset
delete request.page
let order = parseInt(request.order) || 'createdAt'
delete request.order
let direction = request.direction || 'ASC'
delete request.direction
if (request.firstLimpet) {
request.firstLimpetId = request.firstLimpet
delete request.firstLimpet
}
if (request.data) {
let dataQuery = request.data
delete request.data
request.data = {
$contains: JSON.parse(dataQuery)
}
}
let query = {
where: request,
order: [
[order, direction]
],
limit: limit,
offset: offset,
}
return query
}
static version (version) {
return function (req, res, next) {
req.apiVersion = version
next()
}
}
}
module.exports = API
|
'use strict'
class API {
static createQueryFromRequest (request) {
delete request.rats
delete delete request.CMDRs
let limit = parseInt(request.limit) || 25
delete request.limit
let offset = (parseInt(request.page) - 1) * limit || parseInt(request.offset) || 0
delete request.offset
delete request.page
let order = parseInt(request.order) || 'createdAt'
delete request.order
let direction = request.direction || 'ASC'
delete request.direction
if (request.firstLimpet) {
request.firstLimpetId = request.firstLimpet
delete request.firstLimpet
}
if (request.data) {
let dataQuery = request.data
delete request.data
request.data = {
$contains: JSON.parse(dataQuery)
}
}
let query = {
where: request,
order: [
[order, direction]
],
limit: limit,
offset: offset,
}
return query
}
static version (version) {
return function (req, res, next) {
req.apiVersion = version
next()
}
}
}
module.exports = API
|
Add test_a1_to_coord() to assert that only valid board coordinates are in teh _a1_to_coord dictionary
|
import engine
VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
(0, 0), (-1, -1),
(96, 49), (96, 48),
(105, 49), (104, 48),
(96, 56), (97, 57),
(105, 56), (104, 57)
]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8']
def test_coord_to_a1():
for coord in VALID_COORDS:
assert engine._coord_to_a1.get(coord, False) is not False
for coord in INVALID_COORDS:
assert engine._coord_to_a1.get(coord, False) is False
def test_a1_to_coord():
for a1 in VALID_A1:
assert engine._a1_to_coord.get(a1, False) is not False
for a1 in INVALID_A1:
assert engine._a1_to_coord.get(a1, False) is False
|
import engine
VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
(0, 0), (-1, -1),
(96, 49), (96, 48),
(105, 49), (104, 48),
(96, 56), (97, 57),
(105, 56), (104, 57)
]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_A1 = ['a0', 'a9', 'h0', 'h9', 'z1', 'z8']
def test_coord_to_a1():
for coord in VALID_COORDS:
assert engine._coord_to_a1.get(coord, False) is not False
for coord in INVALID_COORDS:
print coord
assert engine._coord_to_a1.get(coord, False) is False
|
Enable inline info instead of hiding it after the blue button in the upper right corner
|
import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: false,
inline: true,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
|
import { configure, addDecorator } from '@storybook/react';
import { setDefaults } from '@storybook/addon-info';
import { setOptions } from '@storybook/addon-options';
import backgroundColor from 'react-storybook-decorator-background';
// addon-info
setDefaults({
header: false,
inline: false,
source: true,
propTablesExclude: [],
});
setOptions({
name: `Version ${process.env.__VERSION__}`,
url: 'https://teamleader.design'
});
addDecorator(backgroundColor(['#ffffff', '#e6f2ff', '#ffeecc', '#d3f3f3', '#ffe3d9', '#e1edfa', '#f1f0ff', '#2a3b4d']));
const req = require.context('../stories', true, /\.js$/);
configure(() => {
req.keys().forEach(filename => req(filename));
}, module);
|
[VarDumper] Allow dd() to be called without arguments
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Component\VarDumper\VarDumper;
if (!function_exists('dump')) {
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
function dump($var, ...$moreVars)
{
VarDumper::dump($var);
foreach ($moreVars as $v) {
VarDumper::dump($v);
}
if (1 < func_num_args()) {
return func_get_args();
}
return $var;
}
}
if (!function_exists('dd')) {
function dd(...$vars)
{
foreach ($vars as $v) {
VarDumper::dump($v);
}
die(1);
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Symfony\Component\VarDumper\VarDumper;
if (!function_exists('dump')) {
/**
* @author Nicolas Grekas <p@tchwork.com>
*/
function dump($var, ...$moreVars)
{
VarDumper::dump($var);
foreach ($moreVars as $v) {
VarDumper::dump($v);
}
if (1 < func_num_args()) {
return func_get_args();
}
return $var;
}
}
if (!function_exists('dd')) {
function dd($var, ...$moreVars)
{
VarDumper::dump($var);
foreach ($moreVars as $v) {
VarDumper::dump($v);
}
exit(1);
}
}
|
Remove the dependency on math package in ptable.Parity
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package ptypes
// parityTable is a parity cache for all 16-bit non-negative integers.
var parityTable = initParityTable()
// initParityTable computes and returns parities for all 16-bit non-negative integers.
func initParityTable() []uint16 {
pt := make([]uint16, 1<<16)
for i := 0; i < len(pt); i++ {
pt[i] = Parity(uint16(i))
}
return pt
}
// Parity returns 1 if the number of bits set to 1 in x is odd, otherwise O.
func Parity(x uint16) (p uint16) {
for x > 0 {
p ^= 1
x &= (x - 1)
}
return p
}
// ParityLookup returns 1 if the number of bits set to 1 in x is odd, otherwise O.
// This function is good for computing the parity of a very large number of
// 64-bit non-negative integers.
func ParityLookup(x uint64) uint16 {
return parityTable[(x>>48)&0xffff] ^
parityTable[(x>>32)&0xffff] ^
parityTable[(x>>16)&0xffff] ^
parityTable[x&0xffff]
}
|
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package ptypes
import "math"
// parityTable is a parity cache for all 16-bit non-negative integers.
var parityTable = initParityTable()
// initParityTable computes and returns parities for all 16-bit non-negative integers.
func initParityTable() []uint16 {
pt := make([]uint16, 1<<16)
for i := 0; i <= math.MaxUint16; i++ {
pt[i] = Parity(uint16(i))
}
return pt
}
// Parity returns 1 if the number of bits set to 1 in x is odd, otherwise O.
func Parity(x uint16) (p uint16) {
for x > 0 {
p ^= 1
x &= (x - 1)
}
return p
}
// ParityLookup returns 1 if the number of bits set to 1 in x is odd, otherwise O.
// This function is good for computing the parity of a very large number of
// 64-bit non-negative integers.
func ParityLookup(x uint64) uint16 {
return parityTable[(x>>48)&0xffff] ^
parityTable[(x>>32)&0xffff] ^
parityTable[(x>>16)&0xffff] ^
parityTable[x&0xffff]
}
|
Add localization key and sound
|
var AWS = require('aws-sdk');
// Hardcoding keys on production is bad for your general health
AWS.config.update({accessKeyId: 'YOURACCESSKEYHERE', secretAccessKey: 'YOURSECRET', region: 'YOURREGION'});
var sns = new AWS.SNS({apiVersion: '2010-03-31'});
var lambdapayload = JSON.stringify({
message: 'Hello World',
custom: {
senderid: 'testsenderid',
localizationkey: "LOCALIZATION_KEY_IN_STRINGS_FILE",
sound: "default",
recipientid: 'testrecipient',
recipientname: 'Test Recipientname',
messageid: 'testmsgid',
devicetoken: 'token',
deviceplatform: 'ios'
}
});
var messagepayload = JSON.stringify({
default: 'This is a default message',
lambda: lambdapayload
});
var params = {
Message: messagepayload,
MessageStructure: 'json',
TopicArn: 'THETOPICTOPUBLISHTO'
};
sns.publish(params, function(err,data) {
console.log(err);
console.log(data);
});
|
var AWS = require('aws-sdk');
// Hardcoding keys on production is bad for your general health
AWS.config.update({accessKeyId: 'YOURACCESSKEYHERE', secretAccessKey: 'YOURSECRET', region: 'YOURREGION'});
var sns = new AWS.SNS({apiVersion: '2010-03-31'});
var lambdapayload = JSON.stringify({
message: 'Hello World',
custom: {
senderid: 'testsenderid',
recipientid: 'testrecipient',
recipientname: 'Test Recipientname',
messageid: 'testmsgid',
devicetoken: 'token',
deviceplatform: 'ios'
}
});
var messagepayload = JSON.stringify({
default: 'This is a default message',
lambda: lambdapayload
});
var params = {
Message: messagepayload,
MessageStructure: 'json',
TopicArn: 'THETOPICTOPUBLISHTO'
};
sns.publish(params, function(err,data) {
console.log(err);
console.log(data);
});
|
Fix indentation of the Python grammar
|
define(function() {
return function(Prism) {
Prism.languages.python= {
'comment': {
pattern: /(^|[^\\])#.*?(\r?\n|$)/g,
lookbehind: true
},
'string' : /("|')(\\?.)*?\1/g,
'keyword' : /\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g,
'boolean' : /\b(True|False)\b/g,
'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g,
'operator' : /[-+]{1,2}|=?<|=?>|!|={1,2}|(&){1,2}|(&){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g,
'ignore' : /&(lt|gt|amp);/gi,
'punctuation' : /[{}[\];(),.:]/g
};
};
});
|
define(function() {
// Export
return function(Prism) {
Prism.languages.python= {
'comment': {
pattern: /(^|[^\\])#.*?(\r?\n|$)/g,
lookbehind: true
},
'string' : /("|')(\\?.)*?\1/g,
'keyword' : /\b(as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/g,
'boolean' : /\b(True|False)\b/g,
'number' : /\b-?(0x)?\d*\.?[\da-f]+\b/g,
'operator' : /[-+]{1,2}|=?<|=?>|!|={1,2}|(&){1,2}|(&){1,2}|\|?\||\?|\*|\/|~|\^|%|\b(or|and|not)\b/g,
'ignore' : /&(lt|gt|amp);/gi,
'punctuation' : /[{}[\];(),.:]/g
};
};
});
|
Enforce the limit to be reset in get query :
```
$query = \Admingenerator\PropelDemoBundle\Model\MovieQuery::create('q')
$paginator = new Pagerfanta(new PagerAdapter($query));
$paginator->setMaxPerPage(3);
$paginator->setCurrentPage($this->getPage(), false, true);
```
```
SELECT propel_movies.ID, propel_movies.TITLE, propel_movies.IS_PUBLISHED, propel_movies.RELEASE_DATE, propel_movies.PRODUCER_ID
FROM `propel_movies` LIMIT 3
Time: 0.041 sec - Memory: 22.1 MB
SELECT COUNT(*)
FROM (SELECT propel_movies.ID, propel_movies.TITLE, propel_movies.IS_PUBLISHED, propel_movies.RELEASE_DATE, propel_movies.PRODUCER_ID
FROM `propel_movies` LIMIT 3) propelmatch4cnt
Time: 0.002 sec - Memory: 24.6 MB
```
So was always make one page !!
|
<?php
/*
* This file is part of the Pagerfanta package.
*
* (c) Pablo Díez <pablodip@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pagerfanta\Adapter;
/**
* PropelAdapter.
*
* @author William DURAND <william.durand1@gmail.com>
*/
class PropelAdapter implements AdapterInterface
{
private $query;
/**
* Constructor.
*/
public function __construct($query)
{
$this->query = $query;
}
/**
* Returns the query.
*/
public function getQuery()
{
return $this->query;
}
/**
* {@inheritdoc}
*/
public function getNbResults()
{
return $this->query->limit(0)->count();
}
/**
* {@inheritdoc}
*/
public function getSlice($offset, $length)
{
return $this->query->limit($length)->offset($offset)->find();
}
}
|
<?php
/*
* This file is part of the Pagerfanta package.
*
* (c) Pablo Díez <pablodip@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Pagerfanta\Adapter;
/**
* PropelAdapter.
*
* @author William DURAND <william.durand1@gmail.com>
*/
class PropelAdapter implements AdapterInterface
{
private $query;
/**
* Constructor.
*/
public function __construct($query)
{
$this->query = $query;
}
/**
* Returns the query.
*/
public function getQuery()
{
return $this->query;
}
/**
* {@inheritdoc}
*/
public function getNbResults()
{
return $this->query->count();
}
/**
* {@inheritdoc}
*/
public function getSlice($offset, $length)
{
return $this->query->limit($length)->offset($offset)->find();
}
}
|
Fix tests with Octave 5.
|
"""Example use of jupyter_kernel_test, with tests for IPython."""
import sys
import unittest
import jupyter_kernel_test as jkt
class OctaveKernelTests(jkt.KernelTests):
kernel_name = "octave"
language_name = "octave"
code_hello_world = "disp('hello, world')"
code_display_data = [
{'code': '%plot -f png\nplot([1,2,3])', 'mime': 'image/png'},
{'code': '%plot -f svg\nplot([1,2,3])', 'mime': 'image/svg+xml'}
] if sys.platform == 'darwin' else []
completion_samples = [
{
'text': 'acos',
'matches': {'acos', 'acosd', 'acosh'},
},
]
code_page_something = "ones?"
if __name__ == '__main__':
unittest.main()
|
"""Example use of jupyter_kernel_test, with tests for IPython."""
import sys
import unittest
import jupyter_kernel_test as jkt
class OctaveKernelTests(jkt.KernelTests):
kernel_name = "octave"
language_name = "octave"
code_hello_world = "disp('hello, world')"
code_display_data = [
{'code': '%plot -f png\nplot([1,2,3])', 'mime': 'image/png'},
{'code': '%plot -f svg\nplot([1,2,3])', 'mime': 'image/svg+xml'}
] if sys.platform == 'darwin' else []
completion_samples = [
{
'text': 'one',
'matches': {'ones', 'onenormest'},
},
]
code_page_something = "ones?"
if __name__ == '__main__':
unittest.main()
|
Remove fs from test dependencies.
|
'use strict';
var expect = require('chai').expect,
uncss = require('../lib/uncss');
describe('Using globbing patterns', function () {
it('should find both index pages in the directory and return the used CSS for both of them', function (done) {
this.timeout(25000);
uncss(['tests/glob/**/*.html'], function (err, output) {
expect(err).to.be.null;
expect(output).to.exist;
expect(output).to.contain('h1');
expect(output).to.contain('h2');
expect(output).not.to.contain('h3');
expect(output).not.to.contain('h4');
expect(output).not.to.contain('h5');
expect(output).not.to.contain('h6');
done();
});
});
});
|
'use strict';
var expect = require('chai').expect,
fs = require('fs'),
uncss = require('../lib/uncss');
describe('Using globbing patterns', function () {
it('should find both index pages in the directory and return the used CSS for both of them', function (done) {
this.timeout(25000);
uncss(['tests/glob/**/*.html'], function (err, output) {
expect(err).to.be.null;
expect(output).to.exist;
expect(output).to.contain('h1');
expect(output).to.contain('h2');
expect(output).not.to.contain('h3');
expect(output).not.to.contain('h4');
expect(output).not.to.contain('h5');
expect(output).not.to.contain('h6');
done();
});
});
});
|
Append newline after 'COMMIT' in iptables policies.
Without newline, the iptables-restore command complains.
|
#!/usr/bin/python2.4
#
# Copyright 2011 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.
#
"""Speedway iptables generator.
This is a subclass of Iptables library. The primary difference is
that this library produced 'iptable-restore' compatible output."""
__author__ = 'watson@google.com (Tony Watson)'
import iptables
class Term(iptables.Term):
"""Generate Iptables policy terms."""
_PLATFORM = 'speedway'
_PREJUMP_FORMAT = None
_POSTJUMP_FORMAT = '-A %s -j %s'
class Speedway(iptables.Iptables):
"""Generates filters and terms from provided policy object."""
_PLATFORM = 'speedway'
_DEFAULT_PROTOCOL = 'all'
_SUFFIX = '.ipt'
_RENDER_PREFIX = '*filter'
_RENDER_SUFFIX = 'COMMIT\n'
_DEFAULTACTION_FORMAT = ':%s %s'
_TERM = Term
|
#!/usr/bin/python2.4
#
# Copyright 2011 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.
#
"""Speedway iptables generator.
This is a subclass of Iptables library. The primary difference is
that this library produced 'iptable-restore' compatible output."""
__author__ = 'watson@google.com (Tony Watson)'
import iptables
class Term(iptables.Term):
"""Generate Iptables policy terms."""
_PLATFORM = 'speedway'
_PREJUMP_FORMAT = None
_POSTJUMP_FORMAT = '-A %s -j %s'
class Speedway(iptables.Iptables):
"""Generates filters and terms from provided policy object."""
_PLATFORM = 'speedway'
_DEFAULT_PROTOCOL = 'all'
_SUFFIX = '.ipt'
_RENDER_PREFIX = '*filter'
_RENDER_SUFFIX = 'COMMIT'
_DEFAULTACTION_FORMAT = ':%s %s'
_TERM = Term
|
Add socketio websocket status check
|
import AppDispatcher from '../dispatcher/AppDispatcher';
let runtimeAddress = localStorage.getItem('runtimeAddress') || '127.0.0.1';
let socket = io('http://' + runtimeAddress + ':5000/');
socket.on('connect', ()=>console.log('Connected to runtime.'));
socket.on('connect_error', (err)=>console.log(err));
/*
* Hack for Ansible messages to enter Flux flow.
* Received messages are dispatched as actions,
* with action's type deteremined by msg_type
*/
socket.on('message', (message)=>{
let transportName = socket.io.engine.transport.name;
if (transportName !== 'websocket') {
console.log('Websockets not working! Using:', transportName);
}
let unpackedMsg = message.content;
unpackedMsg.type = message.header.msg_type;
AppDispatcher.dispatch(unpackedMsg);
});
/*
* Module for communicating with the runtime.
*/
let Ansible = {
/* Private, use sendMessage */
_send(obj) {
return socket.emit('message', JSON.stringify(obj));
},
/* Send data over ZMQ to the runtime */
sendMessage(msgType, content) {
let msg = {
header: {
msg_type: msgType
},
content: content
};
this._send(msg);
}
};
export default Ansible;
|
import AppDispatcher from '../dispatcher/AppDispatcher';
let runtimeAddress = localStorage.getItem('runtimeAddress') || '127.0.0.1';
let socket = io('http://' + runtimeAddress + ':5000/');
socket.on('connect', ()=>console.log('Connected to runtime.'));
socket.on('connect_error', (err)=>console.log(err));
/*
* Hack for Ansible messages to enter Flux flow.
* Received messages are dispatched as actions,
* with action's type deteremined by msg_type
*/
socket.on('message', (message)=>{
let unpackedMsg = message.content;
unpackedMsg.type = message.header.msg_type;
AppDispatcher.dispatch(unpackedMsg);
});
/*
* Module for communicating with the runtime.
*/
let Ansible = {
/* Private, use sendMessage */
_send(obj) {
return socket.emit('message', JSON.stringify(obj));
},
/* Send data over ZMQ to the runtime */
sendMessage(msgType, content) {
let msg = {
header: {
msg_type: msgType
},
content: content
};
this._send(msg);
}
};
export default Ansible;
|
Add a test to configure GA event tracking
|
// Function to load and initiate the Analytics tracker
function gaTracker(id){
$.getScript('//www.google-analytics.com/analytics.js'); // jQuery shortcut
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', id, 'auto');
ga('send', 'pageview');
}
// Function to track a virtual page view
function gaTrack(path, title) {
ga('set', { page: path, title: title });
ga('send', 'pageview');
}
// Initiate the tracker after app has loaded
gaTracker('UA-69304119-1');
// Track a virtual page
gaTrack('/', 'Accueil');
gaTrack('/index.html', 'Accueil');
gaTrack('/legroupe.html', 'Le groupe');
gaTrack('/concerts.html', 'Concerts');
gaTrack('/albums.html', 'Albums');
gaTrack('/ateliers.html', 'Ateliers');
gaTrack('/presse.html', 'Presse');
gaTrack('/contact.html', 'Contact');
gaTrack('/404.html', '404');
// Event tracking on contact button click
$('#contactbutton').click(function() {
ga('send', {
hitType: 'event',
eventCategory: 'Contact',
eventAction: 'click',
eventLabel: 'contact button click'
});
});
|
// Function to load and initiate the Analytics tracker
function gaTracker(id){
$.getScript('//www.google-analytics.com/analytics.js'); // jQuery shortcut
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', id, 'auto');
ga('send', 'pageview');
}
// Function to track a virtual page view
function gaTrack(path, title) {
ga('set', { page: path, title: title });
ga('send', 'pageview');
}
// Initiate the tracker after app has loaded
gaTracker('UA-69304119-1');
// Track a virtual page
gaTrack('/', 'Accueil');
gaTrack('/index.html', 'Accueil');
gaTrack('/legroupe.html', 'Le groupe');
gaTrack('/concerts.html', 'Concerts');
gaTrack('/albums.html', 'Albums');
gaTrack('/ateliers.html', 'Ateliers');
gaTrack('/presse.html', 'Presse');
gaTrack('/contact.html', 'Contact');
gaTrack('/404.html', '404');
// Track an event on contact button click
$('#contactbutton').click(function() {
ga('send', 'event', 'Contact', 'click', 'contact button click');
});
|
Make toMail method compatible with the base class
|
<?php
namespace App\Base\Auth;
use Illuminate\Auth\Notifications\ResetPassword as BaseResetPassword;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPassword extends BaseResetPassword
{
/**
* Build the mail representation of the notification.
*
* @param mixed $notifiable
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$message = (new MailMessage)
->subject(trans('auth.password.email.action'))
->greeting(trans('auth.password.email.introduction'))
->line(trans('auth.password.email.content'))
->action(trans('auth.password.email.action'), route('password.reset.token', ['token' => $this->token]))
->line(trans('auth.password.email.conclusion'));
return $message;
}
}
|
<?php
namespace App\Base\Auth;
use Illuminate\Auth\Notifications\ResetPassword as BaseResetPassword;
use Illuminate\Notifications\Messages\MailMessage;
class ResetPassword extends BaseResetPassword
{
/**
* Build the mail representation of the notification.
*
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail()
{
$message = (new MailMessage)
->subject(trans('auth.password.email.action'))
->greeting(trans('auth.password.email.introduction'))
->line(trans('auth.password.email.content'))
->action(trans('auth.password.email.action'), route('password.reset.token', ['token' => $this->token]))
->line(trans('auth.password.email.conclusion'));
return $message;
}
}
|
Allow a default value to be specified when fetching a field value
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import sys
import argparse
parser = argparse.ArgumentParser(description='Fetches a field from a single API in the catalog')
parser.add_argument('file', help='File to load')
parser.add_argument('id', help='ID of API to fetch')
parser.add_argument('field', help='Field to find and output')
parser.add_argument('--default', help='Default value to output if field is not present')
args = parser.parse_args()
filename = sys.argv[1]
file = open(filename, "r")
catalog = json.load(file)
query = [api.get(args.field) for api in catalog["apis"] if api["id"] == args.id]
if len(query) != 1:
raise Exception(f"API {args.id} not found (or has duplicate definitions)")
elif not query[0] and args.default:
print(args.default)
elif not query[0]:
raise Exception(f"API {args.id} has no field {args.field}")
else:
print(query[0])
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import sys
import argparse
parser = argparse.ArgumentParser(description='Fetches a field from a single API in the catalog')
parser.add_argument('file', help='File to load')
parser.add_argument('id', help='ID of API to fetch')
parser.add_argument('field', help='Field to find and output')
args = parser.parse_args()
filename = sys.argv[1]
file = open(filename, "r")
catalog = json.load(file)
query = [api.get(args.field) for api in catalog["apis"] if api["id"] == args.id]
if len(query) != 1:
raise Exception(f"API {args.id} not found (or has duplicate definitions)")
elif not query[0]:
raise Exception(f"API {args.id} has no field {args.field}")
else:
print(query[0])
|
Remove unused statement for setting fennecIds in service
|
<?php
namespace AppBundle\API\Details;
use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
use AppBundle\Entity\Organism;
/**
* Web Service.
* Returns trait information to a list of organism ids
*/
class TraitsOfOrganisms
{
private $manager;
/**
* TraitsOfOrganisms constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
/**
* @param 'fennec_ids' => [13,7,12,5]
* @returns array $result
* <code>
* array(type_cvterm_id => array(
* 'trait_type' => 'habitat',
* 'trait_entry_ids' => array(1, 20, 36, 7),
* 'fennec_ids' => array(13, 20, 5)
* );
* </code>
*/
public function execute($fennec_ids)
{
return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids);
}
}
|
<?php
namespace AppBundle\API\Details;
use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;
use AppBundle\Entity\Organism;
/**
* Web Service.
* Returns trait information to a list of organism ids
*/
class TraitsOfOrganisms
{
private $manager;
/**
* TraitsOfOrganisms constructor.
* @param $dbversion
*/
public function __construct(DBVersion $dbversion)
{
$this->manager = $dbversion->getEntityManager();
}
/**
* @param 'fennec_ids' => [13,7,12,5]
* @returns array $result
* <code>
* array(type_cvterm_id => array(
* 'trait_type' => 'habitat',
* 'trait_entry_ids' => array(1, 20, 36, 7),
* 'fennec_ids' => array(13, 20, 5)
* );
* </code>
*/
public function execute($fennec_ids)
{
if(isset($_REQUEST['fennec_ids'])){
$fennec_ids = $_REQUEST['fennec_ids'];
}
return $this->manager->getRepository(Organism::class)->getTraits($fennec_ids);
}
}
|
Test sets instead of lists
|
import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0'}
if __name__ == '__main__':
main()
|
import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert sorted(info['files']) == ['lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib']
elif sys.platform.startswith('linux'):
assert sorted(info['files']) == ['lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', 'lib/libpng16.so.16.17.0']
if __name__ == '__main__':
main()
|
Add 'disabled' parameter to Activity renderer
|
<?php
namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;
use Honeybee\Ui\Renderer\ActivityRenderer;
class HtmlActivityRenderer extends ActivityRenderer
{
protected function getTemplateParameters()
{
$activity = $this->getPayload('subject');
$default_css = [
'activity',
'activity-' . strtolower($activity->getName())
];
$params = [];
$params['css'] = $this->getOption('css', $default_css);
$params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
$params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
$params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
$params['form_css'] = $this->getOption('form_css');
$params['activity_map_options'] = $this->getOption('activity_map_options', []);
$params['disabled'] = $this->getOption('disabled', false);
if ($params['disabled']) {
$params['css'][] = 'disabled';
}
return array_replace_recursive(parent::getTemplateParameters(), $params);
}
}
|
<?php
namespace Honeybee\Ui\Renderer\Html\Honeybee\Ui\Activity;
use Honeybee\Ui\Renderer\ActivityRenderer;
class HtmlActivityRenderer extends ActivityRenderer
{
protected function getTemplateParameters()
{
$activity = $this->getPayload('subject');
$default_css = [
'activity',
'activity-' . strtolower($activity->getName())
];
$params = [];
$params['css'] = $this->getOption('css', $default_css);
$params['form_id'] = $this->getOption('form_id', $activity->getSettings()->get('form_id', 'formid'));
$params['form_parameters'] = $this->getOption('form_parameters', $activity->getUrl()->getParameters());
$params['form_method'] = $this->getOption('form_method', ($activity->getVerb() === 'read') ? 'GET' : 'POST');
$params['form_css'] = $this->getOption('form_css');
$params['activity_map_options'] = $this->getOption('activity_map_options', []);
return array_replace_recursive(parent::getTemplateParameters(), $params);
}
}
|
Use require for this special case
|
import gutil from 'gulp-util';
import makeWebpackConfig from './makeConfig';
import webpack from 'webpack';
export default function build(callback) {
const config = makeWebpackConfig(false);
webpack(config, (fatalError, stats) => {
const jsonStats = stats.toJson();
// We can save jsonStats to be analyzed with
// http://webpack.github.io/analyse or
// https://github.com/robertknight/webpack-bundle-size-analyzer.
// const fs = require('fs');
// fs.writeFileSync('./bundle-stats.json', JSON.stringify(jsonStats));
const buildError = fatalError || jsonStats.errors[0] || jsonStats.warnings[0];
if (buildError) {
throw new gutil.PluginError('webpack', buildError);
}
gutil.log('[webpack]', stats.toString({
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}));
callback();
});
}
|
import gutil from 'gulp-util';
import makeWebpackConfig from './makeConfig';
import webpack from 'webpack';
export default function build(callback) {
const config = makeWebpackConfig(false);
webpack(config, (fatalError, stats) => {
const jsonStats = stats.toJson();
// We can save jsonStats to be analyzed with
// http://webpack.github.io/analyse or
// https://github.com/robertknight/webpack-bundle-size-analyzer.
// import fs from 'fs';
// fs.writeFileSync('./bundle-stats.json', JSON.stringify(jsonStats));
const buildError = fatalError || jsonStats.errors[0] || jsonStats.warnings[0];
if (buildError) {
throw new gutil.PluginError('webpack', buildError);
}
gutil.log('[webpack]', stats.toString({
colors: true,
version: false,
hash: false,
timings: false,
chunks: false,
chunkModules: false
}));
callback();
});
}
|
Add count param to mostRecent()
|
<?php
namespace ATPCms\Model;
class Category extends \ATP\ActiveRecord
{
protected function createDefinition()
{
$this->hasData('Name', 'Url', 'IsViewable', 'ShowPages', 'ShowInHeader', 'Text')
->hasStaticBlocks()
->hasPages()
->isIdentifiedBy('Url')
->tableNamespace("cms")
->isOrderedBy("name ASC");
}
public function displayName()
{
return $this->name;
}
public static function headerCategories()
{
$where = "show_in_header=1";
$cat = new self();
return $cat->loadMultiple($where);
}
public function mostRecent($count)
{
$page = new Page();
return $page->loadMultiple("category_id = ? AND is_active=1", array($this->id), array(), "post_date DESC", $count);
}
}
Category::init();
|
<?php
namespace ATPCms\Model;
class Category extends \ATP\ActiveRecord
{
protected function createDefinition()
{
$this->hasData('Name', 'Url', 'IsViewable', 'ShowPages', 'ShowInHeader', 'Text')
->hasStaticBlocks()
->hasPages()
->isIdentifiedBy('Url')
->tableNamespace("cms")
->isOrderedBy("name ASC");
}
public function displayName()
{
return $this->name;
}
public static function headerCategories()
{
$where = "show_in_header=1";
$cat = new self();
return $cat->loadMultiple($where);
}
public function mostRecent($count)
{
$page = new Page();
return $page->loadMultiple("category_id = ? AND is_active=1", array($this->id), array(), "post_date DESC");
}
}
Category::init();
|
Add support for secure connection
|
package irc
import "net"
import "fmt"
import "bufio"
import "crypto/tls"
type Client struct {
socket net.Conn
Host string
Port int
Nickname string
Ident string
Realname string
Secure bool
Handler EventHandler
}
func (c *Client) Write(s string) error {
_, err := c.socket.Write([]byte(s + "\r\n"))
return err
}
func (c *Client) Connect() error {
var socket net.Conn
var err error
if c.Secure {
socket, err = tls.Dial("tcp", fmt.Sprintf("%s:%v", c.Host, c.Port), &tls.Config{})
} else {
socket, err = net.Dial("tcp", fmt.Sprintf("%s:%v", c.Host, c.Port))
}
if err != nil {
return err
}
c.socket = socket
c.Write("NICK " + c.Nickname)
c.Write("USER " + c.Ident + " 0 * :" + c.Realname)
if err = c.readPump(); err != nil {
return err
}
return nil
}
func (c *Client) readPump() error {
reader := bufio.NewReader(c.socket)
for {
line, err := reader.ReadString('\n')
if err != nil {
return err
}
line = line[0 : len(line)-2]
message := Message{raw: line}
message.parse()
c.Handler.trigger(c, &message)
}
}
|
package irc
import "net"
import "fmt"
import "bufio"
type Client struct {
socket net.Conn
Host string
Port int
Nickname string
Ident string
Realname string
Handler EventHandler
}
func (c *Client) Write(s string) error {
_, err := c.socket.Write([]byte(s + "\r\n"))
return err
}
func (c *Client) Connect() error {
socket, err := net.Dial("tcp", fmt.Sprintf("%s:%v", c.Host, c.Port))
if err != nil {
return err
}
c.socket = socket
c.Write("NICK " + c.Nickname)
c.Write("USER " + c.Ident + " 0 * :" + c.Realname)
if err = c.readPump(); err != nil {
return err
}
return nil
}
func (c *Client) readPump() error {
reader := bufio.NewReader(c.socket)
for {
line, err := reader.ReadString('\n')
if err != nil {
return err
}
line = line[0 : len(line)-2]
message := Message{raw: line}
message.parse()
c.Handler.trigger(c, &message)
}
}
|
Add configure flags to for 32-bit build on 64-bit Mac OS X machine
|
'use strict';
var bin = require('./');
var BinBuild = require('bin-build');
var logSymbols = require('log-symbols');
var path = require('path');
/**
* Install binary and check whether it works.
* If the test fails, try to build it.
*/
var args = [
'-copy', 'none',
'-optimize',
'-outfile', path.join(__dirname, '../test/fixtures/test-optimized.jpg'),
path.join(__dirname, '../test/fixtures/test.jpg')
];
bin.run(args, function (err) {
if (err) {
console.log(logSymbols.warning + ' pre-build test failed, compiling from source...');
var flags = '';
if (process.platform === 'darwin' && process.arch === 'x64') {
flags = 'CFLAGS="-m32" LDFLAGS="-m32" ';
}
var builder = new BinBuild()
.src('http://downloads.sourceforge.net/project/libjpeg-turbo/' + bin.v + '/libjpeg-turbo-' + bin.v + '.tar.gz')
.cmd(flags + './configure --disable-shared --prefix="' + bin.dest() + '" --bindir="' + bin.dest() + '"')
.cmd('make install');
return builder.build(function (err) {
if (err) {
console.log(logSymbols.error, err);
return;
}
console.log(logSymbols.success + ' jpegtran built successfully!');
});
}
console.log(logSymbols.success + ' pre-build test passed successfully!');
});
|
'use strict';
var bin = require('./');
var BinBuild = require('bin-build');
var logSymbols = require('log-symbols');
var path = require('path');
/**
* Install binary and check whether it works.
* If the test fails, try to build it.
*/
var args = [
'-copy', 'none',
'-optimize',
'-outfile', path.join(__dirname, '../test/fixtures/test-optimized.jpg'),
path.join(__dirname, '../test/fixtures/test.jpg')
];
bin.run(args, function (err) {
if (err) {
console.log(logSymbols.warning + ' pre-build test failed, compiling from source...');
var builder = new BinBuild()
.src('http://downloads.sourceforge.net/project/libjpeg-turbo/' + bin.v + '/libjpeg-turbo-' + bin.v + '.tar.gz')
.cmd('./configure --disable-shared --prefix="' + bin.dest() + '" --bindir="' + bin.dest() + '"')
.cmd('make install');
return builder.build(function (err) {
if (err) {
console.log(logSymbols.error, err);
return;
}
console.log(logSymbols.success + ' jpegtran built successfully!');
});
}
console.log(logSymbols.success + ' pre-build test passed successfully!');
});
|
Watch OpenGL Shading Language files as well
|
'use strict';
var utils = require('./_utils'),
eslint = require('./eslint'),
build = require('./build'),
chokidar = require('chokidar');
module.exports = function(options) {
options = utils.extend({
// chokidar events we are going to watch
// generally you should not touch them
watchEvents: [
'change',
'add',
'unlink',
'unlinkDir',
'addDir'
]
}, options);
// return a promise based on a certain task triggered
var runOnlyOn = function(event) {
if (~options.watchEvents.indexOf(event)) {
// go to the next task
return Promise.resolve();
} else {
return Promise.reject();
}
};
// run eslint when a source file gets updated
utils.print('Watching the files in the src/**/**/*.js path', 'cool');
chokidar.watch(['src/**/**/*.js', 'src/**/**/*.glsl'], {
ignoreInitial: true
}).on('all', function(event) {
// this tasks will run only if the current event matches the ones in the watchEvents array
runOnlyOn(event)
.then(build);
});
};
|
'use strict';
var utils = require('./_utils'),
eslint = require('./eslint'),
build = require('./build'),
chokidar = require('chokidar');
module.exports = function(options) {
options = utils.extend({
// chokidar events we are going to watch
// generally you should not touch them
watchEvents: [
'change',
'add',
'unlink',
'unlinkDir',
'addDir'
]
}, options);
// return a promise based on a certain task triggered
var runOnlyOn = function(event) {
if (~options.watchEvents.indexOf(event)) {
// go to the next task
return Promise.resolve();
} else {
return Promise.reject();
}
};
// run eslint when a source file gets updated
utils.print('Watching the files in the src/**/**/*.js path', 'cool');
chokidar.watch('src/**/**/*.js', {
ignoreInitial: true
}).on('all', function(event) {
// this tasks will run only if the current event matches the ones in the watchEvents array
runOnlyOn(event)
.then(build);
});
};
|
Delete emails before deleting users
--HG--
branch : production
|
#!/usr/bin/python
import sys
import os
prefix = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, prefix)
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
import config
import store
CONFIG_FILE = os.environ.get("PYPI_CONFIG", os.path.join(prefix, 'config.ini'))
conf = config.Config(CONFIG_FILE)
store = store.Store(conf)
cursor = store.get_cursor()
cursor.execute("delete from cookies where last_seen < now()-INTERVAL'1day';")
cursor.execute("delete from openid_sessions where expires < now();")
cursor.execute("delete from openid_nonces where created < now()-INTERVAL'1day'; ")
cursor.execute("delete from openids where name in (select name from rego_otk where date < now()-INTERVAL'7days');")
cursor.execute("delete from accounts_email where user_id in (select id from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles)));")
cursor.execute("delete from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles));")
store.commit()
|
#!/usr/bin/python
import sys
import os
prefix = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, prefix)
# Workaround current bug in docutils:
# http://permalink.gmane.org/gmane.text.docutils.devel/6324
import docutils.utils
import config
import store
CONFIG_FILE = os.environ.get("PYPI_CONFIG", os.path.join(prefix, 'config.ini'))
conf = config.Config(CONFIG_FILE)
store = store.Store(conf)
cursor = store.get_cursor()
cursor.execute("delete from cookies where last_seen < now()-INTERVAL'1day';")
cursor.execute("delete from openid_sessions where expires < now();")
cursor.execute("delete from openid_nonces where created < now()-INTERVAL'1day'; ")
cursor.execute("delete from openids where name in (select name from rego_otk where date < now()-INTERVAL'7days');")
cursor.execute("delete from accounts_user where username in (select name from rego_otk where date < now()-INTERVAL'7days' and name not in (select user_name from roles));")
store.commit()
|
Normalize fn name for change objects
|
import {curry, values} from 'ladda-fp';
import {createCache} from './cache';
import {decorateCreate} from './operations/create';
import {decorateRead} from './operations/read';
import {decorateUpdate} from './operations/update';
import {decorateDelete} from './operations/delete';
import {decorateNoOperation} from './operations/no-operation';
const HANDLERS = {
CREATE: decorateCreate,
READ: decorateRead,
UPDATE: decorateUpdate,
DELETE: decorateDelete,
NO_OPERATION: decorateNoOperation
};
const normalizeFnName = (fnName) => fnName.replace(/^bound /, '');
const notify = curry((onChange, entity, fn, changeType, args, payload) => {
onChange({
type: changeType,
entity: entity.name,
apiFn: normalizeFnName(fn.name),
values: Array.isArray(payload) ? payload : [payload],
args
});
});
export const cachePlugin = (onChange) => ({ config, entityConfigs }) => {
const cache = createCache(values(entityConfigs));
return ({ entity, fn }) => {
const handler = HANDLERS[fn.operation];
const notify_ = notify(onChange, entity, fn);
return handler(config, cache, notify_, entity, fn);
};
};
|
import {curry, values} from 'ladda-fp';
import {createCache} from './cache';
import {decorateCreate} from './operations/create';
import {decorateRead} from './operations/read';
import {decorateUpdate} from './operations/update';
import {decorateDelete} from './operations/delete';
import {decorateNoOperation} from './operations/no-operation';
const HANDLERS = {
CREATE: decorateCreate,
READ: decorateRead,
UPDATE: decorateUpdate,
DELETE: decorateDelete,
NO_OPERATION: decorateNoOperation
};
const notify = curry((onChange, entity, fn, changeType, args, payload) => {
onChange({
type: changeType,
entity: entity.name,
apiFn: fn.name,
values: Array.isArray(payload) ? payload : [payload],
args
});
});
export const cachePlugin = (onChange) => ({ config, entityConfigs }) => {
const cache = createCache(values(entityConfigs));
return ({ entity, fn }) => {
const handler = HANDLERS[fn.operation];
const notify_ = notify(onChange, entity, fn);
return handler(config, cache, notify_, entity, fn);
};
};
|
Add error log for execCheck
|
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 - 2019 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan
*
* 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/>.
*/
package ml.duncte123.skybot.unstable.utils;
import ml.duncte123.skybot.Author;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Author(nickname = "Sanduhr32", author = "Maurice R S")
public class ComparatingUtils {
private static final Logger logger = LoggerFactory.getLogger(ComparatingUtils.class);
// Needs to be fixed
public static void execCheck(Throwable t) {
logger.error("An error occurred", t);
t.printStackTrace();
Throwable cause = t.getCause();
while (cause != null) {
cause.printStackTrace();
cause = cause.getCause();
}
}
}
|
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 - 2019 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan
*
* 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/>.
*/
package ml.duncte123.skybot.unstable.utils;
import ml.duncte123.skybot.Author;
@Author(nickname = "Sanduhr32", author = "Maurice R S")
public class ComparatingUtils {
// Needs to be fixed
public static void execCheck(Throwable t) {
t.printStackTrace();
Throwable cause = t.getCause();
while (cause != null) {
cause.printStackTrace();
cause = cause.getCause();
}
}
}
|
Send proper 404 code: fix
|
<?php
/**
* SpinDash — A web development framework
* © 2007–2015 Ilya I. Averkov
*
* Contributors:
* Irfan Mahfudz Guntur <ayes@bsmsite.com>
* Evgeny Bulgakov <evgeny@webline-masters.ru>
*/
namespace SpinDash\Http;
final class Response
{
private $code = 200;
private $body = '';
public function setBody($data) {
$this->body = $data;
}
public function statusCodeDescription() {
switch($this->code) {
case 404: return 'Not Found'; break;
default: return 'OK'; break;
}
}
public function sendBasic() {
if($this->code !== 200) {
header("HTTP/1.1 {$this->code} " . $this->statusCodeDescription());
}
echo $this->body;
}
public function sendPHPSGI() {
return ["{$this->code} " . $this->statusCodeDescription(), ['Content-Type' => 'text/html'], $this->body];
}
public function setStatusCode($code) {
$this->code = $code;
}
}
|
<?php
/**
* SpinDash — A web development framework
* © 2007–2015 Ilya I. Averkov
*
* Contributors:
* Irfan Mahfudz Guntur <ayes@bsmsite.com>
* Evgeny Bulgakov <evgeny@webline-masters.ru>
*/
namespace SpinDash\Http;
final class Response
{
private $status_code = 200;
private $body = '';
public function setBody($data) {
$this->body = $data;
}
public function statusCodeDescription() {
switch($this->status_code) {
case 404: return 'Not Found'; break;
default: return 'OK'; break;
}
}
public function sendBasic() {
if($this->status_code !== 200) {
header("HTTP/1.1 {$this->status_code} " . $this->statusCodeDescription());
}
echo $this->body;
}
public function sendPHPSGI() {
return ["{$this->status_code} " . $this->statusCodeDescription(), ['Content-Type' => 'text/html'], $this->body];
}
public function setStatusCode($code) {
$this->code = $code;
}
}
|
Fix allowable domain otherwise filtered
|
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
|
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/data/en']
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
|
Update code to accomodate new blog index page
|
/*!
* Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
$('div.modal').on('show.bs.modal', function() {
var modal = this;
var hash = modal.id;
window.location.hash = hash;
window.onhashchange = function() {
if (!location.hash){
$(modal).modal('hide');
}
}
});
$(function() {
var fullPath = window.location.pathname.substring(1);
var parentPath = fullPath.split('/')[0];
var path = fullPath.replace(/\//g, '');
if (path) {
// For blog post pages.
if (/blog/.test(path)) {
parentPath = parentPath +'/';
}
$("#bs-example-navbar-collapse-1 a[href='/"+parentPath+"']").addClass('active');
}
});
|
/*!
* Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
$('div.modal').on('show.bs.modal', function() {
var modal = this;
var hash = modal.id;
window.location.hash = hash;
window.onhashchange = function() {
if (!location.hash){
$(modal).modal('hide');
}
}
});
$(function() {
var fullPath = window.location.pathname.substring(1);
var parentPath = fullPath.split('/')[0];
var path = fullPath.replace(/\//g, '');
if (path) {
// For blog post pages.
if (path.match(/^\d{4}/)) { path = 'blog' }
$("#bs-example-navbar-collapse-1 a[href='/"+parentPath+"']").addClass('active');
}
});
|
Fix tests to use new key structure
|
from roglick.engine.ecs import Entity,EntityManager
from roglick.components import SkillComponent,SkillSubComponent
from roglick.systems import SkillSystem
from roglick.engine import event
from roglick.events import SkillCheckEvent
def test_skill_check():
wins = 0
iters = 1000
em = EntityManager()
em.set_component(em.pc, SkillComponent())
skills = em.get_component(em.pc, SkillComponent)
# 7 has ~41% odds of success
skills.skills['melee.swords.dagger'] = SkillSubComponent(7)
sys = SkillSystem()
sys.set_entity_manager(em)
event.register(sys)
for x in range(iters):
ch = SkillCheckEvent(em.pc, "melee.swords.dagger")
event.dispatch(ch)
if ch.result[2]:
wins += 1
# Use a fudge factor, because random
assert wins >= (iters * 0.38)
assert wins <= (iters * 0.44)
|
from roglick.engine.ecs import Entity,EntityManager
from roglick.components import SkillComponent,SkillSubComponent
from roglick.systems import SkillSystem
from roglick.engine import event
from roglick.events import SkillCheckEvent
def test_skill_check():
wins = 0
iters = 1000
em = EntityManager()
em.set_component(em.pc, SkillComponent())
skills = em.get_component(em.pc, SkillComponent)
# 7 has ~41% odds of success
skills.skills['Dagger'] = SkillSubComponent(7)
sys = SkillSystem()
sys.set_entity_manager(em)
event.register(sys)
for x in range(iters):
ch = SkillCheckEvent(em.pc, "Dagger")
event.dispatch(ch)
if ch.result[2]:
wins += 1
# Use a fudge factor, because random
assert wins >= (iters * 0.38)
assert wins <= (iters * 0.44)
|
Add randomized option for example
|
require('coffee-script/register');
var path = require('path');
var Jasmine = require('jasmine');
var SpecReporter = require('../src/jasmine-spec-reporter.js');
var noop = function () {};
var jrunner = new Jasmine();
jrunner.configureDefaultReporter({print: noop});
jasmine.getEnv().addReporter(new SpecReporter({
displayStacktrace: 'none',
displayFailuresSummary: true,
displayPendingSummary: true,
displaySuccessfulSpec: true,
displayFailedSpec: true,
displayPendingSpec: true,
displaySpecDuration: false,
displaySuiteNumber: false,
colors: {
success: 'green',
failure: 'red',
pending: 'yellow'
},
prefixes: {
success: '✓ ',
failure: '✗ ',
pending: '* '
},
customProcessors: []
}));
jrunner.projectBaseDir = '';
jrunner.specDir = '';
jrunner.randomizeTests(false);
jrunner.addSpecFiles([path.resolve('example/example-spec.coffee')]);
jrunner.execute();
|
require('coffee-script/register');
var path = require('path');
var Jasmine = require('jasmine');
var SpecReporter = require('../src/jasmine-spec-reporter.js');
var noop = function () {};
var jrunner = new Jasmine();
jrunner.configureDefaultReporter({print: noop});
jasmine.getEnv().addReporter(new SpecReporter({
displayStacktrace: 'none',
displayFailuresSummary: true,
displayPendingSummary: true,
displaySuccessfulSpec: true,
displayFailedSpec: true,
displayPendingSpec: true,
displaySpecDuration: false,
displaySuiteNumber: false,
colors: {
success: 'green',
failure: 'red',
pending: 'yellow'
},
prefixes: {
success: '✓ ',
failure: '✗ ',
pending: '* '
},
customProcessors: []
}));
jrunner.projectBaseDir = '';
jrunner.specDir = '';
jrunner.addSpecFiles([path.resolve('example/example-spec.coffee')]);
jrunner.execute();
|
Add test for the transpose function.
|
#!/usr/bin/env python3
from libpals.util import (
xor_find_singlechar_key,
hamming_distance,
fixed_xor,
transpose
)
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
def test_hamming_distance():
assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
def test_fixed_xor():
input = bytes.fromhex("1c0111001f010100061a024b53535009181c")
key = bytes.fromhex("686974207468652062756c6c277320657965")
assert fixed_xor(input, key) == b"the kid don't play"
def test_transpose():
chunks = [b'adg', b'beh', b'cfi']
assert transpose(chunks) == b'abcdefghi'
|
#!/usr/bin/env python3
from libpals.util import (
xor_find_singlechar_key,
hamming_distance,
fixed_xor
)
def test_xor_find_singlechar_key():
input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
ciphertext = bytes.fromhex(input)
result = xor_find_singlechar_key(ciphertext)
assert result['key'] == 88
assert result['plaintext'] == b"Cooking MC's like a pound of bacon"
def test_hamming_distance():
assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37
def test_fixed_xor():
input = bytes.fromhex("1c0111001f010100061a024b53535009181c")
key = bytes.fromhex("686974207468652062756c6c277320657965")
assert fixed_xor(input, key) == b"the kid don't play"
|
Fix tests on Python2.7 xmlrpclib.Transport.parse_response calls 'getheader' on its response input
|
"""Utils for Zinnia's tests"""
import StringIO
from xmlrpclib import Transport
from django.test.client import Client
class TestTransport(Transport):
"""Handles connections to XML-RPC server
through Django test client."""
def __init__(self, *args, **kwargs):
Transport.__init__(self, *args, **kwargs)
self.client = Client()
def request(self, host, handler, request_body, verbose=0):
self.verbose = verbose
response = self.client.post(handler,
request_body,
content_type="text/xml")
res = StringIO.StringIO(response.content)
setattr(res, 'getheader', lambda *args: '') # For Python >= 2.7
res.seek(0)
return self.parse_response(res)
|
"""Utils for Zinnia's tests"""
import cStringIO
from xmlrpclib import Transport
from django.test.client import Client
class TestTransport(Transport):
"""Handles connections to XML-RPC server
through Django test client."""
def __init__(self, *args, **kwargs):
Transport.__init__(self, *args, **kwargs)
self.client = Client()
def request(self, host, handler, request_body, verbose=0):
self.verbose = verbose
response = self.client.post(handler,
request_body,
content_type="text/xml")
res = cStringIO.StringIO(response.content)
res.seek(0)
return self.parse_response(res)
|
Use standard pattern for utility class
|
package com.getbase.android.autoprovider;
import com.google.common.collect.ImmutableBiMap;
import org.chalup.thneed.ModelGraph;
import org.chalup.thneed.ModelVisitor;
import org.chalup.thneed.models.DatabaseModel;
import org.chalup.thneed.models.PojoModel;
public final class Utils {
private Utils() {
}
public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) {
final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder();
modelGraph.accept(new ModelVisitor<TModel>() {
@Override
public void visit(TModel model) {
classToTableMappingBuilder.put(model.getModelClass(), model.getTableName());
}
});
return classToTableMappingBuilder.build();
}
}
|
package com.getbase.android.autoprovider;
import com.google.common.collect.ImmutableBiMap;
import org.chalup.thneed.ModelGraph;
import org.chalup.thneed.ModelVisitor;
import org.chalup.thneed.models.DatabaseModel;
import org.chalup.thneed.models.PojoModel;
public class Utils {
public static <TModel extends DatabaseModel & PojoModel> ImmutableBiMap<Class<?>, String> buildClassToTableMap(ModelGraph<TModel> modelGraph) {
final ImmutableBiMap.Builder<Class<?>, String> classToTableMappingBuilder = ImmutableBiMap.builder();
modelGraph.accept(new ModelVisitor<TModel>() {
@Override
public void visit(TModel model) {
classToTableMappingBuilder.put(model.getModelClass(), model.getTableName());
}
});
return classToTableMappingBuilder.build();
}
}
|
Fix IE8 bug with email repeat
|
/* global $ */
'use strict'
/**
* Email repeat
*/
function EmailRepeat (element, config) {
var options = {}
$.extend(options, config)
// Private variables
var hintWrapper
var hint
/**
* Set everything up
*/
function create () {
// Bail out if we don't have the proper element to act upon
if (!element) {
return
}
hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p></div>')
hint = $('<p class="bold email-hint-value"></p>')
$(hintWrapper).append(hint)
$(element).on('change', updateHint)
$(element).on('input', updateHint)
}
/**
*
*/
function updateHint () {
$(element).after(hintWrapper)
// If the input field gets emptied out again, remove the hint
if (element.value.length === 0) {
hintWrapper.remove()
return
}
// Update the hint to match the input value
hint.text(element.value)
}
/**
* Tear everything down again
*/
function destroy () {
hintWrapper.remove()
$(element).off('change', updateHint)
$(element).off('input', updateHint)
}
var self = {
create: create,
destroy: destroy
}
return self
}
export { EmailRepeat }
|
/* global $ */
'use strict'
/**
* Email repeat
*/
function EmailRepeat (element, config) {
var options = {}
$.extend(options, config)
// Private variables
var hintWrapper
var hint
/**
* Set everything up
*/
function create () {
// Bail out if we don't have the proper element to act upon
if (!element) {
return
}
hintWrapper = $('<div class="panel panel-border-narrow email-hint spacing-top-single"><p>Please ensure your email address is displayed correctly below. We will need this if you need to reset your password in future.</p><p class="bold email-hint-value"></p></div>')
hint = $(hintWrapper).find('.email-hint-value')
$(element).on('change', updateHint)
$(element).on('input', updateHint)
}
/**
*
*/
function updateHint () {
$(element).after(hintWrapper)
// If the input field gets emptied out again, remove the hint
if (element.value.length === 0) {
hintWrapper.remove()
return
}
// Update the hint to match the input value
hint.text(element.value)
}
/**
* Tear everything down again
*/
function destroy () {
hintWrapper.remove()
$(element).off('change', updateHint)
$(element).off('input', updateHint)
}
var self = {
create: create,
destroy: destroy
}
return self
}
export { EmailRepeat }
|
Update develop version to 1.7-dev since 1.6 is in production
|
__version_info__ = (1, 7, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
socialauth_providers = []
# generate a list of social auth providers associated with this account,
# for use in displaying available backends
if not request.user.is_anonymous():
socialauth_providers = [auth.provider for auth in request.user.social_auth.all()]
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
'user_socialauth_providers': socialauth_providers
}
|
__version_info__ = (1, 6, 1, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environment
def context_extras(request):
socialauth_providers = []
# generate a list of social auth providers associated with this account,
# for use in displaying available backends
if not request.user.is_anonymous():
socialauth_providers = [auth.provider for auth in request.user.social_auth.all()]
return {
# software version
'SW_VERSION': __version__,
# Alternate names for social-auth backends,
# to be used for display and font-awesome icon (lowercased)
# If not entered here, backend name will be used as-is for
# icon and title-cased for display (i.e., twitter / Twitter).
'backend_names': {
'github': 'GitHub',
'google-oauth2': 'Google',
},
'user_socialauth_providers': socialauth_providers
}
|
Add PHP's open and closing tags
|
<?php
function export_posts_as_csv() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'pages',
'post_status' => array( 'publish', 'pending' ),
'orderby' => 'title',
'order' => 'ASC'
);
query_posts( $args );
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=my_pages.csv');
$output = fopen( 'php://output', 'w' );
fputcsv( $output, array( 'Nr', 'Page_ID', 'Page_Title', 'Page_Status' ) );
$i = 1;
while( have_posts() ) : the_post();
fputcsv( $output, array( $i, get_the_ID(), get_the_title(), get_post_status() ) );
$i++;
endwhile;
wp_reset_query();
fclose( $output );
die;
}
?>
|
function export_posts_as_csv() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'pages',
'post_status' => array( 'publish', 'pending' ),
'orderby' => 'title',
'order' => 'ASC'
);
query_posts( $args );
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=my_pages.csv');
$output = fopen( 'php://output', 'w' );
fputcsv( $output, array( 'Nr', 'Page_ID', 'Page_Title', 'Page_Status' ) );
$i = 1;
while( have_posts() ) : the_post();
fputcsv( $output, array( $i, get_the_ID(), get_the_title(), get_post_status() ) );
$i++;
endwhile;
wp_reset_query();
fclose( $output );
die;
}
|
Fix sending a null game object in the base case
|
var models = require('../models');
var GameController = require("./GameController");
var playerQueue = [];
exports.startGame = function(req, res) {
var player1 = req.body.username;
var game = GameController.findGame(player1).then(function(game) {
// player has ongoing game
if (game != null) {
res.json({'game': game});
}
// Start a new game if opponent exists and opponent is not the same player. Pops the last element in queue.
else if (playerQueue.length > 0 && playerQueue.indexOf(player1) === -1) {
GameController.startGame(player1, playerQueue.pop()).then(function(game) {
models.Game.find({
include: [models.Board],
where: {id: game.id}
}).then(function(game) {
res.json({'game': game});
});
});
}
// Put the player in the queue if the player isn't already there
else if(playerQueue.indexOf(player1) === -1) {
playerQueue.unshift(player1);
res.json({'game': null});
}
// If a game doesn't exit yet
else {
res.json({'game': null});
}
})
};
exports.cancelWaitForGame = function(req, res) {
var player = req.body.username;
var index = playerQueue.indexOf(player);
if (index > -1) {
playerQueue.splice(index, 1);
}
};
|
var models = require('../models');
var GameController = require("./GameController");
var playerQueue = [];
exports.startGame = function(req, res) {
var player1 = req.body.username;
var game = GameController.findGame(player1).then(function(game) {
// player has ongoing game
if (game != null) {
res.json({'game': game});
}
// Start a new game if opponent exists and opponent is not the same player. Pops the last element in queue.
else if (playerQueue.length > 0 && playerQueue.indexOf(player1) === -1) {
GameController.startGame(player1, playerQueue.pop()).then(function(game) {
models.Game.find({
include: [models.Board],
where: {id: game.id}
}).then(function(game) {
res.json({'game': game});
});
});
}
// Put the player in the queue if the player isn't already there
else if(playerQueue.indexOf(player1) === -1) {
playerQueue.unshift(player1);
res.json({'game': null});
}
})
};
exports.cancelWaitForGame = function(req, res) {
var player = req.body.username;
var index = playerQueue.indexOf(player);
if (index > -1) {
playerQueue.splice(index, 1);
}
};
|
Set this.music to empty object
|
/*
* mainmenu.js
* Handles main menu
*/
YINS.MainMenu = function(game) {
this.music = {};
};
YINS.MainMenu.prototype = {
create: function() {
/* Our assets are preloaded, so here we just kick things off
by playing some music */
this.music = YINS.game.add.audio('menuMusic');
this.music.loopFull(1);
this.stage.backgroundColor = YINS.color.purple_light;
var title = YINS.game.add.text(YINS.game.world.centerX, YINS.game.world.centerY, 'YINS', YINS.text.title);
title.anchor.set(0.5);
var subtitle = YINS.game.add.text(YINS.game.world.centerX, YINS.game.world.centerY + 80, '- Click to start -', YINS.text.subtitle);
subtitle.anchor.set(0.5);
YINS.game.input.onDown.add(this.startGame, this);
},
startGame: function(pointer) {
this.music.stop();
YINS.game.state.start('game');
}
};
|
/*
* mainmenu.js
* Handles main menu
*/
YINS.MainMenu = function(game) {
this.music;
};
YINS.MainMenu.prototype = {
create: function() {
/* Our assets are preloaded, so here we just kick things off
by playing some music */
this.music = YINS.game.add.audio('menuMusic');
this.music.loopFull(1);
this.stage.backgroundColor = YINS.color.purple_light;
var title = YINS.game.add.text(YINS.game.world.centerX, YINS.game.world.centerY, 'YINS', YINS.text.title);
title.anchor.set(0.5);
var subtitle = YINS.game.add.text(YINS.game.world.centerX, YINS.game.world.centerY + 80, '- Click to start -', YINS.text.subtitle);
subtitle.anchor.set(0.5);
YINS.game.input.onDown.add(this.startGame, this);
},
startGame: function(pointer) {
this.music.stop();
YINS.game.state.start('game');
}
};
|
Rename the login arguments to correspong ProcessWire api.
|
<?php
namespace ProcessWire\GraphQL\Field\Auth;
use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Config\Field\FieldConfig;
use Youshido\GraphQL\Type\Scalar\StringType;
use Youshido\GraphQL\Type\NonNullType;
use Youshido\GraphQL\Execution\ResolveInfo;
use ProcessWire\GraphQL\Type\Object\AuthResponseType;
use ProcessWire\WireData;
class LoginField extends AbstractField {
public function getType()
{
return new NonNullType(new AuthResponseType());
}
public function getName()
{
return 'login';
}
public function getDescription()
{
return 'Allows you to authenticate into the app.';
}
public function build(FieldConfig $config)
{
$config->addArgument('name', new NonNullType(new StringType()));
$config->addArgument('pass', new NonNullType(new StringType()));
}
public function resolve($value, array $args, ResolveInfo $info)
{
$session = \ProcessWire\wire('session');
$username = $args['name'];
$password = $args['pass'];
$user = $session->login($username, $password);
$response = new WireData();
if (is_null($user)) {
$response->statusCode = 401;
$response->message = 'Wrong username and/or password.';
} else {
$response->statusCode = 200;
$response->message = 'Successful login!';
}
return $response;
}
}
|
<?php
namespace ProcessWire\GraphQL\Field\Auth;
use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Config\Field\FieldConfig;
use Youshido\GraphQL\Type\Scalar\StringType;
use Youshido\GraphQL\Type\NonNullType;
use Youshido\GraphQL\Execution\ResolveInfo;
use ProcessWire\GraphQL\Type\Object\AuthResponseType;
use ProcessWire\WireData;
class LoginField extends AbstractField {
public function getType()
{
return new NonNullType(new AuthResponseType());
}
public function getName()
{
return 'login';
}
public function getDescription()
{
return 'Allows you to authenticate into the app.';
}
public function build(FieldConfig $config)
{
$config->addArgument('username', new NonNullType(new StringType()));
$config->addArgument('password', new NonNullType(new StringType()));
}
public function resolve($value, array $args, ResolveInfo $info)
{
$session = \ProcessWire\wire('session');
$username = $args['username'];
$password = $args['password'];
$user = $session->login($username, $password);
$response = new WireData();
if (is_null($user)) {
$response->statusCode = 401;
$response->message = 'Wrong username and/or password.';
} else {
$response->statusCode = 200;
$response->message = 'Successful login!';
}
return $response;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.