text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Change internal iface to eth0
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Meta extends REST_Controller {
public function index_get()
{
$response = array(
'id' => 'sw',
'name' => 'Scaleway',
'server_nick_name' => 'Server',
'default_region' => 'par1',
'default_size' => 'VC1S',
'default_plan' => 'cloud',
'can_reboot' => true,
'can_rename' => true,
'internal_iface' => 'eth0',
'external_iface' => 'eth0',
'ssh_user' => 'root',
'ssh_auth_method' => 'key',
'ssh_key_method' => 'reference',
'bootstrap_script' => 'https://s3.amazonaws.com/tools.nanobox.io/bootstrap/ubuntu.sh',
'credential_fields' => array(
array('key' => 'access-token', 'label' => 'Auth Token')
),
'instructions' => 'For instructions on how to retrieve a Scaleway access token, visit the repository.'
);
$this->set_response($response, 200);
}
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . 'libraries/REST_Controller.php';
class Meta extends REST_Controller {
public function index_get()
{
$response = array(
'id' => 'sw',
'name' => 'Scaleway',
'server_nick_name' => 'Server',
'default_region' => 'par1',
'default_size' => 'VC1S',
'default_plan' => 'cloud',
'can_reboot' => true,
'can_rename' => true,
'internal_iface' => 'eth1',
'external_iface' => 'eth0',
'ssh_user' => 'root',
'ssh_auth_method' => 'key',
'ssh_key_method' => 'reference',
'bootstrap_script' => 'https://s3.amazonaws.com/tools.nanobox.io/bootstrap/ubuntu.sh',
'credential_fields' => array(
array('key' => 'access-token', 'label' => 'Auth Token')
),
'instructions' => 'For instructions on how to retrieve a Scaleway access token, visit the repository.'
);
$this->set_response($response, 200);
}
}
|
Delete unused webob conversion method
|
"""Helpers for WebOb requests and responses."""
import webob
def webob_to_django_response(webob_response):
"""Returns a django response to the `webob_response`"""
from django.http import HttpResponse
django_response = HttpResponse(
webob_response.app_iter,
content_type=webob_response.content_type
)
for name, value in webob_response.headerlist:
django_response[name] = value
return django_response
def django_to_webob_request(django_request):
"""Returns a WebOb request to the `django_request`"""
environ = {}
environ.update(django_request.META)
webob_request = webob.Request(django_request.META)
webob_request.body = django_request.body
return webob_request
|
"""Helpers for WebOb requests and responses."""
import webob
def webob_to_django_response(webob_response):
"""Returns a django response to the `webob_response`"""
from django.http import HttpResponse
django_response = HttpResponse(
webob_response.app_iter,
content_type=webob_response.content_type
)
for name, value in webob_response.headerlist:
django_response[name] = value
return django_response
def django_to_webob_request(django_request):
"""Returns a WebOb request to the `django_request`"""
environ = {}
environ.update(django_request.META)
webob_request = webob.Request(django_request.META)
webob_request.body = django_request.body
return webob_request
def requests_to_webob_response(requests):
"""Converts multiple django requests to a WebOb response."""
response = webob.Response()
response.status = requests.status_code
response.body = requests.content
for hname, hvalue in requests.headers.iteritems():
response.headers[hname] = hvalue
return response
|
Allow vscode install on windows
|
var fs = require('fs');
var getHomePath = require('home-path');
var logHelper = require('../util/log-helper');
var path = require('path');
var process = require('process');
var symlinkOrReplaceFilesInFolderSync = require('../util/symlink-or-replace-files-in-folder-sync');
function getVSCodeConfigDir() {
var baseDir = getHomePath();
if (process.platform === 'win32') {
baseDir = path.join(baseDir, 'AppData', 'Roaming');
} else {
baseDir = path.join(baseDir, '.config');
}
return path.join(baseDir, 'Code', 'User');
}
module.exports.install = function () {
logHelper.logStepStarted('vscode');
var sourceDir = path.join(__dirname, 'config');
var destDir = getVSCodeConfigDir();
var files = fs.readdirSync(sourceDir);
logHelper.logSubStepPartialStarted('applying config files');
symlinkOrReplaceFilesInFolderSync(files, sourceDir, destDir);
logHelper.logSubStepPartialSuccess();
};
|
var fs = require('fs');
var getHomePath = require('home-path');
var logHelper = require('../util/log-helper');
var path = require('path');
var process = require('process');
var symlinkOrReplaceFilesInFolderSync = require('../util/symlink-or-replace-files-in-folder-sync');
function getVSCodeConfigDir() {
var baseDir = getHomePath();
if (process.platform === 'win32') {
baseDir = path.join(baseDir, 'AppData', 'Roaming');
} else {
baseDir = path.join(baseDir, '.config');
}
return path.join(baseDir, 'Code', 'User');
}
module.exports.install = function () {
if (process.platform !== 'win32') {
logHelper.logStepStarted('vscode');
var sourceDir = path.join(__dirname, 'config');
var destDir = getVSCodeConfigDir();
var files = fs.readdirSync(sourceDir);
logHelper.logSubStepPartialStarted('applying config files');
symlinkOrReplaceFilesInFolderSync(files, sourceDir, destDir);
logHelper.logSubStepPartialSuccess();
}
};
|
Enable gcm and email module
|
import 'newrelic';
// Socket
import '../modules/socket/socket-server';
// Auth modules
import '../modules/facebook/facebook';
import '../modules/google/google';
import '../modules/session/session';
import '../modules/signin/signin';
import '../modules/signup/signup';
import '../modules/resource/resource';
/* ########### */
import '../modules/relation/relation';
import '../modules/guard/guard-server';
import '../modules/count/count';
import '../modules/note/note';
import '../modules/score/score';
import '../modules/gcm/gcm-server';
import '../modules/postgres/postgres';
import '../modules/image-upload/image-upload';
import '../modules/email/unsubscribe';
import '../modules/contacts/contacts';
import '../modules/avatar/avatar';
import '../modules/client/client';
import '../modules/client/routes';
import '../modules/debug/debug-server';
import '../modules/belong/belong';
import '../modules/content-seeding/content-seeding';
// Email server
import '../modules/email/email-daemon';
// Moderator UI
import '../modules/modui/modui-server';
// if fired before socket server then the http/init listener might not be listening.
import '../modules/http/http';
|
import 'newrelic';
// Socket
import '../modules/socket/socket-server';
// Auth modules
import '../modules/facebook/facebook';
import '../modules/google/google';
import '../modules/session/session';
import '../modules/signin/signin';
import '../modules/signup/signup';
import '../modules/resource/resource';
/* ########### */
import '../modules/relation/relation';
import '../modules/guard/guard-server';
import '../modules/count/count';
import '../modules/note/note';
import '../modules/score/score';
// import '../modules/gcm/gcm-server';
import '../modules/postgres/postgres';
import '../modules/image-upload/image-upload';
import '../modules/email/unsubscribe';
import '../modules/contacts/contacts';
import '../modules/avatar/avatar';
import '../modules/client/client';
import '../modules/client/routes';
import '../modules/debug/debug-server';
import '../modules/belong/belong';
import '../modules/content-seeding/content-seeding';
// Email server
// import '../modules/email/email-daemon';
// Moderator UI
import '../modules/modui/modui-server';
// if fired before socket server then the http/init listener might not be listening.
import '../modules/http/http';
|
Add .mpg video extension to supported list
|
module.exports = {
isPlayable,
isVideo,
isAudio,
isPlayableTorrent
}
var path = require('path')
/**
* Determines whether a file in a torrent is audio/video we can play
*/
function isPlayable (file) {
return isVideo(file) || isAudio(file)
}
function isVideo (file) {
var ext = path.extname(file.name).toLowerCase()
return [
'.avi',
'.m4v',
'.mkv',
'.mov',
'.mp4',
'.mpg',
'.ogv',
'.webm'
].includes(ext)
}
function isAudio (file) {
var ext = path.extname(file.name).toLowerCase()
return [
'.aac',
'.ac3',
'.mp3',
'.ogg',
'.wav'
].includes(ext)
}
function isPlayableTorrent (torrentSummary) {
return torrentSummary.files && torrentSummary.files.some(isPlayable)
}
|
module.exports = {
isPlayable,
isVideo,
isAudio,
isPlayableTorrent
}
var path = require('path')
/**
* Determines whether a file in a torrent is audio/video we can play
*/
function isPlayable (file) {
return isVideo(file) || isAudio(file)
}
function isVideo (file) {
var ext = path.extname(file.name).toLowerCase()
return [
'.avi',
'.m4v',
'.mkv',
'.mov',
'.mp4',
'.ogv',
'.webm'
].includes(ext)
}
function isAudio (file) {
var ext = path.extname(file.name).toLowerCase()
return [
'.aac',
'.ac3',
'.mp3',
'.ogg',
'.wav'
].includes(ext)
}
function isPlayableTorrent (torrentSummary) {
return torrentSummary.files && torrentSummary.files.some(isPlayable)
}
|
Use addAssets to add font files.
Since v1.2, 2015-Sept-21:
Backwards-incompatible change for package authors: Static assets in
package.js files must now be explicitly declared by using addAssets
instead of addFiles. Previously, any file that didn't have a source
handler was automatically registered as a server-side asset. The
isAsset option to addFiles is also deprecated in favor of addAssets.
https://github.com/meteor/meteor/blob/devel/History.md
|
Package.describe({
name: 'chriswessels:glyphicons-halflings',
version: '2.0.0',
summary: "This simple smart package adds the Glyphicon Halflings font-face to Meteor.",
git: 'https://github.com/chriswessels/meteor-glyphicons-halflings.git'
});
Package.onUse(function (api){
api.addAssets([
'lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.eot',
'lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.svg',
'lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.ttf',
'lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.woff'
], 'client');
api.addFiles('lib/glyphicons-halflings/css/glyphicons.css', 'client');
});
|
Package.describe({
name: 'chriswessels:glyphicons-halflings',
version: '2.0.0',
summary: "This simple smart package adds the Glyphicon Halflings font-face to Meteor.",
git: 'https://github.com/chriswessels/meteor-glyphicons-halflings.git'
});
Package.onUse(function (api){
api.addFiles('lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.eot', 'client');
api.addFiles('lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.svg', 'client');
api.addFiles('lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.ttf', 'client');
api.addFiles('lib/glyphicons-halflings/fonts/glyphicons-halflings-regular.woff', 'client');
api.addFiles('lib/glyphicons-halflings/css/glyphicons.css', 'client');
});
|
Add more description to input example.
|
'use strict';
/* eslint-disable indent */
module.exports = function(tx) {
var body = tx.get('body');
tx.create({
id: 'title',
type: 'heading',
level: 1,
content: 'Input Element'
});
body.show('title');
tx.create({
id: 'intro',
type: 'paragraph',
content: [
"You can use custom elements with an HTML input element"
].join('')
});
body.show('intro');
tx.create({
type: 'input',
id: 'input',
content: 'Lorem ipsum...'
});
body.show('input');
tx.create({
id: 'the-end',
type: 'paragraph',
content: [
"That way you can implement editor functionality using class web development practices."
].join('')
});
body.show('the-end');
};
|
'use strict';
/* eslint-disable indent */
module.exports = function(tx) {
var body = tx.get('body');
tx.create({
id: 'title',
type: 'heading',
level: 1,
content: 'Input Element'
});
body.show('title');
tx.create({
id: 'intro',
type: 'paragraph',
content: [
"You can use custom elements with an HTML input element"
].join('')
});
body.show('intro');
tx.create({
type: 'input',
id: 'input',
content: 'Lorem ipsum...'
});
body.show('input');
tx.create({
id: 'the-end',
type: 'paragraph',
content: [
"That's it."
].join('')
});
body.show('the-end');
};
|
Update old fixtures and add a method to filter site on deleted=false
|
<?php
namespace PHPOrchestra\ModelBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
use PHPOrchestra\ModelInterface\Model\SiteInterface;
use PHPOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
/**
* Class SiteRepository
*/
class SiteRepository extends DocumentRepository implements SiteRepositoryInterface
{
/**
* @param string $siteId
*
* @return SiteInterface
*/
public function findOneBySiteId($siteId)
{
return $this->findOneBy(array('siteId' => $siteId));
}
/**
* @param $siteId
*
* @return SiteInterface
*/
public function findOneBySiteIdNotDeleted($siteId)
{
return $this->findOneBy(array('siteId' => $siteId, 'deleted' => false));
}
/**
* @param boolean $deleted
*
* @return array
*/
public function findByDeleted($deleted)
{
return $this->findBy(array('deleted' => $deleted));
}
}
|
<?php
namespace PHPOrchestra\ModelBundle\Repository;
use Doctrine\ODM\MongoDB\DocumentRepository;
use PHPOrchestra\ModelInterface\Model\SiteInterface;
use PHPOrchestra\ModelInterface\Repository\SiteRepositoryInterface;
/**
* Class SiteRepository
*/
class SiteRepository extends DocumentRepository implements SiteRepositoryInterface
{
/**
* @param string $siteId
*
* @return SiteInterface
*/
public function findOneBySiteId($siteId)
{
return $this->findOneBy(array('siteId' => $siteId));
}
/**
* @param boolean $deleted
*
* @return array
*/
public function findByDeleted($deleted)
{
return $this->findBy(array('deleted' => $deleted));
}
}
|
Remove the fully qualified module reference 'trombi.client'
If there happens to be more than one version of trombi on the system
(such as stable vs testing) the one in the PYTHONPATH that gets
encountered will be silently loaded when specifically loading the
module __init__ file for the other client. Now using the relative
'from .client import *'.
|
# Copyright (c) 2010 Inoi Oy
#
# 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.
from .client import *
|
# Copyright (c) 2010 Inoi Oy
#
# 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.
from trombi.client import *
|
Add the new contrail extension to neutron plugin config file
Change-Id: I2a1e90a2ca31314b7a214943b0f312471b11da9f
|
import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc,contrail:None
[KEYSTONE]
;auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0
;admin_token = $__contrail_admin_token__
admin_user=$__contrail_admin_user__
admin_password=$__contrail_admin_password__
admin_tenant_name=$__contrail_admin_tenant_name__
""")
|
import string
template = string.Template("""
[APISERVER]
api_server_ip = $__contrail_api_server_ip__
api_server_port = $__contrail_api_server_port__
multi_tenancy = $__contrail_multi_tenancy__
contrail_extensions = ipam:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_ipam.NeutronPluginContrailIpam,policy:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_policy.NeutronPluginContrailPolicy,route-table:neutron_plugin_contrail.plugins.opencontrail.contrail_plugin_vpc.NeutronPluginContrailVpc
[KEYSTONE]
;auth_url = $__contrail_ks_auth_protocol__://$__contrail_keystone_ip__:$__contrail_ks_auth_port__/v2.0
;admin_token = $__contrail_admin_token__
admin_user=$__contrail_admin_user__
admin_password=$__contrail_admin_password__
admin_tenant_name=$__contrail_admin_tenant_name__
""")
|
Modify the interpnd cython generator to allow .NET output
|
#!/usr/bin/env python
import tempfile
import subprocess
import os
import sys
import re
import shutil
from mako.template import Template
dotnet = False
if len(sys.argv) > 1 and sys.argv[1] == '--dotnet':
dotnet = True
f = open('interpnd.pyx', 'r')
template = f.read()
f.close()
tmp_dir = tempfile.mkdtemp()
try:
# Run templating engine
fn = os.path.join(tmp_dir, 'interpnd.pyx')
f = open(fn, 'w')
f.write(Template(template).render())
f.close()
# Run Cython
if dotnet:
dst_name = 'interpnd.cpp'
args_extra = ['--dotnet']
else:
dst_name = 'interpnd.c'
args_extra = []
dst_fn = os.path.join(tmp_dir, dst_name)
ret = subprocess.call(['cython', '-I', '../..', '-o'] + args_extra + [dst_fn, fn])
if ret != 0:
sys.exit(ret)
# Strip comments
f = open(dst_fn, 'r')
text = f.read()
f.close()
r = re.compile(r'/\*(.*?)\*/', re.S)
text = r.sub('', text)
f = open(dst_name, 'w')
f.write(text)
f.close()
finally:
shutil.rmtree(tmp_dir)
|
#!/usr/bin/env python
import tempfile
import subprocess
import os
import sys
import re
import shutil
from mako.template import Template
f = open('interpnd.pyx', 'r')
template = f.read()
f.close()
tmp_dir = tempfile.mkdtemp()
try:
# Run templating engine
fn = os.path.join(tmp_dir, 'interpnd.pyx')
f = open(fn, 'w')
f.write(Template(template).render())
f.close()
# Run Cython
dst_fn = os.path.join(tmp_dir, 'interpnd.c')
ret = subprocess.call(['cython', '-I', '../..', '-o', dst_fn, fn])
if ret != 0:
sys.exit(ret)
# Strip comments
f = open(dst_fn, 'r')
text = f.read()
f.close()
r = re.compile(r'/\*(.*?)\*/', re.S)
text = r.sub('', text)
f = open('interpnd.c', 'w')
f.write(text)
f.close()
finally:
shutil.rmtree(tmp_dir)
|
Add constant SUID and minor reformatting
svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=410556
|
/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.util.jar;
import java.util.zip.ZipException;
/**
* This runtime exception is thrown when a problem occurrs while reading a JAR
* file.
*/
public class JarException extends ZipException {
private static final long serialVersionUID = 7159778400963954473L;
/**
* Constructs a new instance of this class with its walkback filled in.
*/
public JarException() {
super();
}
/**
* Constructs a new instance of this class with its walkback and message
* filled in.
*
* @param detailMessage
* String The detail message for the exception.
*/
public JarException(String detailMessage) {
super(detailMessage);
}
}
|
/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.util.jar;
import java.util.zip.ZipException;
/**
* This runtime exception is thrown when a problem occurrs while reading a JAR
* file.
*
*/
public class JarException extends ZipException {
/**
* Constructs a new instance of this class with its walkback filled in.
*/
public JarException() {
super();
}
/**
* Constructs a new instance of this class with its walkback and message
* filled in.
*
* @param detailMessage
* String The detail message for the exception.
*/
public JarException(String detailMessage) {
super(detailMessage);
}
}
|
Set ‘build’ as the default Grunt task
|
module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */'
},
src: 'src/progress-button.css',
dest: 'dist/progress-button.min.css'
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['cssmin', 'uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', ['build'])
}
|
module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */'
},
src: 'src/progress-button.css',
dest: 'dist/progress-button.min.css'
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['cssmin', 'uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
|
Hide action buttons if the company is archived
This prevents bad data being added when a company
has been archived
|
const { getCompanyInvestmentProjects } = require('../../investment-projects/repos')
const { transformInvestmentProjectToListItem } = require('../../investment-projects/transformers')
const { transformApiResponseToCollection } = require('../../transformers')
async function renderInvestments (req, res, next) {
const token = req.session.token
const page = req.query.page || 1
const { id, name, archived } = res.locals.company
try {
const results = await getCompanyInvestmentProjects(token, id, page)
.then(transformApiResponseToCollection(
{ query: req.query },
transformInvestmentProjectToListItem,
))
const actionButtons = archived ? undefined : [{
label: 'Add investment project',
url: `/investment-projects/create/${req.params.companyId}`,
}]
res
.breadcrumb(name, `/companies/${id}`)
.breadcrumb('Investment')
.render('companies/views/investments', {
results,
actionButtons,
})
} catch (error) {
next(error)
}
}
module.exports = {
renderInvestments,
}
|
const { getCompanyInvestmentProjects } = require('../../investment-projects/repos')
const { transformInvestmentProjectToListItem } = require('../../investment-projects/transformers')
const { transformApiResponseToCollection } = require('../../transformers')
async function renderInvestments (req, res, next) {
const token = req.session.token
const page = req.query.page || 1
const { id, name } = res.locals.company
try {
const results = await getCompanyInvestmentProjects(token, id, page)
.then(transformApiResponseToCollection(
{ query: req.query },
transformInvestmentProjectToListItem,
))
res
.breadcrumb(name, `/companies/${id}`)
.breadcrumb('Investment')
.render('companies/views/investments', {
results,
actionButtons: [{
label: 'Add investment project',
url: `/investment-projects/create/${req.params.companyId}`,
}],
})
} catch (error) {
next(error)
}
}
module.exports = {
renderInvestments,
}
|
Return active thread count from the threadpool
|
/*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.core.server.task;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.vanilladb.core.util.CoreProperties;
/**
* The task manager of VanillaCore. This manager is responsible for maintaining
* the thread pool of worker thread.
*/
public class TaskMgr {
public final static int THREAD_POOL_SIZE;
static {
THREAD_POOL_SIZE = CoreProperties.getLoader().getPropertyAsInteger(
TaskMgr.class.getName() + ".THREAD_POOL_SIZE", 150);
}
private ThreadPoolExecutor executor;
public TaskMgr() {
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
public void runTask(Task task) {
executor.execute(task);
}
public int getActiveCount() {
return executor.getActiveCount();
}
}
|
/*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.core.server.task;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.vanilladb.core.util.CoreProperties;
/**
* The task manager of VanillaCore. This manager is responsible for maintaining
* the thread pool of worker thread.
*/
public class TaskMgr {
public final static int THREAD_POOL_SIZE;
static {
THREAD_POOL_SIZE = CoreProperties.getLoader().getPropertyAsInteger(
TaskMgr.class.getName() + ".THREAD_POOL_SIZE", 150);
}
private ExecutorService executor;
public TaskMgr() {
executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
public void runTask(Task task) {
executor.execute(task);
}
}
|
Use metaclasses to register node types.
|
import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
_nodeTypes = {}
class _NodeTypeRegistrar(type):
def __init__(self, name, bases, dict):
type.__init__(self, name, bases, dict)
_nodeTypes[self.nodeType] = self
class NodeType(object):
__metaclass__ = _NodeTypeRegistrar
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Client(NodeType):
nodeType = 'CLIENT'
def thawNodeType(info):
nodeType = info[0]
return _nodeTypes[nodeType].thaw(info[1])
|
import inspect
import sys
import types
from rmake.lib.apiutils import thaw, freeze
class NodeType(object):
nodeType = 'UNKNOWN'
def __init__(self):
pass
def freeze(self):
return (self.nodeType, self.__dict__)
@classmethod
def thaw(class_, d):
return class_(**d)
class Client(NodeType):
nodeType = 'CLIENT'
_nodeTypes = {}
def registerNodeTypes(moduleName):
global _nodeTypes
for item in sys.modules[moduleName].__dict__.values():
if inspect.isclass(item) and issubclass(item, NodeType):
_nodeTypes[item.nodeType] = item
registerNodeTypes(__name__)
def registerNodeType(class_):
_nodeTypes[class_.nodeType] = class_
def thawNodeType(info):
nodeType = info[0]
return _nodeTypes[nodeType].thaw(info[1])
|
Raise maxListeners so if you have 16 cores it doesn't complain
|
#!/usr/bin/env node
var log = require('./src/log.js'),
Parent = require('./src/parent.js'),
ctrl = require('daemonctrl'),
currentParent = new Parent(),
config, sender;
function onExit(error) {
currentParent.stop();
ctrl.end();
if (error) {
throw e;
}
process.exit();
}
//since each of our children are going to be listening on all 3 of these raise the max listeners limit
process.setMaxListeners(32);
process.on('exit', onExit);
process.on('SIGTERM', onExit);
process.on('SIGINT', onExit);
//we gotta first strip the command otherwise flags will complain
ctrl.strip();
currentParent.loadConfig();
ctrl.socketOptions({path: currentParent.config.controlsock});
if (!currentParent.config.controlsock) {
currentParent.start();
return;
}
sender = ctrl.send();
if (!sender) {
log('Starting parent');
currentParent.start();
return;
}
sender.pipe(process.stdout);
|
#!/usr/bin/env node
var log = require('./src/log.js'),
Parent = require('./src/parent.js'),
ctrl = require('daemonctrl'),
currentParent = new Parent(),
config, sender;
function onExit(error) {
currentParent.stop();
ctrl.end();
if (error) {
throw e;
}
process.exit();
}
process.on('exit', onExit);
process.on('SIGTERM', onExit);
process.on('SIGINT', onExit);
//we gotta first strip the command otherwise flags will complain
ctrl.strip();
currentParent.loadConfig();
ctrl.socketOptions({path: currentParent.config.controlsock});
if (!currentParent.config.controlsock) {
currentParent.start();
return;
}
sender = ctrl.send();
if (!sender) {
log('Starting parent');
currentParent.start();
return;
}
sender.pipe(process.stdout);
|
Refactor MeanQ to use Array.reduce().
|
/**
* checks if there are scores which can be combined
*/
function checkValidity (scores) {
if (scores == null) {
throw new Error('There must be a scores object parameter')
}
if (Object.keys(scores).length <= 0) {
throw new Error('At least one score must be passed')
}
}
/**
* Score canidate based on the mean value of two or more parent Qs.
*/
class MeanQ {
/**
* Returns the mean value of the given scores.
* @param scores - obect that contains the keys and scores
* for each used scoring method
* @return mean value of given scores
*/
combine (scores) {
checkValidity(scores)
let values = Object.values(scores)
let sum = values.reduce((sum, score) => sum + score, 0)
return sum / values.length
}
}
/**
* Chooses the biggest score out of all possible scores
*/
class LargestQ {
/**
* combines all scores by choosing the largest score
*/
combine (scores) {
checkValidity(scores)
return Math.max.apply(null, Object.values(scores))
}
}
module.exports = {
Mean: MeanQ,
Largest: LargestQ
}
|
/**
* checks if there are scores which can be combined
*/
function checkValidity (scores) {
if (scores == null) {
throw new Error('There must be a scores object parameter')
}
if (Object.keys(scores).length <= 0) {
throw new Error('At least one score must be passed')
}
}
/**
* Score canidate based on the mean value of two or more parent Qs.
*/
class MeanQ {
/**
* Returns the mean value of the given scores.
* @param scores - obect that contains the keys and scores
* for each used scoring method
* @return mean value of given scores
*/
combine (scores) {
checkValidity(scores)
var sum = 0
Object.keys(scores).map((key, index, arr) => {
sum += scores[key]
})
return sum / Object.keys(scores).length
}
}
/**
* Chooses the biggest score out of all possible scores
*/
class LargestQ {
/**
* combines all scores by choosing the largest score
*/
combine (scores) {
checkValidity(scores)
return Math.max.apply(null, Object.values(scores))
}
}
module.exports = {
Mean: MeanQ,
Largest: LargestQ
}
|
Allow users to read the name
|
package se.arbetsformedlingen.venice.probe;
import java.util.Objects;
public class Application {
private String application;
Application(String application) {
this.application = application;
}
String getApplicationName() {
return application;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Application that = (Application) o;
return Objects.equals(application, that.application);
}
@Override
public int hashCode() {
return Objects.hash(application);
}
@Override
public String toString() {
return "Application{" +
"application='" + application + '\'' +
'}';
}
}
|
package se.arbetsformedlingen.venice.probe;
import java.util.Objects;
public class Application {
private String application;
Application(String application) {
this.application = application;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Application that = (Application) o;
return Objects.equals(application, that.application);
}
@Override
public int hashCode() {
return Objects.hash(application);
}
@Override
public String toString() {
return "Application{" +
"application='" + application + '\'' +
'}';
}
}
|
Add ip on ip dev
|
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1', '89.158.15.146')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1')) || php_sapi_name() === 'cli-server')
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
|
Refactor pairing internals into functions for readability
|
var uuid = require('uuid/v1')
var requests = new Set()
function getRequest () {
var reqs = Array.from(requests.values())
if (reqs.length > 0) {
var req = reqs[Math.floor(Math.random() * reqs.length)]
requests.delete(req)
return req
} else {
return null;
}
}
function newEvent (socket) {
if (socket.room) {
disconnectEvent(socket)
}
var req = getRequest()
if (req) {
socket.room = req
socket.join(req)
socket.emit('join')
socket.to(socket.room).emit('join')
} else {
var room = uuid()
socket.room = room
socket.join(room)
requests.add(room)
}
}
function messageSendEvent (socket, msg) {
if (socket.room && msg.length > 0) {
socket.to(socket.room).emit('message-receive', msg)
}
}
function disconnectEvent (socket) {
requests.delete(socket.room)
socket.to(socket.room).emit('left')
socket.leave(socket.room)
socket.room = null
}
module.exports.io = (socket) => {
socket.on('disconnect', () => {disconnectEvent(socket)})
socket.on('new', () => {newEvent(socket)})
socket.on('message-send', (msg) => {messageSendEvent(socket, msg)})
}
|
var uuid = require('uuid/v1')
var requests = new Set()
function getRequest () {
var reqs = Array.from(requests.values())
if (reqs.length > 0) {
var req = reqs[Math.floor(Math.random() * reqs.length)]
requests.delete(req)
return req
} else {
return null;
}
}
function initialize (socket) {
socket.on('disconnect', () => {
requests.delete(socket.room)
socket.to(socket.room).emit('left')
socket.room = null
})
socket.on('new', () => {
if (socket.room) {
socket.to(socket.room).emit('left')
socket.leave(socket.room)
requests.delete(socket.room)
}
var req = getRequest()
if (req) {
socket.room = req
socket.join(req)
socket.emit('join')
socket.to(socket.room).emit('join')
} else {
var room = uuid()
socket.room = room
socket.join(room)
requests.add(room)
}
})
socket.on('message-send', (msg) => {
if (socket.room && msg.length > 0) {
socket.to(socket.room).emit('message-receive', msg)
}
})
}
module.exports.io = initialize
|
Use python interpreter instead of sys.executable
|
"""
Docs with Sphinx.
"""
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
['python3', 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
|
"""
Docs with Sphinx.
"""
import sys
import abc
import os.path
import subprocess
from . import vcs
from .. import DOCS_PATH
class Sphinx(vcs.VCS):
"""Abstract class for project folder tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, path, branch='master', url=None):
path = os.path.join(DOCS_PATH, path)
super(Sphinx, self).__init__(path, branch, url)
class Git(Sphinx, vcs.Git):
"""Git tool."""
def update(self):
self._repository.fetch()
self._repository.reset('--hard', 'origin/' + self.branch)
subprocess.check_call(
[sys.executable, 'setup.py', 'build_sphinx', '-b', 'dirhtml'],
cwd=self.path)
|
Add TODO for removing stubs
|
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus
admin.site = AdminSitePlus()
admin.autodiscover()
urlpatterns = patterns('',
(r'', include('fjord.analytics.urls')),
(r'', include('fjord.base.urls')),
(r'', include('fjord.feedback.urls')),
(r'', include('fjord.search.urls')),
# TODO: Remove this stub. /about and /search point to it.
url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'),
# Generate a robots.txt
(r'^robots\.txt$',
lambda r: HttpResponse(
"User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow',
mimetype="text/plain"
)
),
(r'^browserid/', include('django_browserid.urls')),
(r'^admin/', include(admin.site.urls)),
)
# In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
|
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus
admin.site = AdminSitePlus()
admin.autodiscover()
urlpatterns = patterns('',
(r'', include('fjord.analytics.urls')),
(r'', include('fjord.base.urls')),
(r'', include('fjord.feedback.urls')),
(r'', include('fjord.search.urls')),
url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'),
# Generate a robots.txt
(r'^robots\.txt$',
lambda r: HttpResponse(
"User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow',
mimetype="text/plain"
)
),
(r'^browserid/', include('django_browserid.urls')),
(r'^admin/', include(admin.site.urls)),
)
## In DEBUG mode, serve media files through Django.
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
|
style: Fix the misspell in docstring
Datatime -> Datetime
|
"""Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"""
Serialize datetime and date objects of iso format.
datetime objects are converted to UTC.
"""
if isinstance(obj, datetime):
if obj.tzinfo is None:
# Localize to UTC naive datetime objects
obj = UTC.localize(obj)
else:
# Convert to UTC datetime objects from other timezones
obj = obj.astimezone(UTC)
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
return super(DateTimeJSONEncoder, self).default(obj)
|
"""Utility functions and classes for track backends"""
import json
from datetime import datetime, date
from pytz import UTC
class DateTimeJSONEncoder(json.JSONEncoder):
"""JSON encoder aware of datetime.datetime and datetime.date objects"""
def default(self, obj): # pylint: disable=method-hidden
"""
Serialize datetime and date objects of iso format.
datatime objects are converted to UTC.
"""
if isinstance(obj, datetime):
if obj.tzinfo is None:
# Localize to UTC naive datetime objects
obj = UTC.localize(obj)
else:
# Convert to UTC datetime objects from other timezones
obj = obj.astimezone(UTC)
return obj.isoformat()
elif isinstance(obj, date):
return obj.isoformat()
return super(DateTimeJSONEncoder, self).default(obj)
|
MINOR: Advance system test ducktape dependency from 0.3.10 to 0.4.0
Previous version of ducktape was found to have a memory leak which caused occasional failures in nightly runs.
Author: Geoff Anderson <geoff@confluent.io>
Reviewers: Ewen Cheslack-Postava <ewen@confluent.io>
Closes #1165 from granders/minor-advance-ducktape-to-0.4.0
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# see kafka.server.KafkaConfig for additional details and defaults
import re
from setuptools import find_packages, setup
version = ''
with open('kafkatest/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
setup(name="kafkatest",
version=version,
description="Apache Kafka System Tests",
author="Apache Kafka",
platforms=["any"],
license="apache2.0",
packages=find_packages(),
include_package_data=True,
install_requires=["ducktape==0.4.0", "requests>=2.5.0"]
)
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# see kafka.server.KafkaConfig for additional details and defaults
import re
from setuptools import find_packages, setup
version = ''
with open('kafkatest/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
setup(name="kafkatest",
version=version,
description="Apache Kafka System Tests",
author="Apache Kafka",
platforms=["any"],
license="apache2.0",
packages=find_packages(),
include_package_data=True,
install_requires=["ducktape==0.3.10", "requests>=2.5.0"]
)
|
Use Google Charts as like before
We don't have to do this upgrade right now.
|
import Component from '@ember/component';
function createEvent(name) {
let event = document.createEvent('Event');
event.initEvent(name, true, true);
return event;
}
export default Component.extend({
tagName: '',
didInsertElement() {
let script = document.createElement('script');
script.onload = () => {
window.google.load('visualization', '1.0', {
packages: ['corechart'],
callback() {
window.googleChartsLoaded = true;
document.dispatchEvent(createEvent('googleChartsLoaded'));
},
});
};
document.body.appendChild(script);
script.src = 'https://www.google.com/jsapi';
},
});
|
/*global google*/
import Component from '@ember/component';
function createEvent(name) {
let event = document.createEvent('Event');
event.initEvent(name, true, true);
return event;
}
export default Component.extend({
tagName: '',
didInsertElement() {
let script = document.createElement('script');
script.onload = () => {
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(() => {
window.googleChartsLoaded = true;
document.dispatchEvent(createEvent('googleChartsLoaded'));
});
};
document.body.appendChild(script);
script.src = 'https://www.gstatic.com/charts/loader.js';
},
});
|
Refactor timeline method call to use kwargs
|
from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( datasets = [data] )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
|
from __future__ import division, print_function
import datetime
import timeline
from collections import *
def describe( data ):
if len(data) == 0:
print( "Dataset empty." )
return
print( "Entries together", len(data) )
print( "Number of different authors", len( set( map( lambda d: d['creator'], filter( lambda d: d['creator'] is not '', data ) ) ) ) )
## remove dates which can not be true
date_ok = filter( lambda d: d['timestamp'] is not '', data )
date_ok = filter( lambda d: d['timestamp'] > datetime.datetime(1970,1,1,0,10), date_ok )
print( "First post", min( map( lambda d: d['timestamp'], date_ok ) ) )
print( "Last post", max( map( lambda d: d['timestamp'], date_ok ) ) )
print("Data sources")
## todo: reimplement?
counter = defaultdict( int )
for post in data:
counter[ post['source_detail'] ] += 1
for name, count in counter.items():
print( '-', name, count )
return timeline.create_timeline( data )
if __name__ == '__main__':
for function_name in dir( data_loader ):
if 'load_' in function_name:
print( function_name )
f = getattr( data_loader, function_name )
data = f()
describe( data )
|
Change conversation token to a pointer to allow it to be null in the json
|
package api
// RootResponse object which will be formatted to json and sent back to google and onto the user.
type RootResponse struct {
ConversationToken *string `json:"conversation_token"`
ExpectUserResponse bool `json:"expect_user_response"`
ExpectedInputs []ExpectedInput `json:"expected_inputs"`
FinalResponse_ FinalResponse `json:"final_response"`
}
type ExpectedInput struct {
PossibleIntents []ExpectedIntent `json:"possible_intents"`
}
type ExpectedIntent struct {
Intent string `json:"intent"`
InputValueSpec_ InputValueSpec `json:"input_value_spec"`
}
type FinalResponse struct {
SpeechResponse_ SpeechResponse `json:"speech_response"`
}
type InputValueSpec struct {
PermissionValueSpec_ PermissionValueSpec `json:"permission_value_spec"`
}
type PermissionValueSpec struct {
OptContext string `json:"opt_context"`
Permissions []string `json:"permissions"`
}
type SpeechResponse struct {
TextToSpeech string `json:"text_to_speech"`
SSML string `json:"ssml"`
}
|
package api
// RootResponse object which will be formatted to json and sent back to google and onto the user.
type RootResponse struct {
ConversationToken string `json:"conversation_token"`
ExpectUserResponse bool `json:"expect_user_response"`
ExpectedInputs []ExpectedInput `json:"expected_inputs"`
FinalResponse_ FinalResponse `json:"final_response"`
}
type ExpectedInput struct {
PossibleIntents []ExpectedIntent `json:"possible_intents"`
}
type ExpectedIntent struct {
Intent string `json:"intent"`
InputValueSpec_ InputValueSpec `json:"input_value_spec"`
}
type FinalResponse struct {
SpeechResponse_ SpeechResponse `json:"speech_response"`
}
type InputValueSpec struct {
PermissionValueSpec_ PermissionValueSpec `json:"permission_value_spec"`
}
type PermissionValueSpec struct {
OptContext string `json:"opt_context"`
Permissions []string `json:"permissions"`
}
type SpeechResponse struct {
TextToSpeech string `json:"text_to_speech"`
SSML string `json:"ssml"`
}
|
Replace range prop to values
|
/**
* @copyright Copyright (c) 2020 Maxim Khorin <maksimovichu@gmail.com>
*/
'use strict';
const Base = require('./Validator');
module.exports = class RangeValidator extends Base {
constructor (config) {
super({
// values: []
not: false,
allowArray: false,
...config
});
if (!Array.isArray(this.values)) {
throw new Error('Values property must be array');
}
}
getMessage () {
return this.createMessage(this.message, 'Invalid range');
}
validateValue (value) {
if (Array.isArray(value) && !this.allowArray) {
return this.getMessage();
}
let inRange = true;
const values = Array.isArray(value) ? value : [value];
for (const item of values) {
if (!this.values.includes(item)) {
inRange = false;
break;
}
}
return this.not !== inRange ? null : this.getMessage();
}
};
|
/**
* @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
*/
'use strict';
const Base = require('./Validator');
module.exports = class RangeValidator extends Base {
constructor (config) {
super({
range: null,
not: false,
allowArray: false,
...config
});
if (!Array.isArray(this.range)) {
throw new Error('Range property must be array');
}
}
getMessage () {
return this.createMessage(this.message, 'Invalid range');
}
validateValue (value) {
if (Array.isArray(value) && !this.allowArray) {
return this.getMessage();
}
let inRange = true;
const values = Array.isArray(value) ? value : [value];
for (const item of values) {
if (!this.range.includes(item)) {
inRange = false;
break;
}
}
return this.not !== inRange ? null : this.getMessage();
}
};
|
Update py2app script for Qt 5.11
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'iconfile':'resources/icon.icns',
'includes': {'PySide2.QtCore', 'PySide2.QtUiTools', 'PySide2.QtGui','PySide2.QtWidgets', 'certifi'},
'excludes': {'PySide', 'PySide.QtCore', 'PySide.QtUiTools', 'PySide.QtGui'},
'qt_plugins': ['platforms/libqcocoa.dylib', 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
'plist': {
'CFBundleName':'Syncplay',
'CFBundleShortVersionString':syncplay.version,
'CFBundleIdentifier':'pl.syncplay.Syncplay',
'NSHumanReadableCopyright': '@ 2017 Syncplay All Rights Reserved'
}
}
setup(
app=APP,
name='Syncplay',
data_files=DATA_FILES,
options={'py2app': OPTIONS},
setup_requires=['py2app'],
)
|
Add missing installed apps for tests
|
"""
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'hrzeqwz0@nps2#ns3_qkqz*#5=)1bxcdwa*h__hta0f1bqr2e!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = ("tests/templates", )
INSTALLED_APPS = (
'django_nose',
'django.contrib.contenttypes',
'django.contrib.auth'
)
for dir in os.listdir("tests/apps"):
if os.path.isfile("tests/apps/%s/urls.py" % dir):
INSTALLED_APPS += ( "tests.apps.%s" % dir, )
MIDDLEWARE_CLASSES = (
)
ROOT_URLCONF = 'tests.urls'
WSGI_APPLICATION = 'tests.wsgi.application'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
|
"""
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'hrzeqwz0@nps2#ns3_qkqz*#5=)1bxcdwa*h__hta0f1bqr2e!'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = ("tests/templates", )
INSTALLED_APPS = (
'django_nose',
)
for dir in os.listdir("tests/apps"):
if os.path.isfile("tests/apps/%s/urls.py" % dir):
INSTALLED_APPS += ( "tests.apps.%s" % dir, )
MIDDLEWARE_CLASSES = (
)
ROOT_URLCONF = 'tests.urls'
WSGI_APPLICATION = 'tests.wsgi.application'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
|
Introduce base party form, limit `archived` flag to update form
|
"""
byceps.blueprints.admin.party.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import BooleanField, DateTimeField, IntegerField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ....util.l10n import LocalizedForm
class _BaseForm(LocalizedForm):
title = StringField('Titel', validators=[Length(min=1, max=40)])
starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()])
ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()])
max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()])
shop_id = StringField('Shop-ID', validators=[Optional()])
class CreateForm(_BaseForm):
id = StringField('ID', validators=[Length(min=1, max=40)])
class UpdateForm(_BaseForm):
archived = BooleanField('archiviert')
|
"""
byceps.blueprints.admin.party.forms
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from wtforms import BooleanField, DateTimeField, IntegerField, StringField
from wtforms.validators import InputRequired, Length, Optional
from ....util.l10n import LocalizedForm
class UpdateForm(LocalizedForm):
title = StringField('Titel', validators=[Length(min=1, max=40)])
starts_at = DateTimeField('Beginn', format='%d.%m.%Y %H:%M', validators=[InputRequired()])
ends_at = DateTimeField('Ende', format='%d.%m.%Y %H:%M', validators=[InputRequired()])
max_ticket_quantity = IntegerField('Maximale Anzahl Tickets', validators=[Optional()])
shop_id = StringField('Shop-ID', validators=[Optional()])
archived = BooleanField('archiviert')
class CreateForm(UpdateForm):
id = StringField('ID', validators=[Length(min=1, max=40)])
|
Implement a test specifically for abbreviations
|
from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
def test_expand_abbreviations():
template = 'gh:audreyr/cookiecutter-pypackage'
# This is not a valid repo url just yet!
# First `main.expand_abbreviations` needs to translate it
assert is_repo_url(template) is False
expanded_template = expand_abbreviations(template, {})
assert is_repo_url(expanded_template) is True
|
from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
assert is_repo_url('gh:audreyr/cookiecutter-pypackage') is True
assert is_repo_url('https://bitbucket.org/pokoli/cookiecutter.hg') is True
assert is_repo_url('/audreyr/cookiecutter.git') is False
assert is_repo_url('/home/audreyr/cookiecutter') is False
appveyor_temp_dir = (
'c:\\users\\appveyor\\appdata\\local\\temp\\1\\pytest-0\\'
'test_default_output_dir0\\template'
)
assert is_repo_url(appveyor_temp_dir) is False
|
Use switches rather than switches.keys().
Minor cosmetic change, really.
|
#!/usr/bin/python
"Create a 64-node tree network, and test connectivity using ping."
from mininet.log import setLogLevel
from mininet.net import init, Mininet
from mininet.node import KernelSwitch, UserSwitch, OVSKernelSwitch
from mininet.topolib import TreeNet
def treePing64():
"Run ping test on 64-node tree networks."
results = {}
switches = { 'reference kernel': KernelSwitch,
'reference user': UserSwitch,
'Open vSwitch kernel': OVSKernelSwitch }
for name in switches:
print "*** Testing", name, "datapath"
switch = switches[ name ]
network = TreeNet( depth=2, fanout=8, switch=switch )
result = network.run( network.pingAll )
results[ name ] = result
print
print "*** Tree network ping results:"
for name in switches:
print "%s: %d%% packet loss" % ( name, results[ name ] )
print
if __name__ == '__main__':
setLogLevel( 'info' )
treePing64()
|
#!/usr/bin/python
"Create a 64-node tree network, and test connectivity using ping."
from mininet.log import setLogLevel
from mininet.net import init, Mininet
from mininet.node import KernelSwitch, UserSwitch, OVSKernelSwitch
from mininet.topolib import TreeNet
def treePing64():
"Run ping test on 64-node tree networks."
results = {}
switches = { 'reference kernel': KernelSwitch,
'reference user': UserSwitch,
'Open vSwitch kernel': OVSKernelSwitch }
for name in switches.keys():
print "*** Testing", name, "datapath"
switch = switches[ name ]
network = TreeNet( depth=2, fanout=8, switch=switch )
result = network.run( network.pingAll )
results[ name ] = result
print
print "*** Tree network ping results:"
for name in switches.keys():
print "%s: %d%% packet loss" % ( name, results[ name ] )
print
if __name__ == '__main__':
setLogLevel( 'info' )
treePing64()
|
Add .js extension for require
|
/**
* Run test specs in node environment
* Usage:
* $ cd seajs
* $ node tests/runner-node.js
*/
require('../lib/sea.js')
define('./tests/node-runner', function(require) {
var test = require('./test')
var suites = require('./meta').map(function(suite) {
return './' + suite + '/meta'
})
require.async(suites, function() {
var args = [].slice.call(arguments)
var specs = []
args.forEach(function(meta, i) {
specs = specs.concat(meta.map(function(spec) {
return suites[i].split('/')[2] + '/' + spec
}))
})
var total = specs.length
var time = Date.now()
test.run(specs)
test.print('Summary')
test.print(total + ' suites in ' + (Date.now() - time) / 1000 + 's')
test.print('END')
})
})
seajs.use('./tests/node-runner')
|
/**
* Run test specs in node environment
* Usage:
* $ cd seajs
* $ node tests/runner-node.js
*/
require('../lib/sea')
define('./tests/node-runner', function(require) {
var test = require('./test')
var suites = require('./meta').map(function(suite) {
return './' + suite + '/meta'
})
require.async(suites, function() {
var args = [].slice.call(arguments)
var specs = []
args.forEach(function(meta, i) {
specs = specs.concat(meta.map(function(spec) {
return suites[i].split('/')[2] + '/' + spec
}))
})
var total = specs.length
var time = Date.now()
test.run(specs)
test.print('Summary')
test.print(total + ' suites in ' + (Date.now() - time) / 1000 + 's')
test.print('END')
})
})
seajs.use('./tests/node-runner')
|
Allow dev server to be accessed from the network.
|
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: './build',
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /src\/.+\.js$/,
loader: 'babel?presets[]=es2015'
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file?name=[name].[ext]?[hash]'
}
]
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.optimize.OccurenceOrderPlugin()
]
} else {
module.exports.devtool = '#source-map'
module.exports.devServer.host = '0.0.0.0'
}
|
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: './build',
publicPath: '/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /src\/.+\.js$/,
loader: 'babel?presets[]=es2015'
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file?name=[name].[ext]?[hash]'
}
]
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.optimize.OccurenceOrderPlugin()
]
} else {
module.exports.devtool = '#source-map'
}
|
Use PORT env var for Heroku
|
'use strict';
let config = require('./config');
let express = require('express');
let app = express();
console.log('Starting.');
app.listen(process.env.PORT || 12345, () => {
console.log('Server started.');
});
// API parent route
let api = express.Router({ mergeParams: true });
app.use(config.API_ROOT, api);
/**
* API endpoints
*/
let recipe = require('./recipes');
// Run the ratings engine for current year
api.post('/calc', (req, res) => {
res.json({
'year': config.CURRENT_YEAR
})
});
// Run the ratings engine for a certain year
api.post('/calc/:year', (req, res) => {
try {
recipe(req.params.year, req.query)
.then((data) => {
res.status(200);
res.json(data);
})
.catch((error) => {
res.status(404);
res.json({ 'error': error })
});
} catch(ex) {
res.json(ex);
}
});
|
'use strict';
let config = require('./config');
let express = require('express');
let app = express();
console.log('Starting.');
app.listen(12345, () => {
console.log('Server started.');
});
// API parent route
let api = express.Router({ mergeParams: true });
app.use(config.API_ROOT, api);
/**
* API endpoints
*/
let recipe = require('./recipes');
// Run the ratings engine for current year
api.post('/calc', (req, res) => {
res.json({
'year': config.CURRENT_YEAR
})
});
// Run the ratings engine for a certain year
api.post('/calc/:year', (req, res) => {
try {
recipe(req.params.year, req.query)
.then((data) => {
res.status(200);
res.json(data);
})
.catch((error) => {
res.status(404);
res.json({ 'error': error })
});
} catch(ex) {
res.json(ex);
}
});
|
Remove start main activity task from handler if back button is pressed during loading process.
|
package com.tuenti.tuentitv.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import butterknife.InjectView;
import com.tuenti.tuentitv.R;
import java.util.LinkedList;
import java.util.List;
/**
* @author Pedro Vicente Gómez Sánchez.
*/
public class LoadingActivity extends BaseActivity {
private static final long LOADING_TIME_IN_MILLIS = 3000;
@InjectView(R.id.pb_loading) ProgressBar pb_loading;
private Runnable startMainActivity;
private Handler handler;
@Override protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.loading_activity);
super.onCreate(savedInstanceState);
pb_loading.getIndeterminateDrawable()
.setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY);
handler = new Handler();
startMainActivity = new Runnable() {
@Override public void run() {
startMainActivity();
}
};
handler.postDelayed(startMainActivity, LOADING_TIME_IN_MILLIS);
}
@Override public void onBackPressed() {
super.onBackPressed();
handler.removeCallbacks(startMainActivity);
}
private void startMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
@Override protected List getModules() {
return new LinkedList();
}
}
|
package com.tuenti.tuentitv.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import butterknife.InjectView;
import com.tuenti.tuentitv.R;
import java.util.LinkedList;
import java.util.List;
/**
* @author Pedro Vicente Gómez Sánchez.
*/
public class LoadingActivity extends BaseActivity {
private static final long LOADING_TIME_IN_MILLIS = 3000;
@InjectView(R.id.pb_loading) ProgressBar pb_loading;
@Override protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.loading_activity);
super.onCreate(savedInstanceState);
pb_loading.getIndeterminateDrawable()
.setColorFilter(0x32FFFFFF, android.graphics.PorterDuff.Mode.MULTIPLY);
new Handler().postDelayed(new Runnable() {
@Override public void run() {
startMainActivity();
}
}, LOADING_TIME_IN_MILLIS);
}
private void startMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
@Override protected List getModules() {
return new LinkedList();
}
}
|
Use score as well in annotations table
|
#!/usr/bin/env python
"""A script to sum the rpkm values for all genes for each annotation."""
import pandas as pd
import argparse
import sys
def main(args):
rpkm_table =pd.read_table(args.rpkm_table, index_col=0)
annotations = pd.read_table(args.annotation_table, header=None, names=["gene_id", "annotation", "evalue", "score"])
annotation_rpkm = {}
for annotation, annotation_df in annotations.groupby('annotation'):
annotation_rpkm[annotation] = rpkm_table.ix[annotation_df.gene_id].sum()
annotation_rpkm_df = pd.DataFrame.from_dict(annotation_rpkm, orient='index')
# sort the columns of the dataframe
annotation_rpkm_df = annotation_rpkm_df.reindex(columns=sorted(rpkm_table.columns))
annotation_rpkm_df.to_csv(sys.stdout, sep='\t')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("rpkm_table")
parser.add_argument("annotation_table")
args = parser.parse_args()
main(args)
|
#!/usr/bin/env python
"""A script to sum the rpkm values for all genes for each annotation."""
import pandas as pd
import argparse
import sys
def main(args):
rpkm_table =pd.read_table(args.rpkm_table, index_col=0)
annotations = pd.read_table(args.annotation_table, header=None, names=["gene_id", "annotation", "evalue"])
annotation_rpkm = {}
for annotation, annotation_df in annotations.groupby('annotation'):
annotation_rpkm[annotation] = rpkm_table.ix[annotation_df.gene_id].sum()
annotation_rpkm_df = pd.DataFrame.from_dict(annotation_rpkm, orient='index')
# sort the columns of the dataframe
annotation_rpkm_df = annotation_rpkm_df.reindex(columns=sorted(rpkm_table.columns))
annotation_rpkm_df.to_csv(sys.stdout, sep='\t')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("rpkm_table")
parser.add_argument("annotation_table")
args = parser.parse_args()
main(args)
|
Remove special case from StringIO.
|
from io import StringIO
try:
FileNotFoundError = FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
FileNotFoundError = FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
from contextlib import redirect_stdout
except ImportError:
import contextlib
import sys
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
yield
sys.stdout = original
def string_to_file(string):
return StringIO(text(string) if string else None)
def capture_print(func, args=None):
f = StringIO()
with redirect_stdout(f):
if args:
func(args)
else:
func()
return f.getvalue()
try:
from re import fullmatch
except ImportError:
from re import match
def fullmatch(regex, *args, **kwargs):
if not regex.pattern.endswith("$"):
return match(regex.pattern + "$", *args, flags=regex.flags, **kwargs)
return match(regex.pattern, *args, **kwargs)
try:
unicode('')
except NameError:
unicode = str
def text(value):
return unicode(value)
|
Remove extract magic string for DOT, use String.format for greater clarity
|
package seedu.todo.ui.components;
import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import seedu.todo.models.Task;
import seedu.todo.ui.UiPartLoader;
public class TaskListTaskItem extends MultiComponent {
private static final String FXML_PATH = "components/TaskListTaskItem.fxml";
// Props
public Task task;
public int displayIndex;
// FXML
@FXML
private Text taskText;
public static TaskListTaskItem load(Stage primaryStage, Pane placeholderPane) {
return UiPartLoader.loadUiPart(primaryStage, placeholderPane, new TaskListTaskItem());
}
@Override
public String getFxmlPath() {
return FXML_PATH;
}
@Override
public void componentDidMount() {
taskText.setText(formatTaskText(displayIndex, task.getName()));
}
private String formatTaskText(int index, String taskName) {
return String.format("%s. %s", index, taskName);
}
}
|
package seedu.todo.ui.components;
import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import seedu.todo.models.Task;
import seedu.todo.ui.UiPartLoader;
public class TaskListTaskItem extends MultiComponent {
private static final String FXML_PATH = "components/TaskListTaskItem.fxml";
private static final String DOT = ".";
// Props
public Task task;
public int displayIndex;
// FXML
@FXML
private Text taskText;
public static TaskListTaskItem load(Stage primaryStage, Pane placeholderPane) {
return UiPartLoader.loadUiPart(primaryStage, placeholderPane, new TaskListTaskItem());
}
@Override
public String getFxmlPath() {
return FXML_PATH;
}
@Override
public void componentDidMount() {
taskText.setText(formatTaskText(displayIndex, task.getName()));
}
private String formatTaskText(int index, String taskName) {
return String.format("%s %s", index + DOT, taskName);
}
}
|
Bump version for new build
|
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup (
name = 'pyvault',
version = '1.4.4.3',
description = 'Python password manager',
long_description = long_description,
author = 'Gabriel Bordeaux',
author_email = 'pypi@gab.lc',
url = 'https://github.com/gabfl/vault',
license = 'MIT',
packages = ['vault', 'vault.lib'],
package_dir = { 'vault': 'src' },
install_requires = ['pycryptodome', 'pyperclip', 'tabulate', 'argparse', 'passwordgenerator'], # external dependencies
entry_points = {
'console_scripts': [
'vault = vault.vault:main',
],
},
)
|
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
long_description = open('README.md').read()
setup (
name = 'pyvault',
version = '1.4.4.2',
description = 'Python password manager',
long_description = long_description,
author = 'Gabriel Bordeaux',
author_email = 'pypi@gab.lc',
url = 'https://github.com/gabfl/vault',
license = 'MIT',
packages = ['vault', 'vault.lib'],
package_dir = { 'vault': 'src' },
install_requires = ['pycryptodome', 'pyperclip', 'tabulate', 'argparse', 'passwordgenerator'], # external dependencies
entry_points = {
'console_scripts': [
'vault = vault.vault:main',
],
},
)
|
fix(switch): Switch component refactored to stateful.
|
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
const styles = () => ({
switchBase: {
color: '#c7c8c9',
'&$checked': {
color: '#0072CE',
},
'&$checked + $track': {
backgroundColor: '#0072CE',
opacity: '.4'
},
},
checked: {},
track: {},
});
class CustomSwitch extends Component {
render(){
const {classes} = this.props;
return(
<Switch
value="checkedB"
color="primary"
className={classes.switchBase}
/>
)
}
}
export default withStyles(styles)(CustomSwitch)
|
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
const CustomSwitch = withStyles({
switchBase: {
color: '#c7c8c9',
'&$checked': {
color: '#0072CE',
},
'&$checked + $track': {
backgroundColor: '#0072CE',
opacity: '.4'
},
},
checked: {},
track: {},
})(Switch);
export default function Switches() {
const [state, setState] = React.useState({
checkedB: true,
});
const handleChange = name => event => {
setState({ ...state, [name]: event.target.checked });
};
return (
<CustomSwitch
checked={state.checkedB}
onChange={handleChange('checkedB')}
value="checkedB"
color="primary"
/>
);
}
|
Use README.md as long description
|
#!/usr/bin/env python
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='hashmerge',
version='0.1',
url='https://github.com/lebauce/hashmerge',
author='Sylvain Baubeau',
author_email='bob@glumol.com',
description="Merges two arbitrarily deep hashes into a single hash.",
license='MIT',
include_package_data=False,
zip_safe=False,
py_modules=['hashmerge'],
long_description=long_description,
long_description_content_type='text/markdown',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='hashmerge',
version='0.1',
url='https://github.com/lebauce/hashmerge',
author='Sylvain Baubeau',
author_email='bob@glumol.com',
description="Merges two arbitrarily deep hashes into a single hash.",
license='MIT',
include_package_data=False,
zip_safe=False,
py_modules=['hashmerge'],
long_description="",
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: Unix',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries'],
)
|
Make epsilon smaller to be able to compare smaller scores
|
<?php
namespace lucidtaz\minimax\engine;
use Closure;
use lucidtaz\minimax\game\Decision;
class DecisionWithScore
{
const EPSILON = 0.00001;
/**
* @var Decision
*/
public $decision = null;
/**
* @var float
*/
public $score;
/**
* @var integer How deep in the execution tree this result was found. Higher
* means earlier. This is to prefer earlier solutions to later solutions
* with the same score.
*/
public $age;
public function isBetterThan(DecisionWithScore $other): bool
{
if (abs($this->score - $other->score) < self::EPSILON) {
return $this->age > $other->age;
}
return $this->score > $other->score;
}
public static function getBestComparator(): Closure
{
return function (DecisionWithScore $a, DecisionWithScore $b) {
return $a->isBetterThan($b) ? $a : $b;
};
}
public static function getWorstComparator(): Closure
{
return function (DecisionWithScore $a, DecisionWithScore $b) {
return $b->isBetterThan($a) ? $a : $b;
};
}
}
|
<?php
namespace lucidtaz\minimax\engine;
use Closure;
use lucidtaz\minimax\game\Decision;
class DecisionWithScore
{
/**
* @var Decision
*/
public $decision = null;
/**
* @var float
*/
public $score;
/**
* @var integer How deep in the execution tree this result was found. Higher
* means earlier. This is to prefer earlier solutions to later solutions
* with the same score.
*/
public $age;
public function isBetterThan(DecisionWithScore $other): bool
{
if (abs($this->score - $other->score) < 0.1) {
return $this->age > $other->age;
}
return $this->score > $other->score;
}
public static function getBestComparator(): Closure
{
return function (DecisionWithScore $a, DecisionWithScore $b) {
return $a->isBetterThan($b) ? $a : $b;
};
}
public static function getWorstComparator(): Closure
{
return function (DecisionWithScore $a, DecisionWithScore $b) {
return $b->isBetterThan($a) ? $a : $b;
};
}
}
|
Remove @Component for optional encoder
Instantiation is optional as to avoid introducing a hard dependency on spring-security.
|
package org.jasig.cas.authentication.handler;
import javax.validation.constraints.NotNull;
/**
* Pass the encode/decode responsibility to a delegated Spring Security
* password encoder.
*
* @author Joe McCall
* @since 4.3
*/
public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder {
@NotNull
private org.springframework.security.crypto.password.PasswordEncoder delegate;
public void setDelegate(final org.springframework.security.crypto.password.PasswordEncoder delegate) {
this.delegate = delegate;
}
@Override
public String encode(final String password) {
return delegate.encode(password);
}
@Override
public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
return delegate.matches(rawPassword, encodedPassword);
}
}
|
package org.jasig.cas.authentication.handler;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
/**
* Pass the encode/decode responsibility to a delegated Spring Security
* password encoder.
*
* @author Joe McCall
* @since 4.3
*/
@Component("springSecurityDelegatingPasswordEncoder")
public class SpringSecurityDelegatingPasswordEncoder implements PasswordEncoder {
@NotNull
private org.springframework.security.crypto.password.PasswordEncoder delegate;
public void setDelegate(final org.springframework.security.crypto.password.PasswordEncoder delegate) {
this.delegate = delegate;
}
@Override
public String encode(final String password) {
return delegate.encode(password);
}
@Override
public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
return delegate.matches(rawPassword, encodedPassword);
}
}
|
Introduce a new error class.
|
#
## PyMoira client library
##
## This file contains the Moira-related errors.
#
import moira_constants
class MoiraBaseError(Exception):
"""Any exception thrown by the library is inhereted from this"""
pass
class MoiraConnectionError(MoiraBaseError):
"""An error which prevents the client from having or continuing a meaningful
dialogue with a server (parsing failure, connection failure, etc)"""
pass
class MoiraError(MoiraBaseError):
"""An error returned from Moira server itself which has a Moira error code."""
def __init__(self, code):
if code in moira_constants.errors:
MoiraBaseError.__init__(self, "Moira error: %s" % moira_constants.errors[code])
else:
MoiraBaseError.__init__(self, "Unknown Moira error (code %i)" % code)
class MoiraUnavailableError(MoiraBaseError):
"""An error raised in case when Moira MOTD is not empty."""
pass
class MoiraUserError(MoiraBaseError):
"""An error related to Moira but not returned from the server."""
pass
|
#
## PyMoira client library
##
## This file contains the Moira-related errors.
#
import moira_constants
class MoiraBaseError(Exception):
"""Any exception thrown by the library is inhereted from this"""
pass
class MoiraConnectionError(MoiraBaseError):
"""An error which prevents the client from having or continuing a meaningful
dialogue with a server (parsing failure, connection failure, etc)"""
pass
class MoiraError(MoiraBaseError):
"""An error returned from Moira server itself which has a Moira error code."""
def __init__(self, code):
if code in moira_constants.errors:
MoiraBaseError.__init__(self, "Moira error: %s" % moira_constants.errors[code])
else:
MoiraBaseError.__init__(self, "Unknown Moira error (code %i)" % code)
class MoiraUnavailableError(MoiraBaseError):
"""An error raised in case when Moira MOTD is not empty."""
pass
|
Add support for debug mode
|
var AWS = require("aws-sdk");
var s3 = new AWS.S3({
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET
});
var elasticsearchUrl = process.env.ELASTICSEARCH_URL;
var s3Bucket = process.env.S3_BUCKET;
var debug = process.env.DEBUG;
var importer = require("./importer")(s3, {debug: debug});
if (!elasticsearchUrl) {
console.log("You must specify ELASTICSEARCH_URL");
process.exit(1);
}
if (s3Bucket) {
importer.importFolder(s3Bucket, elasticsearchUrl).then(function(data) {
console.log("Finished importing from bucket", s3Bucket, "to", elasticsearchUrl);
console.log("Summary:", data);
}, function(error) {
if (typeof(error) === "object" && error.message) {
console.error(error.message);
if (error.stack) {
console.error(error.stack);
}
} else {
console.error(error);
}
process.exit(1);
});
} else {
console.error("You must specify S3_BUCKET");
process.exit(1);
}
|
var AWS = require("aws-sdk");
var s3 = new AWS.S3({
accessKeyId: process.env.AWS_KEY,
secretAccessKey: process.env.AWS_SECRET
});
var importer = require("./importer")(s3);
if (!process.env.ELASTICSEARCH_URL) {
console.log("You must specify ELASTICSEARCH_URL");
process.exit(1);
}
if (process.env.S3_BUCKET) {
importer.importFolder(process.env.S3_BUCKET, process.env.ELASTICSEARCH_URL).then(function(data) {
console.log(data);
}, function(error) {
if (typeof(error) === "object" && error.message) {
console.error(error.message);
if (error.stack) {
console.error(error.stack);
}
} else {
console.error(error);
}
process.exit(1);
});
} else {
console.error("You must specify S3_BUCKET");
process.exit(1);
}
|
Add order to PerObjectSettings tool
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml",
"weight": 3
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml"
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
Add a `m.Fragment = "["` utility for JSX users.
|
"use strict"
var hyperscript = require("./hyperscript")
var request = require("./request")
var mountRedraw = require("./mount-redraw")
var m = function m() { return hyperscript.apply(this, arguments) }
m.m = hyperscript
m.trust = hyperscript.trust
m.fragment = hyperscript.fragment
m.Fragment = "["
m.mount = mountRedraw.mount
m.route = require("./route")
m.render = require("./render")
m.redraw = mountRedraw.redraw
m.request = request.request
m.jsonp = request.jsonp
m.parseQueryString = require("./querystring/parse")
m.buildQueryString = require("./querystring/build")
m.parsePathname = require("./pathname/parse")
m.buildPathname = require("./pathname/build")
m.vnode = require("./render/vnode")
m.PromisePolyfill = require("./promise/polyfill")
m.censor = require("./util/censor")
module.exports = m
|
"use strict"
var hyperscript = require("./hyperscript")
var request = require("./request")
var mountRedraw = require("./mount-redraw")
var m = function m() { return hyperscript.apply(this, arguments) }
m.m = hyperscript
m.trust = hyperscript.trust
m.fragment = hyperscript.fragment
m.mount = mountRedraw.mount
m.route = require("./route")
m.render = require("./render")
m.redraw = mountRedraw.redraw
m.request = request.request
m.jsonp = request.jsonp
m.parseQueryString = require("./querystring/parse")
m.buildQueryString = require("./querystring/build")
m.parsePathname = require("./pathname/parse")
m.buildPathname = require("./pathname/build")
m.vnode = require("./render/vnode")
m.PromisePolyfill = require("./promise/polyfill")
m.censor = require("./util/censor")
module.exports = m
|
[scripts] Use different way to determine 32/64-bit which returns mode of current binary, not of the system
|
import sim, syscall_strings, sys
if sys.maxsize == 2**31-1:
__syscall_strings = syscall_strings.syscall_strings_32
else:
__syscall_strings = syscall_strings.syscall_strings_64
def syscall_name(syscall_number):
return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_number)
class LogSyscalls:
def hook_syscall_enter(self, threadid, coreid, time, syscall_number, args):
print '[SYSCALL] @%10d ns: %-27s thread(%3d) core(%3d) args%s' % (time/1e6, syscall_name(syscall_number), threadid, coreid, args)
def hook_syscall_exit(self, threadid, coreid, time, ret_val, emulated):
print '[SYSCALL] @%10d ns: exit thread(%3d) core(%3d) ret_val(%d) emulated(%s)' % (time/1e6, threadid, coreid, ret_val, emulated)
sim.util.register(LogSyscalls())
|
import sim, syscall_strings, platform
if platform.architecture()[0] == '64bit':
__syscall_strings = syscall_strings.syscall_strings_64
else:
__syscall_strings = syscall_strings.syscall_strings_32
def syscall_name(syscall_number):
return '%s[%d]' % (__syscall_strings.get(syscall_number, 'unknown'), syscall_number)
class LogSyscalls:
def hook_syscall_enter(self, threadid, coreid, time, syscall_number, args):
print '[SYSCALL] @%10d ns: %-27s thread(%3d) core(%3d) args%s' % (time/1e6, syscall_name(syscall_number), threadid, coreid, args)
def hook_syscall_exit(self, threadid, coreid, time, ret_val, emulated):
print '[SYSCALL] @%10d ns: exit thread(%3d) core(%3d) ret_val(%d) emulated(%s)' % (time/1e6, threadid, coreid, ret_val, emulated)
sim.util.register(LogSyscalls())
|
bugfix: Exclude results with matching inline configs when testing files
|
var _ = require('lodash');
module.exports = function(ast, filePath, plugins) {
var errors = [],
warnings = [];
_.each(plugins, function(plugin){
var results,
array;
if (plugin.severity === 2) {
array = errors;
} else if (plugin.severity === 1) {
array = warnings;
} else {
return;
}
results = plugin.test(ast, filePath, plugin.options);
if (!results || !results.length || !_.isArray(results)){
return;
}
// Remove failures that are on plugins with inline configs
_.each(results, function (result){
if (!result.node || !result.node._polishIgnore || !_.contains(result.node._polishIgnore, plugin.name)) {
return;
}
results = _.without(results, result);
});
_.each(results, function(result){
array.push({
plugin: _.pick(plugin, ['name', 'message', 'severity']),
error: result
});
});
});
return {
errors : errors,
warnings : warnings
};
};
|
var _ = require('lodash');
module.exports = function(ast, filePath, plugins) {
var errors = [],
warnings = [];
_.each(plugins, function(plugin){
var results,
array;
if (plugin.severity === 2) {
array = errors;
} else if (plugin.severity === 1) {
array = warnings;
} else {
return;
}
results = plugin.test(ast, filePath, plugin.options);
if (!results || !results.length || !_.isArray(results)){
return;
}
// Remove failures that are on plugins with inline configs
_.each(results, function (result){
if (!result.node || !result.node.ruleConfig) {
return;
}
if (result.node.ruleConfig[plugin.name] === false) {
results = _.without(results, result);
}
});
_.each(results, function(result){
array.push({
plugin: _.pick(plugin, ['name', 'message', 'severity']),
error: result
});
});
});
return {
errors : errors,
warnings : warnings
};
};
|
Add optional path parameter to module_path helper
|
<?php
if (! function_exists('module_path')) {
function module_path($name, $path = '')
{
$module = app('modules')->find($name);
return $module->getPath().($path ? DIRECTORY_SEPARATOR.$path : $path);
}
}
if (! function_exists('config_path')) {
/**
* Get the configuration path.
*
* @param string $path
* @return string
*/
function config_path($path = '')
{
return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
}
}
if (! function_exists('public_path')) {
/**
* Get the path to the public folder.
*
* @param string $path
* @return string
*/
function public_path($path = '')
{
return app()->make('path.public') . ($path ? DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR) : $path);
}
}
|
<?php
if (! function_exists('module_path')) {
function module_path($name)
{
$module = app('modules')->find($name);
return $module->getPath();
}
}
if (! function_exists('config_path')) {
/**
* Get the configuration path.
*
* @param string $path
* @return string
*/
function config_path($path = '')
{
return app()->basePath() . '/config' . ($path ? '/' . $path : $path);
}
}
if (! function_exists('public_path')) {
/**
* Get the path to the public folder.
*
* @param string $path
* @return string
*/
function public_path($path = '')
{
return app()->make('path.public') . ($path ? DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR) : $path);
}
}
|
Add test suite to the distribution
|
from setuptools import setup
from tcxparser import __version__
setup(
name='python-tcxparser',
version=__version__,
author='Vinod Kurup',
author_email='vinod@kurup.com',
py_modules=['tcxparser', 'test_tcxparser'],
url='https://github.com/vkurup/python-tcxparser/',
license='BSD',
description='Simple parser for Garmin TCX files',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
long_description=open('README.md').read(),
install_requires=[
"lxml",
],
test_suite="test_tcxparser",
)
|
from setuptools import setup
from tcxparser import __version__
setup(
name='python-tcxparser',
version=__version__,
author='Vinod Kurup',
author_email='vinod@kurup.com',
py_modules=['tcxparser', ],
url='https://github.com/vkurup/python-tcxparser/',
license='BSD',
description='Simple parser for Garmin TCX files',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
long_description=open('README.md').read(),
install_requires=[
"lxml",
],
)
|
Bump the package version - 0.1.7
Change log:
- Updated documentation for better PyPI support
- Includes all the latest fixes until now
|
import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_email = "pytesseract@madmaze.net",
description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
long_description = longDesc,
license = "GPLv3",
keywords = "python-tesseract OCR Python",
url = "https://github.com/madmaze/python-tesseract",
packages=['pytesseract'],
package_dir={'pytesseract': 'src'},
package_data = {'pytesseract': ['*.png','*.jpg']},
entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
|
import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.6",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_email = "pytesseract@madmaze.net",
description = ("Python-tesseract is a python wrapper for google's Tesseract-OCR"),
long_description = longDesc,
license = "GPLv3",
keywords = "python-tesseract OCR Python",
url = "https://github.com/madmaze/python-tesseract",
packages=['pytesseract'],
package_dir={'pytesseract': 'src'},
package_data = {'pytesseract': ['*.png','*.jpg']},
entry_points = {'console_scripts': ['pytesseract = pytesseract.pytesseract:main']},
classifiers = [
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
]
)
|
Delete name nad email also
|
const initialState = {
readMore: false,
jwToken: null,
myEmail: null,
myName: null,
myFetch: null
}
export default function update (state = initialState, action) {
switch (action.type) {
case 'TOGGLE_READ_MORE':
return Object.assign({}, state, {
readMore: action.readMore
})
case 'RECEIVE_TOKEN_FROM_SERVER':
return Object.assign({}, state, {
jwToken: action.jwToken,
myEmail: action.email,
myName: action.name
})
case 'RECEIVE_TOKEN_FROM_LOCAL_STORAGE': {
return Object.assign({}, state, {
jwToken: action.jwToken,
myEmail: action.email,
myName: action.name
})
}
case '@@me/DELETE_TOKEN':
return Object.assign({}, state, {
jwToken: null,
myEmail: null,
myName: null
})
case '@@login/DELETE_TOKEN':
return Object.assign({}, state, {
jwToken: null,
myEmail: null,
myName: null
})
default:
return state
}
}
|
const initialState = {
readMore: false,
jwToken: null,
myEmail: null,
myName: null,
myFetch: null
}
export default function update (state = initialState, action) {
switch (action.type) {
case 'TOGGLE_READ_MORE':
return Object.assign({}, state, {
readMore: action.readMore
})
case 'RECEIVE_TOKEN_FROM_SERVER':
return Object.assign({}, state, {
jwToken: action.jwToken,
myEmail: action.email,
myName: action.name
})
case 'RECEIVE_TOKEN_FROM_LOCAL_STORAGE': {
return Object.assign({}, state, {
jwToken: action.jwToken,
myEmail: action.email,
myName: action.name
})
}
case '@@me/DELETE_TOKEN':
return Object.assign({}, state, {
jwToken: null
})
case '@@login/DELETE_TOKEN':
return Object.assign({}, state, {
jwToken: null
})
default:
return state
}
}
|
Fix no-replace-server to accurately preview update
This override of OS::Nova::Server needs to reflect the fact
that it never replaces on update or the update --dry-run output
ends up being wrong.
Closes-Bug: 1561076
Change-Id: I9256872b877fbe7f91befb52995c62de006210ef
|
#
# 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 heat.engine.resources.openstack.nova import server
class ServerUpdateAllowed(server.Server):
'''Prevent any properties changes from replacing an existing server.
'''
update_allowed_properties = server.Server.properties_schema.keys()
def needs_replace_with_prop_diff(self, changed_properties_set,
after_props, before_props):
return False
def resource_mapping():
return {'OS::Nova::Server': ServerUpdateAllowed}
|
#
# 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 heat.engine.resources.openstack.nova import server
class ServerUpdateAllowed(server.Server):
'''Prevent any properties changes from replacing an existing server.
'''
update_allowed_properties = server.Server.properties_schema.keys()
def resource_mapping():
return {'OS::Nova::Server': ServerUpdateAllowed}
|
Remove rules which are now enabled by default
These template lint rules are now enabled in the 'recommended'
configuration so we don't need to override them in our config.
|
/* eslint-env node */
'use strict';
var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];
module.exports = {
extends: 'recommended',
rules: {
'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
'block-indentation': true,
'html-comments': true,
'nested-interactive': true,
'self-closing-void-elements': true,
'img-alt-attributes': false,
'invalid-interactive': false,
'inline-link-to': true,
'triple-curlies': false,
'deprecated-each-syntax': true,
'deprecated-inline-view-helper': false,
}
};
|
/* eslint-env node */
'use strict';
var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];
module.exports = {
extends: 'recommended',
rules: {
'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
'block-indentation': true,
'html-comments': true,
'nested-interactive': true,
'self-closing-void-elements': true,
'img-alt-attributes': false,
'link-rel-noopener': true,
'invalid-interactive': false,
'inline-link-to': true,
'style-concatenation': true,
'triple-curlies': false,
'deprecated-each-syntax': true,
'deprecated-inline-view-helper': false,
}
};
|
Revert "Updated the boto requirement to 2.8.0"
This reverts commit add8a4a7d68b47ed5c24fefa5dde6e8e372804bf.
|
from setuptools import setup, find_packages
import dynamodb_sessions
long_description = open('README.rst').read()
major_ver, minor_ver = dynamodb_sessions.__version__
version_str = '%d.%d' % (major_ver, minor_ver)
setup(
name='django-dynamodb-sessions',
version=version_str,
packages=find_packages(),
description="A Django session backend using Amazon's DynamoDB",
long_description=long_description,
author='Gregory Taylor',
author_email='gtaylor@gc-taylor.com',
license='BSD License',
url='https://github.com/gtaylor/django-dynamodb-sessions',
platforms=["any"],
install_requires=['django', "boto>=2.2.2"],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Environment :: Web Environment',
],
)
|
from setuptools import setup, find_packages
import dynamodb_sessions
long_description = open('README.rst').read()
major_ver, minor_ver = dynamodb_sessions.__version__
version_str = '%d.%d' % (major_ver, minor_ver)
setup(
name='django-dynamodb-sessions',
version=version_str,
packages=find_packages(),
description="A Django session backend using Amazon's DynamoDB",
long_description=long_description,
author='Gregory Taylor',
author_email='gtaylor@gc-taylor.com',
license='BSD License',
url='https://github.com/gtaylor/django-dynamodb-sessions',
platforms=["any"],
install_requires=['django', "boto>=2.8.0"],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Environment :: Web Environment',
],
)
|
Clean up control model tests
|
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for control model."""
from ggrc import db
from ggrc.models import Control
from integration.ggrc import TestCase
from integration.ggrc.models import factories
class TestControl(TestCase):
def test_simple_categorization(self):
category = factories.ControlCategoryFactory(scope_id=100)
control = factories.ControlFactory()
control.categories.append(category)
db.session.commit()
self.assertIn(category, control.categories)
# be really really sure
control = db.session.query(Control).get(control.id)
self.assertIn(category, control.categories)
def test_has_test_plan(self):
control = factories.ControlFactory(test_plan="This is a test text")
control = db.session.query(Control).get(control.id)
self.assertEqual(control.test_plan, "This is a test text")
|
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
from ggrc import db
from ggrc.models import Control
from integration.ggrc import TestCase
from .factories import ControlCategoryFactory, ControlFactory
from nose.plugins.skip import SkipTest
from nose.tools import assert_in, eq_
class TestControl(TestCase):
def test_simple_categorization(self):
category = ControlCategoryFactory(scope_id=100)
control = ControlFactory()
control.categories.append(category)
db.session.commit()
self.assertIn(category, control.categories)
# be really really sure
control = db.session.query(Control).get(control.id)
self.assertIn(category, control.categories)
def test_has_test_plan(self):
control = ControlFactory(test_plan="This is a test text")
db.session.commit()
control = db.session.query(Control).get(control.id)
eq_(control.test_plan, "This is a test text")
|
Use actual byte string instead of hex2bin() on hex string
|
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Rfc4122;
/**
* Provides common functionality for nil UUIDs
*
* The nil UUID is special form of UUID that is specified to have all 128 bits
* set to zero.
*
* @link https://tools.ietf.org/html/rfc4122#section-4.1.7 RFC 4122, § 4.1.7: Nil UUID
*
* @psalm-immutable
*/
trait NilTrait
{
/**
* Returns the bytes that comprise the fields
*/
abstract public function getBytes(): string;
/**
* Returns true if the byte string represents a nil UUID
*/
public function isNil(): bool
{
return $this->getBytes() === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
}
}
|
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Rfc4122;
use function hex2bin;
/**
* Provides common functionality for nil UUIDs
*
* The nil UUID is special form of UUID that is specified to have all 128 bits
* set to zero.
*
* @link https://tools.ietf.org/html/rfc4122#section-4.1.7 RFC 4122, § 4.1.7: Nil UUID
*
* @psalm-immutable
*/
trait NilTrait
{
/**
* Returns the bytes that comprise the fields
*/
abstract public function getBytes(): string;
/**
* Returns true if the byte string represents a nil UUID
*/
public function isNil(): bool
{
return $this->getBytes() === hex2bin('00000000000000000000000000000000');
}
}
|
Sort feed items by title first, then date.
|
package feedloggr2
import (
"github.com/jinzhu/gorm"
rss "github.com/jteeuwen/go-pkg-rss"
_ "github.com/mattn/go-sqlite3"
)
type Datastore interface {
GetItems(feed_url string) ([]*FeedItem, error)
ProcessChannels(feed *rss.Feed, channels []*rss.Channel)
ProcessItems(feed *rss.Feed, ch *rss.Channel, items []*rss.Item)
}
type DB struct {
*gorm.DB
}
func OpenSqliteDB(args ...interface{}) (*DB, error) {
// TODO: get rid of gorm
db, e := gorm.Open("sqlite3", args...)
if e != nil {
return nil, e
}
db.AutoMigrate(&FeedItem{})
return &DB{&db}, nil
}
func (db *DB) SaveItems(items []*FeedItem) {
tx := db.Begin()
tx.LogMode(false) // Don't show errors when UNIQUE fails
for _, i := range items {
tx.Create(i)
}
tx.Commit()
}
func (db *DB) GetItems(feed_url string) []*FeedItem {
var items []*FeedItem
// TODO: fix the feed url thing
db.Order("title, date desc").Where(
"feed = ? AND date(date) = date(?)", feed_url, Now(),
).Find(&items)
return items
}
|
package feedloggr2
import (
"github.com/jinzhu/gorm"
rss "github.com/jteeuwen/go-pkg-rss"
_ "github.com/mattn/go-sqlite3"
)
type Datastore interface {
GetItems(feed_url string) ([]*FeedItem, error)
ProcessChannels(feed *rss.Feed, channels []*rss.Channel)
ProcessItems(feed *rss.Feed, ch *rss.Channel, items []*rss.Item)
}
type DB struct {
*gorm.DB
}
func OpenSqliteDB(args ...interface{}) (*DB, error) {
// TODO: get rid of gorm
db, e := gorm.Open("sqlite3", args...)
if e != nil {
return nil, e
}
db.AutoMigrate(&FeedItem{})
return &DB{&db}, nil
}
func (db *DB) SaveItems(items []*FeedItem) {
tx := db.Begin()
tx.LogMode(false) // Don't show errors when UNIQUE fails
for _, i := range items {
tx.Create(i)
}
tx.Commit()
}
func (db *DB) GetItems(feed_url string) []*FeedItem {
var items []*FeedItem
// TODO: fix the feed url thing
db.Order("date desc, title").Where(
"feed = ? AND date(date) = date(?)", feed_url, Now(),
).Find(&items)
return items
}
|
Remove extra whitespace from bug title
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
|
# -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# 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 re
WHITESPACE = re.compile(r'\s{2,}')
def tidy_bug_title(title, package):
"""
Strips various package name prefixes from a bug title.
For example:
"emacs: Not as good as vim" => "Not as good as vim"
"[emacs] Not as good as vim" => "Not as good as vim"
"""
title = title.strip()
for prefix in ('%s: ', '[%s]: ', '[%s] '):
if title.lower().startswith(prefix % package.lower()):
title = title[len(package) + len(prefix) - 2:]
title = WHITESPACE.sub(' ', title)
return title
|
# -*- coding: utf-8 -*-
#
# Debian Changes Bot
# Copyright (C) 2008 Chris Lamb <chris@chris-lamb.co.uk>
#
# 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/>.
def tidy_bug_title(title, package):
"""
Strips various package name prefixes from a bug title.
For example:
"emacs: Not as good as vim" => "Not as good as vim"
"[emacs] Not as good as vim" => "Not as good as vim"
"""
for prefix in ('%s: ', '[%s]: ', '[%s] '):
if title.lower().startswith(prefix % package.lower()):
title = title[len(package) + len(prefix) - 2:]
return title
|
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
|
# -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information.
LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages.
GOOGLE_MAPS_API_KEY = None
GOOGLE_KEY = None
CACHE_LIFETIME = 600 # 10 minutes in seconds
class Meta:
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None:
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
|
# -*- coding: utf-8 -*-
import warnings
from django.conf import settings # pylint: disable=W0611
from appconf import AppConf
class EasyMapsSettings(AppConf):
CENTER = (-41.3, 32)
GEOCODE = 'easy_maps.geocode.google_v3'
ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information.
LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages.
GOOGLE_MAPS_API_KEY = None
GOOGLE_KEY = None
CACHE_LIFETIME = 600 # 10 minutes in seconds
class Meta:
prefix = 'easy_maps'
holder = 'easy_maps.conf.settings'
if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'):
warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
|
Fix decimal numbers limit to 2
while calculating the row total, javascript was called and on some quantity, a number with a big decimal part was appearing.In this PR it is fixed
Fixes https://github.com/opensuse/osem/issues/1709
|
function update_price($this){
var id = $this.data('id');
// Calculate price for row
var value = $this.val();
var price = $('#price_' + id).text();
$('#total_row_' + id).text((value * price).toFixed(2));
// Calculate total price
var total = 0;
$('.total_row').each(function( index ) {
total += parseFloat($(this).text());
});
$('#total_price').text(total);
}
$( document ).ready(function() {
$('.quantity').each(function() {
update_price($(this));
});
$('.quantity').change(function() {
update_price($(this));
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
});
|
function update_price($this){
var id = $this.data('id');
// Calculate price for row
var value = $this.val();
var price = $('#price_' + id).text();
$('#total_row_' + id).text(value * price);
// Calculate total price
var total = 0;
$('.total_row').each(function( index ) {
total += parseFloat($(this).text());
});
$('#total_price').text(total);
}
$( document ).ready(function() {
$('.quantity').each(function() {
update_price($(this));
});
$('.quantity').change(function() {
update_price($(this));
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
});
});
|
Use re instead of regex.
Don't rewrite the file in place.
(Reported by Andy Dustman.)
|
#!/usr/bin/env python
# Fix Python script(s) to reference the interpreter via /usr/bin/env python.
# Warning: this overwrites the file without making a backup.
import sys
import re
def main():
for file in sys.argv[1:]:
try:
f = open(file, 'r')
except IOError, msg:
print file, ': can\'t open :', msg
continue
line = f.readline()
if not re.match('^#! */usr/local/bin/python', line):
print file, ': not a /usr/local/bin/python script'
f.close()
continue
rest = f.read()
f.close()
line = re.sub('/usr/local/bin/python',
'/usr/bin/env python', line)
print file, ':', `line`
f = open(file, "w")
f.write(line)
f.write(rest)
f.close()
main()
|
#! /usr/bin/env python
# Fix Python script(s) to reference the interpreter via /usr/bin/env python.
import sys
import regex
import regsub
def main():
for file in sys.argv[1:]:
try:
f = open(file, 'r+')
except IOError:
print file, ': can\'t open for update'
continue
line = f.readline()
if regex.match('^#! */usr/local/bin/python', line) < 0:
print file, ': not a /usr/local/bin/python script'
f.close()
continue
rest = f.read()
line = regsub.sub('/usr/local/bin/python',
'/usr/bin/env python', line)
print file, ':', `line`
f.seek(0)
f.write(line)
f.write(rest)
f.close()
main()
|
Add comment explaining where runtime value comes from
|
"use strict";
var _ = require('lodash');
var defaultSettings = {
title: 'Model My Watershed',
itsi_embed: false,
itsi_enabled: true,
data_catalog_enabled: false,
base_layers: {},
stream_layers: {},
coverage_layers: {},
boundary_layers: {},
conus_perimeter: {},
draw_tools: [],
map_controls: [],
vizer_urls: {},
vizer_ignore: [],
vizer_names: {},
model_packages: [],
max_area: 75000, // Default. Populated at runtime by MAX_AREA in base.py
enabled_features: [],
branch: null,
gitDescribe: null,
};
var settings = (function() {
return window.clientSettings ? window.clientSettings : defaultSettings;
})();
function isLayerSelectorEnabled() {
return _.contains(settings['map_controls'], 'LayerSelector');
}
function featureEnabled(feature) {
return _.contains(settings['enabled_features'], feature);
}
function set(key, value) {
settings[key] = value;
return value;
}
function get(key) {
try {
return settings[key];
} catch (exc) {
return undefined;
}
}
module.exports = {
isLayerSelectorEnabled: isLayerSelectorEnabled,
featureEnabled: featureEnabled,
get: get,
set: set
};
|
"use strict";
var _ = require('lodash');
var defaultSettings = {
title: 'Model My Watershed',
itsi_embed: false,
itsi_enabled: true,
data_catalog_enabled: false,
base_layers: {},
stream_layers: {},
coverage_layers: {},
boundary_layers: {},
conus_perimeter: {},
draw_tools: [],
map_controls: [],
vizer_urls: {},
vizer_ignore: [],
vizer_names: {},
model_packages: [],
max_area: 75000,
enabled_features: [],
branch: null,
gitDescribe: null,
};
var settings = (function() {
return window.clientSettings ? window.clientSettings : defaultSettings;
})();
function isLayerSelectorEnabled() {
return _.contains(settings['map_controls'], 'LayerSelector');
}
function featureEnabled(feature) {
return _.contains(settings['enabled_features'], feature);
}
function set(key, value) {
settings[key] = value;
return value;
}
function get(key) {
try {
return settings[key];
} catch (exc) {
return undefined;
}
}
module.exports = {
isLayerSelectorEnabled: isLayerSelectorEnabled,
featureEnabled: featureEnabled,
get: get,
set: set
};
|
Fix null pointer exception when user has 0 devices associated with account
|
package com.google.sps.data;
import com.google.sps.data.ChromeOSDevice;
import java.util.ArrayList;
import java.util.List;
/*
* Class representing response to `list Chrome OS Devices` request.
* See https://developers.google.com/admin-sdk/directory/v1/reference/chromeosdevices/list
*/
public final class ListDeviceResponse {
private final String kind;
private final List<ChromeOSDevice> chromeosdevices;
private final String nextPageToken;
private final String etag;
public ListDeviceResponse(String kind, List<ChromeOSDevice> chromeosdevices, String nextPageToken, String etag) {
this.kind = kind;
this.chromeosdevices = getDeviceListCopy(chromeosdevices);
this.nextPageToken = nextPageToken;
this.etag = etag;
}
public boolean hasNextPageToken() {
return nextPageToken != null;
}
public String getNextPageToken() {
return nextPageToken;
}
public List<ChromeOSDevice> getDeviceListCopy(List<ChromeOSDevice> original) {
final List<ChromeOSDevice> devices = new ArrayList<>();
if (original == null) {
return devices;
}
for (final ChromeOSDevice device : original) {
devices.add(device.copy());
}
return devices;
}
public List<ChromeOSDevice> getDevices() {
return getDeviceListCopy(chromeosdevices);
}
}
|
package com.google.sps.data;
import com.google.sps.data.ChromeOSDevice;
import java.util.ArrayList;
import java.util.List;
/*
* Class representing response to `list Chrome OS Devices` request.
* See https://developers.google.com/admin-sdk/directory/v1/reference/chromeosdevices/list
*/
public final class ListDeviceResponse {
private final String kind;
private final List<ChromeOSDevice> chromeosdevices;
private final String nextPageToken;
private final String etag;
public ListDeviceResponse(String kind, List<ChromeOSDevice> chromeosdevices, String nextPageToken, String etag) {
this.kind = kind;
this.chromeosdevices = getDeviceListCopy(chromeosdevices);
this.nextPageToken = nextPageToken;
this.etag = etag;
}
public boolean hasNextPageToken() {
return nextPageToken != null;
}
public String getNextPageToken() {
return nextPageToken;
}
public List<ChromeOSDevice> getDeviceListCopy(List<ChromeOSDevice> original) {
final List<ChromeOSDevice> devices = new ArrayList<>();
for (final ChromeOSDevice device : original) {
devices.add(device.copy());
}
return devices;
}
public List<ChromeOSDevice> getDevices() {
return getDeviceListCopy(chromeosdevices);
}
}
|
Add more tests for Config
|
# -*- coding: utf-8 -*-
# Copyright 2015 grafana-dashboard-builder contributors
#
# 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.
import os
from grafana_dashboards.config import Config
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_existent_config_file():
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml')
config = Config(config_file)
assert config.get_config('context') == {'component': 'frontend'}
assert config.get_config('unknown') == {}
def test_nonexistent_config_file():
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'no_file.yaml')
config = Config(config_file)
assert config.get_config('context') == {}
assert config.get_config('unknown') == {}
|
# -*- coding: utf-8 -*-
# Copyright 2015 grafana-dashboard-builder contributors
#
# 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.
import os
from grafana_dashboards.config import Config
__author__ = 'Jakub Plichta <jakub.plichta@gmail.com>'
def test_dict():
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.yaml')
config = Config(config_file)
assert config.get_config('context') == {'component': 'frontend'}
assert config.get_config('unknown') == {}
|
Remove braces for one line functions
|
import React from 'react'
export const Checkbox = ({ id, nodes, onToggle }) => {
const node = nodes[id]
const { key, childIds, checked } = node
const handleChange = () => onToggle(id)
return (
<React.Fragment key={id}>
{key &&
<li>
<input type='checkbox' checked={checked} className='pointer'
onChange={handleChange} />
<label className='ml2'>{key}</label>
</li>}
{childIds.length ?
(<ul className='list'>
{childIds.map((childId) => {
return (<Checkbox key={childId} id={childId}
nodes={nodes} onToggle={onToggle} />)
})}
</ul>)
:
null}
</React.Fragment>
)
}
|
import React from 'react'
export const Checkbox = ({ id, nodes, onToggle }) => {
const node = nodes[id]
const { key, childIds, checked } = node
const handleChange = () => {
onToggle(id)
}
return (
<React.Fragment key={id}>
{key &&
<li>
<input type='checkbox' checked={checked} className='pointer'
onChange={handleChange} />
<label className='ml2'>{key}</label>
</li>}
{childIds.length ?
(<ul className='list'>
{childIds.map((childId) => {
return (<Checkbox key={childId} id={childId}
nodes={nodes} onToggle={onToggle} />)
})}
</ul>)
:
null}
</React.Fragment>
)
}
|
Use py_limited_api="auto" in rust_with_cffi example
|
#!/usr/bin/env python
import platform
import sys
from setuptools import setup
from setuptools_rust import RustExtension
setup(
name="rust-with-cffi",
version="0.1.0",
classifiers=[
"License :: OSI Approved :: MIT License",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Rust",
"Operating System :: POSIX",
"Operating System :: MacOS :: MacOS X",
],
packages=["rust_with_cffi"],
rust_extensions=[
RustExtension("rust_with_cffi.rust", py_limited_api="auto"),
],
cffi_modules=["cffi_module.py:ffi"],
install_requires=["cffi"],
setup_requires=["cffi"],
include_package_data=True,
zip_safe=False,
)
|
#!/usr/bin/env python
import platform
import sys
from setuptools import setup
from setuptools_rust import RustExtension
setup(
name="rust-with-cffi",
version="0.1.0",
classifiers=[
"License :: OSI Approved :: MIT License",
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Programming Language :: Python",
"Programming Language :: Rust",
"Operating System :: POSIX",
"Operating System :: MacOS :: MacOS X",
],
packages=["rust_with_cffi"],
rust_extensions=[
RustExtension("rust_with_cffi.rust"),
],
cffi_modules=["cffi_module.py:ffi"],
install_requires=["cffi"],
setup_requires=["cffi"],
include_package_data=True,
zip_safe=False,
)
|
Mark that we need Genshi from trunk.
|
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from setuptools import setup
setup(
name = 'TracMasterTickets',
version = '2.1.1',
packages = ['mastertickets'],
package_data = { 'mastertickets': ['htdocs/*.js', 'htdocs/*.css' ] },
author = "Noah Kantrowitz",
author_email = "coderanger@yahoo.com",
description = "Provides support for ticket dependencies and master tickets.",
license = "BSD",
keywords = "trac plugin ticket dependencies master",
url = "http://trac-hacks.org/wiki/MasterTicketsPlugin",
classifiers = [
'Framework :: Trac',
],
install_requires = ['Trac', 'Genshi >= 0.5.dev-r698,==dev'],
entry_points = {
'trac.plugins': [
'mastertickets.web_ui = mastertickets.web_ui',
'mastertickets.api = mastertickets.api',
]
}
)
|
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from setuptools import setup
setup(
name = 'TracMasterTickets',
version = '2.1',
packages = ['mastertickets'],
package_data = { 'mastertickets': ['htdocs/*.js', 'htdocs/*.css' ] },
author = "Noah Kantrowitz",
author_email = "coderanger@yahoo.com",
description = "Provides support for ticket dependencies and master tickets.",
license = "BSD",
keywords = "trac plugin ticket dependencies master",
url = "http://trac-hacks.org/wiki/MasterTicketsPlugin",
classifiers = [
'Framework :: Trac',
],
install_requires = ['Trac'],
entry_points = {
'trac.plugins': [
'mastertickets.web_ui = mastertickets.web_ui',
'mastertickets.api = mastertickets.api',
]
}
)
|
Move static propTypes & defaultProps outside of the component class
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Avatar extends PureComponent {
render() {
const { children, className, image, imageAlt, imageClassName, size, ...others } = this.props;
const avatarClassNames = cx(theme['avatar'], theme[size], className);
return (
<Box className={avatarClassNames} {...others} data-teamleader-ui="avatar">
<img alt={imageAlt} src={image} className={cx(theme['image'], imageClassName)} />
{children && <div className={theme['children']}>{children}</div>}
</Box>
);
}
}
Avatar.propTypes = {
/** Component that will be placed top right of the avatar image. */
children: PropTypes.any,
/** A class name for the wrapper to give custom styles. */
className: PropTypes.string,
/** An image source or an image element. */
image: PropTypes.string,
/** An alternative text for the image element. */
imageAlt: PropTypes.string,
/** A class name for the image to give custom styles. */
imageClassName: PropTypes.string,
/** The size of the avatar. */
size: PropTypes.oneOf(['tiny', 'small', 'medium']),
};
Avatar.defaultProps = {
size: 'medium',
};
export default Avatar;
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Avatar extends PureComponent {
static propTypes = {
/** Component that will be placed top right of the avatar image. */
children: PropTypes.any,
/** A class name for the wrapper to give custom styles. */
className: PropTypes.string,
/** An image source or an image element. */
image: PropTypes.string,
/** An alternative text for the image element. */
imageAlt: PropTypes.string,
/** A class name for the image to give custom styles. */
imageClassName: PropTypes.string,
/** The size of the avatar. */
size: PropTypes.oneOf(['tiny', 'small', 'medium']),
};
static defaultProps = {
size: 'medium',
};
render() {
const { children, className, image, imageAlt, imageClassName, size, ...others } = this.props;
const avatarClassNames = cx(theme['avatar'], theme[size], className);
return (
<Box className={avatarClassNames} {...others} data-teamleader-ui="avatar">
<img alt={imageAlt} src={image} className={cx(theme['image'], imageClassName)} />
{children && <div className={theme['children']}>{children}</div>}
</Box>
);
}
}
export default Avatar;
|
Add support for custom explorer URL
|
var loopback = require('loopback');
var boot = require('loopback-boot');
var explorer = require('loopback-component-explorer');
var path = require('path');
var app = module.exports = loopback();
//app.use(customBaseUrl+'/explorer', loopback.rest());
app.start = function() {
// start the web server
var customBaseUrl='';
process.argv.forEach(function(element){
var valueArray = element.split('=');
if (valueArray[0]='loopback-custom-base-url')
{
customBaseUrl=valueArray[1];
}
});
console.log('Setting explorer mount point to: '+customBaseUrl+'/explorer');
app.use(customBaseUrl+'/explorer', explorer.routes(app, {
basePath: customBaseUrl+'/api',
uiDirs: [
path.resolve(__dirname, 'public')
]
}));
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
|
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
|
Make the children field in the api read only.
|
from rest_framework import serializers
from models import Page
class PageSerializer(serializers.ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(required=False)
children = serializers.PrimaryKeyRelatedField(many=True, required=False, read_only=True)
class Meta:
model = Page
fields = (
'id',
'parent',
'children',
'title',
'slug',
'url',
'content',
'summary',
'author',
'status',
'publish_date',
'type',
'created',
'modified'
)
|
from rest_framework import serializers
from models import Page
class PageSerializer(serializers.ModelSerializer):
parent = serializers.PrimaryKeyRelatedField(required=False)
children = serializers.PrimaryKeyRelatedField(many=True, required=False)
class Meta:
model = Page
fields = (
'id',
'parent',
'children',
'title',
'slug',
'url',
'content',
'summary',
'author',
'status',
'publish_date',
'type',
'created',
'modified'
)
|
Correct test for the right missing days and present days.
1st and 2nd of September 1752 happened, so did 14th. 3rd to 13th did not.
|
from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
gregorian_triplets = [(1752, 9, 14)]
julian_triplets = [(1752, 9, 1), (1752, 9, 2)]
transition_triplets = [(1752, 9, 3), (1752, 9, 6), (1752, 9, 13)]
|
from test_calendar import CalendarTest
from qual.calendars import EnglishHistoricalCalendar
class TestHistoricalCalendar(object):
def setUp(self):
self.calendar = self.calendar_type()
def test_before_switch(self):
for triplet in self.julian_triplets:
self.check_valid_date(*triplet)
def test_after_switch(self):
for triplet in self.gregorian_triplets:
self.check_valid_date(*triplet)
def test_during_switch(self):
for triplet in self.transition_triplets:
self.check_invalid_date(*triplet)
class TestEnglishHistoricalCalendar(TestHistoricalCalendar, CalendarTest):
calendar_type = EnglishHistoricalCalendar
gregorian_triplets = [(1752, 9, 13)]
julian_triplets = [(1752, 9, 1)]
transition_triplets = [(1752, 9, 6)]
|
Add setSpriteTexture to the SpriteSheet class
|
'use strict';
import Sprite from './sprite';
export default class SpriteSheet {
constructor(texture, width, height) {
this.texture = texture;
this.width = width;
this.height = height;
this.spriteCoordinates = {};
}
register(name, x, y, width, height) {
this.spriteCoordinates[name] = {
x: x,
y: y,
width: width,
height: height
};
}
registerMany(map) {
for (var name in map) {
var coords = map[name];
this.register(name, coords[0], coords[1], coords[2], coords[3]);
}
}
createSprite(name) {
let info = this.spriteCoordinates[name];
let sprite = new Sprite(info.width, info.height, this.texture);
setSpriteTextureFromCoordinates(sprite, info);
return sprite;
}
setSpriteTexture(sprite, name) {
let info = this.spriteCoordinates[name];
setSpriteTextureFromCoordinates(sprite, info);
}
setSpriteTextureFromCoordinates(sprite, info) {
sprite.setTextureCoordinates(
info.x / this.width,
info.y / this.height,
(info.x + info.width) / this.width,
(info.y + info.height) / this.height
);
}
}
|
'use strict';
import Sprite from './sprite';
export default class SpriteSheet {
constructor(texture, width, height) {
this.texture = texture;
this.width = width;
this.height = height;
this.spriteCoordinates = {};
}
register(name, x, y, width, height) {
this.spriteCoordinates[name] = {
x: x,
y: y,
width: width,
height: height
};
}
registerMany(map) {
for (var name in map) {
var coords = map[name];
this.register(name, coords[0], coords[1], coords[2], coords[3]);
}
}
createSprite(name) {
let info = this.spriteCoordinates[name];
let sprite = new Sprite(info.width, info.height, this.texture);
sprite.setTextureCoordinates(
info.x / this.width,
info.y / this.height,
(info.x + info.width) / this.width,
(info.y + info.height) / this.height
);
return sprite;
}
}
|
Add fallbacks for parsed Url
|
<?php
namespace Collectivism\Router;
class Request
{
public $method;
public $scheme;
public $host;
public $uri;
public $query;
public $fragment;
public function __construct()
{
$url = $_SERVER['PATH_INFO'];
$parsedUrl = parse_url($url);
$this->method = $_SERVER['REQUEST_METHOD'];
$this->scheme = isset($parsedUrl['scheme']) ? $parsedUrl['scheme'] : '';
$this->host = isset($parsedUrl['host']) ? $parsedUrl['host'] : '';
$this->uri = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
$this->query = isset($parsedUrl['query']) ? $parsedUrl['query'] : '';
$this->fragment = isset($parsedUrl['fragment']) ? $parsedUrl['fragment'] : '';
}
}
|
<?php
namespace Collectivism\Router;
class Request
{
public $method;
public $scheme;
public $host;
public $uri;
public $query;
public $fragment;
public function __construct()
{
$url = $_SERVER['PATH_INFO'];
$urlParts = parse_url($url);
$this->method = $_SERVER['REQUEST_METHOD'];
$this->scheme = $urlParts['scheme'];
$this->host = $urlParts['host'];
$this->uri = $urlParts['path'];
$this->query = $urlParts['query'];
$this->fragment = $urlParts['fragment'];
}
}
|
Use the spring component as well to allow for migrations
|
package net.stickycode.bootstrap.spring3;
import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;
public class StickySpringBootstrap {
private GenericApplicationContext context;
public StickySpringBootstrap(GenericApplicationContext context) {
this.context = context;
}
public void scan(String... paths) {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
scanner.setScopeMetadataResolver(new StickyScopeMetadataResolver());
scanner.addIncludeFilter(new AnnotationTypeFilter(StickyComponent.class));
scanner.addIncludeFilter(new AnnotationTypeFilter(StickyPlugin.class));
scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));
scanner.scan(paths);
}
}
|
package net.stickycode.bootstrap.spring3;
import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.filter.AnnotationTypeFilter;
public class StickySpringBootstrap {
private GenericApplicationContext context;
public StickySpringBootstrap(GenericApplicationContext context) {
this.context = context;
}
public void scan(String... paths) {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
scanner.setScopeMetadataResolver(new StickyScopeMetadataResolver());
scanner.addIncludeFilter(new AnnotationTypeFilter(StickyComponent.class));
scanner.addIncludeFilter(new AnnotationTypeFilter(StickyPlugin.class));
scanner.scan(paths);
}
}
|
Test on structured patch method updated
|
const VERBOSE = false;
var diff = require('../diff');
function log() {
VERBOSE && console.log.apply(console, arguments);
}
describe('#structuredPatch', function() {
it('should handle files with the last line changed', function() {
var res = diff.structuredPatch(
'oldfile', 'newfile',
'line2\nline3\nline4\n', 'line2\nline3\nline5',
'header1', 'header2'
);
res.should.eql({
oldFileName: 'oldfile', newFileName: 'newfile',
oldHeader: 'header1', newHeader: 'header2',
hunks: [{
oldStart: 1, oldLines: 3, newStart: 1, newLines: 3,
lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'],
}]
});
});
});
|
const VERBOSE = false;
var diff = require('../diff');
function log() {
VERBOSE && console.log.apply(console, arguments);
}
describe('#structuredPatch', function() {
it('should handle files with the last line changed', function() {
var res = diff.structuredPatch(
'oldfile', 'newfile',
'line2\nline3\nline5\n', 'line2\nline3\nline4\nline5\n',
'header1', 'header2'
);
res.should.eql({
oldFileName: 'oldfile', newFileName: 'newfile',
oldHeader: 'header1', newHeader: 'header2',
hunks: [{
oldStart: 1, oldLines: 3, newStart: 1, newLines: 4,
lines: [' line2', ' line3', '+line4', ' line5'],
oldEOFNewline: true, newEOFNewline: true,
}]
});
});
});
|
Remove [] from around open()...split('\n')
`split()` already returns a list so you don't need to wrap it in another list.
|
#!/usr/bin/env python
import os
from setuptools import setup
import versioneer
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="fsspec",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
description="File-system specification",
long_description=long_description,
long_description_content_type="text/markdown",
url="http://github.com/intake/filesystem_spec",
maintainer="Martin Durant",
maintainer_email="mdurant@anaconda.com",
license="BSD",
keywords="file",
packages=["fsspec", "fsspec.implementations"],
python_requires=">=3.5",
install_requires=open("requirements.txt").read().strip().split("\n"),
zip_safe=False,
)
|
#!/usr/bin/env python
import os
from setuptools import setup
import versioneer
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="fsspec",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
],
description="File-system specification",
long_description=long_description,
long_description_content_type="text/markdown",
url="http://github.com/intake/filesystem_spec",
maintainer="Martin Durant",
maintainer_email="mdurant@anaconda.com",
license="BSD",
keywords="file",
packages=["fsspec", "fsspec.implementations"],
python_requires=">=3.5",
install_requires=[open("requirements.txt").read().strip().split("\n")],
zip_safe=False,
)
|
Update live object tests so that they know they should fire at 120fps
|
QUnit.test("CanGetLiveTicks", function(assert) {
var someGame = new TameGame.StandardGame();
var someObject = someGame.createObject();
var someScene = someGame.createScene();
var numTicks = 0;
someScene.addObject(someObject);
someScene.events.onTick(TameGame.UpdatePass.Mechanics, function (tickData) {
if (numTicks === 0) {
assert.ok(tickData.liveObjects.length === 1, "Our live object is actually live");
assert.ok(tickData.duration === 1000.0/120.0, "Have a duration indicating 120fps");
}
++numTicks;
});
someObject.aliveStatus.isAlive = true;
someGame.startScene(someScene);
someGame.tick(0);
someGame.tick(999.0);
assert.ok(numTicks > 0, "Got some ticks");
assert.ok(numTicks === 120, "Running at 120 ticks per second");
});
|
QUnit.test("CanGetLiveTicks", function(assert) {
var someGame = new TameGame.StandardGame();
var someObject = someGame.createObject();
var someScene = someGame.createScene();
var numTicks = 0;
someScene.addObject(someObject);
someScene.events.onTick(TameGame.UpdatePass.Mechanics, function (tickData) {
if (numTicks === 0) {
assert.ok(tickData.liveObjects.length === 1, "Our live object is actually live");
assert.ok(tickData.duration === 1000.0/60.0, "Have a duration indicating 60fps");
}
++numTicks;
});
someObject.aliveStatus.isAlive = true;
someGame.startScene(someScene);
someGame.tick(0);
someGame.tick(999.0);
assert.ok(numTicks > 0, "Got some ticks");
assert.ok(numTicks === 60, "Running at 60 ticks per second");
});
|
Enable keyword arguments when requesting metafields
|
import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self, _options=None, **kwargs):
if _options is None:
_options = kwargs
return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id, **_options)
def add_metafield(self, metafield):
if self.is_new():
raise ValueError("You can only add metafields to a resource that has been saved")
metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
metafield.save()
return metafield
class Events(object):
def events(self):
return shopify.resources.Event.find(resource=self.__class__.plural, resource_id=self.id)
|
import shopify.resources
class Countable(object):
@classmethod
def count(cls, _options=None, **kwargs):
if _options is None:
_options = kwargs
return int(cls.get("count", **_options))
class Metafields(object):
def metafields(self):
return shopify.resources.Metafield.find(resource=self.__class__.plural, resource_id=self.id)
def add_metafield(self, metafield):
if self.is_new():
raise ValueError("You can only add metafields to a resource that has been saved")
metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id)
metafield.save()
return metafield
class Events(object):
def events(self):
return shopify.resources.Event.find(resource=self.__class__.plural, resource_id=self.id)
|
Use new extension setup() API
|
from __future__ import unicode_literals
import os
import pygst
pygst.require('0.10')
import gst
import gobject
from mopidy import config, ext
__version__ = '1.0.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-NAD'
ext_name = 'nad'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf')
return config.read(conf_file)
def setup(self, registry):
from .mixer import NadMixer
gobject.type_register(NadMixer)
gst.element_register(NadMixer, 'nadmixer', gst.RANK_MARGINAL)
|
from __future__ import unicode_literals
import os
import pygst
pygst.require('0.10')
import gst
import gobject
from mopidy import config, ext
__version__ = '1.0.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-NAD'
ext_name = 'nad'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf')
return config.read(conf_file)
def register_gstreamer_elements(self):
from .mixer import NadMixer
gobject.type_register(NadMixer)
gst.element_register(NadMixer, 'nadmixer', gst.RANK_MARGINAL)
|
Simplify repository name component regexp
|
package common
import (
"regexp"
)
// RepositoryNameComponentRegexp restricts registtry path components names to
// start with at least two letters or numbers, with following parts able to
// separated by one period, dash or underscore.
var RepositoryNameComponentRegexp = regexp.MustCompile(`[a-z0-9]{2,}(?:[._-][a-z0-9]+)*`)
// RepositoryNameRegexp builds on RepositoryNameComponentRegexp to allow 2 to
// 5 path components, separated by a forward slash.
var RepositoryNameRegexp = regexp.MustCompile(`(?:` + RepositoryNameComponentRegexp.String() + `/){1,4}` + RepositoryNameComponentRegexp.String())
// TagNameRegexp matches valid tag names. From docker/docker:graph/tags.go.
var TagNameRegexp = regexp.MustCompile(`[\w][\w.-]{0,127}`)
// TODO(stevvooe): Contribute these exports back to core, so they are shared.
|
package common
import (
"regexp"
)
// RepositoryNameComponentRegexp restricts registtry path components names to
// start with at least two letters or numbers, with following parts able to
// separated by one period, dash or underscore.
var RepositoryNameComponentRegexp = regexp.MustCompile(`[a-z0-9](?:[a-z0-9]+[._-]?)*[a-z0-9]`)
// RepositoryNameRegexp builds on RepositoryNameComponentRegexp to allow 2 to
// 5 path components, separated by a forward slash.
var RepositoryNameRegexp = regexp.MustCompile(`(?:` + RepositoryNameComponentRegexp.String() + `/){1,4}` + RepositoryNameComponentRegexp.String())
// TagNameRegexp matches valid tag names. From docker/docker:graph/tags.go.
var TagNameRegexp = regexp.MustCompile(`[\w][\w.-]{0,127}`)
// TODO(stevvooe): Contribute these exports back to core, so they are shared.
|
Fix bug where vector calculations returned Ints only
|
"""
Linear algebra is cool.
"""
import math
def rotation(point, axis, sign=1):
"""
Rotate a point (or vector) about the origin in 3D space.
"""
def Rx(x, y, z, theta):
return (round(x, 1),
round(math.cos(theta) * y - math.sin(theta) * z, 1),
round(math.sin(theta) * y + math.cos(theta) * z, 1))
def Ry(x, y, z, theta):
return (round(math.cos(theta) * x + math.sin(theta) * z, 1),
round(y, 1),
round(-math.sin(theta) * x + math.cos(theta) * z, 1))
def Rz(x, y, z, theta):
return (round(math.cos(theta) * x - math.sin(theta) * y, 1),
round(math.sin(theta) * x + math.cos(theta) * y, 1),
round(z, 1))
R = {'x': Rx, 'y': Ry, 'z': Rz}[axis] # Select a rotation matrix
theta = sign * math.pi / 2 # Always 90 degrees
x, y, z = point # Assumes 3D point or vector
return R(x, y, z, theta) # Calculate our new normal vector
|
"""
Linear algebra is cool.
"""
import math
def rotation(point, axis, sign=1):
"""
Rotate a point (or vector) about the origin in 3D space.
"""
def Rx(x, y, z, theta):
return (int(x),
int(math.cos(theta) * y - math.sin(theta) * z),
int(math.sin(theta) * y + math.cos(theta) * z))
def Ry(x, y, z, theta):
return (int(math.cos(theta) * x + math.sin(theta) * z),
int(y),
int(-math.sin(theta) * x + math.cos(theta) * z))
def Rz(x, y, z, theta):
return (int(math.cos(theta) * x - math.sin(theta) * y),
int(math.sin(theta) * x + math.cos(theta) * y),
int(z))
R = {'x': Rx, 'y': Ry, 'z': Rz}[axis] # Select a rotation matrix
theta = sign * math.pi / 2 # Always 90 degrees
x, y, z = point # Assumes 3D point or vector
return R(x, y, z, theta) # Calculate our new normal vector
|
Add english version in FooterTest
|
package pt.fccn.sobre.arquivo.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import pt.fccn.sobre.arquivo.tests.CommonQuestionsTest;
import pt.fccn.sobre.arquivo.tests.ExamplesTest;
import pt.fccn.sobre.arquivo.tests.FooterTest;
import pt.fccn.sobre.arquivo.tests.NavigationTest;
import pt.fccn.sobre.arquivo.tests.NewsTest;
import pt.fccn.sobre.arquivo.tests.PublicationsTest;
import pt.fccn.sobre.arquivo.tests.SiteMapTest;
import pt.fccn.sobre.arquivo.tests.SuggestionSiteTest;
/**
* @author João Nobre
*
*/
@RunWith( Suite.class )
@SuiteClasses( { FooterTest.class} )
//TODO done CommonQuestionsTest.class, ExamplesTest.class , , PublicationsTest.class, NewsTest.class , NavigationTest.class
//TODO error SuggestionSiteTest.class , SiteMapTest.class
public class TestSuite {
}
|
package pt.fccn.sobre.arquivo.suite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import pt.fccn.sobre.arquivo.tests.CommonQuestionsTest;
import pt.fccn.sobre.arquivo.tests.ExamplesTest;
import pt.fccn.sobre.arquivo.tests.FooterTest;
import pt.fccn.sobre.arquivo.tests.NavigationTest;
import pt.fccn.sobre.arquivo.tests.NewsTest;
import pt.fccn.sobre.arquivo.tests.PublicationsTest;
import pt.fccn.sobre.arquivo.tests.SiteMapTest;
import pt.fccn.sobre.arquivo.tests.SuggestionSiteTest;
/**
* @author João Nobre
*
*/
@RunWith( Suite.class )
@SuiteClasses( { ExamplesTest.class } )
//TODO done CommonQuestionsTest.class, , FooterTest.class , PublicationsTest.class, NewsTest.class , NavigationTest.class
//TODO error SuggestionSiteTest.class , SiteMapTest.class
public class TestSuite {
}
|
Remove unnecessary check of php version
The minimum php version required in composer is 7.1 and the code
was checking with version 5
|
<?php
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use function interface_exists;
use function sprintf;
use function trait_exists;
/**
* Exception for invalid arguments provided to the instantiator
*/
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
public static function fromNonExistingClass(string $className) : self
{
if (interface_exists($className)) {
return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
}
if (trait_exists($className)) {
return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
}
return new self(sprintf('The provided class "%s" does not exist', $className));
}
public static function fromAbstractClass(ReflectionClass $reflectionClass) : self
{
return new self(sprintf(
'The provided class "%s" is abstract, and can not be instantiated',
$reflectionClass->getName()
));
}
}
|
<?php
namespace Doctrine\Instantiator\Exception;
use InvalidArgumentException as BaseInvalidArgumentException;
use ReflectionClass;
use const PHP_VERSION_ID;
use function interface_exists;
use function sprintf;
use function trait_exists;
/**
* Exception for invalid arguments provided to the instantiator
*/
class InvalidArgumentException extends BaseInvalidArgumentException implements ExceptionInterface
{
public static function fromNonExistingClass(string $className) : self
{
if (interface_exists($className)) {
return new self(sprintf('The provided type "%s" is an interface, and can not be instantiated', $className));
}
if (PHP_VERSION_ID >= 50400 && trait_exists($className)) {
return new self(sprintf('The provided type "%s" is a trait, and can not be instantiated', $className));
}
return new self(sprintf('The provided class "%s" does not exist', $className));
}
public static function fromAbstractClass(ReflectionClass $reflectionClass) : self
{
return new self(sprintf(
'The provided class "%s" is abstract, and can not be instantiated',
$reflectionClass->getName()
));
}
}
|
Use 'array' rather than 'real' for data array name in olfactory stimulus generation script.
|
#!/usr/bin/env python
"""
Generate sample olfactory model stimulus.
"""
import numpy as np
import h5py
osn_num = 1375
dt = 1e-4 # time step
Ot = 2000 # number of data point during reset period
Rt = 1000 # number of data point during odor delivery period
Nt = 4*Ot + 3*Rt # number of data points in time
t = np.arange(0, dt*Nt, dt)
I = 0.5195 # amplitude of odorant concentration
u_on = I*np.ones(Ot, dtype=np.float64)
u_off = np.zeros(Ot, dtype=np.float64)
u_reset = np.zeros(Rt, dtype=np.float64)
u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on))
u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u))
with h5py.File('olfactory_input.h5', 'w') as f:
f.create_dataset('array', (Nt, osn_num),
dtype=np.float64,
data=u_all)
|
#!/usr/bin/env python
"""
Generate sample olfactory model stimulus.
"""
import numpy as np
import h5py
osn_num = 1375
dt = 1e-4 # time step
Ot = 2000 # number of data point during reset period
Rt = 1000 # number of data point during odor delivery period
Nt = 4*Ot + 3*Rt # number of data points in time
t = np.arange(0, dt*Nt, dt)
I = 0.5195 # amplitude of odorant concentration
u_on = I*np.ones(Ot, dtype=np.float64)
u_off = np.zeros(Ot, dtype=np.float64)
u_reset = np.zeros(Rt, dtype=np.float64)
u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on))
u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u))
with h5py.File('olfactory_input.h5', 'w') as f:
f.create_dataset('real', (Nt, osn_num),
dtype=np.float64,
data=u_all)
|
Fix compilation error in test.
|
package alien4cloud.it.maintenance;
import static alien4cloud.it.Context.getRestClientInstance;
import org.alien4cloud.server.MaintenanceUpdateDTO;
import alien4cloud.it.Context;
import cucumber.api.java.en.When;
/**
* Steps for maintenance mode cucumber rest it.
*/
public class MaintenanceStepsDefinition {
@When("^I enable maintenance mode$")
public void enable() throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().post("/rest/v1/maintenance"));
}
@When("^I disable maintenance mode$")
public void disable() throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().delete("/rest/v1/maintenance"));
}
@When("^I get maintenance state$")
public void getState() throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().get("/rest/v1/maintenance"));
}
@When("^I update maintenance state, message: \"([^\"]*)\" percent: (\\d+)$")
public void updateState(String message, Integer percent) throws Throwable {
MaintenanceUpdateDTO updateDTO = new MaintenanceUpdateDTO(message, percent);
Context.getInstance()
.registerRestResponse(getRestClientInstance().putJSon("/rest/v1/maintenance", Context.getJsonMapper().writeValueAsString(updateDTO)));
}
}
|
package alien4cloud.it.maintenance;
import static alien4cloud.it.Context.getRestClientInstance;
import org.alien4cloud.server.MaintenanceUpdateDTO;
import alien4cloud.it.Context;
import cucumber.api.java.en.When;
/**
* Steps for maintenance mode cucumber rest it.
*/
public class MaintenanceStepsDefinition {
@When("^I enable maintenance mode$")
public void enable() throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().post("/rest/v1/maintenance"));
}
@When("^I disable maintenance mode$")
public void disable() throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().delete("/rest/v1/maintenance"));
}
@When("^I get maintenance state$")
public void getState() throws Throwable {
Context.getInstance().registerRestResponse(getRestClientInstance().get("/rest/v1/maintenance"));
}
@When("^I update maintenance state, message: \"([^\"]*)\" percent: (\\d+)$")
public void updateState(String message, Float percent) throws Throwable {
MaintenanceUpdateDTO updateDTO = new MaintenanceUpdateDTO(message, percent);
Context.getInstance()
.registerRestResponse(getRestClientInstance().putJSon("/rest/v1/maintenance", Context.getJsonMapper().writeValueAsString(updateDTO)));
}
}
|
Fix for DummyLayout: pass 'focussed_element' instead of 'focussed_window'.
|
"""
Dummy layout. Used when somebody creates an `Application` without specifying a
`Layout`.
"""
from __future__ import unicode_literals
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from .containers import Window
from .controls import FormattedTextControl
from .dimension import D
from .layout import Layout
__all__ = (
'create_dummy_layout',
)
def create_dummy_layout():
"""
Create a dummy layout for use in an 'Application' that doesn't have a
layout specified. When ENTER is pressed, the application quits.
"""
kb = KeyBindings()
@kb.add('enter')
def enter(event):
event.app.set_result(None)
control = FormattedTextControl(
HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'),
key_bindings=kb)
window = Window(content=control, height=D(min=1))
return Layout(container=window, focussed_element=window)
|
"""
Dummy layout. Used when somebody creates an `Application` without specifying a
`Layout`.
"""
from __future__ import unicode_literals
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from .containers import Window
from .controls import FormattedTextControl
from .dimension import D
from .layout import Layout
__all__ = (
'create_dummy_layout',
)
def create_dummy_layout():
"""
Create a dummy layout for use in an 'Application' that doesn't have a
layout specified. When ENTER is pressed, the application quits.
"""
kb = KeyBindings()
@kb.add('enter')
def enter(event):
event.app.set_result(None)
control = FormattedTextControl(
HTML('No layout specified. Press <reverse>ENTER</reverse> to quit.'),
key_bindings=kb)
window = Window(content=control, height=D(min=1))
return Layout(container=window, focussed_window=window)
|
Move method list to node client
|
var RestClient = require('carbon-client')
var util = require('util')
var fibrous = require('fibrous');
/****************************************************************************************************
* monkey patch the endpoint class to support sync get/post/put/delete/head/patch
*/
var Endpoint = RestClient.super_
/****************************************************************************************************
* syncifyClassMethod
*
* @param clazz the class
* @param methodName name of the method to syncify
*/
function syncifyClassMethod(clazz, methodName){
var asyncMethod = clazz.prototype[methodName]
clazz.prototype[methodName] = function() {
// if last argument is a callback then run async
if(arguments && (typeof(arguments[arguments.length-1]) === 'function') ) {
asyncMethod.apply(this, arguments);
} else { // sync call!
return asyncMethod.sync.apply(this, arguments);
}
}
}
// syncify all Endpoint methods
var ENDPOINT_METHODS = [
"get",
"post",
"head",
"put",
"delete",
"patch"
]
ENDPOINT_METHODS.forEach(function(m) { syncifyClassMethod(Endpoint, m) })
// syncify Collection methods
var COLLECTION_METHODS = [
"find",
"insert",
"update",
"remove"
]
var Collection = Endpoint.collectionClass
COLLECTION_METHODS.forEach(function(m) { syncifyClassMethod(Collection, m) })
/****************************************************************************************************
* exports
*/
module.exports = RestClient
|
var RestClient = require('carbon-client')
var util = require('util')
var fibrous = require('fibrous');
/****************************************************************************************************
* monkey patch the endpoint class to support sync get/post/put/delete/head/patch
*/
var Endpoint = RestClient.super_
/****************************************************************************************************
* syncifyClassMethod
*
* @param clazz the class
* @param methodName name of the method to syncify
*/
function syncifyClassMethod(clazz, methodName){
var asyncMethod = clazz.prototype[methodName]
clazz.prototype[methodName] = function() {
// if last argument is a callback then run async
if(arguments && (typeof(arguments[arguments.length-1]) === 'function') ) {
asyncMethod.apply(this, arguments);
} else { // sync call!
return asyncMethod.sync.apply(this, arguments);
}
}
}
// syncify all Endpoint methods
Endpoint.ALL_METHODS.forEach(function(m) { syncifyClassMethod(Endpoint, m) })
// syncify Collection methods
var Collection = Endpoint.collectionClass
Collection.ALL_METHODS.forEach(function(m) { syncifyClassMethod(Collection, m) })
/****************************************************************************************************
* exports
*/
module.exports = RestClient
|
Fix file name on webpack configuration
|
/**
* Module dependencies.
*/
import webpack from 'webpack';
/**
* Webpack configuration.
*/
export default {
entry: './src/browser/index.js',
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
plugins: [
['transform-es2015-for-of', {
loose: true
}]
],
presets: ['es2015']
},
test: /\.js$/
}, {
exclude: /node_modules\/(?!html-tags).+/,
loader: 'json-loader',
test: /\.json$/
}]
},
output: {
filename: 'uphold-sdk-javascript.js',
library: 'uphold-sdk-javascript',
libraryTarget: 'commonjs2',
path: `${__dirname}/dist/browser`
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
|
/**
* Module dependencies.
*/
import packageConfig from './package.json';
import webpack from 'webpack';
/**
* Webpack configuration.
*/
export default {
entry: './src/browser/index.js',
module: {
loaders: [
{
exclude: /node_modules/,
loader: 'babel-loader',
query: {
plugins: [
['transform-es2015-for-of', {
loose: true
}]
],
presets: ['es2015']
},
test: /\.js$/
},
{
exclude: /node_modules\/(?!html-tags).+/,
loader: 'json-loader',
test: /\.json$/
}
]
},
output: {
filename: `${packageConfig.name}.js`,
library: packageConfig.name,
libraryTarget: 'commonjs2',
path: `${__dirname}/dist/browser`
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
|
Fix for the return value of delete method
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
retval = super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
return retval
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""
# XXX: circular import
from fields import RatingField
qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type')
to_update = []
for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]):
ct = ContentType.objects.get(pk=content_type)
to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0])))
super(VoteQuerySet, self).delete(*args, **kwargs)
# TODO: this could be improved
for obj in to_update:
for field in getattr(obj, '_djangoratings', []):
getattr(obj, field.name)._update()
obj.save()
class VoteManager(Manager):
def get_query_set(self):
return VoteQuerySet(self.model)
|
Update format of welcome message and notification
|
let Config = require('../../config');
let url = require('url');
let webHook = url.resolve(Config.app.url, '/codeship/');
class FormatterService {
format(type, build) {
return defaultFormat(build)
}
getStartMessage(chatId) {
let hook = this.getWebHook(chatId);
return `${FormatterService.EMOJI.ship} Hi! I see you want to receive Codeship notifications.
Just add this URL as a Webhook to your Codeship notification settings to receive notifications in this conversation.
To receive <b>only failing builds</b> (and the recovering builds)
${hook}
To receive <b>all builds</b> (succeeding and failing)
${hook}?mode=all
@codeship_bot by @dominic0`;
}
getWebHook(chatId) {
return url.resolve(webHook, `${chatId}`);
}
}
FormatterService.EMOJI = {
ship: '\u{1F6A2}',
success: '\u{2705}',
error: '\u{274C}'
};
function defaultFormat(build) {
return `${FormatterService.EMOJI.ship} <b>${build.project_name}</b> - <code>${build.branch}</code> ${FormatterService.EMOJI[build.status] || ''}
<b>${build.committer}</b>: ${build.message}
<a href="${build.build_url}">Open on Codeship</a>`;
}
module.exports = new FormatterService();
|
let Config = require('../../config');
let url = require('url');
let webHook = url.resolve(Config.app.url, '/codeship/');
class FormatterService {
format(type, build) {
return defaultFormat(build)
}
getStartMessage(chatId) {
let hook = this.getWebHook(chatId);
return `${FormatterService.EMOJI.ship} Add this URL to your Codeship notification settings:
${hook}
@codeship_bot by @dominic0`;
}
getWebHook(chatId) {
return url.resolve(webHook, `${chatId}`);
}
}
FormatterService.EMOJI = {
ship: '\u{1F6A2}',
success: '\u{2705}',
error: '\u{274C}'
};
function defaultFormat(build) {
return `${FormatterService.EMOJI.ship} <b>${build.project_name}:</b> ${build.message}
on <code>${build.branch}</code> - <b>${build.status}</b> ${FormatterService.EMOJI[build.status] || ''}
<a href="${build.build_url}">Open on Codeship</a>`;
}
module.exports = new FormatterService();
|
Rename the resultant CSS file to fix the empty demo problem
|
var gulp = require('gulp'),
sass = require('gulp-sass'),
neat = require('node-neat'),
styleguide = require('./lib/styleguide'),
source = 'lib/app/**/*.scss',
outputPath = 'demo-output';
gulp.task('styleguide:generate', function() {
return gulp.src(source)
.pipe(styleguide.generate({
title: 'SC5 Styleguide',
server: true,
rootPath: outputPath,
overviewPath: 'README.md',
styleVariables: 'lib/app/sass/_styleguide_variables.scss'
}))
.pipe(gulp.dest(outputPath));
});
gulp.task('styleguide:applystyles', function() {
return gulp.src('lib/app/sass/styleguide-app.scss')
.pipe(sass({
errLogToConsole: true,
includePaths: neat.includePaths
}))
.pipe(styleguide.applyStyles())
.pipe(gulp.dest(outputPath));
});
gulp.task('styleguide', ['styleguide:static', 'styleguide:generate', 'styleguide:applystyles']);
gulp.task('styleguide:static', function() {
gulp.src(['lib/demo/**'])
.pipe(gulp.dest(outputPath + '/demo'));
});
gulp.task('watch', ['styleguide'], function() {
// Start watching changes and update styleguide whenever changes are detected
gulp.watch(source, ['styleguide']);
});
|
var gulp = require('gulp'),
sass = require('gulp-sass'),
neat = require('node-neat'),
styleguide = require('./lib/styleguide'),
source = 'lib/app/**/*.scss',
outputPath = 'demo-output';
gulp.task('styleguide:generate', function() {
return gulp.src(source)
.pipe(styleguide.generate({
title: 'SC5 Styleguide',
server: true,
rootPath: outputPath,
overviewPath: 'README.md',
styleVariables: 'lib/app/sass/_styleguide_variables.scss'
}))
.pipe(gulp.dest(outputPath));
});
gulp.task('styleguide:applystyles', function() {
return gulp.src('lib/app/sass/app.scss')
.pipe(sass({
errLogToConsole: true,
includePaths: neat.includePaths
}))
.pipe(styleguide.applyStyles())
.pipe(gulp.dest(outputPath));
});
gulp.task('styleguide', ['styleguide:static', 'styleguide:generate', 'styleguide:applystyles']);
gulp.task('styleguide:static', function() {
gulp.src(['lib/demo/**'])
.pipe(gulp.dest(outputPath + '/demo'));
});
gulp.task('watch', ['styleguide'], function() {
// Start watching changes and update styleguide whenever changes are detected
gulp.watch(source, ['styleguide']);
});
|
Change toString()
Rename field thingClass to contentType
|
package ru.nsu.ccfit.bogush.factory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
private Storage<T> storage;
private static final long DEFAULT_PERIOD = 0;
private Class<T> contentType;
private Thread thread;
private static final String LOGGER_NAME = "Supplier";
private static final Logger logger = LogManager.getLogger(LOGGER_NAME);
public Supplier(Storage<T> storage, Class<T> contentType) {
this(storage, contentType, DEFAULT_PERIOD);
}
public Supplier(Storage<T> storage, Class<T> contentType, long period) {
super(period);
logger.trace("initialize with period " + period);
this.storage = storage;
this.contentType = contentType;
this.thread = new Thread(this);
thread.setName(toString());
}
@Override
public void run() {
while (true) {
try {
storage.store(contentType.newInstance());
waitPeriod();
} catch (InterruptedException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}
@Override
public String toString() {
return contentType.getSimpleName() + "-" + getClass().getSimpleName() + "-" + thread.getId();
}
public Thread getThread() {
return thread;
}
}
|
package ru.nsu.ccfit.bogush.factory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
private Storage<T> storage;
private static final long DEFAULT_PERIOD = 0;
private Class<T> thingClass;
private Thread thread;
private static final String LOGGER_NAME = "Supplier";
private static final Logger logger = LogManager.getLogger(LOGGER_NAME);
public Supplier(Storage<T> storage, Class<T> thingClass) {
this(storage, thingClass, DEFAULT_PERIOD);
}
public Supplier(Storage<T> storage, Class<T> thingClass, long period) {
super(period);
logger.trace("initialize with period " + period);
this.storage = storage;
this.thingClass = thingClass;
this.thread = new Thread(this);
thread.setName(toString());
}
@Override
public void run() {
while (true) {
try {
storage.store(thingClass.newInstance());
waitPeriod();
} catch (InterruptedException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "-" + thread.getId();
}
public Thread getThread() {
return thread;
}
}
|
Fix wrongly documented return type
|
<?php
namespace Brick\Geo\Engine;
use Brick\Geo\Exception\GeometryEngineException;
/**
* This class holds the GeometryEngine implementation to use for calculations.
*/
final class GeometryEngineRegistry
{
/**
* @var GeometryEngine|null
*/
private static $engine;
/**
* Returns whether a geometry engine is set.
*
* @return boolean
*/
public static function has()
{
return self::$engine !== null;
}
/**
* Sets the GeometryEngine to use for calculations.
*
* @param GeometryEngine $engine
*
* @return void
*/
public static function set(GeometryEngine $engine)
{
self::$engine = $engine;
}
/**
* Returns the GeometryEngine to use for calculations.
*
* @return GeometryEngine
*
* @throws \Brick\Geo\Exception\GeometryException
*/
public static function get()
{
if (self::$engine === null) {
throw GeometryEngineException::noEngineSet();
}
return self::$engine;
}
}
|
<?php
namespace Brick\Geo\Engine;
use Brick\Geo\Exception\GeometryEngineException;
/**
* This class holds the GeometryEngine implementation to use for calculations.
*/
final class GeometryEngineRegistry
{
/**
* @var GeometryEngine|null
*/
private static $engine;
/**
* Returns whether a geometry engine is set.
*
* @return boolean
*/
public static function has()
{
return self::$engine !== null;
}
/**
* Sets the GeometryEngine to use for calculations.
*
* @param GeometryEngine $engine
*
* @return void
*/
public static function set(GeometryEngine $engine)
{
self::$engine = $engine;
}
/**
* Returns the GeometryEngine to use for calculations.
*
* @return GeometryEngineException
*
* @throws \Brick\Geo\Exception\GeometryException
*/
public static function get()
{
if (self::$engine === null) {
throw GeometryEngineException::noEngineSet();
}
return self::$engine;
}
}
|
Rename Source's get_episodes_for() method to fetch()
|
from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
def fetch(self, tvshow_reference: str) -> list:
"""
Fetches all available episode files, corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
|
from abc import ABC, abstractmethod
class TVShowNotFound(Exception):
""" Raised when a reference does not match any TV Show available """
class EpisodeSource(ABC):
"""
Abstract base class to define the interface for and episode source.
An episode source is used by the tracker to obtain episode files. A
source is usually based on a feed that provides links to TV Show's
episodes.
Every source has its own protocol to obtain the information and it uses
its own format to present that information. Implementations of this
interface are responsible for implementing the details of how to obtain
the episode files' information and present them to the tracker.
"""
# Called by the tracker when it wants to get the episodes available for
# a specific TVShow
@abstractmethod
def get_episodes_for(self, tvshow_reference: str) -> list:
"""
Retrieve all available episode files corresponding to the specified
TV show. Multiple files for the same episode may be retrieved.
The TV show to obtain the episodes from is identified by some reference
that uniquely identifies it within the episode source in question.
:param tvshow_reference: reference that uniquely identifies the TV show
to get the episodes for
:return: a list containing all episode files available for the specified
TV Show. An empty list if none is found.
:raise TVShowNotFound: if the specified reference does not match to any
TV show available
"""
|
Handle rejected promise, handle zero message case.
|
/*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
http = require('http');
// Handle any request to this server and parse the POST
function handleRequest(req, res){
let body = "";
req.on('data', data => body += data);
req.on('end', () => handleCommand(qs.parse(body)));
res.end('');
}
// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
let {channel_id, response_url} = payload;
// load channel history
let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
let buildReport = result => Promise.resolve( triage(payload, result.data.messages || []) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
getHistory.then(buildReport).then(postResults).catch(console.error);
}
// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));
|
/*
* This is a very basic webserver and HTTP Client.
* In production, you may want to use something like Express.js
* or Botkit to host a webserver and manage API calls
*/
const {TOKEN, PORT} = process.env,
triage = require('./triage'),
qs = require('querystring'),
axios = require('axios'),
http = require('http');
// Handle any request to this server and parse the POST
function handleRequest(req, res){
let body = "";
req.on('data', data => body += data);
req.on('end', () => handleCommand(qs.parse(body)));
res.end('');
}
// Get channel history, build triage report, and respond with results
function handleCommand(payload) {
let {channel_id, response_url} = payload;
// load channel history
let params = qs.stringify({ count: 1000, token: TOKEN, channel: channel_id });
let getHistory = axios.post('https://slack.com/api/channels.history', params);
// build the triage report
let buildReport = result => Promise.resolve( triage(payload, result.data.messages) );
// post back to channel
let postResults = results => axios.post(response_url, results);
// execute
getHistory.then(buildReport).then(postResults);
}
// start server
http.createServer(handleRequest).listen(PORT, () => console.log(`server started on ${PORT}`));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.