text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add comment to streamingprf_test's limitFromHash().
PiperOrigin-RevId: 476540085
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 streamingprf_test
import (
"crypto/sha256"
"crypto/sha512"
"testing"
commonpb "github.com/google/tink/go/proto/common_go_proto"
)
// limitFromHash returns the maximum output bytes from a HKDF using hash.
func limitFromHash(t *testing.T, hash commonpb.HashType) (limit int) {
t.Helper()
switch hash {
case commonpb.HashType_SHA256:
limit = sha256.Size * 255
case commonpb.HashType_SHA512:
limit = sha512.Size * 255
default:
t.Fatalf("unsupported hash type: %s", hash.String())
}
return
}
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 streamingprf_test
import (
"crypto/sha256"
"crypto/sha512"
"testing"
commonpb "github.com/google/tink/go/proto/common_go_proto"
)
func limitFromHash(t *testing.T, hash commonpb.HashType) (limit int) {
t.Helper()
switch hash {
case commonpb.HashType_SHA256:
limit = sha256.Size * 255
case commonpb.HashType_SHA512:
limit = sha512.Size * 255
default:
t.Fatalf("unsupported hash type: %s", hash.String())
}
return
}
|
Change babel to stage 1
|
var path = require('path');
module.exports = {
entry: {
auth: "./app/scripts/auth/auth.js",
scraper: "./app/scripts/scraper/scraper.js",
background: "./app/scripts/background/background.js",
popup: "./app/scripts/popup.js",
app: "./app/scripts/app.js"
},
devtool: 'source-map',
output: {
path: path.join(__dirname, "app/build"),
filename: "[name].build.js"
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules|bower_components/, loader: "babel-loader?stage=1"},
{ test: /\.css$/, loader: "style-loader!css-loader?root=." },
{ test: /\.jpg$/, loader: "url-loader" },
{ test: /\.png$/, loader: "file-loader" }
]
}
}
|
var path = require('path');
module.exports = {
entry: {
auth: "./app/scripts/auth/auth.js",
scraper: "./app/scripts/scraper/scraper.js",
background: "./app/scripts/background/background.js",
popup: "./app/scripts/popup.js",
app: "./app/scripts/app.js"
},
devtool: 'source-map',
output: {
path: path.join(__dirname, "app/build"),
filename: "[name].build.js"
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules|bower_components/, loader: "babel-loader"},
{ test: /\.css$/, loader: "style-loader!css-loader?root=." },
{ test: /\.jpg$/, loader: "url-loader" },
{ test: /\.png$/, loader: "file-loader" }
]
}
}
|
add: Copy icons directory under extra resources
|
/**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
const releaseConfig = {
appId: 'com.kongdash',
productName: 'KongDash',
copyright: 'Copyright (c) 2022 Ajay Sreedhar',
asar: true,
compression: 'normal',
removePackageScripts: true,
nodeGypRebuild: false,
buildDependenciesFromSource: false,
files: [
{
from: 'out/platform',
to: 'platform'
},
{
from: 'out/workbench',
to: 'workbench'
},
'package.json'
],
directories: {
output: 'dist'
},
extraResources: [
{from: 'resources/themes', to: 'themes'},
{from: 'resources/icons/', to: 'icons'}
],
extraMetadata: {
main: 'platform/main.js'
}
};
module.exports = {releaseConfig};
|
/**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
const releaseConfig = {
appId: 'com.kongdash',
productName: 'KongDash',
copyright: 'Copyright (c) 2022 Ajay Sreedhar',
asar: true,
compression: 'normal',
removePackageScripts: true,
nodeGypRebuild: false,
buildDependenciesFromSource: false,
files: [
{
from: 'out/platform',
to: 'platform'
},
{
from: 'out/workbench',
to: 'workbench'
},
'package.json'
],
directories: {
output: 'dist'
},
extraResources: [
{
from: 'resources/themes',
to: 'themes'
}
],
extraMetadata: {
main: 'platform/main.js'
}
};
module.exports = {releaseConfig};
|
Remove data attributes from obfuscated email address
|
;(function($){
var email_obfuscated_class = 'obfuscated';
var email_data_attr_prefix = 'data-email-';
$(document)
.on('mouseenter focus click touchstart keydown', 'a.obfuscated-email.' + email_obfuscated_class, function(e){
assemble_email(e);
})
;
function assemble_email(e) {
e.stopPropagation();
e.preventDefault();
var $email_link = $(e.target);
var email_address =
$email_link.attr(email_data_attr_prefix + '1')
+ '@' + $email_link.attr(email_data_attr_prefix + '2')
+ '.' + $email_link.attr(email_data_attr_prefix + '3');
var email_href = 'mailto:' + email_address;
$email_link.attr('href', email_href)
.removeClass(email_obfuscated_class)
.removeAttr(
email_data_attr_prefix + '1'
+ ' ' + email_data_attr_prefix + '2'
+ ' ' + email_data_attr_prefix + '3'
)
.find('span').remove();
// Prevent having to double-tap email link on mobile
if(e.type === 'touchstart') {
window.location = email_href;
}
}
})(jQuery);
|
;(function($){
var email_obfuscated_class = 'obfuscated';
var email_data_attr_prefix = 'data-email-';
$(document)
.on('mouseenter focus click touchstart keydown', 'a.obfuscated-email.' + email_obfuscated_class, function(e){
assemble_email(e);
})
;
function assemble_email(e) {
e.stopPropagation();
e.preventDefault();
var $email_link = $(e.target);
var email_address =
$email_link.attr(email_data_attr_prefix + '1')
+ '@' + $email_link.attr(email_data_attr_prefix + '2')
+ '.' + $email_link.attr(email_data_attr_prefix + '3');
var email_href = 'mailto:' + email_address;
$email_link.attr('href', email_href).removeClass(email_obfuscated_class).removeAttr(email_data_attr_prefix + '1').find('span').remove();
// Prevent having to double-tap email link on mobile
if(e.type === 'touchstart') {
window.location = email_href;
}
}
})(jQuery);
|
Make the tests more reader friendly
|
var testCase = require('nodeunit').testCase,
parser = require('../language/parser'),
tokenizer = require('../language/tokenizer')
/* TESTS */
test('text literal', '"hello world"', static("hello world"))
test('number literal', '1', static(1))
test('declaration', 'let greeting = "hello"', { type:'DECLARATION', name:'greeting', value: static("hello") })
/* UTIL */
function test(name, code, expectedAST) {
module.exports['test '+name] = function(assert) {
var ast = parse(code)
assert.deepEqual(ast, expectedAST)
assert.done()
}
}
function static(value) {
var ast = { type:'STATIC', value:value }
ast.valueType = typeof value
return ast
}
function parse(code) {
tokens = tokenizer.tokenize(code)
return pruneInfo(parser.parse(tokens))
}
function pruneInfo(ast) {
for (var key in ast) {
if (key == 'info') { delete ast[key] }
else if (typeof ast[key] == 'object') { pruneInfo(ast[key]) }
}
return ast
}
|
var testCase = require('nodeunit').testCase,
parser = require('../language/parser'),
tokenizer = require('../language/tokenizer')
test('TextLiteral', '"hello world"', static("hello world"))
test('NumberLiteral', '1', static(1))
test('Declaration', 'let greeting = "hello"', {
type:'DECLARATION',
name:'greeting',
value: static("hello")
})
/* UTIL */
function test(name, code, expectedAST) {
module.exports['test '+name] = function(assert) {
var ast = parse(code)
assert.deepEqual(ast, expectedAST)
assert.done()
}
}
function static(value) {
var ast = { type:'STATIC', value:value }
ast.valueType = typeof value
return ast
}
function parse(code) {
tokens = tokenizer.tokenize(code)
return pruneInfo(parser.parse(tokens))
}
function pruneInfo(ast) {
for (var key in ast) {
if (key == 'info') { delete ast[key] }
else if (typeof ast[key] == 'object') { pruneInfo(ast[key]) }
}
return ast
}
|
Use output name from input name
|
import argparse
import os
import fiona
from shapely.geometry import Polygon, mapping
def remove_file(file_name):
try:
os.remove(file_name)
except OSError:
pass
def read_polygon(polygon_filename):
with open(polygon_filename) as f:
return f.readlines()
def clean_poylgon(polygon_data):
coordinates = polygon_data[2:][:-2]
coordinates = [item.split(' ') for item in coordinates]
coordinates = [filter(None, item) for item in coordinates]
coordinates = [(float(item[0]), float(item[1])) for item in coordinates]
return coordinates
def write_geojson(data, polygon_filename):
geojson_filename = polygon_filename.split('.')[0] + ".geojson"
remove_file(geojson_filename)
schema = {'geometry': 'Polygon','properties': {}}
with fiona.open(geojson_filename, 'w', 'GeoJSON', schema) as output:
output.write({'geometry':mapping(Polygon(data)), 'properties':{}})
def main(polygon_filename):
polygon_data = read_polygon(polygon_filename)
coordinates = clean_poylgon(polygon_data)
write_geojson(coordinates, polygon_filename)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("polygon_filename")
args = parser.parse_args()
main(args.polygon_filename)
|
import argparse
import os
import fiona
from shapely.geometry import Polygon, mapping
def remove_file(file_name):
try:
os.remove(file_name)
except OSError:
pass
def read_polygon(polygon_filename):
with open(polygon_filename) as f:
return f.readlines()
def clean_poylgon(polygon_data):
coordinates = polygon_data[2:][:-2]
coordinates = [item.split(' ') for item in coordinates]
coordinates = [filter(None, item) for item in coordinates]
coordinates = [(float(item[0]), float(item[1])) for item in coordinates]
return coordinates
def write_geojson(data):
geojson_filename = 'activity.geojson'
remove_file(geojson_filename)
schema = {'geometry': 'Polygon','properties': {}}
with fiona.open(geojson_filename, 'w', 'GeoJSON', schema) as output:
output.write({'geometry':mapping(Polygon(data)), 'properties':{}})
def main(polygon_filename):
polygon_data = read_polygon(polygon_filename)
coordinates = clean_poylgon(polygon_data)
write_geojson(coordinates)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("polygon_filename")
args = parser.parse_args()
main(args.polygon_filename)
|
Remove unreliable integration tests from automated testing
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
jshint: {
all: ['Gruntfile.js', 'index.js', 'test/*.js'],
options: {
jshintrc: '.jshintrc'
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/imap-client-unit.js']
}
}
});
// Load the plugin(s)
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-test');
// Default task(s).
grunt.registerTask('test', ['jshint', 'mochaTest']);
};
|
module.exports = function(grunt) {
'use strict';
// Add the grunt-mocha-test tasks.
grunt.loadNpmTasks('grunt-mocha-test');
// Project configuration.
grunt.initConfig({
jshint: {
all: ['Gruntfile.js', 'index.js', 'test/*.js'],
options: {
jshintrc: '.jshintrc'
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['test/imap-client-unit.js', 'test/imap-client-integration-node.js']
}
}
});
// Load the plugin(s)
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task(s).
grunt.registerTask('test', ['jshint', 'mochaTest']);
};
|
Add get raw key from KeyPair
|
import base64
import sha3
import os
from collections import namedtuple
class KeyPair:
def __init__(self, pub, pri):
self.private_key = pri
self.public_key = pub
def raw_public_key(self):
return base64.b64decode(self.public_key)
from iroha_cli.crypto_ed25519 import generate_keypair_ed25519, sign_ed25519, verify_ed25519, ed25519_sha3_512, \
ed25519_sha3_256
def generate_keypair():
return generate_keypair_ed25519()
def sign(key_pair, message):
return sign_ed25519(key_pair, message)
def verify(pub_key, sig, message):
return verify_ed25519(pub_key, sig, message)
def sha3_256(message):
return ed25519_sha3_256(message)
def sha3_512(message):
return ed25519_sha3_512(message)
|
import base64
import sha3
import os
from collections import namedtuple
class KeyPair:
def __init__(self, pub, pri):
self.private_key = pri
self.public_key = pub
from iroha_cli.crypto_ed25519 import generate_keypair_ed25519, sign_ed25519, verify_ed25519, ed25519_sha3_512, \
ed25519_sha3_256
def generate_keypair():
return generate_keypair_ed25519()
def sign(key_pair, message):
return sign_ed25519(key_pair, message)
def verify(pub_key, sig, message):
return verify_ed25519(pub_key, sig, message)
def sha3_256(message):
return ed25519_sha3_256(message)
def sha3_512(message):
return ed25519_sha3_512(message)
|
Disable `add tag` shortcut on mobile
|
import detectIt from 'detect-it';
const { deviceType } = detectIt;
export default {
bind(_el, _, { context: $vue }) {
const el = _el;
el.addEventListener('keydown', (e) => {
const { key } = e;
if (deviceType === 'touchOnly') return;
if (key === '#') {
const { value: content, selectionStart: caret } = el;
if (content.substring(caret - 1, caret) !== '\\') {
e.preventDefault();
$vue.$_eventBus.$emit('addTag');
}
}
});
el.addEventListener('keyup', () => {
if (deviceType === 'touchOnly') return;
el.value = el.value
.replace(/\\\\#/, '\\#') // \<ZERO WIDTH SPACE\u200b>#
.replace(/\\#/, '#');
el.dispatchEvent(new Event('input')); // Force Vuex update
});
},
};
|
export default {
bind(_el, _, { context: $vue }) {
const el = _el;
el.addEventListener('keydown', (e) => {
const { key } = e;
if (typeof key === 'undefined') return;
if (key === '#') {
const { value: content, selectionStart: caret } = el;
if (content.substring(caret - 1, caret) !== '\\') {
e.preventDefault();
$vue.$_eventBus.$emit('addTag');
}
}
});
el.addEventListener('keyup', ({ key }) => {
if (typeof key === 'undefined') return;
el.value = el.value
.replace(/\\\\#/, '\\#') // \<ZERO WIDTH SPACE\u200b>#
.replace(/\\#/, '#');
el.dispatchEvent(new Event('input')); // Force Vuex update
});
},
};
|
Fix function reference in `getSuggestFields`
|
<?php
namespace App\Transformers\Outbound;
trait HasSuggestFields
{
protected function getSuggestFields()
{
return array_replace_recursive(parent::getSuggestFields(), [
'suggest_autocomplete_boosted' => [
'filter' => function ($item) {
return $item->isBoosted() && isset($item->title);
},
],
'suggest_autocomplete_all' => [
'filter' => function ($item) {
return isset($item->title);
},
],
]);
}
}
|
<?php
namespace App\Transformers\Outbound;
trait HasSuggestFields
{
protected function getSuggestFields()
{
return array_replace_recursive(parent::getSearchFields(), [
'suggest_autocomplete_boosted' => [
'filter' => function ($item) {
return $item->isBoosted() && isset($item->title);
},
],
'suggest_autocomplete_all' => [
'filter' => function ($item) {
return isset($item->title);
},
],
]);
}
}
|
Remove hover state from label
|
@can(App\Policies\UserPolicy::ADMIN, App\User::class)
<a href="{{ route('admin.users.show', $user->username()) }}">
<img class="rounded-full" src="{{ $user->gravatarUrl($avatarSize ?? 150) }}">
</a>
@else
<a href="{{ route('profile', $user->username()) }}">
<img class="rounded-full" src="{{ $user->gravatarUrl($avatarSize ?? 150) }}">
</a>
@endcan
<h2 class="text-2xl text-gray-900">{{ $user->name() }}</h2>
@if ($bio = $user->bio())
<p class="text-gray-600">
{{ $bio }}
</p>
@endif
@if ($user->isAdmin())
<p><span class="px-2 py-1 rounded text-xs uppercase bg-green-primary text-white px-2 py-1">Admin</span></p>
@elseif ($user->isModerator())
<p><span class="label">Moderator</span></p>
@endif
<div>
@if ($user->githubUsername())
<a href="https://github.com/{{ $user->githubUsername() }}" class="text-green-darker text-3xl block">
<i class="fa fa-github"></i>
</a>
@endif
</div>
|
@can(App\Policies\UserPolicy::ADMIN, App\User::class)
<a href="{{ route('admin.users.show', $user->username()) }}">
<img class="rounded-full" src="{{ $user->gravatarUrl($avatarSize ?? 150) }}">
</a>
@else
<a href="{{ route('profile', $user->username()) }}">
<img class="rounded-full" src="{{ $user->gravatarUrl($avatarSize ?? 150) }}">
</a>
@endcan
<h2 class="text-2xl text-gray-900">{{ $user->name() }}</h2>
@if ($bio = $user->bio())
<p class="text-gray-600">
{{ $bio }}
</p>
@endif
@if ($user->isAdmin())
<p><span class="label label-primary">Admin</span></p>
@elseif ($user->isModerator())
<p><span class="label">Moderator</span></p>
@endif
<div>
@if ($user->githubUsername())
<a href="https://github.com/{{ $user->githubUsername() }}" class="text-green-darker text-3xl block">
<i class="fa fa-github"></i>
</a>
@endif
</div>
|
core: Change autotuning 'none' to 'off'
|
"""
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
SpeculativeRewriter, init_dle)
from devito.parameters import Parameters, add_sub_configuration
core_configuration = Parameters('core')
core_configuration.add('autotuning', 'basic', ['off', 'basic', 'aggressive'])
env_vars_mapper = {
'DEVITO_AUTOTUNING': 'autotuning',
}
add_sub_configuration(core_configuration, env_vars_mapper)
# Initialize the DLE
modes = {'basic': BasicRewriter,
'advanced': AdvancedRewriter,
'advanced-safemath': AdvancedRewriterSafeMath,
'speculative': SpeculativeRewriter}
init_dle(modes)
# The following used by backends.backendSelector
from devito.function import (Constant, Function, TimeFunction, SparseFunction, # noqa
SparseTimeFunction)
from devito.grid import Grid # noqa
from devito.core.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
"""
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
SpeculativeRewriter, init_dle)
from devito.parameters import Parameters, add_sub_configuration
core_configuration = Parameters('core')
core_configuration.add('autotuning', 'basic', ['none', 'basic', 'aggressive'])
env_vars_mapper = {
'DEVITO_AUTOTUNING': 'autotuning',
}
add_sub_configuration(core_configuration, env_vars_mapper)
# Initialize the DLE
modes = {'basic': BasicRewriter,
'advanced': AdvancedRewriter,
'advanced-safemath': AdvancedRewriterSafeMath,
'speculative': SpeculativeRewriter}
init_dle(modes)
# The following used by backends.backendSelector
from devito.function import (Constant, Function, TimeFunction, SparseFunction, # noqa
SparseTimeFunction)
from devito.grid import Grid # noqa
from devito.core.operator import Operator # noqa
from devito.types import CacheManager # noqa
|
Improve storage manager with method validation and key prefixing
|
function StorageManager(storageMethod, prefix) {
try {
storageMethod.setItem('__available__', true);
if(storageMethod.removeItem) {
storageMethod.removeItem('__available__');
}
} catch(e) {
throw "Storage method is not currently available.";
}
this.storageMethod = storageMethod;
this.prefix = prefix || '';
}
StorageManager.prototype.setCurrentLevel = function(level) {
this.storageMethod.setItem(this.prefix + 'level_current', level);
};
StorageManager.prototype.incrementCurrentLevel = function() {
this.setCurrentLevel(this.getCurrentLevel() + 1);
};
StorageManager.prototype.getCurrentLevel = function() {
return parseInt(this.storageMethod.getItem(this.prefix + 'level_current')) || 1;
};
StorageManager.prototype.getLevelResults = function() {
var results = this.storageMethod.getItem(this.prefix + 'level_results');
return results ? JSON.parse(results) : [];
};
StorageManager.prototype.setLevelResult = function(level, result) {
var results = this.getLevelResults();
results[level - 1] = result;
this.storageMethod.setItem(this.prefix + 'level_results', JSON.stringify(results));
};
StorageManager.prototype.getLevelResult = function(level) {
return this.getLevelResults()[level - 1];
};
|
function StorageManager(storageMethod) {
this.storageMethod = storageMethod;
}
StorageManager.prototype.setCurrentLevel = function(level) {
this.storageMethod.setItem('currentLevel', level);
};
StorageManager.prototype.incrementCurrentLevel = function() {
this.setCurrentLevel(this.getCurrentLevel() + 1);
};
StorageManager.prototype.getCurrentLevel = function() {
return parseInt(this.storageMethod.getItem('currentLevel')) || 1;
};
StorageManager.prototype.setCurrentLevelHistory = function(history) {
this.history = history;
};
StorageManager.prototype.updateCurrentLevelHistory = function() {
if(typeof this.history === 'undefined' ) {
throw "Cannot update history without history object";
}
this.storageMethod.setItem('currentLevelHistory', JSON.stringify(this.history));
};
StorageManager.prototype.getCurrentLevelHistory = function(history) {
var history = this.storageMethod.getItem('currentLevelHistory');
return history ? JSON.parse(history) : [];
};
StorageManager.prototype.getLevelResults = function() {
var results = this.storageMethod.getItem('levelResults');
return results ? JSON.parse(results) : [];
};
StorageManager.prototype.setLevelResult = function(level, result) {
var results = this.getLevelResults();
results[level - 1] = result;
this.storageMethod.setItem('levelResults', JSON.stringify(results));
};
StorageManager.prototype.getLevelResult = function(level) {
return this.getLevelResults()[level - 1];
};
|
Add HouseInventory.jsx to be compiled
|
var path = require('path');
var SRC_DIR = path.join(__dirname, '/client/src');
var DIST_DIR = path.join(__dirname, '/client/dist');
module.exports = {
entry: {
index: `${SRC_DIR}/index.jsx`,
login: `${SRC_DIR}/login.jsx`,
inventory: `${SRC_DIR}/HouseInventory.jsx`
},
output: {
path: DIST_DIR,
filename: '[name]-bundle.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : SRC_DIR,
loader : 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
}
};
|
var path = require('path');
var SRC_DIR = path.join(__dirname, '/client/src');
var DIST_DIR = path.join(__dirname, '/client/dist');
module.exports = {
entry: {
index: `${SRC_DIR}/index.jsx`,
login: `${SRC_DIR}/login.jsx`
},
output: {
path: DIST_DIR,
filename: '[name]-bundle.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : SRC_DIR,
loader : 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
}
};
|
Add Django >= 1.5 requirement
|
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-swiftbrowser',
version='0.1',
packages=['swiftbrowser'],
include_package_data=True,
license='Apache License (2.0)',
description='A simple Django app to access Openstack Swift',
long_description=README,
url='http://www.cschwede.com/',
author='Christian Schwede',
author_email='info@cschwede.de',
install_requires=['django>=1.5', 'python-swiftclient'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache License (2.0)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-swiftbrowser',
version='0.1',
packages=['swiftbrowser'],
include_package_data=True,
license='Apache License (2.0)',
description='A simple Django app to access Openstack Swift',
long_description=README,
url='http://www.cschwede.com/',
author='Christian Schwede',
author_email='info@cschwede.de',
install_requires=['django', 'python-swiftclient'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache License (2.0)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Make sure array buffer does not leak across vm.
|
var bs58 = require('bs58')
function serialize(data) {
// Using == on purpose.
if (data == null) {
return null
}
if (data instanceof Error) {
data = {
$type: 'Error',
msg: '' + data,
stack: data.stack
}
}
else if (data instanceof ArrayBuffer) {
data = {
$type: 'ArrayBuffer',
// It should be bs58.encode(new Buffer(data)), but it does not work in mock implementation
// in node v6.3.0 (but has been fixed at least in v6.10.0) because Buffer comes from outside
// of vm, while ArrayBuffer from inside. But it seems converting to Uint8Array first works.
data: bs58.encode(new Uint8Array(data))
}
}
return JSON.stringify(data)
}
function deserialize(string) {
// Using == on purpose.
if (string == null) {
return null
}
var data = JSON.parse(string)
if (data.$type === 'Error') {
var newData = new Error(data.msg)
newData.stack = data.stack
data = newData
}
else if (data.$type === 'ArrayBuffer') {
data = new Uint8Array(bs58.decode(data.data).values()).buffer
}
return data
}
module.exports = {
serialize: serialize,
deserialize: deserialize
}
|
var bs58 = require('bs58')
function serialize(data) {
// Using == on purpose.
if (data == null) {
return null
}
if (data instanceof Error) {
data = {
$type: 'Error',
msg: '' + data,
stack: data.stack
}
}
else if (data instanceof ArrayBuffer) {
data = {
$type: 'ArrayBuffer',
// It should be bs58.encode(new Buffer(data)), but it does not work in mock implementation
// in node v6.3.0 (but has been fixed at least in v6.10.0) because Buffer comes from outside
// of vm, while ArrayBuffer from inside. But it seems converting to Uint8Array first works.
data: bs58.encode(new Uint8Array(data))
}
}
return JSON.stringify(data)
}
function deserialize(string) {
// Using == on purpose.
if (string == null) {
return null
}
var data = JSON.parse(string)
if (data.$type === 'Error') {
var newData = new Error(data.msg)
newData.stack = data.stack
data = newData
}
else if (data.$type === 'ArrayBuffer') {
data = new Uint8Array(bs58.decode(data.data)).buffer
}
return data
}
module.exports = {
serialize: serialize,
deserialize: deserialize
}
|
Check if Backbone.history matches a route when started. [rev:
alex.scown]
BaseApp starts Backbone.History. It now checks the return value of
Backbone.history.start to see if a route was matched, if not, it
navigates to the default route.
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone',
'jquery',
'find/app/util/test-browser',
'find/app/vent'
], function(Backbone, $, testBrowser, vent) {
return Backbone.View.extend({
el: '.page',
initialize: function() {
$.ajaxSetup({ cache: false });
this.render();
var matchedRoute = Backbone.history.start();
if (!matchedRoute) {
vent.navigate(this.defaultRoute);
}
testBrowser();
},
render: function() {
this.$el.html(this.template(this.getTemplateParameters()));
this.pages.render();
this.$('.content').append(this.pages.el);
},
getTemplateParameters: function() {
return {};
}
});
});
|
/*
* Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone',
'find/app/util/test-browser',
'find/app/vent'
], function(Backbone, testBrowser, vent) {
return Backbone.View.extend({
el: '.page',
initialize: function() {
jQuery.ajaxSetup({ cache: false });
this.render();
Backbone.history.start();
if (!window.location.hash || window.location.hash === "#undefined" || window.location.hash === "undefined") {
vent.navigate(this.defaultRoute);
}
testBrowser();
},
render: function() {
this.$el.html(this.template(this.getTemplateParameters()));
this.pages.render();
this.$('.content').append(this.pages.el);
},
getTemplateParameters: function() {
return {};
}
});
});
|
Exclude mock directory from coverage.
|
<?php
use mageekguy\atoum\reports;
$runner
->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
->disallowUndefinedMethodInInterface()
;
$runner->getScore()->getCoverage()->excludeDirectory(__DIR__ . '/tests/units/mock');
$travis = getenv('TRAVIS');
if ($travis)
{
$script->addDefaultReport();
$coverallsToken = getenv('COVERALLS_REPO_TOKEN');
if ($coverallsToken)
{
$coverallsReport = new reports\asynchronous\coveralls('classes', $coverallsToken);
$defaultFinder = $coverallsReport->getBranchFinder();
$coverallsReport
->setBranchFinder(function() use ($defaultFinder) {
if (($branch = getenv('TRAVIS_BRANCH')) === false)
{
$branch = $defaultFinder();
}
return $branch;
}
)
->setServiceName('travis-ci')
->setServiceJobId(getenv('TRAVIS_JOB_ID'))
->addDefaultWriter()
;
$runner->addReport($coverallsReport);
}
}
|
<?php
use mageekguy\atoum\reports;
$runner
->addTestsFromDirectory(__DIR__ . '/tests/units/classes')
->disallowUndefinedMethodInInterface()
;
$travis = getenv('TRAVIS');
if ($travis)
{
$script->addDefaultReport();
$coverallsToken = getenv('COVERALLS_REPO_TOKEN');
if ($coverallsToken)
{
$coverallsReport = new reports\asynchronous\coveralls('classes', $coverallsToken);
$defaultFinder = $coverallsReport->getBranchFinder();
$coverallsReport
->setBranchFinder(function() use ($defaultFinder) {
if (($branch = getenv('TRAVIS_BRANCH')) === false)
{
$branch = $defaultFinder();
}
return $branch;
}
)
->setServiceName('travis-ci')
->setServiceJobId(getenv('TRAVIS_JOB_ID'))
->addDefaultWriter()
;
$runner->addReport($coverallsReport);
}
}
|
Add SweetAlert for authentication errors
|
import Ember from 'ember';
import swalert from 'sweetAlert';
/**
* This is the basic route to handle all routes that needs authentication.
* If there's a route that needs previous auth, it will need to extend this one.
*/
var AuthenticatedRoute = Ember.Route.extend({
// verify that there's a session token.
// if not, redirect to the login route.
beforeModel: function(transition) {
var token = this.controllerFor('sessions').get('token');
if (Ember.isEmpty(token)) {
return this.redirectToLogin(transition);
}
},
// redirect to the login route and store the attempted transition so we can
// move to it later.
redirectToLogin: function(transition) {
this.controllerFor('sessions').set('attemptedTransition', transition);
return this.transitionTo('sessions');
},
actions: {
error: function(reason, transition) {
if (reason.status === 401 || reason.status === 403) {
this.redirectToLogin(transition);
} else {
swalert('Oops...', 'This is embarrassing, but there was an unknown error. Try again later', 'error');
}
}
}
});
export default AuthenticatedRoute;
|
import Ember from 'ember';
/**
* This is the basic route to handle all routes that needs authentication.
* If there's a route that needs previous auth, it will need to extend this one.
*/
var AuthenticatedRoute = Ember.Route.extend({
// verify that there's a session token.
// if not, redirect to the login route.
beforeModel: function(transition) {
var token = this.controllerFor('sessions').get('token');
if (Ember.isEmpty(token)) {
return this.redirectToLogin(transition);
}
},
// redirect to the login route and store the attempted transition so we can
// move to it later.
redirectToLogin: function(transition) {
this.controllerFor('sessions').set('attemptedTransition', transition);
return this.transitionTo('sessions');
},
actions: {
error: function(reason, transition) {
if (reason.status === 401 || reason.status === 403) {
this.redirectToLogin(transition);
} else {
alert('Unknown error'); // TODO: use a beautiful popup with a better message
}
}
}
});
export default AuthenticatedRoute;
|
Upgrade dependency appdirs to ==1.4.1
|
import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.1',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.0',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Add more to debug message.
|
var PythonShell = require('python-shell');
module.exports = function(RED) {
function AdafruitMax31855Node(config) {
RED.nodes.createNode(this,config);
var node = this;
var scriptPath = './spi_read.py'
var args = []
console.log("Adafruit MAX 31855: Checking for muxing... "+this.muxing)
if (this.muxing == 1) {
console.log("Adafruit MAX 31855: Enabled muxing.")
args = [0,1,17,6,5,4,7,18,1]
}
var pyshell = new PythonShell(scriptPath, { scriptPath: __dirname, args: args });
pyshell.on('message', function (message) {
node.send({
payload: message
});
});
this.on("close", function() {
if (pyshell) { pyshell.end(); }
});
}
RED.nodes.registerType("adafruit-max31855", AdafruitMax31855Node);
}
|
var PythonShell = require('python-shell');
module.exports = function(RED) {
function AdafruitMax31855Node(config) {
RED.nodes.createNode(this,config);
var node = this;
var scriptPath = './spi_read.py'
var args = []
console.log("Adafruit MAX 31855: Checking for muxing...")
if (this.muxing) {
console.log("Adafruit MAX 31855: Enabled muxing.")
args = [0,1,17,6,5,4,7,18,1]
}
var pyshell = new PythonShell(scriptPath, { scriptPath: __dirname, args: args });
pyshell.on('message', function (message) {
node.send({
payload: message
});
});
this.on("close", function() {
if (pyshell) { pyshell.end(); }
});
}
RED.nodes.registerType("adafruit-max31855", AdafruitMax31855Node);
}
|
Allow commas in assessment fees and expenses values
|
"use strict";
var adp = adp || {};
adp.determination = {
init : function(container_id) {
this.addChangeEvent(container_id);
},
calculateAmount: function(fee, expenses) {
var f = fee || 0,
e = expenses || 0;
f = f < 0 ? 0 : f;
e = e < 0 ? 0 : e;
var t = (f + e).toFixed(2);
t = t < 0 ? 0 : t;
return t;
},
addChangeEvent: function(container_id) {
$('#' + container_id).on('change', '#claim_assessment_attributes_fees, #claim_assessment_attributes_expenses', function(e) {
var fees = parseFloat($('#claim_assessment_attributes_fees').val().replace(/,/g, ""));
var expenses = parseFloat($('#claim_assessment_attributes_expenses').val().replace(/,/g, ""));
var total = adp.determination.calculateAmount(fees,expenses);
if (isNaN(total) ){
$('.total-determination').text('£0.00');
}
else{
$('.total-determination').text('£ '+ total);
}
});
}
};
|
"use strict";
var adp = adp || {};
adp.determination = {
init : function(container_id) {
this.addChangeEvent(container_id);
},
calculateAmount: function(fee, expenses) {
var f = fee || 0,
e = expenses || 0;
f = f < 0 ? 0 : f;
e = e < 0 ? 0 : e;
var t = (f + e).toFixed(2);
t = t < 0 ? 0 : t;
return t;
},
addChangeEvent: function(container_id) {
$('#' + container_id).on('change', '#claim_assessment_attributes_fees, #claim_assessment_attributes_expenses', function(e) {
var fees = parseFloat($('#claim_assessment_attributes_fees').val());
var expenses = parseFloat($('#claim_assessment_attributes_expenses').val());
var total = adp.determination.calculateAmount(fees,expenses);
if (isNaN(total) ){
$('.total-determination').text('£0.00');
}
else{
$('.total-determination').text('£ '+ total);
}
});
}
};
|
Create both admin test user and no permissions test user
|
'use strict'
process.env.NODE_ENV = 'testing'
let db = require('../api/db').db
let User = require('../api/db').User
let bcrypt = require('bcrypt')
let winston = require('winston')
db.sync({ force: true }).then(function () {
bcrypt.hash('testuser', 16, function (error, hash) {
let adminTestUser = {
email: 'admintestuser@fuelrats.com',
password: hash,
nicknames: db.literal('ARRAY[\'admintestnick\']::citext[]'),
groups: ['rat', 'dispatch', 'admin']
}
User.create(adminTestUser).then(function () {
winston.info('Admin Test User Created')
}).catch(function (error) {
winston.error(error)
})
let testUser = {
email: 'testuser@fuelrats.com',
password: hash,
nicknames: db.literal('ARRAY[\'testnick\']::citext[]'),
groups: []
}
User.create(testUser).then(function () {
winston.info('Test User Created')
}).catch(function (error) {
winston.error(error)
})
})
})
|
'use strict'
process.env.NODE_ENV = 'testing'
let db = require('../api/db').db
let User = require('../api/db').User
let bcrypt = require('bcrypt')
let winston = require('winston')
db.sync({ force: true }).then(function () {
bcrypt.hash('testuser', 16, function (error, hash) {
let testUser = {
email: 'support@fuelrats.com',
password: hash,
drilled: true,
drilledDispatch: true,
nicknames: db.literal('ARRAY[\'testnick\']::citext[]'),
group: 'admin'
}
User.create(testUser).then(function () {
winston.info('Test User Created')
}).catch(function (error) {
winston.error(error)
})
})
})
|
Remove the now unused Log import
|
<?php
namespace Rogue\Services;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a GraphQL query using the client and return the data result.
*
* @param $query String
* @param $variables Array
* @return array
*/
public function query($query, $variables)
{
$response = $this->client->query($query, $variables);
return $response ? $response->getData() : [];
}
/**
* Query for a CampaignWebsite by campaignId field.
*
* @param $campaignId String
* @return array
*/
public function getCampaignWebsiteByCampaignId($campaignId)
{
$query = '
query GetCampaignWebsiteByCampaignId($campaignId: String!) {
campaignWebsiteByCampaignId(campaignId: $campaignId) {
title
slug
}
}';
$variables = [
'campaignId' => $campaignId,
];
return $this->query($query, $variables);
}
}
|
<?php
namespace Rogue\Services;
use Illuminate\Support\Facades\Log;
use Softonic\GraphQL\ClientBuilder;
class GraphQL
{
/**
* Build a new GraphQL client.
*/
public function __construct()
{
$this->client = ClientBuilder::build(config('services.graphql.url'));
}
/**
* Run a GraphQL query using the client and return the data result.
*
* @param $query String
* @param $variables Array
* @return array
*/
public function query($query, $variables)
{
$response = $this->client->query($query, $variables);
return $response ? $response->getData() : [];
}
/**
* Query for a CampaignWebsite by campaignId field.
*
* @param $campaignId String
* @return array
*/
public function getCampaignWebsiteByCampaignId($campaignId)
{
$query = '
query GetCampaignWebsiteByCampaignId($campaignId: String!) {
campaignWebsiteByCampaignId(campaignId: $campaignId) {
title
slug
}
}';
$variables = [
'campaignId' => $campaignId,
];
return $this->query($query, $variables);
}
}
|
Add rotation of CSRF token to prevent form resubmission
|
from django.shortcuts import render, HttpResponse
from django.shortcuts import HttpResponseRedirect
from django.template import Context, Template
from django.middleware.csrf import rotate_token
from models import UploadFileForm
from models import extGenOptimizer1
OPTIONS = """
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek',
},
defaultView: 'agendaWeek',
editable: true,
eventLimit: true, // allow "more" link when too many events
scrollTime: '08:00:00',
"""
# Create your views here.
def index(request):
indexContext = {}
indexContext['fileReturnError'] = 'false'
events = 'events:[],'
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
print "form is valid or not = ", form.is_valid()
if form.is_valid():
myOptimizerParser = extGenOptimizer1()
events = myOptimizerParser.run(request.FILES)
# else:
# indexContext['fileReturnError'] = 'true'
else:
form = UploadFileForm()
indexContext['form'] = form
indexContext['calendar_config_options'] = OPTIONS
indexContext['calendar_events'] = events
rotate_token(request)
return render(request, 'EXT_GEN/index.html', indexContext)
|
from django.shortcuts import render, HttpResponse
from django.shortcuts import HttpResponseRedirect
from django.template import Context, Template
from models import UploadFileForm
from models import extGenOptimizer1
OPTIONS = """
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek',
},
defaultView: 'agendaWeek',
editable: true,
eventLimit: true, // allow "more" link when too many events
scrollTime: '08:00:00',
"""
# Create your views here.
def index(request):
indexContext = {}
indexContext['fileReturnError'] = 'false'
events = 'events:[],'
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
print "form is valid or not = ", form.is_valid()
if form.is_valid():
myOptimizerParser = extGenOptimizer1()
events = myOptimizerParser.run(request.FILES)
# else:
# indexContext['fileReturnError'] = 'true'
else:
form = UploadFileForm()
indexContext['form'] = form
indexContext['calendar_config_options'] = OPTIONS
indexContext['calendar_events'] = events
return render(request, 'EXT_GEN/index.html', indexContext)
|
Return string instead of list
|
# encoding=utf8
from lxml import html
import json
def _recursive_convert(element):
# All strings outside tags should be ignored
fragment_root_element = {
'_': element.tag
}
content = []
if element.text:
content.append({'t': element.text})
if element.attrib:
fragment_root_element.update({
'a': dict(element.attrib)
})
for child in element:
content.append(_recursive_convert(child))
# Append Text node after element, if exists
if child.tail:
content.append({'t': child.tail})
if len(content):
fragment_root_element.update({
'c': content
})
return fragment_root_element
def convert_html_to_telegraph_format(html_string):
content = []
for fragment in html.fragments_fromstring(html_string):
if not isinstance(fragment, html.HtmlElement):
continue
content.append(_recursive_convert(fragment))
return json.dumps(content, ensure_ascii=False)
|
# encoding=utf8
from lxml import html
def _recursive_convert(element):
# All strings outside tags should be ignored
if not isinstance(element, html.HtmlElement):
return
fragment_root_element = {
'_': element.tag
}
content = []
if element.text:
content.append({'t': element.text})
if element.attrib:
fragment_root_element.update({
'a': dict(element.attrib)
})
for child in element:
content.append(_recursive_convert(child))
# Append Text node after element, if exists
if child.tail:
content.append({'t': child.tail})
if len(content):
fragment_root_element.update({
'c': content
})
return fragment_root_element
def convert_html_to_telegraph_format(html_string):
return [
_recursive_convert(fragment) for fragment in html.fragments_fromstring(html_string)
]
|
Add copyright to source files
|
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
'use strict';
var walk = require('rework-walk');
exports.prefix = prefixSelector;
exports.replace = replaceSelector;
function prefixSelector(prefix) {
return function (style) {
walk(style, function (rule) {
if (!rule.selectors) { return; }
rule.selectors = rule.selectors.map(function (selector) {
if (selector.match(/^(html|body)/)) {
return selector.replace(/^(html|body)/, prefix);
}
return prefix + ' ' + selector;
});
});
};
}
function replaceSelector(search, replace) {
return function (style) {
walk(style, function (rule) {
if (!rule.selectors) { return; }
rule.selectors = rule.selectors.map(function (selector) {
return selector.replace(search, replace);
});
});
};
}
|
'use strict';
var walk = require('rework-walk');
exports.prefix = prefixSelector;
exports.replace = replaceSelector;
function prefixSelector(prefix) {
return function (style) {
walk(style, function (rule) {
if (!rule.selectors) { return; }
rule.selectors = rule.selectors.map(function (selector) {
if (selector.match(/^(html|body)/)) {
return selector.replace(/^(html|body)/, prefix);
}
return prefix + ' ' + selector;
});
});
};
}
function replaceSelector(search, replace) {
return function (style) {
walk(style, function (rule) {
if (!rule.selectors) { return; }
rule.selectors = rule.selectors.map(function (selector) {
return selector.replace(search, replace);
});
});
};
}
|
Add SlideShow folder to the dependency graph.
|
//= require_directory ./AbstractDocument
//= require_directory ./BrowserWidget
//= require_directory ./ComponentStateManager
//= require_directory ./Desktop
//= require_directory ./DiagramWidget
//= require_directory ./DocumentEditor
//= require_directory ./FundamentalTypes
//= require_directory ./HierarchicalMenuWidget
//= require_directory ./HtmlDocument
//= require_directory ./Internationalization
//= require_directory ./jStorage
//= require_directory ./LanguageSelectorWidget
//= require_directory ./MochaUI
//= require_directory ./NewsReaderWidget
//= require_directory ./PartyEventWidget
//= require_directory ./PhotoGaleryWidget
//= require_directory ./ResourceManager
//= require_directory ./ScrollingBehaviour
//= require_directory ./Singleton
//= require_directory ./SkinSelectorWidget
//= require_directory ./SlideShow
//= require_directory ./SmartDocument
//= require_directory ./SplashForm
//= require_directory ./TabWidget
//= require_directory ./TextAreaEditor
//= require_directory ./ToolBarWidget
//= require_directory ./TreeWidget
//= require_directory ./VideoPlayerWidget
//= require_directory ./WebUIConfiguration
//= require_directory ./WebUIController
//= require_directory ./WebUILogger
//= require_directory ./WebUIMessageBus
|
//= require_directory ./AbstractDocument
//= require_directory ./BrowserWidget
//= require_directory ./ComponentStateManager
//= require_directory ./Desktop
//= require_directory ./DiagramWidget
//= require_directory ./DocumentEditor
//= require_directory ./FundamentalTypes
//= require_directory ./HierarchicalMenuWidget
//= require_directory ./HtmlDocument
//= require_directory ./Internationalization
//= require_directory ./jStorage
//= require_directory ./LanguageSelectorWidget
//= require_directory ./MochaUI
//= require_directory ./NewsReaderWidget
//= require_directory ./PartyEventWidget
//= require_directory ./PhotoGaleryWidget
//= require_directory ./ResourceManager
//= require_directory ./ScrollingBehaviour
//= require_directory ./Singleton
//= require_directory ./SkinSelectorWidget
//= require_directory ./SmartDocument
//= require_directory ./SplashForm
//= require_directory ./TabWidget
//= require_directory ./TextAreaEditor
//= require_directory ./ToolBarWidget
//= require_directory ./TreeWidget
//= require_directory ./VideoPlayerWidget
//= require_directory ./WebUIConfiguration
//= require_directory ./WebUIController
//= require_directory ./WebUILogger
//= require_directory ./WebUIMessageBus
|
Add total monthly amount to clients container
|
import React, { Component } from 'react'
import ClientCard from '../views/ClientCard'
import { Container } from 'semantic-ui-react'
import styled from 'styled-components'
const StyledLeads = styled.div`
display: flex;
flex-wrap: wrap;
`
class ClientsContainer extends Component {
render() {
const clients = this.props.clients.map(c =>
<ClientCard key={c.id} {...c} />
)
const monthly = this.props.clients.reduce((a, b) => {
return a + b.monthly_rate
}, 0)
return (
<Container>
{monthly}
<StyledLeads>
{clients}
</StyledLeads>
</Container>
)
}
}
export default ClientsContainer
|
import React, { Component } from 'react'
import ClientCard from '../views/ClientCard'
import { Container } from 'semantic-ui-react'
import styled from 'styled-components'
const StyledLeads = styled.div`
display: flex;
flex-wrap: wrap;
`
class ClientsContainer extends Component {
render() {
console.log(this.props)
const clients = this.props.clients.map(c => <ClientCard key={c.id} {...c} />)
const monthly = this.props.clients.reduce((a, b) => {return a + b.monthly_rate}, 0)
return (
<Container>
{monthly}
<StyledLeads>
{clients}
</StyledLeads>
</Container>
)
}
}
export default ClientsContainer
|
Include from the functions directory
|
//Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
//Login to Discord
client.login(config.API.discord);
//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
items.forEach(function(item) {
var file = item.replace(/['"]+/g, '');
command[file] = require("./commands/" + file);
})
})
client.on('ready', function() {
console.log("Successfully connected to Discord!");
client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});
client.on('message', function(message) {
if (!message.content.startsWith(config.MSS.prefix)) return false;
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
if (input[0] === "eval" && message.author.id === "190519304972664832") {
eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
}
});
|
//Get the required shit together
const config = require("./config.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
//Login to Discord
client.login(config.API.discord);
//Include all files in the commands directory
fs.readdir("./commands/", function(err, items) {
items.forEach(function(item) {
var file = item.replace(/['"]+/g, '');
command[file] = require(file);
})
})
client.on('ready', function() {
console.log("Successfully connected to Discord!");
client.user.setGame(config.MSS.prefix + "help | " + config.MSS.version);
});
client.on('message', function(message) {
if (!message.content.startsWith(config.MSS.prefix)) return false;
let input = message.content.replace (/\n/g, "").split(" ");
input[0] = input[0].substring(config.MSS.prefix.length);
if (input[0] === "eval" && message.author.id === "190519304972664832") {
eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
}
});
|
[AC-4875] Improve history sorting and remove dead comments
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: (e["datetime"],
e.get("latest_datetime",
e["datetime"])))
}
return Response(result)
|
# MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from rest_framework.response import Response
from rest_framework.views import APIView
from impact.permissions import (
V1APIPermissions,
)
from impact.v1.metadata import (
ImpactMetadata,
READ_ONLY_LIST_TYPE,
)
class BaseHistoryView(APIView):
metadata_class = ImpactMetadata
permission_classes = (
V1APIPermissions,
)
METADATA_ACTIONS = {"GET": {"history": READ_ONLY_LIST_TYPE}}
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get(self, request, pk):
self.instance = self.model.objects.get(pk=pk)
events = []
for event_class in self.event_classes:
events = events + event_class.events(self.instance)
result = {
"results": sorted([event.serialize() for event in events],
key=lambda e: e["datetime"])
}
return Response(result)
|
[lib] Fix bug in multimedia upload
`uploadBlob` expects an array of multimedia, not a single one.
|
// @flow
import type { FetchJSON } from '../utils/fetch-json';
import type { UploadMultimediaResult } from '../types/media-types';
async function uploadMultimedia(
fetchJSON: FetchJSON,
multimedia: Object,
onProgress: (percent: number) => void,
abortHandler: (abort: () => void) => void,
): Promise<UploadMultimediaResult> {
const response = await fetchJSON(
'upload_multimedia',
{ multimedia: [ multimedia ] },
{ blobUpload: true, onProgress, abortHandler },
);
return { id: response.id, uri: response.uri };
}
const assignMediaServerIDToMessageActionType =
"ASSIGN_MEDIA_SERVER_ID_TO_MESSAGE";
const assignMediaServerURIToMessageActionType =
"ASSIGN_MEDIA_SERVER_URI_TO_MESSAGE";
export {
uploadMultimedia,
assignMediaServerIDToMessageActionType,
assignMediaServerURIToMessageActionType,
};
|
// @flow
import type { FetchJSON } from '../utils/fetch-json';
import type { UploadMultimediaResult } from '../types/media-types';
async function uploadMultimedia(
fetchJSON: FetchJSON,
multimedia: Object,
onProgress: (percent: number) => void,
abortHandler: (abort: () => void) => void,
): Promise<UploadMultimediaResult> {
const response = await fetchJSON(
'upload_multimedia',
{ multimedia },
{ blobUpload: true, onProgress, abortHandler },
);
return { id: response.id, uri: response.uri };
}
const assignMediaServerIDToMessageActionType =
"ASSIGN_MEDIA_SERVER_ID_TO_MESSAGE";
const assignMediaServerURIToMessageActionType =
"ASSIGN_MEDIA_SERVER_URI_TO_MESSAGE";
export {
uploadMultimedia,
assignMediaServerIDToMessageActionType,
assignMediaServerURIToMessageActionType,
};
|
Add more titles and suffixes
|
import tldextract
import pyphen
from random import choice
TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen')
SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD',
'Ah-gowan-gowan-gowan')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
|
import tldextract
import pyphen
from random import choice
TITLES = ('Mister', 'Little Miss')
SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
|
Remove newline that snuck in
|
package certstream
import (
"time"
"github.com/gorilla/websocket"
"github.com/jmoiron/jsonq"
"github.com/pkg/errors"
)
func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
outputStream := make(chan jsonq.JsonQuery)
errStream := make(chan error)
go func() {
for {
c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)
if err != nil {
errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
time.Sleep(5 * time.Second)
continue
}
defer c.Close()
defer close(outputStream)
for {
var v interface{}
err = c.ReadJSON(&v)
if err != nil {
errStream <- errors.Wrap(err, "Error decoding json frame!")
break
}
jq := jsonq.NewQuery(v)
res, err := jq.String("message_type")
if err != nil {
errStream <- errors.Wrap(err, "Could not create jq object. Malformed json input recieved. Skipping.")
continue
}
if skipHeartbeats && res == "heartbeat" {
continue
}
outputStream <- *jq
}
}
}()
return outputStream, errStream
}
|
package certstream
import (
"time"
"github.com/gorilla/websocket"
"github.com/jmoiron/jsonq"
"github.com/pkg/errors"
)
func CertStreamEventStream(skipHeartbeats bool) (chan jsonq.JsonQuery, chan error) {
outputStream := make(chan jsonq.JsonQuery)
errStream := make(chan error)
go func() {
for {
c, _, err := websocket.DefaultDialer.Dial("wss://certstream.calidog.io", nil)
if err != nil {
errStream <- errors.Wrap(err, "Error connecting to certstream! Sleeping a few seconds and reconnecting... ")
time.Sleep(5 * time.Second)
continue
}
defer c.Close()
defer close(outputStream)
for {
var v interface{}
err = c.ReadJSON(&v)
if err != nil {
errStream <- errors.Wrap(err, "Error decoding json frame!")
break
}
jq := jsonq.NewQuery(v)
res, err := jq.String("message_type")
if err != nil {
errStream <- errors.Wrap(err, "Could not create jq object. Malformed json input recieved. Skipping.")
continue
}
if skipHeartbeats && res == "heartbeat" {
continue
}
outputStream <- *jq
}
}
}()
return outputStream, errStream
}
|
Fix displaying of Factlink Bubble
Signed-off-by: tomdev <96835dd8bfa718bd6447ccc87af89ae1675daeca@codigy.nl>
|
(function () {
function createIframe() {
var body = document.getElementsByTagName("body")[0];
var iframe = document.createElement("iframe");
var div = document.createElement("div");
iframe.style.display = "none";
iframe.id = "factlink-iframe";
div.id = "fl";
body.appendChild(div);
div.insertBefore(iframe, div.firstChild);
return iframe;
}
var iframe = createIframe();
var iDocument = iframe.contentWindow.document;
var iHead = iDocument.getElementsByTagName("head")[0];
var head = document.getElementsByTagName("head")[0];
var flScript = document.createElement("script");
flScript.src = FactlinkConfig.lib + (FactlinkConfig.srcPath || "/dist/factlink.core.min.js");
var configScript = document.createElement("script");
configScript.type = "text/javascript";
configScript.innerHTML = "window.FactlinkConfig = " + JSON.stringify(FactlinkConfig) + ";";
iHead.insertBefore(configScript, iHead.firstChild);
iHead.insertBefore(flScript, iHead.firstChild);
}());
|
(function () {
function createIframe() {
var body = document.getElementsByTagName("body")[0];
var iframe = document.createElement("iframe");
var div = document.createElement("div");
iframe.style.display = "none";
iframe.id = "factlink-iframe";
div.id = "fl";
div.style.display = "none";
body.insertBefore(div, body.firstChild);
div.insertBefore(iframe, div.firstChild);
return iframe;
}
var iframe = createIframe();
var iDocument = iframe.contentWindow.document;
var iHead = iDocument.getElementsByTagName("head")[0];
var head = document.getElementsByTagName("head")[0];
var flScript = document.createElement("script");
flScript.src = FactlinkConfig.lib + (FactlinkConfig.srcPath || "/dist/factlink.core.min.js");
var configScript = document.createElement("script");
configScript.type = "text/javascript";
configScript.innerHTML = "window.FactlinkConfig = " + JSON.stringify(FactlinkConfig) + ";";
iHead.insertBefore(configScript, iHead.firstChild);
iHead.insertBefore(flScript, iHead.firstChild);
}());
|
Fix encoding issue with legacy python (2.7)
|
# -*- coding: utf-8 -*-
# This software is distributed under the two-clause BSD license.
# Copyright (c) The django-ldapdb project
from django.conf import settings
import sys
import ldap.filter
def escape_ldap_filter(value):
if sys.version_info[0] < 3:
text_value = unicode(value)
else:
text_value = str(value)
return ldap.filter.escape_filter_chars(text_value)
# Legacy single database support
if hasattr(settings, 'LDAPDB_SERVER_URI'):
from django import db
from ldapdb.router import Router
# Add the LDAP backend
settings.DATABASES['ldap'] = {
'ENGINE': 'ldapdb.backends.ldap',
'NAME': settings.LDAPDB_SERVER_URI,
'USER': settings.LDAPDB_BIND_DN,
'PASSWORD': settings.LDAPDB_BIND_PASSWORD}
# Add the LDAP router
db.router.routers.append(Router())
|
# -*- coding: utf-8 -*-
# This software is distributed under the two-clause BSD license.
# Copyright (c) The django-ldapdb project
from django.conf import settings
import ldap.filter
def escape_ldap_filter(value):
return ldap.filter.escape_filter_chars(str(value))
# Legacy single database support
if hasattr(settings, 'LDAPDB_SERVER_URI'):
from django import db
from ldapdb.router import Router
# Add the LDAP backend
settings.DATABASES['ldap'] = {
'ENGINE': 'ldapdb.backends.ldap',
'NAME': settings.LDAPDB_SERVER_URI,
'USER': settings.LDAPDB_BIND_DN,
'PASSWORD': settings.LDAPDB_BIND_PASSWORD}
# Add the LDAP router
db.router.routers.append(Router())
|
Update github link to cloudenvy org
|
try:
from setuptools import setup
except:
from distutils.core import setup
import os
def parse_requirements(requirements_filename='requirements.txt'):
requirements = []
if os.path.exists(requirements_filename):
with open(requirements_filename) as requirements_file:
for requirement in requirements_file:
requirements.append(requirement)
return requirements
config = dict(
name='cloudenvy',
version='0.1.0',
url='https://github.com/cloudenvy/cloudenvy',
description='Fast provisioning on openstack clouds.',
author='Brian Waldon',
author_email='bcwaldon@gmail.com',
install_requires=parse_requirements(),
packages=['cloudenvy', 'cloudenvy.commands'],
entry_points={
'console_scripts': [
'envy = cloudenvy.main:main',
]
},
)
setup(**config)
|
try:
from setuptools import setup
except:
from distutils.core import setup
import os
def parse_requirements(requirements_filename='requirements.txt'):
requirements = []
if os.path.exists(requirements_filename):
with open(requirements_filename) as requirements_file:
for requirement in requirements_file:
requirements.append(requirement)
return requirements
config = dict(
name='cloudenvy',
version='0.1.0',
url='https://github.com/bcwaldon/cloudenvy',
description='Fast provisioning on openstack clouds.',
author='Brian Waldon',
author_email='bcwaldon@gmail.com',
install_requires=parse_requirements(),
packages=['cloudenvy', 'cloudenvy.commands'],
entry_points={
'console_scripts': [
'envy = cloudenvy.main:main',
]
},
)
setup(**config)
|
[FEATURE] Use new validations, clean up ripple addresses express controller.
|
var RippleAddress = require('../models/ripple_address');
module.exports = (function(){
function create(req, res) {
req.validate('user_id', 'isInt');
req.validate('ripple_address', 'isAlpha');
req.validate('cash_amount', 'isFloat');
if (req.user.admin || (req.user.id == req.body.user_id)) {
RippleAddress.create({
user_id: req.body.userId,
address: req.body.rippleAddress
}).complete(function(err, address){
res.send({ ripple_address: address });
});
} else {
res.status(401);
res.send('Unauthorized');
}
}
function index(req,res) {
if (req.user.admin) {
RippleAddress.findAll().complete(function(err, addresses) {
res.send({ ripple_addresses: addresses });
});
} else {
RippleAddress.findAll({ where: { user_id: req.user.id }})
.complete(function(err, addresses) {
res.send({ ripple_addresses: addresses });
});
}
}
return {
create: create,
index: index
}
})();
|
var RippleAddress = require('../models/ripple_address');
function respondToValidationErrors(req, res) {
var errors = req.validationErrors();
if (errors) {
res.end({ error: util.inspect(errors) }, 400)
return;
}
}
module.exports = (function(){
function userIndex(req, res) {
RippleAddress.findAll({ where: { user_id: req.params.id }}).complete(function(err, addresses) {
res.send({ success: true, ripple_addresses: addresses });
})
}
function create(req, res) {
req.checkBody('userId', 'Invalid bankAccountId')
.notEmpty().isInt();
req.checkBody('rippleAddress', 'Invalid currency')
.notEmpty().isAlpha();
req.checkBody('cashAmount', 'Invalid cashAmount')
.notEmpty().isFloat();
respondToValidationErrors(req, res);
RippleAddress.create({
user_id: req.body.userId,
address: req.body.rippleAddress
})
.success(function(address){
res.send(address);
})
.error(function(err){
res.send({ error: err });
});
}
function index(req,res) {
RippleAddress.findAll()
.success(function(addresses){
res.send(addresses);
})
.error(function(err){
res.send({ error: err });
});
}
return {
userIndex: userIndex,
create: create,
index: index
}
})();
|
lxd/state: Update tests with NewState usage
Signed-off-by: Thomas Parrott <6b778ce645fb0e3dde76d79eccad490955b1ae74@canonical.com>
|
//go:build linux && cgo && !agent
// +build linux,cgo,!agent
package state
import (
"context"
"testing"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/firewall"
"github.com/lxc/lxd/lxd/sys"
)
// NewTestState returns a State object initialized with testable instances of
// the node/cluster databases and of the OS facade.
//
// Return the newly created State object, along with a function that can be
// used for cleaning it up.
func NewTestState(t *testing.T) (*State, func()) {
node, nodeCleanup := db.NewTestNode(t)
cluster, clusterCleanup := db.NewTestCluster(t)
os, osCleanup := sys.NewTestOS(t)
cleanup := func() {
nodeCleanup()
clusterCleanup()
osCleanup()
}
state := NewState(context.TODO(), node, cluster, nil, os, nil, nil, nil, firewall.New(), nil, nil, func() {})
return state, cleanup
}
|
//go:build linux && cgo && !agent
// +build linux,cgo,!agent
package state
import (
"context"
"testing"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/firewall"
"github.com/lxc/lxd/lxd/sys"
)
// NewTestState returns a State object initialized with testable instances of
// the node/cluster databases and of the OS facade.
//
// Return the newly created State object, along with a function that can be
// used for cleaning it up.
func NewTestState(t *testing.T) (*State, func()) {
node, nodeCleanup := db.NewTestNode(t)
cluster, clusterCleanup := db.NewTestCluster(t)
os, osCleanup := sys.NewTestOS(t)
cleanup := func() {
nodeCleanup()
clusterCleanup()
osCleanup()
}
state := NewState(context.TODO(), node, cluster, nil, os, nil, nil, nil, firewall.New(), nil)
return state, cleanup
}
|
Use latest version of schemer
|
import setuptools
setuptools.setup(
name="Mongothon",
version="0.7.8",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
license="BSD",
keywords="mongo mongodb database pymongo odm validation",
url="http://github.com/gamechanger/mongothon",
packages=["mongothon"],
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer==0.2.2'],
tests_require=['mock', 'nose']
)
|
import setuptools
setuptools.setup(
name="Mongothon",
version="0.7.7",
author="Tom Leach",
author_email="tom@gc.io",
description="A MongoDB object-document mapping layer for Python",
license="BSD",
keywords="mongo mongodb database pymongo odm validation",
url="http://github.com/gamechanger/mongothon",
packages=["mongothon"],
long_description="Mongothon is a MongoDB object-document mapping " +
"API for Python, loosely based on the awesome " +
"mongoose.js library.",
install_requires=['pymongo>=2.5.0', 'inflection==0.2.0', 'schemer==0.2.1'],
tests_require=['mock', 'nose']
)
|
Fix build.xml (add javadoc target) and fix version numbers in V8 impl
Review URL: https://chromiumcodereview.appspot.com/10693036
git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@1010 fc8a088e-31da-11de-8fef-1f5ae417a2df
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk.internal.v8native;
import org.chromium.sdk.Version;
/**
* Stores milestone version numbers that marks when a particular feature was implemented.
*/
public class V8VersionFeatures {
private final static Version ACCURATE_RUNNING_FIELD = new Version(1, 3, 16);
public static boolean isRunningAccurate(Version vmVersion) {
return vmVersion != null && ACCURATE_RUNNING_FIELD.compareTo(vmVersion) <= 0;
}
private final static Version REG_EXP_BREAKPOINT = new Version(3, 4, 7);
public static boolean isRegExpBreakpointSupported(Version vmVersion) {
return vmVersion != null && REG_EXP_BREAKPOINT.compareTo(vmVersion) <= 0;
}
private final static Version FUNCTION_SCOPE = new Version(3, 10, 7);
public static boolean isFunctionScopeSupported(Version vmVersion) {
return vmVersion != null && FUNCTION_SCOPE.compareTo(vmVersion) <= 0;
}
private final static Version RESTART_FRAME = new Version(3, 12, 0);
public static boolean isRestartFrameSupported(Version vmVersion) {
return vmVersion != null && RESTART_FRAME.compareTo(vmVersion) <= 0;
}
}
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk.internal.v8native;
import org.chromium.sdk.Version;
/**
* Stores milestone version numbers that marks when a particular feature was implemented.
*/
public class V8VersionFeatures {
private final static Version ACCURATE_RUNNING_FIELD = new Version(1, 3, 16);
public static boolean isRunningAccurate(Version vmVersion) {
return vmVersion != null && ACCURATE_RUNNING_FIELD.compareTo(vmVersion) <= 0;
}
private final static Version REG_EXP_BREAKPOINT = new Version(3, 4, 7);
public static boolean isRegExpBreakpointSupported(Version vmVersion) {
return vmVersion != null && REG_EXP_BREAKPOINT.compareTo(vmVersion) <= 0;
}
private final static Version FUNCTION_SCOPE = new Version(3, 10, 7);
public static boolean isFunctionScopeSupported(Version vmVersion) {
return vmVersion != null && FUNCTION_SCOPE.compareTo(vmVersion) < 0;
}
private final static Version RESTART_FRAME = new Version(3, 12, 0);
public static boolean isRestartFrameSupported(Version vmVersion) {
return vmVersion != null && RESTART_FRAME.compareTo(vmVersion) < 0;
}
}
|
Include spider name in item dedupe pipeline
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
ref = (spider.name, item['ref'])
if ref in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(ref)
return item
class ApplySpiderNamePipeline(object):
def process_item(self, item, spider):
existing_extras = item.get('extras', {})
existing_extras['@spider'] = spider.name
item['extras'] = existing_extras
return item
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
ref = item['ref']
if ref in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(ref)
return item
class ApplySpiderNamePipeline(object):
def process_item(self, item, spider):
existing_extras = item.get('extras', {})
existing_extras['@spider'] = spider.name
item['extras'] = existing_extras
return item
|
Add sourceIsTarget for Android client to work
|
package algorithms;
import graphrep.GraphRep;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NNLookupFactory extends GraphAlgorithmFactory {
public NNLookupFactory(GraphRep graph) {
super(graph);
}
@Override
public List<Map<String, Object>> getPointConstraints() {
return null;
}
@Override
public Map<String, Object> getConstraints() {
Map<String, Object> map = new HashMap<String, Object>(2);
map.put("minPoints", Integer.valueOf(1));
map.put("sourceIsTarget", Boolean.FALSE);
return map;
}
/*
* (non-Javadoc)
*
* @see algorithms.AlgorithmFactory#createAlgorithm()
*/
@Override
public Algorithm createAlgorithm() {
return new NNLookup(graph);
}
@Override
public String getURLSuffix() {
return "nnl";
}
@Override
public String getAlgName() {
return "Nearest Neighbor Lookup";
}
@Override
public int getVersion() {
return 1;
}
}
|
package algorithms;
import graphrep.GraphRep;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NNLookupFactory extends GraphAlgorithmFactory {
public NNLookupFactory(GraphRep graph) {
super(graph);
}
@Override
public List<Map<String, Object>> getPointConstraints() {
return null;
}
@Override
public Map<String, Object> getConstraints() {
Map<String, Object> map = new HashMap<String, Object>(2);
map.put("minPoints", Integer.valueOf(1));
return map;
}
/*
* (non-Javadoc)
*
* @see algorithms.AlgorithmFactory#createAlgorithm()
*/
@Override
public Algorithm createAlgorithm() {
return new NNLookup(graph);
}
@Override
public String getURLSuffix() {
return "nnl";
}
@Override
public String getAlgName() {
return "Nearest Neighbor Lookup";
}
@Override
public int getVersion() {
return 1;
}
}
|
Support for meta and selectAccount properties.
Added meta parameter and selectAccount component property.
|
import Ember from 'ember';
const OPTIONS = ['clientName', 'product', 'key', 'env', 'webhook', 'longtail', 'selectAccount'];
const DEFAULT_LABEL = 'Link Bank Account';
export default Ember.Component.extend({
tagName: 'button',
type: 'button',
action: 'processPlaidToken',
attributeBindings: ['type'],
label: DEFAULT_LABEL,
institution: null,
clientName: null,
product: null,
key: null,
env: null,
webhook: null,
selectAccount: null,
_link: null,
_open: Ember.on('click', function() {
this._link.open(this.get('institution'));
}),
_setup: Ember.on('init', function() {
const options = Ember.merge(this.getProperties(OPTIONS), {
onSuccess: this._onSuccess.bind(this)
});
this._link = Plaid.create(options);
}),
_onSuccess: function(token, meta) {
this.sendAction('action', token, meta);
}
});
|
import Ember from 'ember';
const OPTIONS = ['clientName', 'product', 'key', 'env', 'webhook', 'longtail', 'selectAccount'];
const DEFAULT_LABEL = 'Link Bank Account';
export default Ember.Component.extend({
tagName: 'button',
type: 'button',
action: 'processPlaidToken',
attributeBindings: ['type'],
label: DEFAULT_LABEL,
institution: null,
clientName: null,
product: null,
key: null,
env: null,
webhook: null,
_link: null,
_open: Ember.on('click', function() {
this._link.open(this.get('institution'));
}),
_setup: Ember.on('init', function() {
const options = Ember.merge(this.getProperties(OPTIONS), {
onSuccess: this._onSuccess.bind(this)
});
this._link = Plaid.create(options);
}),
_onSuccess: function(token) {
this.sendAction('action', token);
}
});
|
Fix extending service provider name
|
<?php
/*
* This file is part of Laravel Carriers.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Carriers.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Carriers;
use BrianFaust\Carriers\Console\SeedCarriers;
use BrianFaust\ServiceProvider\AbstractServiceProvider;
class CarriersServiceProvider extends AbstractServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
$this->publishMigrations();
}
/**
* Register the application services.
*/
public function register(): void
{
parent::register();
$this->commands(SeedCarriers::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides(): array
{
return array_merge(parent::provides(), [
SeedCarriers::class,
]);
}
/**
* Get the default package name.
*
* @return string
*/
public function getPackageName(): string
{
return 'carriers';
}
}
|
<?php
/*
* This file is part of Laravel Carriers.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Carriers.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Carriers;
use BrianFaust\Carriers\Console\SeedCarriers;
use BrianFaust\ServiceProvider\ServiceProvider;
class CarriersServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot(): void
{
$this->publishMigrations();
}
/**
* Register the application services.
*/
public function register(): void
{
parent::register();
$this->commands(SeedCarriers::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides(): array
{
return array_merge(parent::provides(), [
SeedCarriers::class,
]);
}
/**
* Get the default package name.
*
* @return string
*/
public function getPackageName(): string
{
return 'carriers';
}
}
|
Remove JSON serialization usages (PY-16388, PY-16389)
|
import sys
IS_PY3K = False
try:
if sys.version_info[0] >= 3:
IS_PY3K = True
except AttributeError:
pass #Not all versions have sys.version_info
if IS_PY3K:
# noinspection PyUnresolvedReferences
from thriftpy3 import TSerialization
# noinspection PyUnresolvedReferences
from thriftpy3.protocol import TBinaryProtocol
# noinspection PyUnresolvedReferences
from profilerpy3.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
else:
# noinspection PyUnresolvedReferences
from thrift import TSerialization
# noinspection PyUnresolvedReferences
from thrift.protocol import TBinaryProtocol
# noinspection PyUnresolvedReferences
from profiler.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
|
import sys
IS_PY3K = False
try:
if sys.version_info[0] >= 3:
IS_PY3K = True
except AttributeError:
pass #Not all versions have sys.version_info
if IS_PY3K:
# noinspection PyUnresolvedReferences
from thriftpy3 import TSerialization
# noinspection PyUnresolvedReferences
from thriftpy3.protocol import TJSONProtocol, TBinaryProtocol
# noinspection PyUnresolvedReferences
from profilerpy3.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
else:
# noinspection PyUnresolvedReferences
from thrift import TSerialization
# noinspection PyUnresolvedReferences
from thrift.protocol import TJSONProtocol, TBinaryProtocol
# noinspection PyUnresolvedReferences
from profiler.ttypes import ProfilerRequest, ProfilerResponse, Stats, FuncStat, Function
|
Add usage of nbins_cats to RF pyunit.
|
import sys
sys.path.insert(1, "../../../")
import h2o
def bigcatRF(ip,port):
# Connect to h2o
h2o.init(ip,port)
# Training set has 100 categories from cat001 to cat100
# Categories cat001, cat003, ... are perfect predictors of y = 1
# Categories cat002, cat004, ... are perfect predictors of y = 0
#Log.info("Importing bigcat_5000x2.csv data...\n")
bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv"))
bigcat["y"] = bigcat["y"].asfactor()
#Log.info("Summary of bigcat_5000x2.csv from H2O:\n")
#bigcat.summary()
# Train H2O DRF Model:
#Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100, nbins_cats=10\n")
model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100, nbins_cats=10)
model.show()
if __name__ == "__main__":
h2o.run_test(sys.argv, bigcatRF)
|
import sys
sys.path.insert(1, "../../../")
import h2o
def bigcatRF(ip,port):
# Connect to h2o
h2o.init(ip,port)
# Training set has 100 categories from cat001 to cat100
# Categories cat001, cat003, ... are perfect predictors of y = 1
# Categories cat002, cat004, ... are perfect predictors of y = 0
#Log.info("Importing bigcat_5000x2.csv data...\n")
bigcat = h2o.import_frame(path=h2o.locate("smalldata/gbm_test/bigcat_5000x2.csv"))
bigcat["y"] = bigcat["y"].asfactor()
#Log.info("Summary of bigcat_5000x2.csv from H2O:\n")
#bigcat.summary()
# Train H2O DRF Model:
#Log.info("H2O DRF (Naive Split) with parameters:\nclassification = TRUE, ntree = 1, depth = 1, nbins = 100\n")
model = h2o.random_forest(x=bigcat[["X"]], y=bigcat["y"], ntrees=1, max_depth=1, nbins=100)
model.show()
if __name__ == "__main__":
h2o.run_test(sys.argv, bigcatRF)
|
Fix sort order since we now display the module logo right aligned to the module name cell
|
jQuery(function ($) {
setup_search_box();
$('.tablesorter').tablesorter({
sortList: [[1,0]],
headers: {
1: { sorter: 'text'},
2: { sorter: false }
}
});
});
function setup_search_box() {
var el = $('#my_search_box .search');
if ( ! el.length ) { return; }
// Here we have logic for handling cases where user views a repo
// and then presses "Back" to go back to the list. We want to
// (a) NOT scroll to search input if scroll position is offset.
// This is a "Back" after scrolling and viewing a repo
// (b) Refresh 'search' if search input has some text.
// This is a "Back" after clicking on search results
if ( $(window).scrollTop() == 0 ) {
el.focus();
}
if ( el.val().length ) {
userList.search(el.val());
}
}
|
jQuery(function ($) {
setup_search_box();
$('.tablesorter').tablesorter({
sortList: [[1,0]],
headers: {
0: { sorter: false },
1: { sorter: 'text'},
3: { sorter: false }
}
});
});
function setup_search_box() {
var el = $('#my_search_box .search');
if ( ! el.length ) { return; }
// Here we have logic for handling cases where user views a repo
// and then presses "Back" to go back to the list. We want to
// (a) NOT scroll to search input if scroll position is offset.
// This is a "Back" after scrolling and viewing a repo
// (b) Refresh 'search' if search input has some text.
// This is a "Back" after clicking on search results
if ( $(window).scrollTop() == 0 ) {
el.focus();
}
if ( el.val().length ) {
userList.search(el.val());
}
}
|
Add buffer test package information
|
/*
Copyright (c) 2014, Colorado State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/
/**
* Tests client-side buffer functionality to ensure that a client queueing too
* many messages does not completely exhaust its own memory.
* <p>
* This functionality is particularly relevant when the client is generating raw
* data rather than reading it from a source and storing it in memory before
* transmission.
*/
package galileo.test.buffer;
|
/*
Copyright (c) 2014, Colorado State University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/
/**
* Tests the client-side send buffer, which can be modified with the
* galileo.net.MessageRouter.writeQueueSize system property. This buffer
* prevents clients from trying to send so much data that they run out of
* memory. Since the send operation won't block, an application can easily
* generate too much data before the network operations are complete.
*/
package galileo.test.buffer;
|
Reduce grid layout logic delay.
|
module.exports = Zeppelin.CollectionView.extend({
tagName: 'ol',
className: 'cards-list list-unstyled clearfix',
subscriptions: {
'cardsList:layout': 'triggerLayout'
},
itemView: function(model) {
return require('account/views/' + model.get('type'));
},
collection: function() {
return App.Cards;
},
initialize: function() {
this.$parent = $('div.content');
_.bindAll(this, ['layout']);
},
onRenderItems: function() {
this.wall = new freewall(this.$list);
this.triggerLayout();
},
onAppendItem: function() {
if (!this.isFirstCollectionRender()) this.layout();
},
triggerLayout: function() {
_.delay(this.layout, 1);
},
layout: function() {
this.wall.reset({
delay: 0,
cellW: 222,
cellH: 222,
animate: false,
selector: 'li.card',
onResize: _.bind(function() {
this.wall.fitWidth();
}, this)
});
this.wall.fitWidth(this.$parent.width());
}
});
|
module.exports = Zeppelin.CollectionView.extend({
tagName: 'ol',
className: 'cards-list list-unstyled clearfix',
subscriptions: {
'cardsList:layout': 'triggerLayout'
},
itemView: function(model) {
return require('account/views/' + model.get('type'));
},
collection: function() {
return App.Cards;
},
initialize: function() {
this.$parent = $('div.content');
_.bindAll(this, ['layout']);
},
onRenderItems: function() {
this.wall = new freewall(this.$list);
this.triggerLayout();
},
onAppendItem: function() {
if (!this.isFirstCollectionRender()) this.layout();
},
triggerLayout: function() {
_.delay(this.layout, 10);
},
layout: function() {
this.wall.reset({
delay: 0,
cellW: 222,
cellH: 222,
animate: false,
selector: 'li.card',
onResize: _.bind(function() {
this.wall.fitWidth();
}, this)
});
this.wall.fitWidth(this.$parent.width());
}
});
|
Revert "[FIX] website_quote: make 'Pay & Confirm' work without website_sale"
No dependency change in stable version
This reverts commit 65a589eb54a1421baa71074701bea2873a83c75f.
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Online Proposals',
'category': 'Website',
'summary': 'Sales',
'website': 'https://www.odoo.com/page/quote-builder',
'version': '1.0',
'description': "",
'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail'],
'data': [
'data/website_quote_data.xml',
'report/sale_order_reports.xml',
'report/sale_order_templates.xml',
'report/website_quote_templates.xml',
'views/sale_order_views.xml',
'views/sale_quote_views.xml',
'views/website_quote_templates.xml',
'views/res_config_settings_views.xml',
'security/ir.model.access.csv',
],
'demo': [
'data/website_quote_demo.xml'
],
'qweb': ['static/src/xml/*.xml'],
'installable': True,
}
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Online Proposals',
'category': 'Website',
'summary': 'Sales',
'website': 'https://www.odoo.com/page/quote-builder',
'version': '1.0',
'description': "",
'depends': ['website', 'sale_management', 'mail', 'payment', 'website_mail', 'sale_payment'],
'data': [
'data/website_quote_data.xml',
'report/sale_order_reports.xml',
'report/sale_order_templates.xml',
'report/website_quote_templates.xml',
'views/sale_order_views.xml',
'views/sale_quote_views.xml',
'views/website_quote_templates.xml',
'views/res_config_settings_views.xml',
'security/ir.model.access.csv',
],
'demo': [
'data/website_quote_demo.xml'
],
'qweb': ['static/src/xml/*.xml'],
'installable': True,
}
|
Improve print message for the server address
|
#!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on http://{ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
import subprocess
import sys
def main():
ip = '127.0.0.1'
port = 5000
workers_count = 4
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
if ':' in arg:
ip, port = arg.split(':')
port = int(port)
break
if '.' in arg:
ip = arg
if arg.isdigit():
port = int(arg)
print('FluCalc started on {ip}:{port}'.format(ip=ip, port=port))
subprocess.run('gunicorn -w {workers_count} -b {ip}:{port} flucalc.server:app'.format(
workers_count=workers_count, ip=ip, port=port
), shell=True)
if __name__ == '__main__':
main()
|
Change from IDs to pl-js- classes
|
/*!
* Simple Layout Rendering for Pattern Lab
*
* Copyright (c) 2014 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*/
try {
/* load pattern nav */
var template = document.querySelector(".pl-js-pattern-nav-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(navItems);
document.querySelector(".pl-js-pattern-nav-target").innerHTML = templateRendered;
/* load ish controls */
var template = document.querySelector(".pl-js-ish-controls-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(ishControls);
document.querySelector(".pl-js-controls").innerHTML = templateRendered;
} catch(e) {
var message = "<p>Please generate your site before trying to view it.</p>";
document.querySelector(".pl-js-pattern-nav-target").innerHTML = message;
}
|
/*!
* Simple Layout Rendering for Pattern Lab
*
* Copyright (c) 2014 Dave Olsen, http://dmolsen.com
* Licensed under the MIT license
*/
try {
/* load pattern nav */
var template = document.getElementById("pl-pattern-nav-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(navItems);
document.querySelector(".pl-js-pattern-nav-target").innerHTML = templateRendered;
/* load ish controls */
var template = document.getElementById("pl-ish-controls-template");
var templateCompiled = Hogan.compile(template.innerHTML);
var templateRendered = templateCompiled.render(ishControls);
document.querySelector(".pl-js-controls").innerHTML = templateRendered;
} catch(e) {
var message = "<p>Please generate your site before trying to view it.</p>";
document.querySelector(".pl-js-pattern-nav-target").innerHTML = message;
}
|
Increase integration cli test memory
Signed-off-by: Euan <82ce0a5f500076a0414f27984d8e19adc458729b@amazon.com>
|
// +build !windows
package main
import (
"github.com/docker/docker/pkg/integration/checker"
"github.com/go-check/check"
)
func (s *DockerSuite) TestInspectOomKilledTrue(c *check.C) {
testRequires(c, DaemonIsLinux, memoryLimitSupport)
name := "testoomkilled"
_, exitCode, _ := dockerCmdWithError("run", "--name", name, "--memory", "32MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
c.Assert(exitCode, checker.Equals, 137, check.Commentf("OOM exit should be 137"))
oomKilled, err := inspectField(name, "State.OOMKilled")
c.Assert(oomKilled, checker.Equals, "true")
c.Assert(err, checker.IsNil)
}
func (s *DockerSuite) TestInspectOomKilledFalse(c *check.C) {
testRequires(c, DaemonIsLinux, memoryLimitSupport)
name := "testoomkilled"
dockerCmd(c, "run", "--name", name, "--memory", "32MB", "busybox", "sh", "-c", "echo hello world")
oomKilled, err := inspectField(name, "State.OOMKilled")
c.Assert(oomKilled, checker.Equals, "false")
c.Assert(err, checker.IsNil)
}
|
// +build !windows
package main
import (
"github.com/docker/docker/pkg/integration/checker"
"github.com/go-check/check"
)
func (s *DockerSuite) TestInspectOomKilledTrue(c *check.C) {
testRequires(c, DaemonIsLinux, memoryLimitSupport)
name := "testoomkilled"
_, exitCode, _ := dockerCmdWithError("run", "--name", name, "-m", "10MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
c.Assert(exitCode, checker.Equals, 137, check.Commentf("OOM exit should be 137"))
oomKilled, err := inspectField(name, "State.OOMKilled")
c.Assert(oomKilled, checker.Equals, "true")
c.Assert(err, checker.IsNil)
}
func (s *DockerSuite) TestInspectOomKilledFalse(c *check.C) {
testRequires(c, DaemonIsLinux, memoryLimitSupport)
name := "testoomkilled"
dockerCmd(c, "run", "--name", name, "-m", "10MB", "busybox", "sh", "-c", "echo hello world")
oomKilled, err := inspectField(name, "State.OOMKilled")
c.Assert(oomKilled, checker.Equals, "false")
c.Assert(err, checker.IsNil)
}
|
refactor(match): Change for loop to Array.find
|
import resolveNode from "./resolveNode";
// import {resolve} from "path";
export default function (filename, regexps, root, extensions) {
const redirectPair = regexps.find(([regexp]) => regexp.test(filename));
if(redirectPair) {
let [regexp, redirect] = redirectPair;
console.log("FOUND MATCH", regexp);
console.log("REDIRECTING TO", redirect);
// if redirect is of "different/path/$1.js" form
if(/\$\d/.test(redirect)) {
// "abs/path/to/path/lib.js".match(/path/(\w+).js$/)[0] ->
// "path/lib.js".replace(/path/(\w+).js$/, "different/path/$1.js") ->
// "different/path/lib.js"
redirect = filename.match(regexp)[0].replace(regexp, redirect);
}
// return resolve(root, redirect);
return {
redirected: resolveNode(root, redirect, extensions),
redirect
};
}
return null;
}
|
import resolveNode from "./resolveNode";
// import {resolve} from "path";
export default function (filename, regexps, root, extensions) {
for(let redirectPair of regexps) {
const regexp = redirectPair[0];
if(regexp.test(filename)) {
console.log("FOUND MATCH", regexp);
let redirect = redirectPair[1];
console.log("REDIRECTING TO", redirect);
// if redirect is of "different/path/$1.js" form
if(/\$\d/.test(redirect)) {
// "abs/path/to/path/lib.js".match(/path/(\w+).js$/)[0] ->
// "path/lib.js".replace(/path/(\w+).js$/, "different/path/$1.js") ->
// "different/path/lib.js"
redirect = filename.match(regexp)[0].replace(regexp, redirect);
}
// return resolve(root, redirect);
return {
redirected: resolveNode(root, redirect, extensions),
redirect
};
}
}
return null;
}
|
Replace deprecated use of `bw.openDevTools`
|
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Open the DevTools.
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
|
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Report crashes to our server.
require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app.
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Open the DevTools.
mainWindow.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
|
[Bugfix] Correct misspelled method name 'contant' to 'constant'
|
(function() {
'use strict';
angular.module('app', [
'app.config',
'app.core',
'app.feature'
]);
angular.module('app').config([
'$logProvider', 'LOG', '$locationProvider',
function($logProvider, log, $locationProvider) {
// Enable or disable debug logging
$logProvider.debugEnabled(log.ENABLE_DEBUG);
$locationProvider.html5Mode(false);
}
]);
// CONFIG SETTINGS
angular.module('app.config', [])
// Log settings
.constant('LOG', {
ENABLE_DEBUG: true
})
.constant('WEATHER_SETTINGS', {
OPEN_WEATHER_MAP: {
BASE_URI: 'http://api.openweathermap.org/data/2.5',
API_KEY: '<api-key>',
CITY_ID: '2925550',
LANGUAGE_ID: 'de',
UNITS: 'metric'
}
});
})();
|
(function() {
'use strict';
angular.module('app', [
'app.config',
'app.core',
'app.feature'
]);
angular.module('app').config([
'$logProvider', 'LOG', '$locationProvider',
function($logProvider, log, $locationProvider) {
// Enable or disable debug logging
$logProvider.debugEnabled(log.ENABLE_DEBUG);
$locationProvider.html5Mode(false);
}
]);
// CONFIG SETTINGS
angular.module('app.config', [])
// Log settings
.constant('LOG', {
ENABLE_DEBUG: true
})
.contant('WEATHER_SETTINGS', {
OPEN_WEATHER_MAP: {
BASE_URI: 'http://api.openweathermap.org/data/2.5',
API_KEY: '<api-key>',
CITY_ID: '2925550',
LANGUAGE_ID: 'de',
UNITS: 'metric'
}
});
})();
|
Make a variable out of the refresh timeout for testing purposes
|
package cache
import (
"encoding/json"
"github.com/centurylinkcloud/clc-go-cli/state"
"time"
)
var (
LONG_AUTOCOMPLETE_REFRESH_TIMEOUT = 30 // seconds
)
func Put(key string, opts []string) {
data, err := json.Marshal(opts)
if err == nil {
state.WriteToFile(data, key, 0666)
}
}
func Get(key string) ([]string, bool) {
info, err := state.GetFileInfo(key)
if err != nil {
return nil, false
}
if time.Now().Sub(info.ModTime()) > time.Second*time.Duration(LONG_AUTOCOMPLETE_REFRESH_TIMEOUT) {
return nil, false
}
data, err := state.ReadFromFile(key)
if err != nil {
return nil, false
}
opts := []string{}
err = json.Unmarshal(data, &opts)
if err != nil {
return nil, false
}
return opts, true
}
|
package cache
import (
"encoding/json"
"github.com/centurylinkcloud/clc-go-cli/state"
"time"
)
const (
LONG_AUTOCOMPLETE_REFRESH_TIMEOUT = 30 // seconds
)
func Put(key string, opts []string) {
data, err := json.Marshal(opts)
if err == nil {
state.WriteToFile(data, key, 0666)
}
}
func Get(key string) ([]string, bool) {
info, err := state.GetFileInfo(key)
if err != nil {
return nil, false
}
if time.Now().Sub(info.ModTime()) > time.Second*LONG_AUTOCOMPLETE_REFRESH_TIMEOUT {
return nil, false
}
data, err := state.ReadFromFile(key)
if err != nil {
return nil, false
}
opts := []string{}
err = json.Unmarshal(data, &opts)
if err != nil {
return nil, false
}
return opts, true
}
|
Update Marbles.State: Add willUpdate/didUpdate hooks
|
//= require ./core
(function () {
"use strict";
/*
* State object mixin
*
* Requires Object `state` and Array `__changeListeners` properties
*/
Marbles.State = {
addChangeListener: function (handler) {
this.__changeListeners.push(handler);
},
removeChangeListener: function (handler) {
this.__changeListeners = this.__changeListeners.filter(function (fn) {
return fn !== handler;
});
},
setState: function (newState) {
this.willUpdate();
var state = this.state;
Object.keys(newState).forEach(function (key) {
state[key] = newState[key];
});
this.handleChange();
this.didUpdate();
},
replaceState: function (newState) {
this.willUpdate();
this.state = newState;
this.handleChange();
this.didUpdate();
},
handleChange: function () {
this.__changeListeners.forEach(function (handler) {
handler();
});
},
willUpdate: function () {},
didUpdate: function () {}
};
})();
|
//= require ./core
(function () {
"use strict";
/*
* State object mixin
*
* Requires Object `state` and Array `__changeListeners` properties
*/
Marbles.State = {
addChangeListener: function (handler) {
this.__changeListeners.push(handler);
},
removeChangeListener: function (handler) {
this.__changeListeners = this.__changeListeners.filter(function (fn) {
return fn !== handler;
});
},
setState: function (newState) {
var state = this.state;
Object.keys(newState).forEach(function (key) {
state[key] = newState[key];
});
this.handleChange();
},
replaceState: function (newState) {
this.state = newState;
this.handleChange();
},
handleChange: function () {
this.__changeListeners.forEach(function (handler) {
handler();
});
}
};
})();
|
Fix textarea / label association
|
var html = require('choo/html')
var picoModal = require('picomodal')
var _ = require('../util')
module.exports = function (props, emit) {
var moves = _.chunksOf(2, props.game.game.moveHistory)
.map(function (move, idx) {
return (idx + 1) + '. ' + move[0].algebraic + (move[1] ? (' ' + move[1].algebraic) : '')
})
.join('\n')
var modal
function handleFocus (e) {
e.target.select()
}
modal = picoModal(html`
<div>
<label for="move-history-textarea">
Copy & paste move history to send to a friend
</label>
<textarea id="move-history-textarea" onfocus=${handleFocus} readonly=${true}>${moves}</textarea>
</div>
`).afterClose(function () {
emit('closeModal')
modal.destroy()
}).show()
return modal
}
|
var html = require('choo/html')
var picoModal = require('picomodal')
var _ = require('../util')
module.exports = function (props, emit) {
var moves = _.chunksOf(2, props.game.game.moveHistory)
.map(function (move, idx) {
return (idx + 1) + '. ' + move[0].algebraic + (move[1] ? (' ' + move[1].algebraic) : '')
})
.join('\n')
var modal
function handleFocus (e) {
e.target.select()
}
modal = picoModal(html`
<div>
<label for="move-history-textarea">
Copy & paste move history to send to a friend
</label>
<textarea onfocus=${handleFocus} readonly=${true}>${moves}</textarea>
</div>
`).afterClose(function () {
emit('closeModal')
modal.destroy()
}).show()
return modal
}
|
Add conditional logic to support asset path resolution for both autocomplete-python and atom-plugin.
|
const fs = require('fs');
const path = require('path');
let LogoPath = '../../../assets/logo.svg';
let LogoSmallPath = '../../../assets/logo-small.svg';
let ScreenshotPath = '../../../assets/plotscreenshot.png';
let DemoVideoPath = '../../../assets/demo.mp4';
let InstallLessPath = '../../../styles/install.less';
// Environment variable set by consumer repository using Webpack Plugins via config.
if (process.env.USING_WEBPACK_FILELOADER_TO_BUNDLE) {
const WEBPACK_FILELOADER_PATH_KEY = "default";
LogoPath = require('../../../assets/logo.svg')[WEBPACK_FILELOADER_PATH_KEY];
LogoSmallPath = require('../../../assets/logo-small.svg')[WEBPACK_FILELOADER_PATH_KEY];
ScreenshotPath = require('../../../assets/plotscreenshot.png')[WEBPACK_FILELOADER_PATH_KEY];
DemoVideoPath = require('../../../assets/demo.mp4')[WEBPACK_FILELOADER_PATH_KEY];
InstallLessPath = require('../../../styles/install.less')[WEBPACK_FILELOADER_PATH_KEY];
}
const logo = String(fs.readFileSync(path.resolve(__dirname, LogoPath)));
const logoSmall = String(fs.readFileSync(path.resolve(__dirname, LogoSmallPath)));
const screenshot = path.resolve(__dirname, ScreenshotPath);
const demoVideo = path.resolve(__dirname, DemoVideoPath);
const installLess = path.resolve(__dirname, InstallLessPath);
module.exports = {logo, logoSmall, screenshot, demoVideo, installLess};
|
const fs = require('fs');
const path = require('path');
const WEBPACK_FILELOADER_PATH_KEY = "default";
const LogoPath = require('../../../assets/logo.svg')[WEBPACK_FILELOADER_PATH_KEY];
const LogoSmallPath = require('../../../assets/logo-small.svg')[WEBPACK_FILELOADER_PATH_KEY];
const ScreenshotPath = require('../../../assets/plotscreenshot.png')[WEBPACK_FILELOADER_PATH_KEY];
const DemoVideoPath = require('../../../assets/demo.mp4')[WEBPACK_FILELOADER_PATH_KEY];
const InstallLessPath = require('../../../styles/install.less')[WEBPACK_FILELOADER_PATH_KEY];
const logo = String(fs.readFileSync(path.resolve(__dirname, LogoPath)));
const logoSmall = String(fs.readFileSync(path.resolve(__dirname, LogoSmallPath)));
const screenshot = path.resolve(__dirname, ScreenshotPath);
const demoVideo = path.resolve(__dirname, DemoVideoPath);
const installLess = path.resolve(__dirname, InstallLessPath);
module.exports = {logo, logoSmall, screenshot, demoVideo, installLess};
|
Add console logging to script
|
var _ = require('underscore');
var AWS = require('aws-sdk');
var moment = require('moment');
var DynamoBackup = require('./lib/dynamo-backup');
var runningAsScript = require.main === module;
if (runningAsScript) {
var runTimes = {};
var dynamoBackup = new DynamoBackup({ bucket: 'markitx-backups-test', stopOnFailure: true, readPercentage: .5 });
dynamoBackup.on('error', function(data) {
console.log('Error backing up ' + data.tableName);
console.log(data.error);
process.exit();
});
dynamoBackup.on('start-backup', function(tableName) {
runTimes[tableName] = moment();
console.log('Starting to copy table ' + tableName);
});
dynamoBackup.on('end-backup', function(tableName) {
var endTime = moment();
var startTime = runTimes[tableName];
console.log('Done copying table ' + tableName + '. Took ' + endTime.diff(startTime, 'minutes', true).toFixed(2) + ' minutes');
});
dynamoBackup.backupAllTables(function() {
console.log('Finished backing up DynamoDB');
});
} else {
module.exports = DynamoBackup;
}
|
var _ = require('underscore');
var AWS = require('aws-sdk');
var moment = require('moment');
var path = require('path');
var async = require('async');
var Uploader = require('s3-streaming-upload').Uploader;
var DynamoBackup = require('./lib/dynamo-backup');
var runningAsScript = require.main === module;
if (runningAsScript) {
var dynamoBackup = new DynamoBackup({ bucket: 'markitx-backups-test', stopOnFailure: true, readPercentage: .5, includedTables: ['development-asset-projects'] });
dynamoBackup.on('error', function(data) {
console.log('Error backing up ' + data.tableName);
console.log(data.error);
process.exit();
});
dynamoBackup.backupAllTables(function() {
console.log('Finished backing up DynamoDB');
});
} else {
module.exports = DynamoBackup;
}
|
Check if brfss data for years 2000 to 2010 available
|
from survey_stats.datasets import SurveyDataset
from survey_stats import log
lgr = log.getLogger(__name__)
dset = {}
def initialize(dbc, cache, init_des, use_feather, init_svy, init_soc):
lgr.info('was summoned into being, loading up some data', dbc=dbc, cache=cache, use_feather=use_feather)
dset['brfss'] = SurveyDataset.load_dataset('config/data/brfss.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['yrbss'] = SurveyDataset.load_dataset('config/data/yrbss.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['prams'] = SurveyDataset.load_dataset('config/data/prams.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['prams_p2011'] = SurveyDataset.load_dataset('config/data/prams_p2011.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
|
from survey_stats.datasets import SurveyDataset
from survey_stats import log
lgr = log.getLogger(__name__)
dset = {}
def initialize(dbc, cache, init_des, use_feather, init_svy, init_soc):
lgr.info('was summoned into being, loading up some data', dbc=dbc, cache=cache, use_feather=use_feather)
dset['brfss'] = SurveyDataset.load_dataset('config/data/brfss.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['brfss_pre2011'] = SurveyDataset.load_dataset('config/data/brfss_pre2011.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['yrbss'] = SurveyDataset.load_dataset('config/data/yrbss.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['prams'] = SurveyDataset.load_dataset('config/data/prams.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
dset['prams_p2011'] = SurveyDataset.load_dataset('config/data/prams_p2011.yaml', dbc, cache, init_des, use_feather, init_svy, init_soc)
|
Add placeholder attribute to textarea
|
<?php namespace Laraplus\Form\Fields;
use Laraplus\Form\Fields\Base\Element;
class TextArea extends Element
{
/**
* @param string $cols
* @return $this
*/
public function cols($cols)
{
$this->attributes['cols'] = $cols;
return $this;
}
/**
* @param string $rows
* @return $this
*/
public function rows($rows)
{
$this->attributes['rows'] = $rows;
return $this;
}
/**
* @param string $placeholder
* @return $this
*/
public function placeholder($placeholder)
{
$this->attributes['placeholder'] = $placeholder;
return $this;
}
/**
* @return string
*/
public function render()
{
$attributes = $this->renderAttributes($this->attributes);
return '<textarea' . $attributes . '>' . htmlspecialchars($this->getValue()) . '</textarea>';
}
}
|
<?php namespace Laraplus\Form\Fields;
use Laraplus\Form\Fields\Base\Element;
class TextArea extends Element
{
/**
* @param string $cols
* @return $this
*/
public function cols($cols)
{
$this->attributes['cols'] = $cols;
return $this;
}
/**
* @param string $rows
* @return $this
*/
public function rows($rows)
{
$this->attributes['rows'] = $rows;
return $this;
}
/**
* @return string
*/
public function render()
{
$attributes = $this->renderAttributes($this->attributes);
return '<textarea' . $attributes . '>' . htmlspecialchars($this->getValue()) . '</textarea>';
}
}
|
Use only absolute imports for python 3
|
"""This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from gaia.pandas.pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from gaia.pandas.geopandas_data import GeopandasDataFrame
from gaia.pandas.geopandas_reader import GeopandasReader
from gaia.pandas.geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from gaia.pandas.xray_data import XrayDataset
__all__ += ('XrayDataset',)
|
"""This package contains interface adapters for pandas.
On import, this package detects if pandas is installed. If it is installed,
then the contained modules are imported to register the pandas classes with
Gaia. If pandas is not found, this package will contain no modules.
"""
try:
import pandas
except ImportError:
pandas = None
__all__ = ()
if pandas is not None:
from pandas_data import PandasDataFrame
__all__ += ('PandasDataFrame',)
try:
import geopandas
except ImportError:
geopandas = None
if geopandas is not None:
from geopandas_data import GeopandasDataFrame
from geopandas_reader import GeopandasReader
from geopandas_plot import GeopandasPlot
__all__ += (
'GeopandasDataFrame',
'GeopandasReader',
'GeopandasPlot'
)
try:
import xray
except ImportError:
xray = None
if xray is not None:
from xray_data import XrayDataset
__all__ += ('XrayDataset',)
|
Fix a bug with an empty database
|
from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.get_from_request(request)
pages = Page.objects.filter(parent__isnull=True).order_by("tree_id")
if len(pages) > 0:
if page_id:
try:
current_page = Page.objects.get(id=int(page_id), status=1)
except Page.DoesNotExist:
raise Http404
else:
# get the first root page
current_page = pages[0]
template = current_page.get_template()
else:
current_page = None
template = settings.DEFAULT_PAGE_TEMPLATE
return template, locals()
|
from pages.models import Page, Language, Content
from pages.utils import auto_render
from django.contrib.admin.views.decorators import staff_member_required
from django import forms
from django.http import Http404
import settings
@auto_render
def details(request, page_id=None):
template = None
lang = Language.get_from_request(request)
pages = Page.objects.filter(parent__isnull=True).order_by("tree_id")
if len(pages) > 0:
if page_id:
try:
current_page = Page.objects.get(id=int(page_id), status=1)
except Page.DoesNotExist:
raise Http404
else:
# get the first root page
current_page = pages[0]
template = current_page.get_template()
else:
template = settings.DEFAULT_PAGE_TEMPLATE
return template, locals()
|
Fix profile photo upload indentation
|
<?
require_once('php/classes/member.php');
$profileEdited = $currentUser;
// TODO: Allow administrators to edit other member's profile pictures
?><div class="row">
<div class="large-12 columns">
<h1>Edit Profile Picture: <?=$profileEdited->rcsid()?></h1>
<p>This picture is displayed publicly on the "About Us" page:</p>
<img src="<?=$profileEdited->photoURL()?>" alt="<?=$profileEdited->fullName()?>">
<p>The new image must be a JPEG (*.jpg) file smaller than 1 MB.</p>
<form enctype="multipart/form-data" action="post.php" method="post">
<input type="hidden" name="rcsid" value="<?=$profileEdited->rcsid()?>">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
<div class="row">
<div class="medium-8 columns">
<input name="new_profile_photo" type="file">
<button type="submit" name="action"
value="profile_photo_edit">Upload</button>
</div>
</div>
</form>
</div>
</div>
|
<?
require_once('php/classes/member.php');
$profileEdited = $currentUser;
// TODO: Allow administrators to edit other member's profile pictures
?><div class="row">
<div class="large-12 columns">
<h1>Edit Profile Picture: <?=$profileEdited->rcsid()?></h1>
<p>This picture is displayed publicly on the "About Us" page:</p>
<img src="<?=$profileEdited->photoURL()?>" alt="<?=$profileEdited->fullName()?>">
<p>The new image must be a JPEG (*.jpg) file smaller than 1 MB.</p>
<form enctype="multipart/form-data" action="post.php" method="post">
<input type="hidden" name="rcsid" value="<?=$profileEdited->rcsid()?>">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576">
<div class="row">
<div class="medium-8 columns">
<input name="new_profile_photo" type="file">
<button type="submit" name="action"
value="profile_photo_edit">Upload</button>
</div>
</div>
</form>
</div>
</div>
|
Make some util functions static
|
package com.impossibl.stencil.api.impl;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import com.google.common.hash.Hashing;
import com.impossibl.stencil.api.TemplateSource;
public class InlineTemplateSource implements TemplateSource {
URI uri;
String text;
public InlineTemplateSource(String text) {
this.text = text;
this.uri = URI.create("file:" + hash(text));
}
static String hash(String text) {
return Hashing.md5().hashString(text).toString();
}
@Override
public void close() throws IOException {
}
@Override
public URI getURI() throws IOException {
return uri;
}
@Override
public Reader openReader() throws IOException {
return new StringReader(text);
}
@Override
public String getTag() throws IOException {
return hash(text);
}
@Override
public String toString() {
return "InlineTemplateSource [" + uri + "]";
}
}
|
package com.impossibl.stencil.api.impl;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URI;
import com.google.common.hash.Hashing;
import com.impossibl.stencil.api.TemplateSource;
public class InlineTemplateSource implements TemplateSource {
URI uri;
String text;
public InlineTemplateSource(String text) {
this.text = text;
this.uri = URI.create("file:" + hash(text));
}
String hash(String text) {
return Hashing.md5().hashString(text).toString();
}
@Override
public void close() throws IOException {
}
@Override
public URI getURI() throws IOException {
return uri;
}
@Override
public Reader openReader() throws IOException {
return new StringReader(text);
}
@Override
public String getTag() throws IOException {
return hash(text);
}
@Override
public String toString() {
return "InlineTemplateSource [" + uri + "]";
}
}
|
Add stability annotation to ol.source.TopoJSON
|
goog.provide('ol.source.TopoJSON');
goog.require('ol.format.TopoJSON');
goog.require('ol.source.VectorFile');
/**
* @constructor
* @extends {ol.source.VectorFile}
* @param {olx.source.TopoJSONOptions=} opt_options Options.
* @todo stability experimental
*/
ol.source.TopoJSON = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, {
attributions: options.attributions,
extent: options.extent,
format: new ol.format.TopoJSON({
defaultProjection: options.defaultProjection
}),
logo: options.logo,
object: options.object,
projection: options.projection,
reprojectTo: options.reprojectTo,
text: options.text,
url: options.url
});
};
goog.inherits(ol.source.TopoJSON, ol.source.VectorFile);
|
goog.provide('ol.source.TopoJSON');
goog.require('ol.format.TopoJSON');
goog.require('ol.source.VectorFile');
/**
* @constructor
* @extends {ol.source.VectorFile}
* @param {olx.source.TopoJSONOptions=} opt_options Options.
*/
ol.source.TopoJSON = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, {
attributions: options.attributions,
extent: options.extent,
format: new ol.format.TopoJSON({
defaultProjection: options.defaultProjection
}),
logo: options.logo,
object: options.object,
projection: options.projection,
reprojectTo: options.reprojectTo,
text: options.text,
url: options.url
});
};
goog.inherits(ol.source.TopoJSON, ol.source.VectorFile);
|
Fix bug when no tools were installed
|
import React from 'react'
import ToolSwitcher from './ToolSwitcher'
import RenderTool from './RenderTool'
import {Router, Route, NotFound, Redirect} from 'router:@sanity/base/router'
import styles from '../styles/DefaultLayout.css'
import tools from 'all:tool:@sanity/base/tool'
import absolutes from 'all:component:@sanity/base/absolutes'
import LoginStatus from './LoginStatus'
import Logo from './Logo'
class DefaultLayout extends React.Component {
render() {
const activeToolName = this.props.params.tool
return (
<div className={styles.defaultLayout}>
<div className={styles.top}>
<div className={styles.logoContainer}>
<Logo />
</div>
<ToolSwitcher tools={tools} activeToolName={activeToolName} className={styles.toolSwitcher} />
<LoginStatus />
</div>
<div className={styles.toolContainer}>
<Router>
<Redirect path="/" to={`/${tools.length ? tools[0].name : ''}`} />
<Route path="/:tool/*" component={RenderTool} />
</Router>
</div>
{absolutes.map((Abs, i) => <Abs key={i} />)}
</div>
)
}
}
export default DefaultLayout
|
import React from 'react'
import ToolSwitcher from './ToolSwitcher'
import RenderTool from './RenderTool'
import {Router, Route, NotFound, Redirect} from 'router:@sanity/base/router'
import styles from '../styles/DefaultLayout.css'
import tools from 'all:tool:@sanity/base/tool'
import absolutes from 'all:component:@sanity/base/absolutes'
import LoginStatus from './LoginStatus'
import Logo from './Logo'
class DefaultLayout extends React.Component {
render() {
const activeToolName = this.props.params.tool
return (
<div className={styles.defaultLayout}>
<div className={styles.top}>
<div className={styles.logoContainer}>
<Logo />
</div>
<ToolSwitcher tools={tools} activeToolName={activeToolName} className={styles.toolSwitcher} />
<LoginStatus />
</div>
<div className={styles.toolContainer}>
<Router>
<Redirect path="/" to={`/${tools[0].name}`} />
<Route path="/:tool/*" component={RenderTool} />
</Router>
</div>
{absolutes.map((Abs, i) => <Abs key={i} />)}
</div>
)
}
}
export default DefaultLayout
|
Comment out wemo stuff for now.
|
"""Wemo proxy code."""
import logging
import sys
import threading
#from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
"""Wemo proxy code."""
import logging
import sys
import threading
from wemo import upnp
class Wemo(object):
"""Hue proxy object."""
def __init__(self, refresh_period, callback):
self._refresh_period = refresh_period
self._callback = callback
def _wemo_callback(self, address, headers):
logging.info('%s, %s', address, headers)
def _set_light(self, message):
"""Turn a light on or off."""
bridge_id = str(message["bridge_id"])
device_id = int(message["device_id"])
mode = message["mode"]
logging.info('bridge_id = %s, device_id = %s, mode = %s',
bridge_id, device_id, mode)
bridge = self._bridges.get(bridge_id, None)
light = bridge[device_id]
light.on = mode
def handle_event(self, message):
"""Handle hue events - turn it on or off."""
command = message.pop('command')
if command == 'light':
self._set_light(message)
elif command == 'scan':
self._trigger_bridge_scan()
else:
logging.info('Unhandled message type \'%s\'', command)
def stop(self):
pass
|
Send JWT token with file uploads
|
import Ember from 'ember';
import EmberUploader from 'ember-uploader';
const { FileField, Uploader } = EmberUploader;
const { inject, computed } = Ember;
const { service } = inject;
let IliosUploader = Uploader.extend({
iliosHeaders: [],
ajaxSettings: computed('iliosHeaders.[]', function() {
return {
headers: this.get('iliosHeaders')
};
}),
});
export default FileField.extend({
session: service(),
url: '',
headers: computed('session.isAuthenticated', function(){
let headers = {};
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
headers[headerName] = headerValue;
});
return headers;
}),
filesDidChange(files) {
const uploadUrl = this.get('url');
const uploader = IliosUploader.create({
url: uploadUrl,
iliosHeaders: this.get('headers')
});
this.sendAction('startUploading');
uploader.on('didUpload', (e) => {
this.sendAction('finishedUploading', e);
});
uploader.on('progress', (e) => {
this.sendAction('setUploadPercentage', e.percent);
});
if (!Ember.isEmpty(files)) {
uploader.upload(files[0]);
}
}
});
|
import Ember from 'ember';
import EmberUploader from 'ember-uploader';
const { FileField, Uploader } = EmberUploader;
const { inject, computed } = Ember;
const { service } = inject;
let IliosUploader = Uploader.extend({
iliosHeaders: [],
ajaxSettings: function() {
let settings = this._super(...arguments);
settings.headers = this.get('iliosHeaders');
return settings;
}
});
export default FileField.extend({
session: service(),
url: '',
headers: computed('session.isAuthenticated', function(){
let headers = {};
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
headers[headerName] = headerValue;
});
return headers;
}),
filesDidChange(files) {
const uploadUrl = this.get('url');
const uploader = IliosUploader.create({
url: uploadUrl,
iliosHeaders: this.get('headers')
});
this.sendAction('startUploading');
uploader.on('didUpload', (e) => {
this.sendAction('finishedUploading', e);
});
uploader.on('progress', (e) => {
this.sendAction('setUploadPercentage', e.percent);
});
if (!Ember.isEmpty(files)) {
uploader.upload(files[0]);
}
}
});
|
Fix style loading in production.
|
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory} from 'react-router'
import configureStore from './store'
import {Provider} from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import APIUtils from './utils/APIUtils'
import { AppContainer } from 'react-hot-loader'
import {makeRoutes} from './routes'
import '../stylus/index.styl'
class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Router history={browserHistory}>
{this.props.routes}
</Router>
</Provider>
)
}
}
const api = new APIUtils()
const store = configureStore(api)
const history = syncHistoryWithStore(browserHistory, store)
function render(routes) {
console.log('render')
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>
</AppContainer>,
document.getElementById('app')
)
}
render(makeRoutes())
if (module.hot)
module.hot.accept('./routes', () => render(makeRoutes()))
|
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory} from 'react-router'
import configureStore from './store'
import {Provider} from 'react-redux'
import {syncHistoryWithStore} from 'react-router-redux'
import APIUtils from './utils/APIUtils'
import { AppContainer } from 'react-hot-loader'
import {makeRoutes} from './routes'
// styles are stored separately in production
if (__DEV__)
require('../stylus/index.styl')
// require('bootstrap/dist/css/bootstrap.css')
class Root extends React.Component {
render() {
return (
<Provider store={this.props.store}>
<Router history={browserHistory}>
{this.props.routes}
</Router>
</Provider>
)
}
}
const api = new APIUtils()
const store = configureStore(api)
const history = syncHistoryWithStore(browserHistory, store)
function render(routes) {
console.log('render')
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>
</AppContainer>,
document.getElementById('app')
)
}
render(makeRoutes())
if (module.hot)
module.hot.accept('./routes', () => render(makeRoutes()))
|
Remove .only from test case
|
var should = require('should');
var QueryCompiler = require('../lib/compiler');
describe('QueryCompiler', function () {
describe('compile', function () {
it('compile ne null query', function () {
var query = {
attachmentId: { $ne: null }
};
var compiler = new QueryCompiler();
should.doesNotThrow(function () {
compiler.compile(query);
});
});
});
describe('_compilePredicates', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._compilePredicates({age:10});
p[0]({age:10}).should.be.true;
})
});
describe('_subQuery', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._subQuery([{age:10}]);
p[0]({age:10}).should.be.true;
})
});
});
|
var should = require('should');
var QueryCompiler = require('../lib/compiler');
describe('QueryCompiler', function () {
describe.only('compile', function () {
it('compile ne null query', function () {
var query = {
attachmentId: { $ne: null }
};
var compiler = new QueryCompiler();
should.doesNotThrow(function () {
compiler.compile(query);
});
});
});
describe('_compilePredicates', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._compilePredicates({age:10});
p[0]({age:10}).should.be.true;
})
});
describe('_subQuery', function () {
it('compile eq query', function () {
var compiler = new QueryCompiler();
var p = compiler._subQuery([{age:10}]);
p[0]({age:10}).should.be.true;
})
});
});
|
Fix webpack hot module reload
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app: ['./static/js/src/app.js'],
},
output: {
path: 'static/js/build/',
pathInfo: true,
publicPath: '/static/js/build/',
filename: 'tchaik.js'
},
devtool: 'inline-source-maps',
plugins: [
new webpack.DefinePlugin({
"process.env": Object.keys(process.env).reduce(function(o, k) {
o[k] = JSON.stringify(process.env[k]);
return o;
}, {})
}),
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot-loader', 'babel-loader?stage=0'],
},
{
test: /\.scss$/,
loader: "style!css!sass?outputStyle=expanded&" +
"includePaths[]=" +
(path.resolve(__dirname, "./bower_components")) + "&" +
"includePaths[]=" +
(path.resolve(__dirname, "./node_modules"))
},
]
}
};
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app: ['./static/js/src/app.js'],
},
output: {
path: 'static/js/build',
pathInfo: true,
publicPath: '/static/js/build',
filename: 'tchaik.js'
},
devtool: 'inline-source-maps',
plugins: [
new webpack.DefinePlugin({
"process.env": Object.keys(process.env).reduce(function(o, k) {
o[k] = JSON.stringify(process.env[k]);
return o;
}, {})
}),
],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot-loader', 'babel-loader?stage=0'],
},
{
test: /\.scss$/,
loader: "style!css!sass?outputStyle=expanded&" +
"includePaths[]=" +
(path.resolve(__dirname, "./bower_components")) + "&" +
"includePaths[]=" +
(path.resolve(__dirname, "./node_modules"))
},
]
}
};
|
Change author and bump version.
|
from __future__ import absolute_import
from pyelasticsearch.client import ElasticSearch
from pyelasticsearch.exceptions import (Timeout, ConnectionError,
ElasticHttpError,
InvalidJsonResponseError,
ElasticHttpNotFoundError,
IndexAlreadyExistsError)
__author__ = 'Erik Rose'
__all__ = ['ElasticSearch', 'ElasticHttpError', 'InvalidJsonResponseError',
'Timeout', 'ConnectionError', 'ElasticHttpNotFoundError',
'IndexAlreadyExistsError']
__version__ = '0.7'
__version_info__ = tuple(__version__.split('.'))
get_version = lambda: __version_info__
|
from __future__ import absolute_import
from pyelasticsearch.client import ElasticSearch
from pyelasticsearch.exceptions import (Timeout, ConnectionError,
ElasticHttpError,
InvalidJsonResponseError,
ElasticHttpNotFoundError,
IndexAlreadyExistsError)
__author__ = 'Robert Eanes'
__all__ = ['ElasticSearch', 'ElasticHttpError', 'InvalidJsonResponseError',
'Timeout', 'ConnectionError', 'ElasticHttpNotFoundError',
'IndexAlreadyExistsError']
__version__ = '0.6.1'
__version_info__ = tuple(__version__.split('.'))
get_version = lambda: __version_info__
|
Update parcel bundler to use correct package name
|
module.exports = {
presetPackages: [
['browserify', 'webpack', 'rollup', 'parcel-bundler'],
['recompose', 'mobx'],
[
'glamor',
'aphrodite',
'radium',
'glamorous',
'styled-components',
'jss',
'emotion',
],
// ['lodash', 'underscore'],
['node-sass', 'less', 'stylus'],
// ['gulp', 'grunt'],
['react', 'angular', '@angular/core', 'ember-cli', 'vue'],
['log4js', 'winston'],
// ['meteor-node-stubs', 'sails'],
],
palette: [
'#2196F3',
'#f44336',
'#FF9800',
'#BBCC24',
'#9C27B0',
'#795548',
'#3F51B5',
'#9E9E9E',
'#FFEB3B',
'##c0392b',
],
};
|
module.exports = {
presetPackages: [
['browserify', 'webpack', 'rollup', 'parcel'],
['recompose', 'mobx'],
[
'glamor',
'aphrodite',
'radium',
'glamorous',
'styled-components',
'jss',
'emotion',
],
// ['lodash', 'underscore'],
['node-sass', 'less', 'stylus'],
// ['gulp', 'grunt'],
['react', 'angular', '@angular/core', 'ember-cli', 'vue'],
['log4js', 'winston'],
// ['meteor-node-stubs', 'sails'],
],
palette: [
'#2196F3',
'#f44336',
'#FF9800',
'#BBCC24',
'#9C27B0',
'#795548',
'#3F51B5',
'#9E9E9E',
'#FFEB3B',
'##c0392b',
],
};
|
fix(referrals-invite): Fix sms link for iOS
|
(function () {
'use strict';
console.log('test');
var smsElem = $('#invite_sms');
var emailElem = $('#invite_email');
var codeElem = $('#invitation_code');
rogerthat.callbacks.ready(function () {
console.log('rogerthat is ready');
var code = rogerthat.user.data.invitation_code;
var userName = rogerthat.user.data.name || rogerthat.user.name;
var appId = rogerthat.system.appId;
var message = 'Hi,\n\n' +
'I\'d like to invite you to join the ThreeFold community.' +
' You can download the Android or iOS app at https://rogerth.at/install?a=' + appId +
'\n\n' +
'To become a registered user in the app, you can use my invitation code ' + code + '.' +
'\n\n' +
'Welcome on board!\n' + userName;
var subject = 'Invitation to Threefold community';
var smsHref;
if (rogerthat.system.os === 'ios') {
smsHref = 'sms:&body=' + encodeURIComponent(message);
} else {
smsHref = 'sms:?body=' + encodeURIComponent(message);
}
var emailHref = 'mailto:?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(message);
smsElem.attr('href', smsHref);
emailElem.attr('href', emailHref);
codeElem.text(code);
});
})();
|
(function () {
'use strict';
console.log('test');
var smsElem = $('#invite_sms');
var emailElem = $('#invite_email');
var codeElem = $('#invitation_code');
rogerthat.callbacks.ready(function () {
console.log('rogerthat is ready');
var code = rogerthat.user.data.invitation_code;
var userName = rogerthat.user.data.name || rogerthat.user.name;
var appId = rogerthat.system.appId;
var message = 'Hi,\n\n' +
'I\'d like to invite you to join the ThreeFold community.' +
' You can download the Android or iOS app at https://rogerth.at/install?a=' + appId +
'\n\n' +
'To become a registered user in the app, you can use my invitation code ' + code + '.' +
'\n\n' +
'Welcome on board!\n' + userName;
var subject = 'Invitation to Threefold community';
var smsHref = 'sms:?body=' + encodeURIComponent(message);
var emailHref = 'mailto:?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(message);
smsElem.attr('href', smsHref);
emailElem.attr('href', emailHref);
codeElem.text(code);
});
})();
|
fix(key): Add QueryParameters in Key struct to fix typo
|
package algoliasearch
type Key struct {
ACL []string `json:"acl"`
CreatedAt int `json:"createdAt,omitempty"`
Description string `json:"description,omitempty"`
Indexes []string `json:"indexes,omitempty"`
MaxHitsPerQuery int `json:"maxHitsPerQuery,omitempty"`
MaxQueriesPerIPPerHour int `json:"maxQueriesPerIPPerHour,omitempty"`
QueryParameters string `json:"queryParameters,omitempty"`
Referers []string `json:"referers,omitempty"`
Validity int `json:"validity,omitempty"`
Value string `json:"value,omitempty"`
}
type listAPIKeysRes struct {
Keys []Key `json:"keys"`
}
type AddKeyRes struct {
CreatedAt string `json:"createdAt"`
Key string `json:"key"`
}
type UpdateKeyRes struct {
Key string `json:"key"`
UpdatedAt string `json:"updatedAt"`
}
|
package algoliasearch
type Key struct {
ACL []string `json:"acl"`
CreatedAt int `json:"createdAt,omitempty"`
Description string `json:"description,omitempty"`
Indexes []string `json:"indexes,omitempty"`
MaxHitsPerQuery int `json:"maxHitsPerQuery,omitempty"`
MaxQueriesPerIPPerHour int `json:"maxQueriesPerIPPerHour,omitempty"`
QueryParamaters string `json:"queryParameters,omitempty"`
Referers []string `json:"referers,omitempty"`
Validity int `json:"validity,omitempty"`
Value string `json:"value,omitempty"`
}
type listAPIKeysRes struct {
Keys []Key `json:"keys"`
}
type AddKeyRes struct {
CreatedAt string `json:"createdAt"`
Key string `json:"key"`
}
type UpdateKeyRes struct {
Key string `json:"key"`
UpdatedAt string `json:"updatedAt"`
}
|
Add the Routing's cacheTime option
|
<?php
/**
* Config
*
* @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
* @version 3.0
*/
use Nova\Config\Config;
/**
* PREFER to be used in Database calls or storing Session data, default is 'nova_'
*/
define('PREFIX', 'nova_');
/**
* Setup the Config API Mode.
* For using the 'database' mode, you need to have a database, with a table generated by 'scripts/nova_options'
*/
define('CONFIG_STORE', 'files'); // Supported: "files", "database"
/**
* Routing configuration
*/
Config::set('routing', array(
/*
* The Asset Files Serving configuration.
*/
'assets' => array(
// The driver type used for serving the Asset Files.
'driver' => 'default', // Supported: "default" and "custom".
// The name of Assets Dispatcher used as 'custom' driver.
'dispatcher' => 'Shared\Routing\Assets\CustomDispatcher',
// The served file Cache Time.
'cacheTime' => 10800,
),
));
|
<?php
/**
* Config
*
* @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
* @version 3.0
*/
use Nova\Config\Config;
/**
* PREFER to be used in Database calls or storing Session data, default is 'nova_'
*/
define('PREFIX', 'nova_');
/**
* Setup the Config API Mode.
* For using the 'database' mode, you need to have a database, with a table generated by 'scripts/nova_options'
*/
define('CONFIG_STORE', 'files'); // Supported: "files", "database"
/**
* Routing configuration
*/
Config::set('routing', array(
/*
* The Asset Files Serving configuration.
*/
'assets' => array(
// The driver type used for serving the Asset Files.
'driver' => 'default', // Supported: "default" and "custom".
// The name of Assets Dispatcher used as 'custom' driver.
'dispatcher' => 'Shared\Routing\Assets\CustomDispatcher',
),
));
|
Add function for accumulating disable validator reject approvals count
|
package keeper
import (
"fmt"
"math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/zigbee-alliance/distributed-compliance-ledger/x/validator/types"
)
type (
Keeper struct {
cdc codec.BinaryCodec
storeKey sdk.StoreKey
memKey sdk.StoreKey
dclauthKeeper types.DclauthKeeper
}
)
func NewKeeper(
cdc codec.BinaryCodec,
storeKey,
memKey sdk.StoreKey,
dclauthKeeper types.DclauthKeeper,
) *Keeper {
return &Keeper{
cdc: cdc,
storeKey: storeKey,
memKey: memKey,
dclauthKeeper: dclauthKeeper,
}
}
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}
func (k Keeper) DisableValidatorApprovalsCount(ctx sdk.Context) int {
return int(math.Round(types.DisableValidatorPercent * float64(k.dclauthKeeper.CountAccountsWithRole(ctx, types.VoteForDisableValidatorRole))))
}
func (k Keeper) DisableValidatorRejectApprovalsCount(ctx sdk.Context) int {
return k.dclauthKeeper.CountAccountsWithRole(ctx, types.VoteForDisableValidatorRole) - k.DisableValidatorApprovalsCount(ctx) + 1
}
|
package keeper
import (
"fmt"
"math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/zigbee-alliance/distributed-compliance-ledger/x/validator/types"
)
type (
Keeper struct {
cdc codec.BinaryCodec
storeKey sdk.StoreKey
memKey sdk.StoreKey
dclauthKeeper types.DclauthKeeper
}
)
func NewKeeper(
cdc codec.BinaryCodec,
storeKey,
memKey sdk.StoreKey,
dclauthKeeper types.DclauthKeeper,
) *Keeper {
return &Keeper{
cdc: cdc,
storeKey: storeKey,
memKey: memKey,
dclauthKeeper: dclauthKeeper,
}
}
func (k Keeper) Logger(ctx sdk.Context) log.Logger {
return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}
func (k Keeper) DisableValidatorApprovalsCount(ctx sdk.Context) int {
return int(math.Round(types.DisableValidatorPercent * float64(k.dclauthKeeper.CountAccountsWithRole(ctx, types.VoteForDisableValidatorRole))))
}
|
Add test for force_pathable_endpoint pathfind param
This parameter is intended to allow pathing to adjacent squares
of an unpassable square. This is necessary because if you want to
pathfind to a monster which blocks a square, you don't want to
actually go *onto* the square, you just want to go next to it,
presumably so you can hit it.
|
import unittest
from hunting.level.map import LevelTile, LevelMap
class TestPathfinding(unittest.TestCase):
def test_basic_diagonal(self):
level_map = LevelMap([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)])
self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4))
def test_paths_around_wall(self):
level_map = LevelMap([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)])
for x in range(1, 5):
level_map[x][1].blocks = True
self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)],
level_map.a_star_path(4, 0, 4, 2))
def tests_force_pathable_endpoint_parameter(self):
level_map = LevelMap([[LevelTile(False, False)], [LevelTile(True, True)]])
self.assertEqual([(1, 0)], level_map.a_star_path(0, 0, 1, 0, True))
self.assertEqual([], level_map.a_star_path(0, 0, 1, 0, False))
|
import unittest
from hunting.level.map import LevelTile, LevelMap
class TestPathfinding(unittest.TestCase):
def test_basic_diagonal(self):
level_map = LevelMap()
level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)])
self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4))
def test_paths_around_wall(self):
level_map = LevelMap()
level_map.set_map([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)])
for x in range(1, 5):
level_map[x][1].blocks = True
self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)],
level_map.a_star_path(4, 0, 4, 2))
|
Set "new Scanner()" to "f" :pencil2:
|
import java.io.File;
public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(String...args){}
public static String readFile(String filePath){
File f = new File(filePath);
Scanner input = new Scanner(f);
}
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
import java.io.File;
public class Wift {
/**
* Wift - The BASIC Programming Language
*
* BASIC FUNCTIONALITY:
* - STRINGS []
* - INTEGERS []
* - ARITHMETIC []
* - VARIABLES []
*
* FUNCTIONS:
* - PRINT []
* - INPUT []
* - IF []
* - FOR []
*
*
*/
public static void main(String...args){}
public static String readFile(String filePath){
File f = new File(filePath);
Scanner input = new Scanner();
}
// #readFile() -> char content
// #tokenize() -> list
// #parse() -> symbol table
}
|
Select one Question at random.
|
var models = require('../models');
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
models.Question.find({
include: [{ model: models.Choice }],
order: [ models.sequelize.fn('RANDOM') ]
})
.then(function(question) {
return {
title: question.title,
seq: [
{ test: 'one' },
{ test: 'two' }
],
choices: question.Choices.map(function(choice) {
return { text: choice.text };
})
};
})
.then(function(question) {
res.render('index', {
question: question
});
});
});
module.exports = router;
|
var models = require('../models');
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
models.Question.findAll({
include: [{ model: models.Choice }]
})
.then(function(questions) {
var qs = questions.map(function(question) {
return {
title: question.title,
seq: [
{ test: 'one' },
{ test: 'two' }
],
choices: question.Choices.map(function(choice) {
return { text: choice.text };
})
};
});
res.render('index', {
question: qs[qs.length - 1]
});
});
});
module.exports = router;
|
Allow unsafeInstance() for ppc64le archiecture
|
package net.jpountz.util;
/*
* 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 java.nio.ByteOrder;
public enum Utils {
;
public static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder();
private static final boolean unalignedAccessAllowed;
static {
String arch = System.getProperty("os.arch");
unalignedAccessAllowed = arch.equals("i386") || arch.equals("x86")
|| arch.equals("amd64") || arch.equals("x86_64")
|| arch.equals("ppc64le");
}
public static boolean isUnalignedAccessAllowed() {
return unalignedAccessAllowed;
}
}
|
package net.jpountz.util;
/*
* 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 java.nio.ByteOrder;
public enum Utils {
;
public static final ByteOrder NATIVE_BYTE_ORDER = ByteOrder.nativeOrder();
private static final boolean unalignedAccessAllowed;
static {
String arch = System.getProperty("os.arch");
unalignedAccessAllowed = arch.equals("i386") || arch.equals("x86")
|| arch.equals("amd64") || arch.equals("x86_64");
}
public static boolean isUnalignedAccessAllowed() {
return unalignedAccessAllowed;
}
}
|
Enable rules that already pass
These rules pass with our current codebase and require no changes.
|
/* 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': false,
'img-alt-attributes': false,
'link-rel-noopener': false,
'invalid-interactive': false,
'inline-link-to': true,
'style-concatenation': true,
'triple-curlies': false,
'deprecated-each-syntax': true,
}
};
|
/* eslint-env node */
'use strict';
var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];
module.exports = {
extends: 'recommended',
rules: {
'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
'block-indentation': true,
'html-comments': true,
'nested-interactive': false,
'self-closing-void-elements': false,
'img-alt-attributes': false,
'link-rel-noopener': false,
'invalid-interactive': false,
'inline-link-to': false,
'style-concatenation': false,
'triple-curlies': false,
'deprecated-each-syntax': false,
}
};
|
Resolve name conflict between commands "list" and "retrieve"
|
package main
import (
"fmt"
"github.com/atotto/clipboard"
)
func init() {
registerSubcommand(&Subcommand{
Name: "retrieve",
Aliases: []string{"r", "checkout", "co"},
Usage: "<website> [username]",
Hint: "Load a password from storage to clipboard",
Handler: cmdRetrieve,
})
}
func cmdRetrieve(args []string) bool {
rec, _, _, ok := openAndFindRecord(args)
if !ok {
return false
}
if err := clipboard.WriteAll(rec.Password); err != nil {
fmt.Println("Error accessing clipboard:")
fmt.Println(err)
return false
}
fmt.Println("Password for: ")
printRecord(rec)
fmt.Println("has been copied to your clipboard.")
fmt.Println("Use Ctrl-V or 'Paste' command to use it.")
return true
}
|
package main
import (
"fmt"
"github.com/atotto/clipboard"
)
func init() {
registerSubcommand(&Subcommand{
Name: "retrieve",
Aliases: []string{"r", "load", "l", "checkout", "co"},
Usage: "<website> [username]",
Hint: "Load a password from storage to clipboard",
Handler: cmdRetrieve,
})
}
func cmdRetrieve(args []string) bool {
rec, _, _, ok := openAndFindRecord(args)
if !ok {
return false
}
if err := clipboard.WriteAll(rec.Password); err != nil {
fmt.Println("Error accessing clipboard:")
fmt.Println(err)
return false
}
fmt.Println("Password for: ")
printRecord(rec)
fmt.Println("has been copied to your clipboard.")
fmt.Println("Use Ctrl-V or 'Paste' command to use it.")
return true
}
|
Include valueName in results for consistency with other converters
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.conversion;
import java.util.HashMap;
import java.util.Map;
import com.opengamma.financial.analytics.LabelledMatrix1D;
/**
*
*/
public class LabelledMatrix1DConverter implements ResultConverter<LabelledMatrix1D<?, ?>> {
@Override
public Map<String, Double> convert(String valueName, LabelledMatrix1D<?, ?> value) {
Map<String, Double> returnValue = new HashMap<String, Double>();
Object[] keys = value.getKeys();
double[] values = value.getValues();
for (int i = 0; i < values.length; i++) {
Object k = keys[i];
double v = values[i];
returnValue.put(valueName + "[" + k.toString() + "]", v);
}
return returnValue;
}
@Override
public Class<?> getConvertedClass() {
return LabelledMatrix1D.class;
}
}
|
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.conversion;
import java.util.HashMap;
import java.util.Map;
import com.opengamma.financial.analytics.LabelledMatrix1D;
/**
*
*/
public class LabelledMatrix1DConverter implements ResultConverter<LabelledMatrix1D<?, ?>> {
@Override
public Map<String, Double> convert(String valueName, LabelledMatrix1D<?, ?> value) {
Map<String, Double> returnValue = new HashMap<String, Double>();
Object[] keys = value.getKeys();
double[] values = value.getValues();
for (int i = 0; i < values.length; i++) {
Object k = keys[i];
double v = values[i];
returnValue.put(k.toString(), v);
}
return returnValue;
}
@Override
public Class<?> getConvertedClass() {
return LabelledMatrix1D.class;
}
}
|
Load to structs from config yaml file
|
package main
import (
"flag"
"fmt"
"io/ioutil"
yaml "gopkg.in/yaml.v2"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
func main() {
var apply bool
var dryrun bool
var file string
flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
flag.StringVar(&file, "file", "config.yml", "file path to setting yaml")
flag.StringVar(&file, "f", "config.yml", "file path to setting yaml (shorthand)")
flag.Parse()
sess, err := session.NewSession(nil)
if err != nil {
fmt.Errorf("Error %v", err)
}
rules := Rules{}
err := loadYaml(file, &rules)
if err != nil {
return err
}
}
func loadYaml(file string, r *Rules) error {
buf, err := ioutil.ReadFile(file)
if err != nil {
return err
}
err = yaml.Unmarshal(buf, &r)
if err != nil {
return err
}
return nil
}
|
package main
import (
"flag"
"fmt"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)
func main() {
var apply bool
var dryrun bool
var file string
flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
flag.StringVar(&file, "file", "config.yml", "file path to setting yaml")
flag.StringVar(&file, "f", "config.yml", "file path to setting yaml (shorthand)")
flag.Parse()
sess, err := session.NewSession(nil)
if err != nil {
fmt.Errorf("Error %v", err)
}
cwe := cloudwatchevents.New(sess)
result, err := cwe.ListRules(nil)
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Success")
fmt.Println(result)
}
}
|
Use lazy regex for parsing html <title/>
/* returns: 'foo</title>bar<title>baz' */
/<title>(.+)<\/title>/.exec('<title>foo</title>bar<title>baz</title>')[1]
/* returns: 'foo' */
/<title>(.+?)<\/title>/.exec('<title>foo</title>bar<title>baz</title>')[1]
|
'use strict';
var httpclient = require('../../http-client');
function messageListener(db, from, channel, message) {
var match = /(https?:\/\/[^ ]+)/.exec(message)
if (match) {
var res = httpclient(db, match[1]);
var match = /<title>(.+?)<\/title>/.exec(res);
if (match) {
var decoded = match[1].replace(/&#\d+;/gm,function(s) {
return String.fromCharCode(s.match(/\d+/gm)[0]);
});
decoded = decoded.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
return [ { to: channel, message: decoded } ] ;
}
}
}
module.exports = messageListener;
|
'use strict';
var httpclient = require('../../http-client');
function messageListener(db, from, channel, message) {
var match = /(https?:\/\/[^ ]+)/.exec(message)
if (match) {
var res = httpclient(db, match[1]);
var match = /<title>(.+)<\/title>/.exec(res);
if (match) {
var decoded = match[1].replace(/&#\d+;/gm,function(s) {
return String.fromCharCode(s.match(/\d+/gm)[0]);
});
decoded = decoded.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, "\"")
.replace(/'/g, "'");
return [ { to: channel, message: decoded } ] ;
}
}
}
module.exports = messageListener;
|
Hide storage reservation and persistent volume claims
https://github.com/rancher/rancher/issues/14859
|
import { get, set } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import layout from './template';
const IGNORED = ['requestsStorage', 'persistentVolumeClaims'];
export default Component.extend({
globalStore: service(),
layout,
tagName: 'TR',
classNames: 'main-row',
resourceChoices: null,
init() {
this._super(...arguments);
this.initResourceChoices();
},
initResourceChoices() {
const choices = [];
const schema = get(this, 'globalStore').getById('schema', 'resourcequotalimit');
if ( schema ) {
Object.keys(get(schema, 'resourceFields')).filter((key) => IGNORED.indexOf(key) === -1).forEach((key) => {
choices.push({
label: `formResourceQuota.resources.${ key }`,
value: key,
});
});
}
set(this, 'resourceChoices', choices);
}
});
|
import { get, set } from '@ember/object';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import layout from './template';
export default Component.extend({
globalStore: service(),
layout,
tagName: 'TR',
classNames: 'main-row',
resourceChoices: null,
init() {
this._super(...arguments);
this.initResourceChoices();
},
initResourceChoices() {
const choices = [];
const schema = get(this, 'globalStore').getById('schema', 'resourcequotalimit');
if ( schema ) {
Object.keys(get(schema, 'resourceFields')).forEach((key) => {
choices.push({
label: `formResourceQuota.resources.${ key }`,
value: key,
});
});
}
set(this, 'resourceChoices', choices);
}
});
|
Restructure GPX according to GPX schema
|
define(['jquery'], function($) {
function Gpx($gpx) {
var tracks = [];
$gpx.find("trk").each(function() {
tracks.push(new Track($(this)));
});
this.tracks = tracks;
}
function Track($trk) {
this.name = $trk.find("name").text();
var trackSegments = [];
$trk.find("trkseg").each(function() {
trackSegments.push(new TrackSegment($(this)));
});
this.trackSegments = trackSegments;
}
function TrackSegment($trkseg) {
var trackPoints = [];
$trkseg.find("trkpt").each(function() {
trackPoints.push(new WayPoint($(this)));
});
this.trackPoints = trackPoints;
}
function WayPoint($wtp) {
var attributes = ["lat", "lon"];
for (var i = 0; i < attributes.length; i++) {
this[attributes[i]] = $wtp.attr(attributes[i]);
}
var elements = ["ele"];
for (var i = 0; i < elements.length; i++) {
this[elements[i]] = $wtp.find(elements[i]).text();
}
}
function load(url, callback) {
$.ajax({
url: url,
dataType: "xml",
success: function(data) {
var gpx = new Gpx($(data));
callback(gpx);
}
});
}
return {
load: load
}
});
|
define(['jquery'], function($) {
function Gpx(data) {
this.points = [];
var trkpts = data.documentElement.getElementsByTagName("trkpt");
for (var i = 0; i < trkpts.length; i++) {
var trkpt = trkpts[i];
var lat = parseFloat(trkpt.getAttribute("lat"));
var lon = parseFloat(trkpt.getAttribute("lon"));
var eles = trkpt.getElementsByTagName("ele");
var ele = undefined;
if (eles) {
ele = parseFloat(eles[0].firstChild.nodeValue);
}
this.points.push({lat: lat, lon: lon, ele: ele});
}
}
function load(url, callback) {
$.ajax({
url: url,
dataType: "xml",
success: function(data) {
var gpx = new Gpx(data);
callback(gpx);
}
});
}
return {
load: load
}
});
|
Deal with errors in a more humane way
|
// Require the http module and the proxy module
var http = require('http'),
httpProxy = require('http-proxy'),
routes = require('./config/routes');
console.log(routes);
// Create the proxy
var proxy = httpProxy.createProxyServer({});
// Setup the proxy server and determine routing
var server = http.createServer(function(req, res) {
var rqstUrl = req.headers.host;
// console.log(rqstUrl);
if(routes[rqstUrl]) {
target_address = routes.ipaddress + routes[rqstUrl].target;
proxy.web(req, res, { target: target_address });
}
else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404: Not Found\n");
res.end();
}
});
// Check to see if an error has occurred
proxy.on('error', function(err, req, res) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.write('A server error occurred! Nothing is running at this address and port!');
res.end();
});
// Determine the port number
var port = 3000;
// Start the Server
server.listen(process.env.PORT || port, process.env.IP || '0.0.0.0', function() {
var address = server.address();
console.log('Proxy server is running on ', address.address + ':' + address.port);
});
|
// Require the http module and the proxy module
var http = require('http'),
httpProxy = require('http-proxy'),
routes = require('./config/routes');
console.log(routes);
// Create the proxy
var proxy = httpProxy.createProxyServer({});
// Setup the proxy server and determine routing
var server = http.createServer(function(req, res) {
var rqstUrl = req.headers.host;
// console.log(rqstUrl);
if(routes[rqstUrl]) {
target_address = routes.ipaddress + routes[rqstUrl].target;
proxy.web(req, res, { target: target_address });
}
else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404: Not Found\n");
res.end();
}
});
// Determine the port number
var port = 3000;
// Start the Server
server.listen(process.env.PORT || port, process.env.IP || '0.0.0.0', function() {
var address = server.address();
console.log('Proxy server is running on ', address.address + ':' + address.port);
});
|
Fix division by zero error when calculating tax rate on migration.
|
# Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True).exclude(total=0)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=0)
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
|
# Generated by Django 3.1.6 on 2021-02-20 15:24
from django.db import migrations
from django.db.models import F
def calculate_taxrate(apps, schema_editor):
'''
Calculate the tax rate based on current totals for any InvoiceItem that
does not currently have a tax rate, so that we can make taxRate non-nullable.
'''
InvoiceItem = apps.get_model("core", "InvoiceItem")
db_alias = schema_editor.connection.alias
to_update = InvoiceItem.objects.using(db_alias).filter(taxRate__isnull=True)
to_update.update(taxRate=100 * (F('taxes') / F('total')))
class Migration(migrations.Migration):
dependencies = [
('core', '0040_invoiceitem_taxrate'),
]
operations = [
migrations.RunPython(calculate_taxrate, migrations.RunPython.noop),
]
|
Allow setting email when creating a staff account.
Otherwise makes it hard to start using HomePort as it requires email validation.
|
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
parser.add_argument('-u', '--username', dest='username', required=True)
parser.add_argument('-p', '--password', dest='password', required=True)
parser.add_argument('-e', '--email', dest='email', required=True)
def handle(self, *args, **options):
User = get_user_model()
username = options['username']
password = options['password']
email = options['email']
user, created = User.objects.get_or_create(
username=username,
email=email,
defaults=dict(last_login=timezone.now(), is_staff=True),
)
if not created:
raise CommandError('Username %s is already taken.' % username)
user.set_password(password)
user.save()
self.stdout.write(self.style.SUCCESS('User %s has been created.' % username))
|
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
parser.add_argument('-u', '--username', dest='username', required=True)
parser.add_argument('-p', '--password', dest='password', required=True)
def handle(self, *args, **options):
User = get_user_model()
username = options['username']
password = options['password']
user, created = User.objects.get_or_create(
username=username, defaults=dict(last_login=timezone.now(), is_staff=True)
)
if not created:
raise CommandError('Username %s is already taken.' % username)
user.set_password(password)
user.save()
self.stdout.write(self.style.SUCCESS('User %s has been created.' % username))
|
Add course: opens new page correctly in ROLE
|
/**
* @file courses-widget.js
* Additional js functions if the course-overview is loaded as separate widget
*/
/**
* change normal overview page to separate widget page
*/
function initCourseOverviewWidget(){
// add url-parameter widget=true to all course page links
var aElememts = document.getElementsByTagName('a');
for(var i = 0; i < aElememts.length; ++i) {
//get old hrefs (that would change the widget)
var href = aElememts[i].href;
//check if link goes to model_viewer:
if(href.indexOf("course.php") > -1) {
//check whether href already contains parameter and add new parameter accordingly
if (href.indexOf("?") > -1) {
aElememts[i].href = aElememts[i].href + "&widget=true";
}
else {
aElememts[i].href = aElememts[i].href + "?widget=true";
}
}
}
console.log("overview-widget: initialized widget");
}
//execute init when page is loaded
document.addEventListener('DOMContentLoaded', initCourseOverviewWidget, false);
|
/**
* @file courses-widget.js
* Additional js functions if the course-overview is loaded as separate widget
*/
/**
* change normal overview page to separate widget page
*/
function initCourseOverviewWidget(){
// add url-parameter widget=true to all course page links
var aElememts = document.getElementsByTagName('a');
for(var i = 0; i < aElememts.length; ++i) {
//get old hrefs (that would change the widget)
var href = aElememts[i].href;
//check if link goes to model_viewer:
if(href.indexOf("course.php") > -1){
//change href
aElememts[i].href = aElememts[i].href + "&widget=true";
}
}
console.log("overview-widget: initialized widget");
}
//execute init when page is loaded
document.addEventListener('DOMContentLoaded', initCourseOverviewWidget, false);
|
Adjust search expander so that it closes when no child elements are focused
|
// JavaScript Document
// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__
const SEARCH_TOGGLE = document.querySelector("[data-toggle=mobile-search]");
const SEARCH_FORM = document.querySelector("#mobile-search");
const SEARCH_INPUT = SEARCH_FORM ? SEARCH_FORM.querySelector("input[type=search]") : false;
const SEARCH_ELEMENTS = SEARCH_FORM ? SEARCH_FORM.querySelectorAll("*") : false;
if (SEARCH_TOGGLE && SEARCH_FORM && SEARCH_INPUT && SEARCH_ELEMENTS) {
SEARCH_TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
SEARCH_FORM.classList.add("is-active");
SEARCH_INPUT.focus();
});
SEARCH_ELEMENTS.forEach((element) => {
element.addEventListener("blur", () => {
setTimeout(() => {
if (!SEARCH_FORM.contains(document.activeElement)) {
SEARCH_FORM.classList.remove("is-active");
SEARCH_TOGGLE.focus();
}
}, 100);
}, { passive: true });
});
}
|
// JavaScript Document
// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__
const SEARCH_TOGGLE = document.querySelector("[data-toggle=mobile-search]");
const SEARCH_FORM = document.querySelector("#mobile-search");
const SEARCH_INPUT = SEARCH_FORM ? SEARCH_FORM.querySelector("input[type=search]") : false;
if (SEARCH_TOGGLE && SEARCH_FORM && SEARCH_INPUT) {
SEARCH_TOGGLE.addEventListener("click", (e) => {
e.preventDefault();
SEARCH_FORM.classList.add("is-active");
SEARCH_INPUT.focus();
});
SEARCH_INPUT.addEventListener("blur", () => {
if (!SEARCH_INPUT.value) {
SEARCH_FORM.classList.remove("is-active");
SEARCH_TOGGLE.focus();
}
}, { passive: true });
}
|
Simplify readable concat w/ Buffer.isBuffer and [].map
|
'use strict'
var toArray = require('stream-to-array')
var Promise = require('bluebird')
module.exports = streamToPromise
function streamToPromise (stream) {
var promise
if (stream.readable) {
promise = fromReadable(stream)
} else if (stream.writable) {
promise = fromWritable(stream)
} else {
promise = Promise.resolve()
}
return promise
}
function fromReadable (stream) {
var promise = toArray(stream)
// Ensure stream is in flowing mode
stream.resume()
return promise
.then(function concat (parts) {
return Buffer.concat(parts.map(bufferize))
})
}
function fromWritable (stream) {
return new Promise(function (resolve, reject) {
stream.once('finish', resolve)
stream.once('error', reject)
})
}
function bufferize (chunk) {
return Buffer.isBuffer(chunk) ? chunk : new Buffer(chunk)
}
|
'use strict'
var toArray = require('stream-to-array')
var Promise = require('bluebird')
module.exports = streamToPromise
function streamToPromise (stream) {
var promise
if (stream.readable) {
promise = fromReadable(stream)
} else if (stream.writable) {
promise = fromWritable(stream)
} else {
promise = Promise.resolve()
}
return promise
}
function fromReadable (stream) {
var promise = toArray(stream)
// Ensure stream is in flowing mode
stream.resume()
return promise
.then(function (parts) {
var buffers = []
for (var i = 0, l = parts.length; i < l; ++i) {
var part = parts[i]
buffers.push((part instanceof Buffer) ? part : new Buffer(part))
}
return Buffer.concat(buffers)
})
}
function fromWritable (stream) {
return new Promise(function (resolve, reject) {
stream.once('finish', resolve)
stream.once('error', reject)
})
}
|
Change Ace editor default size.
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'io.c9.ace',
name: 'Config',
properties: [
{
class: 'Int',
name: 'height',
value: 400
},
{
class: 'Int',
name: 'width',
value: 500
},
{
class: 'Enum',
of: 'io.c9.ace.Theme',
name: 'theme'
},
{
class: 'Enum',
of: 'io.c9.ace.Mode',
name: 'mode',
value: 'JAVA'
},
{
class: 'Enum',
of: 'io.c9.ace.KeyBinding',
name: 'keyBinding',
value: 'ACE'
},
{
class: 'Boolean',
name: 'isReadOnly'
}
]
});
|
/**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'io.c9.ace',
name: 'Config',
properties: [
{
class: 'Int',
name: 'height',
value: 500
},
{
class: 'Int',
name: 'width',
value: 700
},
{
class: 'Enum',
of: 'io.c9.ace.Theme',
name: 'theme'
},
{
class: 'Enum',
of: 'io.c9.ace.Mode',
name: 'mode',
value: 'JAVA'
},
{
class: 'Enum',
of: 'io.c9.ace.KeyBinding',
name: 'keyBinding',
value: 'ACE'
},
{
class: 'Boolean',
name: 'isReadOnly'
}
]
});
|
Allow "-" chars in the resync view
|
# Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
from django.conf.urls import patterns, url
urlpatterns = patterns('externalsites.views',
url(r'^resync/(?P<video_url_id>\d+)/(?P<language_code>[\w-]+)/$', 'resync', name='resync'),
)
|
# Amara, universalsubtitles.org
#
# Copyright (C) 2013 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
from django.conf.urls import patterns, url
urlpatterns = patterns('externalsites.views',
url(r'^resync/(?P<video_url_id>\d+)/(?P<language_code>\w+)/$', 'resync', name='resync'),
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.