text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use pympler only if available
|
import guv
guv.monkey_patch()
import guv.server
import logging
import time
from util import create_example
import logger
try:
from pympler import tracker
tr = tracker.SummaryTracker()
except ImportError:
tr = None
if not hasattr(time, 'perf_counter'):
time.perf_counter = time.clock
logger.configure()
log = logging.getLogger()
def handle(sock, addr):
# client connected
sock.sendall(create_example())
sock.close()
if __name__ == '__main__':
pool = guv.GreenPool()
try:
log.debug('Start')
server_sock = guv.listen(('0.0.0.0', 8001))
server = guv.server.Server(server_sock, handle, pool, 'spawn_n')
server.start()
except (SystemExit, KeyboardInterrupt):
if tr:
tr.print_diff()
log.debug('Bye!')
|
import guv
guv.monkey_patch()
import guv.server
import logging
import time
from util import create_example
import logger
from pympler import tracker
tr = tracker.SummaryTracker()
if not hasattr(time, 'perf_counter'):
time.perf_counter = time.clock
logger.configure()
log = logging.getLogger()
response_times = []
def get_avg_time():
global response_times
times = response_times[-1000:]
avg = sum(times) / len(times)
if len(response_times) > 5000:
response_times = times
return avg
def handle(sock, addr):
# client connected
start_time = time.perf_counter()
sock.sendall(create_example())
sock.close()
total_time = time.perf_counter() - start_time
response_times.append(total_time)
if __name__ == '__main__':
pool = guv.GreenPool()
try:
log.debug('Start')
server_sock = guv.listen(('0.0.0.0', 8001))
server = guv.server.Server(server_sock, handle, pool, 'spawn_n')
server.start()
except (SystemExit, KeyboardInterrupt):
tr.print_diff()
log.debug('Bye!')
|
Use a saner requirements for python-dateutil
The requirement >=1.0, <2.0, >=2.1 doesn't make a lot of logical sense and it
will break in the future. There is no version that is >= 1.0, and < 2.0, and
>= 2.1 becasue these versions are mutually exclusive. Even if you interpret
the , as OR it still doesn't make sense because this includes every version.
What this spec is actually trying to represent is any version >= 1.0 but not
2.0, so instead we'll just say that.
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
requires = ['six']
if sys.version_info[0] == 2:
requires += ['python-dateutil>=1.0, != 2.0']
else:
# Py3k
requires += ['python-dateutil>=2.0']
setup(
name='freezegun',
version='0.2.2',
description='Let your Python tests travel through time',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/freezegun',
packages=find_packages(exclude=("tests", "tests.*",)),
install_requires=requires,
include_package_data=True,
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
requires = ['six']
if sys.version_info[0] == 2:
requires += ['python-dateutil>=1.0, <2.0, >=2.1']
else:
# Py3k
requires += ['python-dateutil>=2.0']
setup(
name='freezegun',
version='0.2.2',
description='Let your Python tests travel through time',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/freezegun',
packages=find_packages(exclude=("tests", "tests.*",)),
install_requires=requires,
include_package_data=True,
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
)
|
Fix origin-checking logic in postMessage
This allows us to post messages where the origin is something other than `*`. Closes #1789.
|
"use strict";
const isValidTargetOrigin = require("../utils").isValidTargetOrigin;
const DOMException = require("../web-idl/DOMException");
module.exports = function (message, targetOrigin) {
if (arguments.length < 2) {
throw new TypeError("'postMessage' requires 2 arguments: 'message' and 'targetOrigin'");
}
targetOrigin = String(targetOrigin);
if (!isValidTargetOrigin(targetOrigin)) {
throw new DOMException(DOMException.SYNTAX_ERR, "Failed to execute 'postMessage' on 'Window': " +
"Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
}
// TODO: targetOrigin === '/' - requires reference to source window
// See https://github.com/tmpvar/jsdom/pull/1140#issuecomment-111587499
if (targetOrigin !== "*" && targetOrigin !== this.location.origin) {
return;
}
// TODO: event.source - requires reference to source window
// TODO: event.origin - requires reference to source window
// TODO: event.ports
// TODO: event.data - structured clone message - requires cloning DOM nodes
const event = new this.MessageEvent("message", {
data: message
});
event.initEvent("message", false, false);
setTimeout(() => {
this.dispatchEvent(event);
}, 0);
};
|
"use strict";
const isValidTargetOrigin = require("../utils").isValidTargetOrigin;
const DOMException = require("../web-idl/DOMException");
module.exports = function (message, targetOrigin) {
if (arguments.length < 2) {
throw new TypeError("'postMessage' requires 2 arguments: 'message' and 'targetOrigin'");
}
targetOrigin = String(targetOrigin);
if (!isValidTargetOrigin(targetOrigin)) {
throw new DOMException(DOMException.SYNTAX_ERR, "Failed to execute 'postMessage' on 'Window': " +
"Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
}
// TODO: targetOrigin === '/' - requires reference to source window
// See https://github.com/tmpvar/jsdom/pull/1140#issuecomment-111587499
if (targetOrigin !== "*" && targetOrigin !== this.origin) {
return;
}
// TODO: event.source - requires reference to source window
// TODO: event.origin - requires reference to source window
// TODO: event.ports
// TODO: event.data - structured clone message - requires cloning DOM nodes
const event = new this.MessageEvent("message", {
data: message
});
event.initEvent("message", false, false);
setTimeout(() => {
this.dispatchEvent(event);
}, 0);
};
|
Check ember-source version from NPM, if not found use ember from bower
|
/* jshint node: true */
'use strict';
var path = require('path');
var filterInitializers = require('fastboot-filter-initializers');
var VersionChecker = require('ember-cli-version-checker');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-head',
treeForApp: function(defaultTree) {
var checker = new VersionChecker(this);
var emberVersion = checker.for('ember-source', 'npm');
if (!emberVersion.version) {
emberVersion = checker.for('ember', 'bower');
}
var trees = [defaultTree];
// 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not)
// 2.10.0-beta.1+ includes glimmer2
if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) {
trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10')));
}
var tree = mergeTrees(trees, { overwrite: true });
return filterInitializers(tree);
}
};
|
/* jshint node: true */
'use strict';
var path = require('path');
var filterInitializers = require('fastboot-filter-initializers');
var VersionChecker = require('ember-cli-version-checker');
var mergeTrees = require('broccoli-merge-trees');
module.exports = {
name: 'ember-cli-head',
treeForApp: function(defaultTree) {
var checker = new VersionChecker(this);
var emberVersion = checker.for('ember', 'bower');
var trees = [defaultTree];
// 2.9.0-beta.1 - 2.9.0-beta.5 used glimmer2 (but 2.9.0 did not)
// 2.10.0-beta.1+ includes glimmer2
if (!(emberVersion.gt('2.9.0-beta') && emberVersion.lt('2.9.0')) && !emberVersion.gt('2.10.0-beta')) {
trees.push(this.treeGenerator(path.resolve(this.root, 'app-lt-2-10')));
}
var tree = mergeTrees(trees, { overwrite: true });
return filterInitializers(tree);
}
};
|
Remove noise from default COBRA configs.
PiperOrigin-RevId: 265733849
Change-Id: Ie0e7c0385497852fd85c769ee85c951542c14463
|
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# python2 python3
"""Shared definitions and methods across all COBRA tasks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from spriteworld import action_spaces
from spriteworld import renderers as spriteworld_renderers
def action_space():
return action_spaces.SelectMove(scale=0.25)
def renderers():
return {
'image':
spriteworld_renderers.PILRenderer(
image_size=(64, 64),
anti_aliasing=5,
color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb,
)
}
|
# Copyright 2019 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
# python2 python3
"""Shared definitions and methods across all COBRA tasks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from spriteworld import action_spaces
from spriteworld import renderers as spriteworld_renderers
def action_space():
return action_spaces.SelectMove(scale=0.25, noise_scale=0.05)
def renderers():
return {
'image':
spriteworld_renderers.PILRenderer(
image_size=(64, 64),
anti_aliasing=5,
color_to_rgb=spriteworld_renderers.color_maps.hsv_to_rgb,
)
}
|
Make open assets command trackable
|
module.exports = {
run(editor, sender, opts = {}) {
const modal = editor.Modal;
const am = editor.AssetManager;
const config = am.getConfig();
const amContainer = am.getContainer();
const title = opts.modalTitle || config.modalTitle || '';
const types = opts.types;
const accept = opts.accept;
am.setTarget(opts.target);
am.onClick(opts.onClick);
am.onDblClick(opts.onDblClick);
am.onSelect(opts.onSelect);
if (!this.rendered || types) {
let assets = am.getAll();
if (types) {
assets = assets.filter(a => types.indexOf(a.get('type')) !== -1);
}
am.render(assets);
this.rendered = 1;
}
if (accept) {
const uploadEl = amContainer.querySelector(
`input#${config.stylePrefix}uploadFile`
);
uploadEl && uploadEl.setAttribute('accept', accept);
}
modal
.open({
title,
content: amContainer
})
.getModel()
.once('change:open', () => editor.stopCommand(this.id));
return this;
},
stop(editor) {
editor.Modal.close();
return this;
}
};
|
module.exports = {
run(editor, sender, opts = {}) {
const modal = editor.Modal;
const am = editor.AssetManager;
const config = am.getConfig();
const amContainer = am.getContainer();
const title = opts.modalTitle || config.modalTitle || '';
const types = opts.types;
const accept = opts.accept;
am.setTarget(opts.target);
am.onClick(opts.onClick);
am.onDblClick(opts.onDblClick);
am.onSelect(opts.onSelect);
if (!this.rendered || types) {
let assets = am.getAll();
if (types) {
assets = assets.filter(a => types.indexOf(a.get('type')) !== -1);
}
am.render(assets);
this.rendered = 1;
}
if (accept) {
const uploadEl = amContainer.querySelector(
`input#${config.stylePrefix}uploadFile`
);
uploadEl && uploadEl.setAttribute('accept', accept);
}
modal.setTitle(title);
modal.setContent(amContainer);
modal.open();
}
};
|
Remove scroll listener when it is really not necessary
|
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('scrollindo', factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
root.scrollindo = factory;
}
}(this, function scrollindo(element, newClass) {
if (typeof element !== 'string' || typeof newClass !== 'string') {
return;
}
var $element = document.querySelector(element);
var shouldScroll = true;
function init () {
window.addEventListener('scroll', handleScroll, false);
}
function handleScroll () {
if (!shouldScroll) {
return;
}
blockScroll();
var windowScroll = window.scrollY + window.innerHeight;
var elementOffsetTop = $element.offsetTop;
if (windowScroll >= elementOffsetTop) {
$element.classList.add(newClass);
window.removeEventListener('scroll', handleScroll);
}
setTimeout(allowScroll, 500);
}
function blockScroll () {
shouldScroll = false;
}
function allowScroll () {
shouldScroll = true;
}
init();
}));
|
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('scrollindo', factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
root.scrollindo = factory;
}
}(this, function scrollindo(element, newClass) {
if (typeof element !== 'string' || typeof newClass !== 'string') {
return;
}
var $element = document.querySelector(element);
var shouldScroll = true;
function init () {
window.addEventListener('scroll', handleScroll, false);
}
function handleScroll () {
if (!shouldScroll) {
return;
}
blockScroll();
var windowScroll = window.scrollY + window.innerHeight;
var elementOffsetTop = $element.offsetTop;
if (windowScroll >= elementOffsetTop) {
$element.classList.add(newClass);
}
setTimeout(allowScroll, 500);
}
function blockScroll () {
shouldScroll = false;
}
function allowScroll () {
shouldScroll = true;
}
init();
}));
|
Fix cache clearer doc block.
|
<?php declare(strict_types=1);
/**
* @author Alexander Volodin <mr-stanlik@yandex.ru>
* @copyright Copyright (c) 2020, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Cache\Clear;
/**
* Cache clearer
*/
interface CacheClearerInterface
{
/**
* @param string $set Command set
*
* @return string[]
* @throws \InvalidArgumentException
*/
public function getCommandAliases(string $set): array;
/**
* @param string $set Command set
*
* @return bool
*/
public function hasCommands(string $set): bool;
/**
* @param string $set Command set
* @param string[]|string|null $aliases Command aliases
*
* @return int
* @throws \InvalidArgumentException
*/
public function runCommands(string $set, $aliases = null): int;
}
|
<?php declare(strict_types=1);
/**
* @author Alexander Volodin <mr-stanlik@yandex.ru>
* @copyright Copyright (c) 2020, Darvin Studio
* @link https://www.darvin-studio.ru
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Darvin\AdminBundle\Cache\Clear;
/**
* Cache clearer
*/
interface CacheClearerInterface
{
/**
* @param string $set Command set
*
* @return string[]
* @throws \InvalidArgumentException
*/
public function getCommandAliases(string $set): array;
/**
* @param string $set Command set
*
* @return bool
*/
public function hasCommands(string $set): bool;
/**
* @param string $set Command set
* @param array|string|null $aliases Command aliases
*
* @return int
* @throws \InvalidArgumentException
*/
public function runCommands(string $set, $aliases = null): int;
}
|
Call super constructor for BitforgeError
|
class BitforgeError(Exception):
def __init__(self, *args, **kwargs):
self.cause = kwargs.pop('cause', None)
self.prepare(*args, **kwargs)
message = self.__doc__.format(**self.__dict__)
super(BitforgeError, self).__init__(message)
def prepare(self):
pass
def __str__(self):
return self.message
class ObjectError(BitforgeError):
def prepare(self, object):
self.object = object
class StringError(BitforgeError):
def prepare(self, string):
self.string = repr(string)
self.length = len(string)
class NumberError(BitforgeError):
def prepare(self, number):
self.number = number
class KeyValueError(BitforgeError):
def prepare(self, key, value):
self.key = key
self.value = value
|
class BitforgeError(Exception):
def __init__(self, *args, **kwargs):
self.cause = kwargs.pop('cause', None)
self.prepare(*args, **kwargs)
self.message = self.__doc__.format(**self.__dict__)
def prepare(self):
pass
def __str__(self):
return self.message
class ObjectError(BitforgeError):
def prepare(self, object):
self.object = object
class StringError(BitforgeError):
def prepare(self, string):
self.string = repr(string)
self.length = len(string)
class NumberError(BitforgeError):
def prepare(self, number):
self.number = number
class KeyValueError(BitforgeError):
def prepare(self, key, value):
self.key = key
self.value = value
|
Fix bug: Action name should be split into 2 elements (not 1)
|
import { createActions, handleActions } from 'redux-actions'
import { takeEvery } from 'redux-saga/effects'
export const createModule = (moduleName, definitions, defaultState) => {
const identityActions = []
const actionMap = {}
const reducerMap = {}
const sagas = []
for (const [type, definition] of Object.entries(definitions)) {
const ACTION_TYPE = `${moduleName}/${type}`
const { creator, reducer, saga } = typeof definition === 'function' ? { reducer: definition } : definition
creator ? actionMap[ACTION_TYPE] = creator : identityActions.push(ACTION_TYPE)
reducerMap[ACTION_TYPE] = reducer
saga && sagas.push(takeEvery(ACTION_TYPE, saga))
}
return {
reducer: handleActions(reducerMap, defaultState),
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
.reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 2)[1]]: value }), {}),
}
}
|
import { createActions, handleActions } from 'redux-actions'
import { takeEvery } from 'redux-saga/effects'
export const createModule = (moduleName, definitions, defaultState) => {
const identityActions = []
const actionMap = {}
const reducerMap = {}
const sagas = []
for (const [type, definition] of Object.entries(definitions)) {
const ACTION_TYPE = `${moduleName}/${type}`
const { creator, reducer, saga } = typeof definition === 'function' ? { reducer: definition } : definition
creator ? actionMap[ACTION_TYPE] = creator : identityActions.push(ACTION_TYPE)
reducerMap[ACTION_TYPE] = reducer
saga && sagas.push(takeEvery(ACTION_TYPE, saga))
}
return {
reducer: handleActions(reducerMap, defaultState),
...sagas.length && { sagas },
...Object
.entries(createActions(actionMap, ...identityActions))
.reduce((prev, [key, value]) => ({ ...prev, [key.split('/', 1)[1]]: value }), {}),
}
}
|
Append binary file mode to write RSA exported key needed by Python 3
|
from Crypto.PublicKey import RSA
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Randomly generate a new RSA key for the OpenID server'
def handle(self, *args, **options):
try:
key = RSA.generate(1024)
file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem'
with open(file_path, 'wb') as f:
f.write(key.exportKey('PEM'))
self.stdout.write('RSA key successfully created at: ' + file_path)
except Exception as e:
self.stdout.write('Something goes wrong: {0}'.format(e))
|
from Crypto.PublicKey import RSA
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Randomly generate a new RSA key for the OpenID server'
def handle(self, *args, **options):
try:
key = RSA.generate(1024)
file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem'
with open(file_path, 'w') as f:
f.write(key.exportKey('PEM'))
self.stdout.write('RSA key successfully created at: ' + file_path)
except Exception as e:
self.stdout.write('Something goes wrong: {0}'.format(e))
|
Fix the --verbose argument to properly take an int
Without this, the `i % args.verbose` check would fail since `args.verbose` was
a string
|
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose", type=int,
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if not args.retain:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
|
import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representation of the timeline")
parser.add_argument("user_email",
help="specify the user email to load the data as")
parser.add_argument("-r", "--retain", action="store_true",
help="specify whether the entries should overwrite existing ones (default) or create new ones")
parser.add_argument("-v", "--verbose",
help="after how many lines we should print a status message.")
args = parser.parse_args()
fn = args.timeline_filename
print fn
print "Loading file " + fn
tsdb = edb.get_timeseries_db()
user = ecwu.User.register(args.user_email)
override_uuid = user.uuid
print("After registration, %s -> %s" % (args.user_email, override_uuid))
entries = json.load(open(fn), object_hook = bju.object_hook)
for i, entry in enumerate(entries):
entry["user_id"] = override_uuid
if not args.retain:
del entry["_id"]
if args.verbose is not None and i % args.verbose == 0:
print "About to save %s" % entry
tsdb.save(entry)
|
Fix include for group inbox class
|
<?php
/**
* Table Definition for group_inbox
*/
require_once 'classes/Memcached_DataObject.php';
class Group_inbox extends Memcached_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'group_inbox'; // table name
public $group_id; // int(4) primary_key not_null
public $notice_id; // int(4) primary_key not_null
public $created; // datetime() not_null
/* Static get */
function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Group_inbox',$k,$v); }
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
}
|
<?php
/**
* Table Definition for group_inbox
*/
require_once 'classes/Memcached_DataObject';
class Group_inbox extends Memcached_DataObject
{
###START_AUTOCODE
/* the code below is auto generated do not remove the above tag */
public $__table = 'group_inbox'; // table name
public $group_id; // int(4) primary_key not_null
public $notice_id; // int(4) primary_key not_null
public $created; // datetime() not_null
/* Static get */
function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('Group_inbox',$k,$v); }
/* the code above is auto generated do not remove the tag below */
###END_AUTOCODE
}
|
Update gdbase client main script
|
//GDBase client tool
//Usage: node gdbase-client.js command --specie <SPECIE> --assembly <ASSEMBLY> --dataset <DATASET>
//Import dependencies
var getArgs = require('get-args');
//Get the command line args
var args = getArgs();
//Check the command
if(args.command === ''){ return console.error('No command provided...'); }
//Check the specie
if(typeof args.options.specie === 'undefined'){ return console.error('No specie provided...'); }
//Check the assembly
if(typeof args.options.assembly === 'undefined'){ return console.error('No assembly provided...'); }
//Check the dataset option
if(typeof args.options.dataset === 'undefined'){ return console.error('No dataset provided...'); }
//Get the action file
var action = './commands/' + args.command + '.js';
//Show in console
console.log('Running ' + action);
//Import
require(action)(args.options);
|
//GDBase client tool
//Usage: node gdbase-client.js command --specie <SPECIE> --assembly <ASSEMBLY> --dataset <DATASET>
//Import dependencies
var getArgs = require('get-args');
//Source datasets
var source = require('./source.json');
//Get the command line args
var args = getArgs();
//Check the command
if(args.command === ''){ return console.error('No command provided...'); }
//Check the specie
if(typeof args.options.specie === 'undefined'){ return console.error('No specie provided...'); }
//Check the assembly
if(typeof args.options.assembly === 'undefined'){ return console.error('No assembly provided...'); }
//Check the dataset option
if(typeof args.options.dataset === 'undefined'){ return console.error('No dataset provided...'); }
//Get the action file
var action = './{source}_{dataset}/{command}.js';
//Replace the dataset
action = action.replace('{dataset}', args.options.dataset);
//Replace the command
action = action.replace('{command}', args.command);
//Source keys
var source_keys = Object.keys(source);
//Check the sources
for(var i = 0; i < source_keys.length; i++)
{
//Get the source value
var s = source[source_keys[i]];
//Check
if(s.indexOf(args.options.dataset) === -1){ continue; }
//Replace
action = action.replace('{source}', source_keys[i]);
}
//Show in console
console.log('Running ' + action);
//Import
require(action)(args.options);
|
:new: Add specs for rejecting promise on stream error
|
'use strict'
describe('StreamPromise', function() {
const StreamPromise = require('../')
const FS = require('fs')
it('works', function() {
waitsForPromise(function() {
return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`))
.then(function(contents) {
expect(contents).toBe(`Something\n`)
})
})
})
it('limits by bytes', function() {
waitsForPromise(function() {
let Threw = false
return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`), 1)
.catch(function() {
Threw = true
})
.then(function() {
expect(Threw).toBe(true)
})
})
})
it('rejects promise on stream error', function() {
waitsForPromise(function() {
let Threw = false
return StreamPromise.create(FS.createReadStream(`/etc/some-non-existing-file`))
.catch(function(e) {
Threw = true
})
.then(function() {
expect(Threw).toBe(true)
})
})
})
})
|
'use strict'
describe('StreamPromise', function() {
const StreamPromise = require('../')
const FS = require('fs')
it('works', function() {
waitsForPromise(function() {
return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`))
.then(function(contents) {
expect(contents).toBe(`Something\n`)
})
})
})
it('limits by bytes', function() {
waitsForPromise(function() {
let Threw = false
return StreamPromise.create(FS.createReadStream(`${__dirname}/fixtures/something.txt`), 1)
.catch(function() {
Threw = true
})
.then(function() {
expect(Threw).toBe(true)
})
})
})
})
|
Test: Expand globbing pattern to match tests in directories
|
#!/usr/bin/env node
'use strict';
var Mocha = require('mocha');
require('mocha-as-promised')(Mocha);
var chai = require('chai');
chai.use(require('chai-as-promised'));
require('sinon').assert.expose(chai.assert, { prefix: '' });
var mocha = new Mocha({
reporter: 'spec',
timeout: 200,
slow: Infinity
});
var patterns = [];
if (process.argv[2]) {
patterns.push(process.argv[2]);
} else {
patterns.push('**/*-test.js');
}
var path = require('path');
var glob = require('glob');
patterns.reduce(function(paths, pattern) {
return paths.concat(glob.sync(pattern, {
cwd: __dirname
}));
}, []).forEach(function(file) {
mocha.addFile(path.join('test', file));
});
mocha.run(function(failures) {
process.exit(failures);
});
|
#!/usr/bin/env node
'use strict';
var Mocha = require('mocha');
require('mocha-as-promised')(Mocha);
var chai = require('chai');
chai.use(require('chai-as-promised'));
require('sinon').assert.expose(chai.assert, { prefix: '' });
var mocha = new Mocha({
reporter: 'spec',
timeout: 200,
slow: Infinity
});
var patterns = [];
if (process.argv[2]) {
patterns.push(process.argv[2]);
} else {
patterns.push('*-test.js');
}
var path = require('path');
var glob = require('glob');
patterns.reduce(function(paths, pattern) {
return paths.concat(glob.sync(pattern, {
cwd: __dirname
}));
}, []).forEach(function(file) {
mocha.addFile(path.join('test', file));
});
mocha.run(function(failures) {
process.exit(failures);
});
|
Fix a name collision for two types of types.
|
#
## PyMoira client library
##
## This file contains the more abstract methods which allow user to work with
## lists and list members.
#
import protocol
import utils
import datetime
from errors import *
class Filesys(object):
info_query_description = (
('label', str),
('type', str),
('machine', str),
('name', str),
('mountpoint', str),
('access_mode', str),
('description', str),
('owner_user', str),
('owner_group', str),
('create', bool),
('locker_type', str),
('lastmod_datetime', datetime.datetime),
('lastmod_by', str),
('lastmod_with', str),
)
def __init__(self, client, name):
self.client = client
self.name = name
def loadInfo(self):
"""Loads the information about the list from the server into the object."""
response, = self.client.query( 'get_filesys_by_label', (self.name, ), version = 14 )
result = utils.responseToDict(self.info_query_description, response)
self.__dict__.update(result)
|
#
## PyMoira client library
##
## This file contains the more abstract methods which allow user to work with
## lists and list members.
#
import protocol
import utils
import datetime
from errors import *
class Filesys(object):
info_query_description = (
('label', str),
('type', str),
('machine', str),
('name', str),
('mountpoint', str),
('access_mode', str),
('description', str),
('owner_user', str),
('owner_group', str),
('create', bool),
('type', str),
('lastmod_datetime', datetime.datetime),
('lastmod_by', str),
('lastmod_with', str),
)
def __init__(self, client, name):
self.client = client
self.name = name
def loadInfo(self):
"""Loads the information about the list from the server into the object."""
response, = self.client.query( 'get_filesys_by_label', (self.name, ), version = 14 )
result = utils.responseToDict(self.info_query_description, response)
self.__dict__.update(result)
|
Add rudimentary testing for thread-mapped pools
Refs #174
|
try:
import queue
except ImportError:
import Queue as queue
import pylibmc
from nose.tools import eq_, ok_
from tests import PylibmcTestCase
class PoolTestCase(PylibmcTestCase):
pass
class ClientPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
def test_exhaust(self):
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc1:
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
class ThreadMappedPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ThreadMappedPool(self.mc)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
|
try:
import queue
except ImportError:
import Queue as queue
import pylibmc
from nose.tools import eq_, ok_
from tests import PylibmcTestCase
class PoolTestCase(PylibmcTestCase):
pass
class ClientPoolTests(PoolTestCase):
def test_simple(self):
a_str = "a"
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc:
ok_(smc)
ok_(smc.set(a_str, 1))
eq_(smc[a_str], 1)
def test_exhaust(self):
p = pylibmc.ClientPool(self.mc, 2)
with p.reserve() as smc1:
with p.reserve() as smc2:
self.assertRaises(queue.Empty, p.reserve().__enter__)
# TODO Thread-mapped pool tests
|
Fix PyPI README.MD showing problem.
There is a problem in the project's pypi page. To fix this I added the following line in the setup.py file:
```python
long_description_content_type='text/markdown'
```
|
from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name='django-heroku-memcacheify',
version='1.0.0',
py_modules=('memcacheify',),
# Packaging options:
zip_safe=False,
include_package_data=True,
# Package dependencies:
install_requires=['django-pylibmc>=0.6.1'],
# Metadata for PyPI:
author='Randall Degges',
author_email='r@rdegges.com',
license='UNLICENSE',
url='https://github.com/rdegges/django-heroku-memcacheify',
keywords='django heroku cloud cache memcache memcached awesome epic',
classifiers=[
'Framework :: Django',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
],
description='Automatic Django memcached configuration on Heroku.',
long_description=open(normpath(join(dirname(abspath(__file__)),
'README.md'))).read(),
long_description_content_type='text/markdown'
)
|
from os.path import abspath, dirname, join, normpath
from setuptools import setup
setup(
# Basic package information:
name='django-heroku-memcacheify',
version='1.0.0',
py_modules=('memcacheify',),
# Packaging options:
zip_safe=False,
include_package_data=True,
# Package dependencies:
install_requires=['django-pylibmc>=0.6.1'],
# Metadata for PyPI:
author='Randall Degges',
author_email='r@rdegges.com',
license='UNLICENSE',
url='https://github.com/rdegges/django-heroku-memcacheify',
keywords='django heroku cloud cache memcache memcached awesome epic',
classifiers=[
'Framework :: Django',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
],
description='Automatic Django memcached configuration on Heroku.',
long_description=open(normpath(join(dirname(abspath(__file__)),
'README.md'))).read()
)
|
Fix MonitorClient not working to detect failed jobs
|
package org.rundeck.api;
import org.rundeck.api.RundeckApiException;
import org.rundeck.api.RundeckApiException.RundeckApiLoginException;
import org.rundeck.api.RundeckApiException.RundeckApiTokenException;
import org.rundeck.api.RundeckClient;
import org.rundeck.api.domain.RundeckHistory;
import org.rundeck.api.parser.HistoryParser;
import org.rundeck.api.util.AssertUtil;
public class RundeckMonitorClient extends RundeckClient{
private static final long serialVersionUID = 6744841390473909439L;
public RundeckMonitorClient(String url, String login, String password)
throws IllegalArgumentException {
super(url, login, password);
}
@Override
public RundeckHistory getHistory( final String project, final String statut, final Long max, final Long offset) throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException, IllegalArgumentException {
AssertUtil.notBlank(project, "project is mandatory to get the history !"); //$NON-NLS-1$
return new ApiCall(this).get( new ApiPathBuilder( "/history" ).param( "project", project).param( "statFilter", statut ).param( "max", max ).param("offset", offset), new HistoryParser( "/events" ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
}
}
|
package org.rundeck.api;
import org.rundeck.api.RundeckApiException;
import org.rundeck.api.RundeckApiException.RundeckApiLoginException;
import org.rundeck.api.RundeckApiException.RundeckApiTokenException;
import org.rundeck.api.RundeckClient;
import org.rundeck.api.domain.RundeckHistory;
import org.rundeck.api.parser.HistoryParser;
import org.rundeck.api.util.AssertUtil;
public class RundeckMonitorClient extends RundeckClient{
private static final long serialVersionUID = 6744841390473909439L;
public RundeckMonitorClient(String url, String login, String password)
throws IllegalArgumentException {
super(url, login, password);
}
@Override
public RundeckHistory getHistory( final String project, final String statut, final Long max, final Long offset) throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException, IllegalArgumentException {
AssertUtil.notBlank(project, "project is mandatory to get the history !"); //$NON-NLS-1$
return new ApiCall(this).get( new ApiPathBuilder( "/history" ).param( "project", project).param( "statFilter", statut ).param( "max", max ).param("offset", offset), new HistoryParser( "result/events" ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
}
}
|
Update register if user exists
|
<?php
if($_SERVER['SERVER_NAME'] == 'builder.osmand.net') {
include '../reports/db_conn.php';
$dbconn = db_conn();
$visiblename = pg_escape_string($dbconn, $_GET["visibleName"]);
$useremail = pg_escape_string($dbconn, $_GET["email"]);
$email = pg_escape_string($dbconn, $_GET["cemail"]);
$country = pg_escape_string($dbconn, $_GET["preferredCountry"]);
$userid = pg_escape_string($dbconn, $_GET["userid"]);
$result = pg_query($dbconn, "UPDATE supporters SET visiblename='{$visiblename}', useremail='{$useremail}', preferred_region='{$country}' ".
" where userid = '{$userid}' and useremail='${email}';");
if(!$result) {
$res = array();
$res['error'] = "Error";
echo json_encode($res);
die;
}
$row = pg_fetch_row($result);
$res = array();
$res['visibleName'] = $_GET["visibleName"];
$res['email'] = $_GET["email"];
$res['preferredCountry'] = $_GET["preferredCountry"];
$res['userid'] = $_GET["userid"];
echo json_encode($res);
} else {
echo file_get_contents("http://builder.osmand.net/subscription/update.php?".$_SERVER['QUERY_STRING']);
}
?>
|
<?php
if($_SERVER['SERVER_NAME'] == 'builder.osmand.net') {
include '../reports/db_conn.php';
$dbconn = db_conn();
$visiblename = pg_escape_string($dbconn, $_GET["visibleName"]);
$useremail = pg_escape_string($dbconn, $_GET["email"]);
$email = pg_escape_string($dbconn, $_GET["cemail"]);
$country = pg_escape_string($dbconn, $_GET["preferredCountry"]);
$userid = pg_escape_string($dbconn, $_GET["userid"]);
$result = pg_query($dbconn, "UPDATE supporters SET visiblename='{$visiblename}', useremail='{$useremail}', preferred_region='{$country}' ".
" where userid = '{$userid}' and useremail='${cemail}';");
if(!$result) {
$res = array();
$res['error'] = "Error";
echo json_encode($res);
die;
}
$row = pg_fetch_row($result);
$res = array();
$res['visibleName'] = $_GET["visibleName"];
$res['email'] = $_GET["email"];
$res['preferredCountry'] = $_GET["preferredCountry"];
$res['userid'] = $row[0];
echo json_encode($res);
} else {
echo file_get_contents("http://builder.osmand.net/subscription/register.php?".$_SERVER['QUERY_STRING']);
}
?>
|
Fix icon for time component
|
export default (iconset, name, spinning) => {
if (iconset === 'fa') {
switch (name) {
case 'save':
name = 'download';
break;
case 'zoom-in':
name = 'search-plus';
break;
case 'zoom-out':
name = 'search-minus';
break;
case 'question-sign':
name = 'question-circle';
break;
case 'remove-circle':
name = 'times-circle-o';
break;
case 'new-window':
name = 'window-restore';
break;
case 'move':
name = 'arrows';
break;
case 'time':
name = 'clock-o';
break;
}
}
return spinning ? `${iconset} ${iconset}-${name} ${iconset}-spin` : `${iconset} ${iconset}-${name}`;
};
|
export default (iconset, name, spinning) => {
if (iconset === 'fa') {
switch (name) {
case 'save':
name = 'download';
break;
case 'zoom-in':
name = 'search-plus';
break;
case 'zoom-out':
name = 'search-minus';
break;
case 'question-sign':
name = 'question-circle';
break;
case 'remove-circle':
name = 'times-circle-o';
break;
case 'new-window':
name = 'window-restore';
break;
case 'move':
name = 'arrows';
break;
}
}
return spinning ? `${iconset} ${iconset}-${name} ${iconset}-spin` : `${iconset} ${iconset}-${name}`;
};
|
Make logic benchmarks runner more portable
|
from __future__ import print_function, division
from sympy.logic.utilities import load_file
from sympy.logic import satisfiable
import time
import os
import sys
input_path = os.path.dirname(__file__)
INPUT = [5 * i for i in range(2, 16)]
ALGORITHMS = ['dpll', 'dpll2']
results = {}
if __name__ == '__main__':
for test in INPUT:
results[test] = {}
for test in INPUT:
for alg in ALGORITHMS:
file_name = os.path.join(input_path, 'input', '%s.cnf' % test)
theory = load_file(file_name)
start = time.time()
if not satisfiable(theory, algorithm=alg):
raise ValueError("Function returned false")
end = time.time()
results[test][alg] = end - start
print("Test %d in time %.2f seconds for algorithm %s." %
(test, end - start, alg))
print("problem," + ','.join(ALGORITHMS))
for test in INPUT:
line = "%d" % test
for alg in ALGORITHMS:
line += ",%f" % results[test][alg]
print(line)
|
from __future__ import print_function, division
from sympy.logic.utilities import load_file
from sympy.logic import satisfiable
import time
import os
import sys
input_path = os.getcwd() + '/' + '/'.join(sys.argv[0].split('/')[:-1])
INPUT = [5 * i for i in range(2, 16)]
ALGORITHMS = ['dpll', 'dpll2']
results = {}
for test in INPUT:
results[test] = {}
for test in INPUT:
for alg in ALGORITHMS:
file_name = "%s/input/%d.cnf" % (input_path, test)
theory = load_file(file_name)
start = time.time()
if not satisfiable(theory, algorithm=alg):
raise ValueError("Function returned false")
end = time.time()
results[test][alg] = end - start
print("Test %d in time %.2f seconds for algorithm %s." %
(test, end - start, alg))
print("problem," + ','.join(ALGORITHMS))
for test in INPUT:
line = "%d" % test
for alg in ALGORITHMS:
line += ",%f" % results[test][alg]
print(line)
|
Remove token from session once back on the index page
|
package controllers;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.confighelper;
import views.html.index;
/**
* This controller contains an action to handle HTTP requests
* to the application's home page.
*/
public class HomeController extends Controller {
/**
* Renders the main home page and provides the Gnag client ID used to create the GitHub authentication
* link.
* @return
*/
public Result index() {
session().remove(GitHubAuthController.TOKEN_KEY);
return ok(index.render());
}
/**
* Will show the page for generating a Gradle config for a specific project. If the user has not authorized GitHub
* this will redirect to start the authentication flow.
* @return
*/
public Result configHelper() {
if (session(GitHubAuthController.TOKEN_KEY) == null) {
return redirect("/startAuth");
} else {
return ok(confighelper.render(session(GitHubAuthController.TOKEN_KEY)));
}
}
}
|
package controllers;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.confighelper;
import views.html.index;
/**
* This controller contains an action to handle HTTP requests
* to the application's home page.
*/
public class HomeController extends Controller {
/**
* Renders the main home page and provides the Gnag client ID used to create the GitHub authentication
* link.
* @return
*/
public Result index() {
return ok(index.render());
}
/**
* Will show the page for generating a Gradle config for a specific project. If the user has not authorized GitHub
* this will redirect to start the authentication flow.
* @return
*/
public Result configHelper() {
if (session(GitHubAuthController.TOKEN_KEY) == null) {
return redirect("/startAuth");
} else {
return ok(confighelper.render(session(GitHubAuthController.TOKEN_KEY)));
}
}
}
|
Fix environment.validate() being called without branch name.
|
#!/usr/bin/python
# The MIT License (MIT)
#
# Copyright (c) 2013 CFEngine AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import cfdoc_environment as environment
import cfdoc_git as git
import sys
config = environment.validate(sys.argv[1])
try:
git.createData(config)
except:
print "cfdoc_preprocess: Fatal error generating git tags"
sys.stdout.write(" Exception: ")
print sys.exc_info()
exit(1)
exit(0)
|
#!/usr/bin/python
# The MIT License (MIT)
#
# Copyright (c) 2013 CFEngine AS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import cfdoc_environment as environment
import cfdoc_git as git
import sys
config = environment.validate()
try:
git.createData(config)
except:
print "cfdoc_preprocess: Fatal error generating git tags"
sys.stdout.write(" Exception: ")
print sys.exc_info()
exit(1)
exit(0)
|
joystick: Add missing '* ' in example
Signed-off-by: Francois Berder <59eaf4bb0211c66c3d7532da6d77ecf42a779d82@outlook.fr>
|
#!/usr/bin/env python3
"""This example shows how to use the Joystick Click wrapper of the LetMeCreate.
It continuously reads the position of the joystick, prints it in the terminal
and displays a pattern on the LED's based on the x coordinate.
The Joystick Click must be inserted in Mikrobus 1 before running this program.
"""
from letmecreate.core import i2c
from letmecreate.core import led
from letmecreate.click import joystick
OFFSET = 98
MAXIMUM = OFFSET * 2
def get_led_mask(perc):
div = int((1. - perc) * led.LED_CNT)
if div > led.LED_CNT:
div = led.LED_CNT
mask = 0
for i in range(div):
mask |= (1 << i)
return mask
i2c.init()
led.init()
while True:
pos = joystick.get_position()
print('{} {}'.format(pos[0], pos[1]))
mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM))
led.switch_on(mask)
led.switch_off(~mask)
i2c.release()
led.release()
|
#!/usr/bin/env python3
"""This example shows how to use the Joystick Click wrapper of the LetMeCreate.
It continuously reads the position of the joystick, prints it in the terminal
and displays a pattern on the LED's based on the x coordinate.
The Joystick Click must be inserted in Mikrobus 1 before running this program.
"""
from letmecreate.core import i2c
from letmecreate.core import led
from letmecreate.click import joystick
OFFSET = 98
MAXIMUM = OFFSET2
def get_led_mask(perc):
div = int((1. - perc)led.LED_CNT)
if div > led.LED_CNT:
div = led.LED_CNT
mask = 0
for i in range(div):
mask |= (1 << i)
return mask
i2c.init()
led.init()
while True:
pos = joystick.get_position()
print('{} {}'.format(pos[0], pos[1]))
mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM))
led.switch_on(mask)
led.switch_off(~mask)
i2c.release()
led.release()
|
Remove rogue Cloneable interface implementation
|
package semantics.model;
import com.google.gson.JsonElement;
import java.util.Arrays;
import semantics.KnowBase;
import semantics.Util;
public abstract class Binary extends Conceptual {
private final Conceptual[] cs;
public Binary(Conceptual[] cs) {
this.cs = cs;
}
protected abstract Binary construct(Conceptual[] cs);
protected abstract String getTag();
protected abstract String getOperator();
public void checkSignature(KnowBase kb) {
for (Conceptual c : cs) {
c.checkSignature(kb);
}
}
public JsonElement toJson() {
return Util.toTaggedArray(getTag(), Util.allToJson(cs));
}
@Override
public boolean containsUnknown() {
for (Conceptual c : cs) {
if (c.containsUnknown()) {
return true;
}
}
return false;
}
@Override
public Conceptual stripUnknown() {
if (!containsUnknown()) {
return this;
}
Conceptual[] stripped = new Conceptual[cs.length];
for (int i = 0; i < cs.length; ++i) {
stripped[i] = cs[i].stripUnknown();
}
return construct(stripped);
}
@Override
public String toString() {
return String.format("[%s]", Util.join(" " + getOperator() + " ", cs));
}
@Override
public boolean equals(Object o) {
if (o instanceof Binary) {
return Arrays.equals(cs, ((Binary) o).cs);
}
return false;
}
}
|
package semantics.model;
import com.google.gson.JsonElement;
import java.util.Arrays;
import semantics.KnowBase;
import semantics.Util;
public abstract class Binary extends Conceptual implements Cloneable {
private final Conceptual[] cs;
public Binary(Conceptual[] cs) {
this.cs = cs;
}
protected abstract Binary construct(Conceptual[] cs);
protected abstract String getTag();
protected abstract String getOperator();
public void checkSignature(KnowBase kb) {
for (Conceptual c : cs) {
c.checkSignature(kb);
}
}
public JsonElement toJson() {
return Util.toTaggedArray(getTag(), Util.allToJson(cs));
}
@Override
public boolean containsUnknown() {
for (Conceptual c : cs) {
if (c.containsUnknown()) {
return true;
}
}
return false;
}
@Override
public Conceptual stripUnknown() {
if (!containsUnknown()) {
return this;
}
Conceptual[] stripped = new Conceptual[cs.length];
for (int i = 0; i < cs.length; ++i) {
stripped[i] = cs[i].stripUnknown();
}
return construct(stripped);
}
@Override
public String toString() {
return String.format("[%s]", Util.join(" " + getOperator() + " ", cs));
}
@Override
public boolean equals(Object o) {
if (o instanceof Binary) {
return Arrays.equals(cs, ((Binary) o).cs);
}
return false;
}
}
|
Remove checks for sliced arraybuffer since blob handles that now
|
var WritableStream = require('stream').Writable;
var util = require('util');
var Blob = require('blob');
var URL = global.URL || global.webkitURL || global.mozURL;
function BlobStream() {
if (!(this instanceof BlobStream))
return new BlobStream;
WritableStream.call(this);
this._chunks = [];
this.length = 0;
}
util.inherits(BlobStream, WritableStream);
BlobStream.prototype._write = function(chunk, encoding, callback) {
// convert chunks to Uint8Arrays (e.g. Buffer when array fallback is being used)
if (!(chunk instanceof Uint8Array))
chunk = new Uint8Array(chunk);
this.length += chunk.length;
this._chunks.push(chunk);
callback();
};
BlobStream.prototype.toBlob = function(type) {
return new Blob(this._chunks, {
type: type || 'application/octet-stream'
});
};
BlobStream.prototype.toBlobURL = function(type) {
return URL.createObjectURL(this.toBlob(type));
};
module.exports = BlobStream;
|
var WritableStream = require('stream').Writable;
var util = require('util');
var Blob = require('blob');
var URL = global.URL || global.webkitURL || global.mozURL;
function BlobStream() {
if (!(this instanceof BlobStream))
return new BlobStream;
WritableStream.call(this);
this._chunks = [];
this.length = 0;
}
util.inherits(BlobStream, WritableStream);
BlobStream.prototype._write = function(chunk, encoding, callback) {
// convert chunks to Uint8Arrays (e.g. Buffer when array fallback is being used)
// also make a copy if this is a slice of the ArrayBuffer
// since BlobBuilder requires an ArrayBuffer not a typed array
if (!(chunk instanceof Uint8Array)
|| chunk.byteOffset > 0
|| chunk.byteLength !== chunk.buffer.byteLength)
chunk = new Uint8Array(chunk);
this.length += chunk.length;
this._chunks.push(chunk.buffer);
callback();
};
BlobStream.prototype.toBlob = function(type) {
return new Blob(this._chunks, {
type: type || 'application/octet-stream'
});
};
BlobStream.prototype.toBlobURL = function(type) {
return URL.createObjectURL(this.toBlob(type));
};
module.exports = BlobStream;
|
Add eager loading of reviews for single product.
|
'use strict'
const db = require('APP/db');
const Product = db.model('products');
const Review = db.model('review');
const router = require('express').Router();
router.get('/', (req, res, next) => {
Product.findAll({})
.then(products => res.json(products))
.catch(next)
})
router.get('/:id', (req, res, next) => {
Product.findOne({
where: {
id: req.params.id
},
include: [{model: Review}]
})
.then(product => res.json(product))
.catch(next)
})
// router.get('/:id/reviews', (req, res, next) => {
// Review.findAll({
// where: {
// product_id: req.params.id
// }
// })
// .then(reviews => {
// res.json(reviews);
// })
// })
module.exports = router;
|
'use strict'
const db = require('APP/db');
const Product = db.model('products');
const Review = db.model('review');
const router = require('express').Router();
router.get('/', (req, res, next) => {
Product.findAll({})
.then(products => res.json(products))
.catch(next)
})
router.get('/:id', (req, res, next) => {
Product.findOne({
where: {
id: req.params.id
}
})
.then(product => res.json(product))
.catch(next)
})
router.get('/:id/reviews', (req, res, next) => {
Review.findAll({
where: {
product_id: req.params.id
}
})
.then(reviews => {
res.json(reviews);
})
})
module.exports = router;
|
[fix] Prepend a refernce to the spark for `data` events
|
'use strict';
/**
* The server-side plugin for Primus which adds EventEmitter functionality.
*
* @param {Primus} primus The initialised Primus server.
* @api public
*/
exports.server = function server(primus) {
var Spark = primus.Spark
, emit = Spark.prototype.emit;
primus.transform('incoming', function incoming(packet) {
var data = packet.data;
if (
'object' !== typeof data // Events are objects.
|| !Array.isArray(data.emit) // Not an emit object.
) {
primus.emit.apply(primus, ['data', this].concat(data));
return;
}
//
// Check if we've received an event that is already used internally. We
// splice in a reference to the spark as first argument that will be
// received by the emitted function.
//
if (!primus.reserved(data.emit[0])) {
data.emit.splice(1, 0, this);
primus.emit.apply(primus, data.emit);
}
return false;
});
Spark.prototype.emit = function emitter(event) {
if (
this.reserved(event)
|| 'newListener' === event
|| 'removeListener' === event
) return emit.apply(this, arguments);
this.write({ emit: Array.prototype.slice.call(arguments, 0) });
return true;
};
};
//
// The client interface can be exactly the same, we just don't need it anymore.
//
exports.client = require('./').client;
|
'use strict';
/**
* The server-side plugin for Primus which adds EventEmitter functionality.
*
* @param {Primus} primus The initialised Primus server.
* @api public
*/
exports.server = function server(primus) {
var Spark = primus.Spark
, emit = Spark.prototype.emit;
primus.transform('incoming', function incoming(packet) {
var data = packet.data;
if (
'object' !== typeof data // Events are objects.
|| !Array.isArray(data.emit) // Not an emit object.
) {
primus.emit.apply(primus, ['data'].concat(data));
return;
}
//
// Check if we've received an event that is already used internally. We
// splice in a reference to the spark as first argument that will be
// received by the emitted function.
//
if (!primus.reserved(data.emit[0])) {
data.emit.splice(1, 0, this);
primus.emit.apply(primus, data.emit);
}
return false;
});
Spark.prototype.emit = function emitter(event) {
if (
this.reserved(event)
|| 'newListener' === event
|| 'removeListener' === event
) return emit.apply(this, arguments);
this.write({ emit: Array.prototype.slice.call(arguments, 0) });
return true;
};
};
//
// The client interface can be exactly the same, we just don't need it anymore.
//
exports.client = require('./').client;
|
Fix for historylinks connecting to missing objects
|
"""Middleware used by the history links service."""
from django.shortcuts import redirect
from cms.apps.historylinks.models import HistoryLink
class HistoryLinkFallbackMiddleware(object):
"""Middleware that attempts to rescue 404 responses with a redirect to it's new location."""
def process_response(self, request, response):
"""Attempts to rescue 404 responses."""
if response.status_code == 404:
# Try to rescue the response.
try:
link = HistoryLink.objects.get(path=request.path)
obj = link.object
if obj:
path = obj.get_absolute_url()
if path != request.path:
return redirect(link.object, permanent=True)
return response
except HistoryLink.DoesNotExist:
pass
return response
|
"""Middleware used by the history links service."""
from django.shortcuts import redirect
from cms.apps.historylinks.models import HistoryLink
class HistoryLinkFallbackMiddleware(object):
"""Middleware that attempts to rescue 404 responses with a redirect to it's new location."""
def process_response(self, request, response):
"""Attempts to rescue 404 responses."""
if response.status_code == 404:
# Try to rescue the response.
try:
link = HistoryLink.objects.get(path=request.path)
path = link.object.get_absolute_url()
if path != request.path:
return redirect(link.object, permanent=True)
return response
except HistoryLink.DoesNotExist:
pass
return response
|
[FIX] Increment timeout when getting images
Signed-off-by: Ludovic Ferrandis <22de32f469b6975001fde4e8fec94685fb50d109@intel.com>
|
# media-service-demo
#
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
#
# Mark Ryan <mark.d.ryan@intel.com>
#
import tempfile
import pygtk
pygtk.require('2.0')
import gtk
import urllib2
import os
def image_from_file(url):
tmpfile = tempfile.NamedTemporaryFile(delete=False)
tmpFileName = tmpfile.name
image = None
try:
with tmpfile:
message = urllib2.urlopen(url, None, 15)
tmpfile.write(message.read())
image = gtk.Image()
image.set_from_file(tmpfile.name)
finally:
os.unlink(tmpFileName)
return image
|
# media-service-demo
#
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
#
# Mark Ryan <mark.d.ryan@intel.com>
#
import tempfile
import pygtk
pygtk.require('2.0')
import gtk
import urllib2
import os
def image_from_file(url):
tmpfile = tempfile.NamedTemporaryFile(delete=False)
tmpFileName = tmpfile.name
image = None
try:
with tmpfile:
message = urllib2.urlopen(url, None, 1)
tmpfile.write(message.read())
image = gtk.Image()
image.set_from_file(tmpfile.name)
finally:
os.unlink(tmpFileName)
return image
|
Order CMD according to alphabet, to make /cmds easier
|
var { createActions } = require('./helpers');
module.exports = {
CHATIDLEN: 18,
STEAMIDLEN: 17,
CMD: createActions(
'accept',
'add',
'autojoin',
'block',
'cmds',
'connect',
'debug',
'disconnect',
'dump',
'games',
'get',
'help',
'join',
'logfile',
'nick',
'part',
'pm',
'quit',
'quit!',
'reload',
'remove',
'save',
'scrollb',
'scrollf',
'scrolluser',
'set',
'status',
'unblock',
'w'
)
};
|
var { createActions } = require('./helpers');
module.exports = {
CHATIDLEN: 18,
STEAMIDLEN: 17,
CMD: createActions(
'connect',
'disconnect',
'add',
'accept',
'autojoin',
'block',
'join',
'nick',
'part',
'pm',
'remove',
'status',
'unblock',
'cmds',
'games',
'get',
'help',
'set',
'scrollb',
'scrollf',
'scrolluser',
'w',
'debug',
'dump',
'logfile',
'reload',
'save',
'quit',
'quit!'
)
};
|
Split multiline tests to actual multiple lines
For better readability.
|
import createTestHelpers from '../createTestHelpers';
const {expectTransform, expectNoChange} = createTestHelpers(['no-strict']);
describe('Removal of "use strict"', () => {
it('should remove statement with "use strict" string', () => {
expectTransform('"use strict";').toReturn('');
expectTransform('\'use strict\';').toReturn('');
});
it('should remove the whole line where "use strict" used to be', () => {
expectTransform(
'"use strict";\n' +
'foo();'
).toReturn(
'foo();'
);
expectTransform(
'foo();\n' +
'"use strict";\n' +
'bar();'
).toReturn(
'foo();\n' +
'bar();'
);
});
it('should not remove comments before "use strict"', () => {
expectTransform(
'// comment\n' +
'"use strict";\n' +
'bar();'
).toReturn(
'// comment\n' +
'bar();'
);
});
it('should keep "use strict" used inside other code', () => {
expectNoChange('x = "use strict";');
expectNoChange('foo("use strict");');
});
});
|
import createTestHelpers from '../createTestHelpers';
const {expectTransform, expectNoChange} = createTestHelpers(['no-strict']);
describe('Removal of "use strict"', () => {
it('should remove statement with "use strict" string', () => {
expectTransform('"use strict";').toReturn('');
expectTransform('\'use strict\';').toReturn('');
});
it('should remove the whole line where "use strict" used to be', () => {
expectTransform('"use strict";\nfoo();').toReturn('foo();');
expectTransform('foo();\n"use strict";\nbar();').toReturn('foo();\nbar();');
});
it('should not remove comments before "use strict"', () => {
expectTransform('// foo();\n"use strict";\nbar();').toReturn('// foo();\nbar();');
});
it('should keep "use strict" used inside other code', () => {
expectNoChange('x = "use strict";');
expectNoChange('foo("use strict");');
});
});
|
[FEATURE] Put commonly used constants on main export
|
"use strict";
var TypeDecorator = require( "./lib/type/decorator" );
var TypeHelper = require( "./lib/type/helper" );
var TypeInfo = require( "./lib/type/info" );
module.exports = {
DecoratorError : require( "./lib/error/decorator" ),
HelperError : require( "./lib/error/helper" ),
ChangeSet : require( "./lib/history/changeset" ),
Conductor : require( "./lib/transaction/conductor" ),
WebSockets : require( "./lib/transaction/websockets" ),
TypeDecorator : TypeDecorator,
Factory : require( "./lib/type/factory" ),
TypeHelper : TypeHelper,
TypeInfo : TypeInfo,
Type : require( "./lib/type/type" ),
decorate : decorate,
info : info,
helper : helper
};
function decorate( type ) {
return new TypeDecorator( type );
}
function info( typeName, type ) {
return new TypeInfo( typeName, type );
}
function helper( typeInfo ) {
return new TypeHelper( typeInfo );
}
module.exports.USERCLASS_ADMIN = TypeInfo.USERCLASS_ADMIN;
module.exports.USERCLASS_USER = TypeInfo.USERCLASS_USER;
module.exports.CONCEALED = TypeInfo.CONCEALED;
module.exports.HIDDEN = TypeInfo.HIDDEN;
module.exports.READ_ONLY = TypeInfo.READ_ONLY;
|
"use strict";
var TypeDecorator = require( "./lib/type/decorator" );
var TypeHelper = require( "./lib/type/helper" );
var TypeInfo = require( "./lib/type/info" );
module.exports = {
DecoratorError : require( "./lib/error/decorator" ),
HelperError : require( "./lib/error/helper" ),
ChangeSet : require( "./lib/history/changeset" ),
Conductor : require( "./lib/transaction/conductor" ),
WebSockets : require( "./lib/transaction/websockets" ),
TypeDecorator : TypeDecorator,
Factory : require( "./lib/type/factory" ),
TypeHelper : TypeHelper,
TypeInfo : TypeInfo,
Type : require( "./lib/type/type" ),
decorate : decorate,
info : info,
helper : helper
};
function decorate( type ) {
return new TypeDecorator( type );
}
function info( typeName, type ) {
return new TypeInfo( typeName, type );
}
function helper( typeInfo ) {
return new TypeHelper( typeInfo );
}
|
Include python interpreter implementation name in rule keys
Reviewed By: andrewjcg
fbshipit-source-id: 16e4503cb9
|
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.features.python.toolchain;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import org.immutables.value.Value;
@Value.Immutable(builder = false, copy = false)
@BuckStyleImmutable
public abstract class AbstractPythonVersion implements AddsToRuleKey {
@Value.Parameter
@AddToRuleKey
public abstract String getInterpreterName();
@Value.Parameter
@AddToRuleKey
public abstract String getVersionString(); // X.Y
@Override
public String toString() {
return getInterpreterName() + " " + getVersionString();
}
}
|
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.features.python.toolchain;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import org.immutables.value.Value;
@Value.Immutable(builder = false, copy = false)
@BuckStyleImmutable
public abstract class AbstractPythonVersion implements AddsToRuleKey {
// TODO(cjhopman): This should add the interpreter name to the rulekey.
@Value.Parameter
public abstract String getInterpreterName();
@Value.Parameter
@AddToRuleKey
public abstract String getVersionString(); // X.Y
@Override
public String toString() {
return getInterpreterName() + " " + getVersionString();
}
}
|
Update branch for git updater
|
<?php
/**
* Plugin Name: Culture Object
* Plugin URI: http://cultureobject.co.uk
* Description: A framework as a plugin to enable sync of culture objects into WordPress.
* Version: 3.0.0-alpha.2
* Author: Liam Gladdy / Thirty8 Digital
* Text Domain: culture-object
* Author URI: https://github.com/lgladdy
* GitHub Plugin URI: Thirty8Digital/CultureObject
* GitHub Branch: schemas
* License: Apache 2 License
*/
require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();
/* General Functions. These need to go into their own file one day. */
function cos_get_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_get_remapped_field_name($field_key);
}
function cos_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_remapped_field_name($field_key);
}
function cos_get_field($field_key) {
$id = get_the_ID();
if (!$id) return false;
return get_post_meta($id, $field_key, true);
}
function cos_the_field($field_key) {
echo cos_get_field($field_key);
}
|
<?php
/**
* Plugin Name: Culture Object
* Plugin URI: http://cultureobject.co.uk
* Description: A framework as a plugin to enable sync of culture objects into WordPress.
* Version: 3.0.0-alpha.2
* Author: Liam Gladdy / Thirty8 Digital
* Text Domain: culture-object
* Author URI: https://github.com/lgladdy
* GitHub Plugin URI: Thirty8Digital/CultureObject
* GitHub Branch: master
* License: Apache 2 License
*/
require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();
/* General Functions. These need to go into their own file one day. */
function cos_get_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_get_remapped_field_name($field_key);
}
function cos_remapped_field_name($field_key) {
global $cos;
return $cos->helper->cos_remapped_field_name($field_key);
}
function cos_get_field($field_key) {
$id = get_the_ID();
if (!$id) return false;
return get_post_meta($id, $field_key, true);
}
function cos_the_field($field_key) {
echo cos_get_field($field_key);
}
|
Fix addGhost not properly checking for existing id
|
package com.pm.server.player;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Repository;
import com.pm.server.utils.JsonUtils;
@Repository
public class GhostRepositoryImpl implements GhostRepository {
private List<Ghost> ghosts;
private final static Logger log =
LogManager.getLogger(GhostRepositoryImpl.class.getName());
GhostRepositoryImpl() {
ghosts = new ArrayList<Ghost>();
}
public Ghost getGhostById(Integer id) {
for(Ghost ghost : ghosts) {
if(ghost.getId() == id) {
return ghost;
}
}
return null;
}
public List<Ghost> getAllGhosts() {
return ghosts;
}
public void addGhost(Ghost ghost) throws Exception {
if(getGhostById(ghost.getId()) == null) {
String ghostString = JsonUtils.objectToJson(ghost);
if(ghostString != null) {
log.debug("Adding ghost {}", ghostString);
}
ghosts.add(ghost);
}
else {
throw new IllegalArgumentException(
"addGhost() was given an id belonging to a ghost which is " +
"already in the registry."
);
}
}
public Integer numOfGhosts() {
return ghosts.size();
}
}
|
package com.pm.server.player;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Repository;
import com.pm.server.utils.JsonUtils;
@Repository
public class GhostRepositoryImpl implements GhostRepository {
private List<Ghost> ghosts;
private final static Logger log =
LogManager.getLogger(GhostRepositoryImpl.class.getName());
GhostRepositoryImpl() {
ghosts = new ArrayList<Ghost>();
}
public Ghost getGhostById(Integer id) {
for(Ghost ghost : ghosts) {
if(ghost.getId() == id) {
return ghost;
}
}
return null;
}
public List<Ghost> getAllGhosts() {
return ghosts;
}
public void addGhost(Ghost ghost) throws Exception {
if(getGhostById(ghost.getId()) != null) {
String ghostString = JsonUtils.objectToJson(ghost);
if(ghostString != null) {
log.debug("Adding ghost {}", ghostString);
}
ghosts.add(ghost);
}
else {
throw new IllegalArgumentException(
"addGhost() was given an id belonging to a ghost which is " +
"already in the registry."
);
}
}
public Integer numOfGhosts() {
return ghosts.size();
}
}
|
Fix unexpected error when there is no context in an error
|
var JSLINT = require("../lib/nodelint");
function addDefaults(options) {
'use strict';
['node', 'es5'].forEach(function (opt) {
if (!options.hasOwnProperty(opt)) {
options[opt] = true;
}
});
return options;
}
exports.lint = function (script, options) {
'use strict';
// remove shebang
/*jslint regexp: true*/
script = script.replace(/^\#\!.*/, "");
options = options || {};
delete options.argv;
options = addDefaults(options);
var ok = JSLINT(script, options),
result = {
ok: true,
errors: []
};
if (!ok) {
result = JSLINT.data();
result.errors = (result.errors || []).filter(function (error) {
return !error.evidence || !(/\/\/.*bypass/).test(error.evidence);
});
result.ok = !result.errors.length;
}
result.options = options;
return result;
};
|
var JSLINT = require("../lib/nodelint");
function addDefaults(options) {
'use strict';
['node', 'es5'].forEach(function (opt) {
if (!options.hasOwnProperty(opt)) {
options[opt] = true;
}
});
return options;
}
exports.lint = function (script, options) {
'use strict';
// remove shebang
/*jslint regexp: true*/
script = script.replace(/^\#\!.*/, "");
options = options || {};
delete options.argv;
options = addDefaults(options);
var ok = JSLINT(script, options),
result = {
ok: true,
errors: []
};
if (!ok) {
result = JSLINT.data();
result.errors = (result.errors || []).filter(function (error) {
return !(/\/\/.*bypass/).test(error.evidence);
});
result.ok = !result.errors.length;
}
result.options = options;
return result;
};
|
Add close to DataSource interface.
|
package db
import "gopkg.in/mgo.v2"
// Interface for generic data source (e.g. database).
type DataSource interface {
// Returns collection by name
C(name string) Collection
// Returns copy of data source (may be copy of session as well)
Copy() DataSource
// Closes data source (it will be runtime error to use it after close)
Close()
}
// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
return &MongoDatabase{Database: s.Session.DB(name)}
}
// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
*mgo.Database
}
// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
return &MongoCollection{Collection: d.Database.C(name)}
}
// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
return MongoDatabase{d.With(d.Session.Copy())}
}
// Closes current session with mongo db
func (d MongoDatabase) Close() {
d.Database.Session.Close()
}
|
package db
import "gopkg.in/mgo.v2"
// Interface for generic data source (e.g. database).
type DataSource interface {
// Returns collection by name
C(name string) Collection
// Returns copy of data source (may be copy of session as well)
Copy() DataSource
}
// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
return &MongoDatabase{Database: s.Session.DB(name)}
}
// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
*mgo.Database
}
// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
return &MongoCollection{Collection: d.Database.C(name)}
}
// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
return MongoDatabase{d.With(d.Session.Copy())}
}
|
Clear the screen between frames in asteroids
|
function StaticAsteroids(num, ctx) {
var x;
var y;
var nextPt = function(pt) {
var sign = Math.random() < 0.5 ? -1 : 1;
return pt + (sign * Math.random() * 15);
};
ctx.clearRect(0,0,window.innerWidth,window.innerHeight);
for(i = 0; i < num; i++){
x = Math.random() * window.innerWidth;
y = Math.random() * window.innerHeight;
ctx.beginPath();
ctx.moveTo(x,y);
for(j=0; j < 10; j++){
x = nextPt(x);
y = nextPt(y);
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.stroke();
}
}
|
function StaticAsteroids(num, ctx) {
var x;
var y;
var nextPt = function(pt) {
var sign = Math.random() < 0.5 ? -1 : 1;
return pt + (sign * Math.random() * 15);
};
for(i = 0; i < num; i++){
x = Math.random() * window.innerWidth;
y = Math.random() * window.innerHeight;
ctx.beginPath();
ctx.moveTo(x,y);
for(j=0; j < 10; j++){
x = nextPt(x);
y = nextPt(y);
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.stroke();
}
}
|
Remove unnecessary arguments to composer install.
We don't set these elsewhere and don't need to set them here.
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-clover clover.xml tests/DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
}
echo "Code coverage was 100%\n";
|
#!/usr/bin/env php
<?php
chdir(__DIR__);
$returnStatus = null;
passthru('composer install --dev --no-interaction --prefer-source', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
passthru('./vendor/bin/phpunit --coverage-clover clover.xml tests/DWS', $returnStatus);
if ($returnStatus !== 0) {
exit(1);
}
$xml = new SimpleXMLElement(file_get_contents('clover.xml'));
foreach ($xml->xpath('//file/metrics') as $metric) {
if ((int)$metric['elements'] !== (int)$metric['coveredelements']) {
file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
exit(1);
}
}
echo "Code coverage was 100%\n";
|
Add println so user gets feedback that input accepted
|
// +build freebsd openbsd netbsd darwin linux
package gopass
/*
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
int getch() {
int ch;
struct termios t_old, t_new;
tcgetattr(STDIN_FILENO, &t_old);
t_new = t_old;
t_new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &t_new);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &t_old);
return ch;
}
*/
import "C"
func getch() byte {
return byte(C.getch())
}
// Returns password byte array read from terminal without input being echoed.
// Array of bytes does not include end-of-line characters.
func GetPasswd() []byte {
pass := make([]byte, 0)
for v := getch(); ; v = getch() {
if v == 127 || v == 8 {
if len(pass) > 0 {
pass = pass[:len(pass)-1]
}
} else if v == 13 || v == 10 {
break
} else {
pass = append(pass, v)
}
}
println()
return pass
}
|
// +build freebsd openbsd netbsd darwin linux
package gopass
/*
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
int getch() {
int ch;
struct termios t_old, t_new;
tcgetattr(STDIN_FILENO, &t_old);
t_new = t_old;
t_new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &t_new);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &t_old);
return ch;
}
*/
import "C"
func getch() byte {
return byte(C.getch())
}
// Returns password byte array read from terminal without input being echoed.
// Array of bytes does not include end-of-line characters.
func GetPasswd() []byte {
pass := make([]byte, 0)
for v := getch(); ; v = getch() {
if v == 127 || v == 8 {
if len(pass) > 0 {
pass = pass[:len(pass)-1]
}
} else if v == 13 || v == 10 {
break
} else {
pass = append(pass, v)
}
}
return pass
}
|
Fix where the seat number appears
|
from utils import CanadianJurisdiction
from opencivicdata.divisions import Division
from pupa.scrape import Organization
class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction):
classification = 'legislature' # just to avoid clash
division_id = 'ocd-division/country:ca/province:on'
division_name = 'Ontario English Public School Board boundary"'
name = 'Ontario English Public School Boards'
url = 'http://www.edu.gov.on.ca/eng/sbinfo/boardList.html'
def get_organizations(self):
organization = Organization(self.name, classification=self.classification)
for division in Division.get(self.division_id).children('school_district'):
organization.add_post(role='Chair', label=division.name, division_id=division.id)
for i in range (0, 15): # XXX made-up number
organization.add_post(role='Trustee', label='{} (seat {})'.format(division.name, i), division_id=division.id)
yield organization
|
from utils import CanadianJurisdiction
from opencivicdata.divisions import Division
from pupa.scrape import Organization
class OntarioEnglishPublicSchoolBoards(CanadianJurisdiction):
classification = 'legislature' # just to avoid clash
division_id = 'ocd-division/country:ca/province:on'
division_name = 'Ontario English Public School Board boundary"'
name = 'Ontario English Public School Boards'
url = 'http://www.edu.gov.on.ca/eng/sbinfo/boardList.html'
def get_organizations(self):
organization = Organization(self.name, classification=self.classification)
for division in Division.get(self.division_id).children('school_district'):
organization.add_post(role='Chair', label=division.name, division_id=division.id)
for i in range (0, 15): # XXX made-up number
organization.add_post(role='Trustee (seat {})'.format(i), label=division.name, division_id=division.id)
yield organization
|
Enable source-map for minimized build
|
var path = require('path');
var webpack = require('webpack');
var package = require('./package.json');
minimize = process.argv.indexOf('--minimize') !== -1;
var conf = {
entry: ['babel-polyfill', './src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: package.name + '.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
]},
resolve: {
root: [path.resolve('./src'), path.resolve('./node_modules')],
extensions: ['', '.js'],
},
stats: {
colors: true
},
devtool: 'source-map',
plugins: [
new webpack.optimize.DedupePlugin()
]
}
if(minimize){
conf.plugins.push(new webpack.optimize.UglifyJsPlugin());
conf.output.filename = package.name + '.min.js';
}
module.exports = conf;
|
var path = require('path');
var webpack = require('webpack');
var package = require('./package.json');
minimize = process.argv.indexOf('--minimize') !== -1;
var conf = {
entry: ['babel-polyfill', './src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: package.name + '.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
},
]},
resolve: {
root: [path.resolve('./src'), path.resolve('./node_modules')],
extensions: ['', '.js'],
},
stats: {
colors: true
},
devtool: 'source-map',
plugins: [
new webpack.optimize.DedupePlugin()
]
}
if(minimize){
conf.plugins.push(new webpack.optimize.UglifyJsPlugin());
conf.output.filename = package.name + '.min.js'
delete conf.devtool;
}
module.exports = conf;
|
Add tests for Word class.
|
package com.tyleryates.util;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@SuppressWarnings("JavaDoc")
public class WordTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
private Word word;
private static final String STRING = "lottery";
@Before
public void setUp() throws Exception {
word = new Word(STRING);
}
@Test
public void testWordConstructor() {
exception.expect(IllegalArgumentException.class);
new Word(null);
}
@Test
public void testGetWord() {
assertEquals(STRING, word.getString());
assertEquals("", new Word("").getString());
}
@Test
public void testCanMake() throws Exception {
assertTrue(word.canMake(word));
assertTrue(word.canMake("lot"));
assertTrue(word.canMake("try"));
assertTrue(word.canMake("let"));
assertTrue(word.canMake(""));
assertFalse(word.canMake("lotteries"));
assertFalse(word.canMake("caring"));
}
}
|
package com.tyleryates.util;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@SuppressWarnings("JavaDoc")
public class WordTest {
private Word word;
@Before
public void setUp() throws Exception {
word = new Word("lottery");
}
@Test
public void testCanMake() throws Exception {
assertTrue(word.canMake(word));
assertTrue(word.canMake("lot"));
assertTrue(word.canMake("try"));
assertTrue(word.canMake("let"));
assertTrue(word.canMake(""));
assertFalse(word.canMake("lotteries"));
assertFalse(word.canMake("caring"));
}
}
|
Add emailSupport back to the preprint provider model
|
import DS from 'ember-data';
import OsfModel from 'ember-osf/models/osf-model';
export default OsfModel.extend({
name: DS.attr('fixstring'),
description: DS.attr('fixstring'),
domain: DS.attr('string'),
domainRedirectEnabled: DS.attr('boolean'),
example: DS.attr('fixstring'),
advisoryBoard: DS.attr('string'),
emailSupport: DS.attr('fixstring'),
subjectsAcceptable: DS.attr(),
footerLinks: DS.attr('string'),
allowSubmissions: DS.attr('boolean'),
additionalProviders: DS.attr(),
shareSource: DS.attr('string'),
// Relationships
taxonomies: DS.hasMany('taxonomy'),
preprints: DS.hasMany('preprint', { inverse: 'provider', async: true }),
licensesAcceptable: DS.hasMany('license', { inverse: null }),
});
|
import DS from 'ember-data';
import OsfModel from 'ember-osf/models/osf-model';
export default OsfModel.extend({
name: DS.attr('fixstring'),
description: DS.attr('fixstring'),
domain: DS.attr('string'),
domainRedirectEnabled: DS.attr('boolean'),
example: DS.attr('fixstring'),
advisoryBoard: DS.attr('string'),
subjectsAcceptable: DS.attr(),
footerLinks: DS.attr('string'),
allowSubmissions: DS.attr('boolean'),
additionalProviders: DS.attr(),
shareSource: DS.attr('string'),
// Relationships
taxonomies: DS.hasMany('taxonomy'),
preprints: DS.hasMany('preprint', { inverse: 'provider', async: true }),
licensesAcceptable: DS.hasMany('license', { inverse: null }),
});
|
Change component name to 'ILAMB'
This currently conflicts with the component name for the NCL
version of ILAMB; however, I'll change its name to 'ILAMBv1'.
The current version of ILAMB should take the correct name.
|
#! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
#! /usr/bin/env python
import sys
import subprocess
class BmiIlamb(object):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB v2'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
[AllBundles] Mark classes extending twig final
|
<?php
namespace Kunstmaan\UtilitiesBundle\Twig;
use Kunstmaan\UtilitiesBundle\Helper\SlugifierInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
/**
* @final since 5.4
*/
class UtilitiesTwigExtension extends AbstractExtension
{
/**
* @var SlugifierInterface
*/
private $slugifier;
/**
* @param $slugifier
*/
public function __construct($slugifier)
{
$this->slugifier = $slugifier;
}
/**
* Returns a list of filters.
*
* @return array An array of filters
*/
public function getFilters()
{
return [
new TwigFilter('slugify', [$this, 'slugify']),
];
}
/**
* @param string $text
*
* @return string
*/
public function slugify($text)
{
return $this->slugifier->slugify($text);
}
}
|
<?php
namespace Kunstmaan\UtilitiesBundle\Twig;
use Kunstmaan\UtilitiesBundle\Helper\SlugifierInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class UtilitiesTwigExtension extends AbstractExtension
{
/**
* @var SlugifierInterface
*/
private $slugifier;
/**
* @param $slugifier
*/
public function __construct($slugifier)
{
$this->slugifier = $slugifier;
}
/**
* Returns a list of filters.
*
* @return array An array of filters
*/
public function getFilters()
{
return [
new TwigFilter('slugify', [$this, 'slugify']),
];
}
/**
* @param string $text
*
* @return string
*/
public function slugify($text)
{
return $this->slugifier->slugify($text);
}
}
|
Fix object access on None
|
from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs, model):
self.sqs = sqs
self.model = model
def count(self):
return self.sqs.count()
def __iter__(self):
for result in self.sqs:
if result is not None:
yield result.object
def __getitem__(self, key):
if isinstance(key, int) and (key >= 0 or key < self.count()):
# return the object at the specified position
return self.sqs[key].object
# Pass the slice/range on to the delegate
return SearchQuerySetWrapper(self.sqs[key], self.model)
|
from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs, model):
self.sqs = sqs
self.model = model
def count(self):
return self.sqs.count()
def __iter__(self):
for result in self.sqs:
yield result.object
def __getitem__(self, key):
if isinstance(key, int) and (key >= 0 or key < self.count()):
# return the object at the specified position
return self.sqs[key].object
# Pass the slice/range on to the delegate
return SearchQuerySetWrapper(self.sqs[key], self.model)
|
Add some exception handling for dict
|
#!/usr/bin/env python
from nodes import Node
import json
class Dictionary(Node):
char = ".d"
args = 0
results = 1
def __init__(self, word_ids:Node.IntList):
if not hasattr(Dictionary, "word_list"):
Dictionary.word_list = init_words()
self.words = " ".join(Dictionary.word_list[i] for i in word_ids)
def func(self):
return self.words
def compress(inp):
words = init_words()
inp_words = [word.lower()for word in inp.split(" ")]
rtn = chr(len(inp_words))
for word in inp_words:
if word not in words:
rtn += "Word %s not in wordlist" % word
else:
rtn += chr(words.index(word))
return rtn
def init_words(dict_file = "dictionary.json"):
words_f = open(dict_file)
words = json.load(words_f)
words_f.close()
return words
|
#!/usr/bin/env python
from nodes import Node
import json
class Dictionary(Node):
char = ".d"
args = 0
results = 1
def __init__(self, word_ids:Node.IntList):
if not hasattr(Dictionary, "word_list"):
Dictionary.word_list = init_words()
self.words = " ".join(Dictionary.word_list[i] for i in word_ids)
def func(self):
return self.words
def compress(inp):
words = init_words()
inp_words = [word.lower()for word in inp.split(" ")]
rtn = chr(len(inp_words))
for word in inp_words:
assert(word in words)
rtn += chr(words.index(word))
return rtn
def init_words(dict_file = "dictionary.json"):
words_f = open(dict_file)
words = json.load(words_f)
words_f.close()
return words
|
Add PART to tag map
16 of the 17 PoS tags in the UD tag set is added; PART is missing.
|
# encoding: utf8
from __future__ import unicode_literals
from ..symbols import *
TAG_MAP = {
"ADV": {POS: ADV},
"NOUN": {POS: NOUN},
"ADP": {POS: ADP},
"PRON": {POS: PRON},
"SCONJ": {POS: SCONJ},
"PROPN": {POS: PROPN},
"DET": {POS: DET},
"SYM": {POS: SYM},
"INTJ": {POS: INTJ},
"PUNCT": {POS: PUNCT},
"NUM": {POS: NUM},
"AUX": {POS: AUX},
"X": {POS: X},
"CONJ": {POS: CONJ},
"ADJ": {POS: ADJ},
"VERB": {POS: VERB},
"PART": {POS: PART}
}
|
# encoding: utf8
from __future__ import unicode_literals
from ..symbols import *
TAG_MAP = {
"ADV": {POS: ADV},
"NOUN": {POS: NOUN},
"ADP": {POS: ADP},
"PRON": {POS: PRON},
"SCONJ": {POS: SCONJ},
"PROPN": {POS: PROPN},
"DET": {POS: DET},
"SYM": {POS: SYM},
"INTJ": {POS: INTJ},
"PUNCT": {POS: PUNCT},
"NUM": {POS: NUM},
"AUX": {POS: AUX},
"X": {POS: X},
"CONJ": {POS: CONJ},
"ADJ": {POS: ADJ},
"VERB": {POS: VERB}
}
|
Add isLoggedIn knob to story for pollButtons
|
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { withKnobs, text, boolean, number, object } from '@kadira/storybook-addon-knobs';
import { setComposerStub } from 'react-komposer';
import PollButtons from '../poll_buttons.jsx';
import palette from '../../libs/palette';
storiesOf('core.PollButtons', module)
.addDecorator(withKnobs)
.add('default view', () => {
const poll = object('poll', {
_id: 'abc123',
question: 'Ice Cream Flavors',
options: [
{
name: 'Chocolate',
votes: 10
},
{
name: 'Vanilla',
votes: 5
},
{
name: 'Rocky Road',
votes: 20
}
]
});
const isLoggedIn = boolean('isLoggedIn', true);
const colorScale = palette([ 'tol', 'tol-rainbow' ], poll.options.length);
return (
<PollButtons
poll={poll}
colorScale={colorScale}
isLoggedIn={isLoggedIn}
vote={action('pollButtons-vote-clicked')}
/>
);
});
|
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { withKnobs, text, boolean, number, object } from '@kadira/storybook-addon-knobs';
import { setComposerStub } from 'react-komposer';
import PollButtons from '../poll_buttons.jsx';
import palette from '../../libs/palette';
storiesOf('core.PollButtons', module)
.addDecorator(withKnobs)
.add('default view', () => {
const poll = object('poll', {
_id: 'abc123',
question: 'Ice Cream Flavors',
options: [
{
name: 'Chocolate',
votes: 10
},
{
name: 'Vanilla',
votes: 5
},
{
name: 'Rocky Road',
votes: 20
}
]
});
const colorScale = palette([ 'tol', 'tol-rainbow' ], poll.options.length);
return (
<PollButtons
poll={poll}
colorScale={colorScale}
vote={action('pollButtons-vote-clicked')}
/>
);
});
|
Fix one more bug with asset picker
|
import React, { PropTypes, Component } from 'react';
import MarketPickerContainer from '../_common/MarketPickerContainer';
import InputGroup from '../_common/InputGroup';
export default class AssetPickerFilter extends Component {
static propTypes = {
actions: PropTypes.object.isRequired,
filter: PropTypes.object.isRequired,
};
render() {
const { actions, filter } = this.props;
const onSearchQueryChange = e => actions.updateAssetPickerSearchQuery(e.target.value);
const onSubmarketChange = e => actions.updateAssetPickerSubmarket(e);
const showOnlyTickTradable = false;
return (
<fieldset>
<MarketPickerContainer
onChange={onSubmarketChange}
allOptionShown
showMarkets={showOnlyTickTradable ? ['Forex', 'Randoms'] : null}
value={filter.submarket}
/>
<InputGroup
className="asset-search"
defaultValue={filter.query}
type="search"
placeholder="Search for assets"
onChange={onSearchQueryChange}
autoFocus
/>
</fieldset>
);
}
}
|
import React, { PropTypes, Component } from 'react';
import MarketPickerContainer from '../_common/MarketPickerContainer';
import InputGroup from '../_common/InputGroup';
export default class AssetPickerFilter extends Component {
static propTypes = {
actions: PropTypes.object.isRequired,
filter: PropTypes.object.isRequired,
};
render() {
const { actions, filter } = this.props;
const onSearchQueryChange = e => actions.updateAssetPickerSearchQuery(e.target.value);
const onSubmarketChange = e => actions.updateAssetPickerSubmarket(e);
const showOnlyTickTradable = false;
return (
<fieldset>
<MarketPickerContainer
onChange={onSubmarketChange}
allOptionShown
showMarkets={showOnlyTickTradable ? ['Forex', 'Randoms'] : null}
value={filter.submarket}
/>
<InputGroup
className="asset-search"
type="search"
placeholder="Search for assets"
onChange={onSearchQueryChange}
autoFocus
/>
</fieldset>
);
}
}
|
Remove mongoose debug mode from test
Signed-off-by: Ian Macalinao <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@ian.pw>
|
var async = require("async");
var bay6 = require("../lib/");
var expect = require("chai").expect;
var mongoose = require("mongoose");
var request = require("supertest");
describe("Model", function() {
var app;
var model;
beforeEach(function() {
app = bay6();
app.options.prefix = "";
model = app.model("Document", {
title: String,
contents: String
});
});
describe("#limit", function() {
it("should return a maximum of n documents", function(done) {
model.limit(5);
var server = app.serve(9000);
var Document = app.mongoose.model("Document");
async.each([1, 2, 3, 4, 5, 6], function(useless, done2) {
var doc = new Document({ title: "war and peace", contents: "yolo" });
doc.save(done2);
}, function(err) {
if (err) {
throw err;
}
request(server).get("/documents").end(function(err, res) {
expect(res.body.length).to.equal(5);
server.close();
done();
});
});
});
});
afterEach(function(done) {
app.mongoose.db.dropDatabase(done);
});
});
|
var async = require("async");
var bay6 = require("../lib/");
var expect = require("chai").expect;
var mongoose = require("mongoose");
var request = require("supertest");
describe("Model", function() {
var app;
var model;
beforeEach(function() {
app = bay6();
app.options.prefix = "";
model = app.model("Document", {
title: String,
contents: String
});
mongoose.set("debug", true);
});
describe("#limit", function() {
it("should return a maximum of n documents", function(done) {
model.limit(5);
var server = app.serve(9000);
var Document = app.mongoose.model("Document");
async.each([1, 2, 3, 4, 5, 6], function(useless, done2) {
var doc = new Document({ title: "war and peace", contents: "yolo" });
doc.save(done2);
}, function(err) {
if (err) {
throw err;
}
request(server).get("/documents").end(function(err, res) {
expect(res.body.length).to.equal(5);
server.close();
done();
});
});
});
});
afterEach(function(done) {
app.mongoose.db.dropDatabase(done);
});
});
|
Fix to allow “_” (underline) in file path name
|
package seedu.taskmanager.logic.parser;
import java.util.regex.Pattern;
import seedu.taskmanager.logic.parser.ArgumentTokenizer.Prefix;
/**
* Contains Command Line Interface (CLI) syntax definitions common to multiple commands
*/
public class CliSyntax {
/* Prefix definitions */
public static final Prefix PREFIX_STARTDATE = new Prefix("s/");
public static final Prefix PREFIX_ENDDATE = new Prefix("e/");
public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/");
public static final Prefix PREFIX_TAG = new Prefix("#");
/* Alternative prefix definitions for natural variations of user input*/
// public static final Prefix ALTERNATIVE_PREFIX_STARTDATE = new Prefix("start on ");
// public static final Prefix ALTERNATIVE_PREFIX_ENDDATE = new Prefix("end on ");
// public static final Prefix ALTERNATIVE_PREFIX_DESCRIPTION = new Prefix("with description ");
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
// File Path allows numbers, "/.-", space, lowercase and uppercase letters
public static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("([ 0-9a-zA-Z/_.-])+");
}
|
package seedu.taskmanager.logic.parser;
import java.util.regex.Pattern;
import seedu.taskmanager.logic.parser.ArgumentTokenizer.Prefix;
/**
* Contains Command Line Interface (CLI) syntax definitions common to multiple commands
*/
public class CliSyntax {
/* Prefix definitions */
public static final Prefix PREFIX_STARTDATE = new Prefix("s/");
public static final Prefix PREFIX_ENDDATE = new Prefix("e/");
public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/");
public static final Prefix PREFIX_TAG = new Prefix("#");
/* Alternative prefix definitions for natural variations of user input*/
// public static final Prefix ALTERNATIVE_PREFIX_STARTDATE = new Prefix("start on ");
// public static final Prefix ALTERNATIVE_PREFIX_ENDDATE = new Prefix("end on ");
// public static final Prefix ALTERNATIVE_PREFIX_DESCRIPTION = new Prefix("with description ");
/* Patterns definitions */
public static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
// File Path allows numbers, "/.-", space, lowercase and uppercase letters
public static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("([ 0-9a-zA-Z/.-])+");
}
|
Add site footer to each documentation generator
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-clears/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-clears/tachyons-clears.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_clearfix.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/clearfix/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/layout/clearfix/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-clears/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-clears/tachyons-clears.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_clearfix.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/clearfix/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/layout/clearfix/index.html', html)
|
Add contact information and readme in long description.
|
import os
import re
from setuptools import setup, find_packages
_here = os.path.dirname(__file__)
_init = os.path.join(_here, 'van', 'contactology', '__init__.py')
_init = open(_init, 'r').read()
VERSION = re.search(r'^__version__ = "(.*)"', _init, re.MULTILINE).group(1)
README = open(os.path.join(_here, 'README.txt'), 'r').read()
setup(name="van.contactology",
version=VERSION,
packages=find_packages(),
description="Contactology API for Twisted",
author_email='brian@vanguardistas.net',
long_description=README,
namespace_packages=["van"],
install_requires=[
'pyOpenSSL',
'setuptools',
'Twisted',
'simplejson',
],
test_suite="van.contactology.tests",
tests_require=['mock'],
include_package_data=True,
zip_safe=False,
)
|
import os
import re
from setuptools import setup, find_packages
_here = os.path.dirname(__file__)
_init = os.path.join(_here, 'van', 'contactology', '__init__.py')
_init = open(_init, 'r').read()
VERSION = re.search(r'^__version__ = "(.*)"', _init, re.MULTILINE).group(1)
setup(name="van.contactology",
version=VERSION,
packages=find_packages(),
description="Contactology API for Twisted",
namespace_packages=["van"],
install_requires=[
'pyOpenSSL',
'setuptools',
'Twisted',
'simplejson',
],
test_suite="van.contactology.tests",
tests_require=['mock'],
include_package_data=True,
zip_safe=False,
)
|
Change default addr for http server
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"showrss/handlers"
"flag"
"syscall"
"github.com/braintree/manners"
)
const version = "1.0.0"
func main() {
var httpAddr = flag.String("http", "0.0.0.0:8000", "HTTP service address")
flag.Parse()
log.Println("Starting server ...")
log.Printf("HTTP service listening on %s", *httpAddr)
errChan := make(chan error, 10)
mux := http.NewServeMux()
mux.HandleFunc("/", handlers.HelloHandler)
httpServer := manners.NewServer()
httpServer.Addr = *httpAddr
httpServer.Handler = handlers.LoggingHandler(mux)
go func() {
errChan <- httpServer.ListenAndServe()
}()
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
for {
select {
case err := <-errChan:
if err != nil {
log.Fatal(err)
}
case s := <-signalChan:
log.Println(fmt.Sprintf("Captured %v. Exiting...", s))
httpServer.BlockingClose()
os.Exit(0)
}
}
}
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"showrss/handlers"
"flag"
"syscall"
"github.com/braintree/manners"
)
const version = "1.0.0"
func main() {
var httpAddr = flag.String("http", "localhost:7000", "HTTP service address")
flag.Parse()
log.Println("Starting server ...")
log.Printf("HTTP service listening on %s", *httpAddr)
errChan := make(chan error, 10)
mux := http.NewServeMux()
mux.HandleFunc("/", handlers.EpisodeHandler)
httpServer := manners.NewServer()
httpServer.Addr = *httpAddr
httpServer.Handler = handlers.LoggingHandler(mux)
go func() {
errChan <- httpServer.ListenAndServe()
}()
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
for {
select {
case err := <-errChan:
if err != nil {
log.Fatal(err)
}
case s := <-signalChan:
log.Println(fmt.Sprintf("Captured %v. Exiting...", s))
httpServer.BlockingClose()
os.Exit(0)
}
}
}
|
Write correct device id into value
|
/**
* This static UI function fills the given HTML <select> element with HTML
* <option> elements that represent each found device.
* A device type to filter is optional, the default is the video input type.
*/
VideoStream.UI.deviceSelector = function(selectElement, deviceType = VideoStream.DeviceType.VIDEO_INPUT){
VideoStream.listDevices(deviceType)
.then(function(devices){
var genericText;
switch(deviceType){
case VideoStream.DeviceType.VIDEO_INPUT :
genericText = VideoStream.UI.language['generic-camera'];
break;
case VideoStream.DeviceType.AUDIO_INPUT :
genericText = VideoStream.UI.language['generic-audio-input'];
break;
default:
genericText = VideoStream.UI.language['generic-input'];
}
for(var i = 0, genericIndex = 1; i < devices.length; i++){
var label = devices[i].label === '' ? genericText + ' #' + (genericIndex++) : devices[i].label;
var option = document.createElement('OPTION');
option.setAttribute('value', devices[i].deviceId);
var text = document.createTextNode(label);
option.appendChild(text);
selectElement.appendChild(option);
}
});
}
VideoStream.UI.language['generic-input'] = 'Generic Input';
VideoStream.UI.language['generic-camera'] = 'Generic Camera';
VideoStream.UI.language['generic-audio-input'] = 'Generic Audio Input';
|
/**
* This static UI function fills the given HTML <select> element with HTML
* <option> elements that represent each found device.
* A device type to filter is optional, the default is the video input type.
*/
VideoStream.UI.deviceSelector = function(selectElement, deviceType = VideoStream.DeviceType.VIDEO_INPUT){
VideoStream.listDevices(deviceType)
.then(function(devices){
var genericText;
switch(deviceType){
case VideoStream.DeviceType.VIDEO_INPUT :
genericText = VideoStream.UI.language['generic-camera'];
break;
case VideoStream.DeviceType.AUDIO_INPUT :
genericText = VideoStream.UI.language['generic-audio-input'];
break;
default:
genericText = VideoStream.UI.language['generic-input'];
}
for(var i = 0, genericIndex = 1; i < devices.length; i++){
var label = devices[i].label === '' ? genericText + ' #' + (genericIndex++) : devices[i].label;
var option = document.createElement('OPTION');
option.setAttribute('value', i);
var text = document.createTextNode(label);
option.appendChild(text);
selectElement.appendChild(option);
}
});
}
VideoStream.UI.language['generic-input'] = 'Generic Input';
VideoStream.UI.language['generic-camera'] = 'Generic Camera';
VideoStream.UI.language['generic-audio-input'] = 'Generic Audio Input';
|
Add req.Map["admin"], clear req.Map security fields
|
package common
import (
"encoding/base64"
"strings"
"github.com/ricallinson/forgery"
"github.com/spacedock-io/index/models"
)
func UnpackAuth(raw string) (creds []string, err error) {
auth := strings.Split(raw, " ")
decoded, err := base64.StdEncoding.DecodeString(auth[1])
if err != nil { return nil, err }
creds = strings.Split(string(decoded), ":")
return creds, nil
}
func CheckAuth(req *f.Request, res *f.Response, next func()) {
auth := req.Get("authorization")
req.Map["_uid"] = -1
req.Map["_admin"] = false
if len(auth) == 0 {
res.Send("No authorization provided.", 401)
return
}
creds, err := UnpackAuth(auth)
if err != nil {
res.Send("Unauthorized", 401)
return
}
u, ok := models.AuthUser(creds[0], creds[1])
if !ok {
res.Send("Unauthorized", 401)
}
req.Map["_uid"] = u.Id
req.Map["_admin"] = u.Admin
}
|
package common
import (
"encoding/base64"
"strings"
"github.com/ricallinson/forgery"
"github.com/spacedock-io/index/models"
)
func UnpackAuth(raw string) (creds []string, err error) {
auth := strings.Split(raw, " ")
decoded, err := base64.StdEncoding.DecodeString(auth[1])
if err != nil { return nil, err }
creds = strings.Split(string(decoded), ":")
return creds, nil
}
func CheckAuth(req *f.Request, res *f.Response, next func()) {
auth := req.Get("authorization")
if len(auth) == 0 {
res.Send("No authorization provided.", 401)
return
}
creds, err := UnpackAuth(auth)
if err != nil {
res.Send("Unauthorized", 401)
return
}
u, ok := models.AuthUser(creds[0], creds[1])
if !ok {
res.Send("Unauthorized", 401)
}
req.Map["_uid"] = u.Id
}
|
Refresh the page between a test and another
|
describe('Prerequisites', () => {
describe('Call the same resource with both http client and iframe', () => {
it('http headers should be less or equal than iframe ones', () => {
browser.url('/');
browser.leftClick('.httpCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length;
browser.refresh();
browser.leftClick('.iframeCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const iframeHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const iframeBodyCount = Object.keys(browser.elements('.detail_body').value).length;
expect(iframeHeadersCount).toBeGreaterThanOrEqual(httpHeadersCount);
expect(iframeBodyCount).toBeGreaterThanOrEqual(httpBodyCount);
});
})
});
|
describe('Prerequisites', () => {
describe('Call the same resource with both http client and iframe', () => {
it('http headers should be less or equal than iframe ones', () => {
browser.url('/');
browser.leftClick('.httpCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const httpHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const httpBodyCount = Object.keys(browser.elements('.detail_body').value).length;
browser.leftClick('.iframeCall');
browser.waitForExist('.detail_headers');
browser.waitForExist('.detail_body');
const iframeHeadersCount = Object.keys(browser.elements('.detail_headers').value).length;
const iframeBodyCount = Object.keys(browser.elements('.detail_body').value).length;
expect(iframeHeadersCount).toBeGreaterThanOrEqual(httpHeadersCount);
expect(iframeBodyCount).toBeGreaterThanOrEqual(httpBodyCount);
});
})
});
|
Add connect menu item to file menu.
|
package com.github.aureliano.edocs.app.gui.menu.file;
import javax.swing.JMenu;
import javax.swing.JSeparator;
import com.github.aureliano.edocs.common.locale.EdocsLocale;
public class FileMenu extends JMenu {
private static final long serialVersionUID = -662548298147505185L;
private ConnectMenuItem connectMenuItem;
private CloseTabMenuItem closeTabMenuItem;
private CloseAllTabsMenuItem closeAllTabsMenuItem;
private ExitMenuItem exitMenuItem;
public FileMenu() {
super.setText(EdocsLocale.instance().getMessage("gui.menubar.file"));
this.addMenuItems();
}
private void addMenuItems() {
this.connectMenuItem = new ConnectMenuItem();
this.closeTabMenuItem = new CloseTabMenuItem();
this.closeAllTabsMenuItem = new CloseAllTabsMenuItem();
this.exitMenuItem = new ExitMenuItem();
super.add(this.connectMenuItem);
super.add(new JSeparator());
super.add(this.closeTabMenuItem);
super.add(this.closeAllTabsMenuItem);
super.add(new JSeparator());
super.add(this.exitMenuItem);
}
}
|
package com.github.aureliano.edocs.app.gui.menu.file;
import javax.swing.JMenu;
import javax.swing.JSeparator;
import com.github.aureliano.edocs.common.locale.EdocsLocale;
public class FileMenu extends JMenu {
private static final long serialVersionUID = -662548298147505185L;
private CloseTabMenuItem closeTabMenuItem;
private CloseAllTabsMenuItem closeAllTabsMenuItem;
private ExitMenuItem exitMenuItem;
public FileMenu() {
super.setText(EdocsLocale.instance().getMessage("gui.menubar.file"));
this.addMenuItems();
}
private void addMenuItems() {
this.closeTabMenuItem = new CloseTabMenuItem();
this.closeAllTabsMenuItem = new CloseAllTabsMenuItem();
this.exitMenuItem = new ExitMenuItem();
super.add(this.closeTabMenuItem);
super.add(this.closeAllTabsMenuItem);
super.add(new JSeparator());
super.add(this.exitMenuItem);
}
}
|
Use var instead of const
|
'use strict';
/* global env, exec */
var path = require('path');
require('shelljs/global');
var PROJECT_DIR = path.join(__dirname, '..');
var iron = {
'token': env.IRON_TOKEN,
'project_id': env.IRON_PROJECT_ID
};
JSON.stringify(iron).to(PROJECT_DIR + '/iron.json');
var worker = [
'runtime "node"',
'stack "node-0.10"',
'exec "main.js"',
'file "package.json"',
'build "npm config set strict-ssl false; npm install --production"',
'set_env "GH_TOKEN", "' + env.GH_TOKEN + '"',
'set_env "GH_REF", "' + env.GH_REF + '"',
'remote'
];
worker.join('\n').to(PROJECT_DIR + '/blood.worker');
exec('iron_worker upload blood', { silent: true });
|
'use strict';
/* global env, exec */
var path = require('path');
require('shelljs/global');
const PROJECT_DIR = path.join(__dirname, '..');
var iron = {
'token': env.IRON_TOKEN,
'project_id': env.IRON_PROJECT_ID
};
JSON.stringify(iron).to(PROJECT_DIR + '/iron.json');
var worker = [
'runtime "node"',
'stack "node-0.10"',
'exec "main.js"',
'file "package.json"',
'build "npm config set strict-ssl false; npm install --production"',
'set_env "GH_TOKEN", "' + env.GH_TOKEN + '"',
'set_env "GH_REF", "' + env.GH_REF + '"',
'remote'
];
worker.join('\n').to(PROJECT_DIR + '/blood.worker');
exec('iron_worker upload blood', { silent: true });
|
Replace base_name with basename
base_name is deprecated
|
import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], basename=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
|
import copy
from rest_framework.routers import DefaultRouter, SimpleRouter
from events.api import all_views as events_views
from helevents.api import all_views as users_views
class LinkedEventsAPIRouter(DefaultRouter):
# these are from Django REST Framework bulk BulkRouter with 'delete' excluded
routes = copy.deepcopy(SimpleRouter.routes)
routes[0].mapping.update({
'put': 'bulk_update',
'patch': 'partial_bulk_update',
})
def __init__(self):
super(LinkedEventsAPIRouter, self).__init__()
self.registered_api_views = set()
self._register_all_views()
def _register_view(self, view):
if view['class'] in self.registered_api_views:
return
self.registered_api_views.add(view['class'])
self.register(view['name'], view['class'], base_name=view.get("base_name"))
def _register_all_views(self):
for view in events_views:
self._register_view(view)
for view in users_views:
self._register_view(view)
|
feat: Add base test for containing any value
|
describe("About Maps", function () {
describe("Basic Usage", function () {
it("should understand they are key, value stores", function () {
var trooper = new Map();
trooper.set('name', 'Stormtrooper');
trooper.set('Droid you are looking for?', false);
trooper.set('hits target', function() {
return false;
})
expect(trooper.size).toEqual(FILL_ME_IN);
expect(trooper.get('name')).toEqual(FILL_ME_IN);
expect(trooper.get('hits target')()).toEqual(FILL_ME_IN);
});
it("should understand they are mutable values", function() {
var trooper = new Map();
trooper.set('name', 'Stormtrooper');
expect(trooper.get('name')).toEqual(FILL_ME_IN);
trooper.set('name', 'Iron Maiden');
expect(trooper.get('name')).toEqual(FILL_ME_IN);
})
it("should understand they can contain any value", function() {
})
});
});
|
describe("About Maps", function () {
describe("Basic Usage", function () {
it("should understand they are key, value stores", function () {
var trooper = new Map();
trooper.set('name', 'Stormtrooper');
trooper.set('Droid you are looking for?', false);
trooper.set('hits target', function() {
return false;
})
expect(trooper.size).toEqual(FILL_ME_IN);
expect(trooper.get('name')).toEqual(FILL_ME_IN);
expect(trooper.get('hits target')()).toEqual(FILL_ME_IN);
});
it("should understand they are mutable values", function() {
var trooper = new Map();
trooper.set('name', 'Stormtrooper');
expect(trooper.get('name')).toEqual(FILL_ME_IN);
trooper.set('name', 'Iron Maiden');
expect(trooper.get('name')).toEqual(FILL_ME_IN);
})
});
});
|
Reset OCCI_CORE_SCHEME to its previous value.
|
/*******************************************************************************
* Copyright (c) 2016-17 Inria
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* - Philippe Merle <philippe.merle@inria.fr>
* - Faiez Zalila <faiez.zalila@inria.fr>
*******************************************************************************/
package org.eclipse.cmf.occi.core;
/**
* Constants related to OCCI.
*
* @author Philippe Merle - Inria
*/
public interface OcciCoreConstants
{
/**
* OCCI core URI.
*/
public static final String OCCI_CORE_URI = "http://schemas.ogf.org/occi/core";
/**
* OCCI core scheme.
*/
public static final String OCCI_CORE_SCHEME = "http://schemas.ogf.org/occi/core#";
/**
* OCCI Core entity term.
*/
public static final String OCCI_CORE_ENTITY_TERM = "entity";
/**
* OCCI Core resource term.
*/
public static final String OCCI_CORE_RESOURCE_TERM = "resource";
/**
* OCCI Core link term.
*/
public static final String OCCI_CORE_LINK_TERM = "link";
}
|
/*******************************************************************************
* Copyright (c) 2017 Inria
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* - Faiez Zalila <faiez.zalila@inria.fr>
*******************************************************************************/
package org.eclipse.cmf.occi.core;
/**
* Constants related to OCCI.
*
* @author Faiez Zalila - Inria
*/
public interface OCCICoreConstants
{
/**
* OCCI core URI.
*/
public static final String OCCI_CORE_URI = "http://schemas.ogf.org/occi/core/";
/**
* OCCI core scheme.
*/
public static final String OCCI_CORE_SCHEME = "http://schemas.ogf.org/occi/core#";
/**
* OCCI Core entity term.
*/
public static final String OCCI_CORE_ENTITY_TERM = "entity";
/**
* OCCI Core resource term.
*/
public static final String OCCI_CORE_RESOURCE_TERM = "resource";
/**
* OCCI Core link term.
*/
public static final String OCCI_CORE_LINK_TERM = "link";
}
|
Use os.join for testing on multiple platforms.
|
#!/usr/bin/env python
import subprocess
import os.path
NOTEBOOKS_DIR = 'notebooks'
SKIP_NOTEBOOKS = [os.path.join('Bonus','What to do when things go wrong.ipynb')]
def run_notebook(notebook):
args = ['jupyter', 'nbconvert', '--execute',
'--ExecutePreprocessor.timeout=900',
'--ExecutePreprocessor.kernel_name=workshop',
'--to=notebook', '--stdout']
args.append(notebook)
with subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=None) as proc:
proc.wait()
return proc.returncode
if __name__ == '__main__':
import glob
import sys
ret = 0
notebooks = set(glob.glob(os.path.join(NOTEBOOKS_DIR, '**', '*.ipynb'), recursive=True))
notebooks -= set(os.path.join(NOTEBOOKS_DIR, s)
for s in SKIP_NOTEBOOKS)
for path in sorted(notebooks):
ret = max(run_notebook(path), ret)
sys.exit(ret)
|
#!/usr/bin/env python
import subprocess
NOTEBOOKS_DIR = 'notebooks'
SKIP_NOTEBOOKS = ['Bonus/What to do when things go wrong.ipynb']
def run_notebook(notebook):
args = ['jupyter', 'nbconvert', '--execute',
'--ExecutePreprocessor.timeout=900',
'--ExecutePreprocessor.kernel_name=workshop',
'--to=notebook', '--stdout']
args.append(notebook)
with subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=None) as proc:
proc.wait()
return proc.returncode
if __name__ == '__main__':
import glob
import os.path
import sys
ret = 0
notebooks = set(glob.glob(os.path.join(NOTEBOOKS_DIR, '**/*.ipynb'), recursive=True))
notebooks -= set(os.path.join(NOTEBOOKS_DIR, s)
for s in SKIP_NOTEBOOKS)
for path in sorted(notebooks):
ret = max(run_notebook(path), ret)
sys.exit(ret)
|
Fix publicPath for development server
|
import path from "path";
import { ENTRY_PATH, OUTPUT_PATH } from "../constants";
import {
isDevelopment,
isProduction,
isReact,
resolveExternal,
resolveInternal
} from "../utils";
export default (options, partials) => {
const ENTRY = options.server ? [
isReact(options.framework) && "react-hot-loader/patch",
`webpack-dev-server/client?${options.serverURL}`,
"webpack/hot/only-dev-server",
ENTRY_PATH
].filter(Boolean) : ENTRY_PATH;
const OUTPUT_FILENAME = `${isProduction(options.env) ? "[name]-[chunkhash:20]" : "[name]"}.js`;
return {
entry: { application: ENTRY },
output: {
path: resolveExternal(OUTPUT_PATH),
publicPath: options.server ? `${options.serverURL}/` : "/",
filename: OUTPUT_FILENAME,
chunkFilename: `chunks/${OUTPUT_FILENAME}`
},
resolve: {
modules: [resolveExternal(ENTRY_PATH), resolveExternal("node_modules"), resolveInternal("node_modules")],
extensions: ["", ".js", ".jsx", ".ts", ".tsx", ".json", ".css", ".scss"]
},
resolveLoader: {
modules: [resolveExternal("node_modules"), resolveInternal("node_modules")]
},
module: { loaders: partials.loadersConfig },
plugins: partials.pluginsConfig,
devtool: isDevelopment(options.env) && "cheap-inline-module-source-map"
};
}
|
import path from "path";
import { ENTRY_PATH, OUTPUT_PATH } from "../constants";
import {
isDevelopment,
isProduction,
isReact,
resolveExternal,
resolveInternal
} from "../utils";
export default (options, partials) => {
const ENTRY = options.server ? [
isReact(options.framework) && "react-hot-loader/patch",
`webpack-dev-server/client?${options.serverURL}`,
"webpack/hot/only-dev-server",
ENTRY_PATH
].filter(Boolean) : ENTRY_PATH;
const OUTPUT_FILENAME = `${isProduction(options.env) ? "[name]-[chunkhash:20]" : "[name]"}.js`;
return {
entry: { application: ENTRY },
output: {
path: resolveExternal(OUTPUT_PATH),
publicPath: "/",
filename: OUTPUT_FILENAME,
chunkFilename: `chunks/${OUTPUT_FILENAME}`
},
resolve: {
modules: [resolveExternal(ENTRY_PATH), resolveExternal("node_modules"), resolveInternal("node_modules")],
extensions: ["", ".js", ".jsx", ".ts", ".tsx", ".json", ".css", ".scss"]
},
resolveLoader: {
modules: [resolveExternal("node_modules"), resolveInternal("node_modules")]
},
module: { loaders: partials.loadersConfig },
plugins: partials.pluginsConfig,
devtool: isDevelopment(options.env) && "cheap-inline-module-source-map"
};
}
|
Remove integer ID in Telemetry model
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
timestamp = db.Column(db.DateTime, primary_key=True)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
from tsserver import db
from tsserver.dtutils import datetime_to_str
class Telemetry(db.Model):
"""
All the data that is going to be obtained in regular time intervals
(every second or so).
"""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime)
temperature = db.Column(db.Float)
pressure = db.Column(db.Float)
def __init__(self, timestamp, temperature, pressure):
self.timestamp = timestamp
self.temperature = temperature
self.pressure = pressure
def as_dict(self):
return {'timestamp': datetime_to_str(self.timestamp),
'temperature': self.temperature,
'pressure': self.pressure}
|
Check Debug folder for colony, otherwise skip
|
var fs = require('fs')
, falafel = require('falafel')
, colors = require('colors')
, path = require('path')
, spawn = require('child_process').spawn;
var colonize = require('./colonize');
/**
* Bytecode
*/
var compile_lua = process.platform != 'win32'
? fs.existsSync(__dirname + '/../bin/build/Release')
? __dirname + '/../bin/build/Release/compile_lua'
: __dirname + '/../bin/build/Debug/compile_lua'
: __dirname + '/../bin/compile_lua_x64.exe';
function toBytecode (lua, f, next) {
next = typeof f == 'function' ? f : next;
f = typeof f == 'string' ? f : 'usercode.js';
if (!fs.existsSync(compile_lua)) {
console.error('WARNING: Bytecode compiler was not compiled for module "colony". Check that node-gyp is installed properly on your system and reinstall. Skipping for now...');
setImmediate(next, lua, 0);
return;
}
var bufs = [];
var c = spawn(compile_lua, ['@' + f]);
c.stdout.on('data', function (buf) {
bufs.push(buf);
});
c.stdout.on('close', function (code) {
var res = Buffer.concat(bufs);
next(code, res);
});
c.stdin.write(lua);
c.stdin.end();
}
/**
* Module API
*/
exports.colonize = colonize;
exports.toBytecode = toBytecode;
|
var fs = require('fs')
, falafel = require('falafel')
, colors = require('colors')
, path = require('path')
, spawn = require('child_process').spawn;
var colonize = require('./colonize');
/**
* Bytecode
*/
var compile_lua = process.platform != 'win32'
? __dirname + '/../bin/build/Release/compile_lua'
: __dirname + '/../bin/compile_lua_x64.exe';
function toBytecode (lua, f, next) {
next = typeof f == 'function' ? f : next;
f = typeof f == 'string' ? f : 'usercode.js';
var bufs = [];
var c = spawn(compile_lua, ['@' + f]);
c.stdout.on('data', function (buf) {
bufs.push(buf);
});
c.stdout.on('close', function (code) {
var res = Buffer.concat(bufs);
next(code, res);
});
c.stdin.write(lua);
c.stdin.end();
}
/**
* Module API
*/
exports.colonize = colonize;
exports.toBytecode = toBytecode;
|
Allow list to be sorted by a key in the node's data
|
import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listdir(nodes_dir):
if filename.endswith('.json'):
entry = {'name': filename[:-5]}
f = open(os.path.join(nodes_dir, filename), 'r')
entry['data'] = json.load(f)
f.close()
retval.append(entry)
return sort_list_by_data_key(retval, 'chef_environment')
def sort_list_by_data_key(old_list, key):
return sorted(old_list, key=lambda k: k['data'][key])
|
import os
import json
from kitchen.settings import KITCHEN_LOCATION
def load_data(data_type):
retval = []
nodes_dir = os.path.join(KITCHEN_LOCATION, data_type)
if not os.path.isdir(nodes_dir):
raise IOError('Invalid data type or kitchen location. Check your settings.')
for filename in os.listdir(nodes_dir):
if filename.endswith('.json'):
entry = {'name': filename[:-5]}
f = open(os.path.join(nodes_dir, filename), 'r')
entry['data'] = json.load(f)
f.close()
retval.append(entry)
return retval
|
Fix lint report error; Simplify Query function
|
package ipfs
import (
"context"
routing "gx/ipfs/QmPpYHPRGVpSJTkQDQDwTYZ1cYUR2NM4HS6M3iAXi8aoUa/go-libp2p-kad-dht"
peer "gx/ipfs/QmTRhk7cgjUf2gfQ3p2M9KPECNZEW9XUrmHcFCgog4cPgB/go-libp2p-peer"
)
// Query returns the closest peers known for peerID
func Query(dht *routing.IpfsDHT, peerID string) ([]peer.ID, error) {
id, err := peer.IDB58Decode(peerID)
if err != nil {
return nil, err
}
ch, err := dht.GetClosestPeers(context.Background(), string(id))
if err != nil {
return nil, err
}
var closestPeers []peer.ID
for p := range ch {
closestPeers = append(closestPeers, p)
}
return closestPeers, nil
}
|
package ipfs
import (
"context"
routing "gx/ipfs/QmPpYHPRGVpSJTkQDQDwTYZ1cYUR2NM4HS6M3iAXi8aoUa/go-libp2p-kad-dht"
"gx/ipfs/QmTRhk7cgjUf2gfQ3p2M9KPECNZEW9XUrmHcFCgog4cPgB/go-libp2p-peer"
)
func Query(dht *routing.IpfsDHT, peerID string) ([]peer.ID, error) {
id, err := peer.IDB58Decode(peerID)
if err != nil {
return nil, err
}
ch, err := dht.GetClosestPeers(context.Background(), string(id))
if err != nil {
return nil, err
}
var closestPeers []peer.ID
events := make(chan struct{})
go func() {
defer close(events)
for p := range ch {
closestPeers = append(closestPeers, p)
}
}()
<-events
return closestPeers, nil
}
|
Tweak to make the new NativeStore indexes property *optional*.
|
package net.fortytwo.twitlogic.persistence.sail;
import net.fortytwo.twitlogic.TwitLogic;
import net.fortytwo.twitlogic.persistence.SailFactory;
import net.fortytwo.twitlogic.util.properties.PropertyException;
import net.fortytwo.twitlogic.util.properties.TypedProperties;
import org.openrdf.sail.Sail;
import org.openrdf.sail.SailException;
import org.openrdf.sail.nativerdf.NativeStore;
import java.io.File;
import java.util.logging.Logger;
/**
* User: josh
* Date: May 18, 2010
* Time: 5:26:47 PM
*/
public class NativeStoreFactory extends SailFactory {
private static final Logger LOGGER = TwitLogic.getLogger(NativeStoreFactory.class);
public NativeStoreFactory(final TypedProperties conf) {
super(conf);
}
public Sail makeSail() throws SailException, PropertyException {
File dir = conf.getFile(TwitLogic.NATIVESTORE_DIRECTORY);
String indexes = conf.getString(TwitLogic.NATIVESTORE_INDEXES, null);
LOGGER.info("instantiating NativeStore in directory: " + dir);
Sail sail = (null == indexes)
? new NativeStore(dir)
: new NativeStore(dir, indexes.trim());
sail.initialize();
return sail;
}
}
|
package net.fortytwo.twitlogic.persistence.sail;
import net.fortytwo.twitlogic.TwitLogic;
import net.fortytwo.twitlogic.persistence.SailFactory;
import net.fortytwo.twitlogic.util.properties.PropertyException;
import net.fortytwo.twitlogic.util.properties.TypedProperties;
import org.openrdf.sail.Sail;
import org.openrdf.sail.SailException;
import org.openrdf.sail.nativerdf.NativeStore;
import java.io.File;
import java.util.logging.Logger;
/**
* User: josh
* Date: May 18, 2010
* Time: 5:26:47 PM
*/
public class NativeStoreFactory extends SailFactory {
private static final Logger LOGGER = TwitLogic.getLogger(NativeStoreFactory.class);
public NativeStoreFactory(final TypedProperties conf) {
super(conf);
}
public Sail makeSail() throws SailException, PropertyException {
File dir = conf.getFile(TwitLogic.NATIVESTORE_DIRECTORY);
String indexes = conf.getString(TwitLogic.NATIVESTORE_INDEXES);
LOGGER.info("instantiating NativeStore in directory: " + dir);
Sail sail = (null == indexes)
? new NativeStore(dir)
: new NativeStore(dir, indexes.trim());
sail.initialize();
return sail;
}
}
|
Fix submodule attribute check for Django 1.4 compatibility
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'load_template_source')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
Update link to institute in footer to say "Institute for Software Technology"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'DLR'
SITENAME = u'RCE'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
DEFAULT_DATE_FORMAT = '%a %d %B %Y'
THEME = 'themes/polar'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Institute for Software Technology', 'https://www.dlr.de/sc'),
('Imprint', '/pages/imprint.html'),
('Privacy', '/pages/privacy.html'),)
# Social widget
SOCIAL = (('Twitter', 'https://twitter.com/RCEnvironment'),
('YouTube', 'https://www.youtube.com/user/rcenvironment'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
# Static paths
STATIC_PATHS = ['images', 'pages/images', 'extra/CNAME']
# Plugins
PLUGIN_PATHS = ["plugins", "d:\\rce\\plugins"]
PLUGINS = ['pelican-page-hierarchy.page_hierarchy',]
# Github pages domain name
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'DLR'
SITENAME = u'RCE'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
DEFAULT_DATE_FORMAT = '%a %d %B %Y'
THEME = 'themes/polar'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
# Blogroll
LINKS = (('Simulation and Software Technology', 'https://www.dlr.de/sc'),
('Imprint', '/pages/imprint.html'),
('Privacy', '/pages/privacy.html'),)
# Social widget
SOCIAL = (('Twitter', 'https://twitter.com/RCEnvironment'),
('YouTube', 'https://www.youtube.com/user/rcenvironment'),)
DEFAULT_PAGINATION = 10
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True
# Static paths
STATIC_PATHS = ['images', 'pages/images', 'extra/CNAME']
# Plugins
PLUGIN_PATHS = ["plugins", "d:\\rce\\plugins"]
PLUGINS = ['pelican-page-hierarchy.page_hierarchy',]
# Github pages domain name
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
|
Add .git as default ignored file/dir
|
package dotignore
import (
"bufio"
"os"
"path/filepath"
"strings"
"sync"
"github.com/drpotato/dotdot/filesystem"
)
var ignoredFiles map[string]bool
var once sync.Once
func ShouldIgnore(uri string) bool {
GetIgnoredFiles()
dotDirURI := filesystem.GetDotDirURI()
_, fileName := filepath.Split(uri)
return strings.HasPrefix(uri, dotDirURI) && ignoredFiles[fileName]
}
func GetIgnoredFiles() map[string]bool {
once.Do(func() {
ignoredFiles = map[string]bool{
".git": true,
".gitignore": true,
}
loadDotIgnore()
})
return ignoredFiles
}
func loadDotIgnore() {
dotDirURI := filesystem.GetDotDirURI()
dotIgnoreUri := filepath.Join(dotDirURI, ".dotignore")
dotIgnoreFile, err := os.Open(dotIgnoreUri)
if err != nil {
return
}
defer dotIgnoreFile.Close()
scanner := bufio.NewScanner(dotIgnoreFile)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "#") {
continue
}
ignoredFiles[line] = true
}
}
|
package dotignore
import (
"bufio"
"os"
"path/filepath"
"strings"
"sync"
"github.com/drpotato/dotdot/filesystem"
)
var ignoredFiles map[string]bool
var once sync.Once
func ShouldIgnore(uri string) bool {
GetIgnoredFiles()
dotDirURI := filesystem.GetDotDirURI()
_, fileName := filepath.Split(uri)
return strings.HasPrefix(uri, dotDirURI) && ignoredFiles[fileName]
}
func GetIgnoredFiles() map[string]bool {
once.Do(func() {
ignoredFiles = map[string]bool{
".gitignore": true,
}
loadDotIgnore()
})
return ignoredFiles
}
func loadDotIgnore() {
dotDirURI := filesystem.GetDotDirURI()
dotIgnoreUri := filepath.Join(dotDirURI, ".dotignore")
dotIgnoreFile, err := os.Open(dotIgnoreUri)
if err != nil {
return
}
defer dotIgnoreFile.Close()
scanner := bufio.NewScanner(dotIgnoreFile)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "#") {
continue
}
ignoredFiles[line] = true
}
}
|
fix(labels): Fix the demo to remove excess parens
|
import { div, label } from 'hexagon-js'
export default () => {
return [
label().text('Default Label'),
label({ context: 'action' }).text('Action Label'),
label({ context: 'positive' }).text('Positive Label'),
label({ context: 'warning' }).text('Warning Label'),
label({ context: 'negative' }).text('Negative Label'),
label({ context: 'info' }).text('Info Label'),
label({ context: 'complement' }).text('Complement Label'),
label({ context: 'contrast' }).text('Contrast Label'),
div(),
label().classed('hx-label-outline', true).text('Default Label'),
label({ context: 'action' }).classed('hx-label-outline', true).text('Action Label'),
label({ context: 'positive' }).classed('hx-label-outline', true).text('Positive Label'),
label({ context: 'warning' }).classed('hx-label-outline', true).text('Warning Label'),
label({ context: 'negative' }).classed('hx-label-outline', true).text('Negative Label'),
label({ context: 'info' }).classed('hx-label-outline', true).text('Info Label'),
label({ context: 'complement' }).classed('hx-label-outline', true).text('Complement Label'),
label({ context: 'contrast' }).classed('hx-label-outline', true).text('Contrast Label')
]
}
|
import { div, label } from 'hexagon-js'
export default () => {
return [
label().text('Default Label')),
label({ context: 'action' }).text('Action Label')),
label({ context: 'positive' }).text('Positive Label')),
label({ context: 'warning' }).text('Warning Label')),
label({ context: 'negative' }).text('Negative Label')),
label({ context: 'info' }).text('Info Label')),
label({ context: 'complement' }).text('Complement Label')),
label({ context: 'contrast' }).text('Contrast Label')),
div()),
label().classed('hx-label-outline', true).text('Default Label')),
label({ context: 'action' }).classed('hx-label-outline', true).text('Action Label')),
label({ context: 'positive' }).classed('hx-label-outline', true).text('Positive Label')),
label({ context: 'warning' }).classed('hx-label-outline', true).text('Warning Label')),
label({ context: 'negative' }).classed('hx-label-outline', true).text('Negative Label')),
label({ context: 'info' }).classed('hx-label-outline', true).text('Info Label')),
label({ context: 'complement' }).classed('hx-label-outline', true).text('Complement Label')),
label({ context: 'contrast' }).classed('hx-label-outline', true).text('Contrast Label'))
]
}
|
Set token to false by default
|
angular
.module('ngSharepoint')
.provider('$sp', function() {
var siteUrl = '';
var connMode = 'JSOM'; //possible values: JSOM, REST
var token = false;
var autoload = true;
return {
setSiteUrl: function (newUrl) {
siteUrl = newUrl;
},
setConnectionMode: function(connMode) { //Only JSOM Supported for now
if (connMode === 'JSOM' || connMode === 'REST') {
this.connMode = connMode;
}
},
setAccessToken: function(token) {
this.token = token;
},
setAutoload: function(autoload) {
this.autoload = autoload;
},
$get: function() {
return ({
getSiteUrl: function() {
return siteUrl;
},
getConnectionMode: function() {
return connMode;
},
getAccessToken: function(token) {
return token;
},
getContext: function() {
return new SP.ClientContext(siteUrl);
},
getAutoload: function() {
return autoload;
}
});
}
};
});
|
angular
.module('ngSharepoint')
.provider('$sp', function() {
var siteUrl = '';
var connMode = 'JSOM'; //possible values: JSOM, REST
var token = '';
var autoload = true;
return {
setSiteUrl: function (newUrl) {
siteUrl = newUrl;
},
setConnectionMode: function(connMode) { //Only JSOM Supported for now
if (connMode === 'JSOM' || connMode === 'REST') {
this.connMode = connMode;
}
},
setAccessToken: function(token) {
this.token = token;
},
setAutoload: function(autoload) {
this.autoload = autoload;
},
$get: function() {
return ({
getSiteUrl: function() {
return siteUrl;
},
getConnectionMode: function() {
return connMode;
},
getAccessToken: function(token) {
return token;
},
getContext: function() {
return new SP.ClientContext(siteUrl);
},
getAutoload: function() {
return autoload;
}
});
}
};
});
|
Add edge label and rotation.
|
"""
Nodes can contain words
=======================
We here at **Daft** headquarters tend to put symbols (variable
names) in our graph nodes. But you don't have to if you don't
want to.
"""
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_node("cloudy", r"cloudy", 3, 3, aspect=1.8)
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain", label="65\%", xoffset=-.1, label_params={"rotation": 45})
pgm.add_edge("cloudy", "sprinkler", label="35\%", xoffset=.1, label_params={"rotation": -45})
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()
pgm.savefig("wordy.pdf")
pgm.savefig("wordy.png", dpi=150)
|
"""
Nodes can contain words
=======================
We here at **Daft** headquarters tend to put symbols (variable
names) in our graph nodes. But you don't have to if you don't
want to.
"""
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_node("cloudy", r"cloudy", 3, 3, aspect=1.8)
pgm.add_node("rain", r"rain", 2, 2, aspect=1.2)
pgm.add_node("sprinkler", r"sprinkler", 4, 2, aspect=2.1)
pgm.add_node("wet", r"grass wet", 3, 1, aspect=2.4, observed=True)
pgm.add_edge("cloudy", "rain")
pgm.add_edge("cloudy", "sprinkler")
pgm.add_edge("rain", "wet")
pgm.add_edge("sprinkler", "wet")
pgm.render()
pgm.savefig("wordy.pdf")
pgm.savefig("wordy.png", dpi=150)
|
Update teacher survey count script
|
// Print out teacher survey counts by day
// Usage:
// mongo <address>:<port>/<database> <script file> -u <username> -p <password>
var surveyDayMap = {};
var cursor = db['trial.requests'].find();
while (cursor.hasNext()) {
var doc = cursor.next();
var date = doc._id.getTimestamp();
if (doc.created) {
date = doc.created;
}
var day = date.toISOString().substring(0, 10);
if (!surveyDayMap[day]) surveyDayMap[day] = 0;
surveyDayMap[day]++;
}
var surveysSorted = [];
for (var day in surveyDayMap) {
surveysSorted.push({day: day, count: surveyDayMap[day]});
}
surveysSorted.sort(function(a, b) {return a.day.localeCompare(b.day);});
print("Number of teacher surveys per day:")
for (var i = 0; i < surveysSorted.length; i++) {
var stars = new Array(surveysSorted[i].count + 1).join('*');
print(surveysSorted[i].day + "\t" + surveysSorted[i].count + "\t" + stars);
}
|
// Print out teacher survey counts by day
// Usage:
// mongo <address>:<port>/<database> <script file> -u <username> -p <password>
var surveyDayMap = {};
var cursor = db['trial.requests'].find({type: 'subscription'});
while (cursor.hasNext()) {
var doc = cursor.next();
var date = doc._id.getTimestamp();
var day = date.toISOString().substring(0, 10);
if (!surveyDayMap[day]) surveyDayMap[day] = 0;
surveyDayMap[day]++;
}
var surveysSorted = [];
for (var day in surveyDayMap) {
surveysSorted.push({day: day, count: surveyDayMap[day]});
}
surveysSorted.sort(function(a, b) {return b.day.localeCompare(a.day);});
print("Number of teacher surveys per day:")
for (var i = 0; i < surveysSorted.length; i++) {
var stars = new Array(surveysSorted[i].count + 1).join('*');
print(surveysSorted[i].day + "\t" + surveysSorted[i].count + "\t" + stars);
}
|
Fix REST interface of the Behaviour Timeout
|
package net.floodlightcontroller.prediction;
import org.json.JSONObject;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
public class BehaviourManagerResource extends ServerResource {
@Get("json")
public String retrieve() {
INetTopologyService pihr = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
return "{ \"timeout\" : \"" + pihr.getBehaviourStructure().getSleepTime() + "\"}\n";
}
@Post
public String store(String in) {
INetTopologyService service = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
try {
JSONObject jp = new JSONObject(in);
String time = jp.getString("time");
service.getBehaviourStructure().setSleepTime(Integer.parseInt(time));
}
catch(Exception e){
System.out.println(e.getMessage());
return "{ \"status\" : \"err\" }\n";
}
return "{ \"status\" : \"ok\" }\n";
}
}
|
package net.floodlightcontroller.prediction;
import org.json.JSONObject;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
public class BehaviourManagerResource extends ServerResource {
@Get("json")
public String retrieve() {
INetTopologyService pihr = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
return "{ \"timeout\" : \"" + pihr.getBehaviourStructure().getSleepTime() + "\"}\n";
}
@Post
public String store(String in) {
INetTopologyService service = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
try {
JSONObject jp = new JSONObject(in);
String time = jp.getString("time");
service.setTimeout(Integer.parseInt(time));
}
catch(Exception e){
System.out.println(e.getMessage());
return "{ \"status\" : \"err\" }\n";
}
return "{ \"status\" : \"ok\" }\n";
}
}
|
Fix httplib monkey patching problem with Gevent >= 1.0
From v1.0 on, Gevent doesn't support monkey patching of httplib anymore.
CATMAID's example script to run a Gevent WSGI server, however, was still
expecting this to be possible. This commit fixes this.
Thanks to Mikhail Kandel for reporting.
|
#!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all()
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings
setup_environ(settings)
# Configure host and port for the WSGI server
host = getattr(settings, 'WSGI_HOST', '127.0.0.1')
port = getattr(settings, 'WSGI_PORT', 8080)
def runserver():
# Create the server
application = DjangoWSGIApp()
address = host, port
server = WSGIServer( address, application )
# Run the server
try:
server.serve_forever()
except KeyboardInterrupt:
server.stop()
sys.exit(0)
if __name__ == '__main__':
runserver()
|
#!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all(httplib=True)
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings
setup_environ(settings)
# Configure host and port for the WSGI server
host = getattr(settings, 'WSGI_HOST', '127.0.0.1')
port = getattr(settings, 'WSGI_PORT', 8080)
def runserver():
# Create the server
application = DjangoWSGIApp()
address = host, port
server = WSGIServer( address, application )
# Run the server
try:
server.serve_forever()
except KeyboardInterrupt:
server.stop()
sys.exit(0)
if __name__ == '__main__':
runserver()
|
Check that datestamp and status fields exist before setting them, since incoming messages don't have a status view.
|
/*
* Copyright (c) 2015, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.module.messagecenter.view.holder;
import android.view.View;
import android.widget.TextView;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.module.messagecenter.view.MessageView;
/**
* @author Sky Kelsey
*/
public class MessageHolder extends MessageCenterListItemHolder {
public TextView datestamp;
public TextView status;
public MessageHolder(MessageView view) {
datestamp = (TextView) view.findViewById(R.id.datestamp);
status = (TextView) view.findViewById(R.id.status);
}
public void updateMessage(String datestamp, String status) {
if (this.datestamp != null) {
this.datestamp.setText(datestamp);
this.datestamp.setVisibility(datestamp != null ? View.VISIBLE : View.GONE);
}
if (this.status != null) {
this.status.setText(status);
this.status.setVisibility(status != null ? View.VISIBLE : View.GONE);
}
}
}
|
/*
* Copyright (c) 2015, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.module.messagecenter.view.holder;
import android.view.View;
import android.widget.TextView;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.module.messagecenter.view.MessageView;
/**
* @author Sky Kelsey
*/
public class MessageHolder extends MessageCenterListItemHolder {
public TextView datestamp;
public TextView status;
public MessageHolder(MessageView view) {
datestamp = (TextView) view.findViewById(R.id.datestamp);
status = (TextView) view.findViewById(R.id.status);
}
public void updateMessage(String datestamp, String status) {
this.datestamp.setText(datestamp);
this.datestamp.setVisibility(datestamp != null ? View.VISIBLE : View.GONE);
this.status.setText(status);
this.status.setVisibility(status != null ? View.VISIBLE : View.GONE);
}
}
|
Check for errors for operations in BeforeEach and AfterEach/Suite.
Signed-off-by: Phan Le <f2c5995718b197bbd6f63c99e8aab6ee2af1c495@pivotallabs.com>
|
package integration_test
import (
"io/ioutil"
"os"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)
var testCpiFilePath string
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
err := bmtestutils.BuildExecutable()
Expect(err).NotTo(HaveOccurred())
testCpiFilePath, err = bmtestutils.DownloadTestCpiRelease("")
Expect(err).NotTo(HaveOccurred())
})
var (
homePath string
oldHome string
)
BeforeEach(func() {
oldHome = os.Getenv("HOME")
var err error
homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration")
Expect(err).NotTo(HaveOccurred())
err = os.Setenv("HOME", homePath)
Expect(err).NotTo(HaveOccurred())
})
AfterEach(func() {
err := os.Setenv("HOME", oldHome)
Expect(err).NotTo(HaveOccurred())
err = os.RemoveAll(homePath)
Expect(err).NotTo(HaveOccurred())
})
AfterSuite(func() {
err := os.Remove(testCpiFilePath)
Expect(err).NotTo(HaveOccurred())
})
RunSpecs(t, "bosh-micro-cli Integration Suite")
}
|
package integration_test
import (
"io/ioutil"
"os"
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)
var testCpiFilePath string
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
err := bmtestutils.BuildExecutable()
Expect(err).NotTo(HaveOccurred())
testCpiFilePath, err = bmtestutils.DownloadTestCpiRelease("")
Expect(err).NotTo(HaveOccurred())
})
var (
homePath string
oldHome string
)
BeforeEach(func() {
oldHome = os.Getenv("HOME")
var err error
homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration")
Expect(err).NotTo(HaveOccurred())
os.Setenv("HOME", homePath)
})
AfterEach(func() {
os.Setenv("HOME", oldHome)
os.RemoveAll(homePath)
})
AfterSuite(func() {
os.Remove(testCpiFilePath)
})
RunSpecs(t, "bosh-micro-cli Integration Suite")
}
|
release(marvin): Update pins for marvin release
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@release/marvin#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'python-dateutil==2.4.2',
'psqlgraph',
'gdcdictionary',
'dictionaryutils>=2.0.0,<3.0.0',
'cdisutils',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@1.14.0#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
Fix webamp.onTrackDidChange, by actually passing the action to the event emitter
|
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import reducer from "./reducers";
import mediaMiddleware from "./mediaMiddleware";
import { merge } from "./utils";
import { UPDATE_TIME_ELAPSED, STEP_MARQUEE } from "./actionTypes";
const compose = composeWithDevTools({
actionsBlacklist: [UPDATE_TIME_ELAPSED, STEP_MARQUEE]
});
const getStore = (
media,
actionEmitter,
customMiddlewares = [],
stateOverrides
) => {
let initialState;
if (stateOverrides) {
initialState = merge(
reducer(undefined, { type: "@@init" }),
stateOverrides
);
}
// eslint-disable-next-line no-unused-vars
const emitterMiddleware = store => next => action => {
actionEmitter.trigger(action.type, action);
return next(action);
};
return createStore(
reducer,
initialState,
compose(
applyMiddleware(
...[
thunk,
mediaMiddleware(media),
emitterMiddleware,
...customMiddlewares
].filter(Boolean)
)
)
);
};
export default getStore;
|
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import reducer from "./reducers";
import mediaMiddleware from "./mediaMiddleware";
import { merge } from "./utils";
import { UPDATE_TIME_ELAPSED, STEP_MARQUEE } from "./actionTypes";
const compose = composeWithDevTools({
actionsBlacklist: [UPDATE_TIME_ELAPSED, STEP_MARQUEE]
});
const getStore = (
media,
actionEmitter,
customMiddlewares = [],
stateOverrides
) => {
let initialState;
if (stateOverrides) {
initialState = merge(
reducer(undefined, { type: "@@init" }),
stateOverrides
);
}
// eslint-disable-next-line no-unused-vars
const emitterMiddleware = store => next => action => {
actionEmitter.trigger(action.type);
return next(action);
};
return createStore(
reducer,
initialState,
compose(
applyMiddleware(
...[
thunk,
mediaMiddleware(media),
emitterMiddleware,
...customMiddlewares
].filter(Boolean)
)
)
);
};
export default getStore;
|
Fix Integration Test after changing response for index
|
import org.junit.*;
import play.mvc.*;
import play.test.*;
import play.libs.F.*;
import static play.test.Helpers.*;
import static org.junit.Assert.*;
import static org.fluentlenium.core.filter.FilterConstructor.*;
public class IntegrationTest {
/**
* add your integration test here
* in this example we just check if the welcome page is being shown
*/
@Test
public void test() {
running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() {
public void invoke(TestBrowser browser) {
browser.goTo("http://localhost:3333");
assertTrue(browser.pageSource().contains("Welcome to Breakout API. Nothing to see here by now"));
}
});
}
}
|
import org.junit.*;
import play.mvc.*;
import play.test.*;
import play.libs.F.*;
import static play.test.Helpers.*;
import static org.junit.Assert.*;
import static org.fluentlenium.core.filter.FilterConstructor.*;
public class IntegrationTest {
/**
* add your integration test here
* in this example we just check if the welcome page is being shown
*/
@Test
public void test() {
running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() {
public void invoke(TestBrowser browser) {
browser.goTo("http://localhost:3333");
assertTrue(browser.pageSource().contains("Your new application is ready."));
}
});
}
}
|
Add concurrent library to it .
|
package mklib.hosseini.com.vinci.Main;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class Vinci {
private static Context context;
public Vinci(Context context){
Vinci.context = context;
}
public synchronized Drawable PhotoFromDB(byte[] imageByte){
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByte);
Bitmap image = BitmapFactory.decodeStream(imageStream);
return new BitmapDrawable(context.getResources(), image);
}
public synchronized byte[] PhotoInDB(String Url) throws Exception {
ExecutorService service = Executors.newSingleThreadExecutor();
PhotoProcess.logger sumTask = new PhotoProcess.logger(Url);
Future<byte[]> future = service.submit(sumTask);
service.shutdown();
service.awaitTermination(5, TimeUnit.SECONDS);
return future.get();
}
}
|
package mklib.hosseini.com.vinci.Main;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import java.io.ByteArrayInputStream;
public class Vinci {
private static Context context;
public Vinci(Context context){
Vinci.context = context;
}
public synchronized Drawable PhotoFromDB(byte[] imageByte){
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByte);
Bitmap image = BitmapFactory.decodeStream(imageStream);
return new BitmapDrawable(context.getResources(), image);
}
public synchronized byte[] PhotoInDB(String Url) throws Exception {
return new PhotoProcess.logger(Url).call();
}
}
|
Fix bug with Date fields and SOQL.
Fixes https://github.com/freelancersunion/django-salesforce/issues/10
|
# django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
import re
from django.db.backends import BaseDatabaseOperations
"""
Default database operations, with unquoted names.
"""
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "salesforce.backend.compiler"
def __init__(self, connection):
# not calling superclass constructor to maintain Django 1.3 support
self.connection = connection
self._cache = None
def connection_init(self):
pass
def sql_flush(self, style, tables, sequences):
return []
def quote_name(self, name):
return name
def value_to_db_datetime(self, value):
"""
We let the JSON serializer handle dates for us.
"""
return value
def value_to_db_date(self, value):
"""
We let the JSON serializer handle dates for us.
"""
return value
def last_insert_id(self, cursor, db_table, db_column):
return cursor.lastrowid
|
# django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
import re
from django.db.backends import BaseDatabaseOperations
"""
Default database operations, with unquoted names.
"""
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "salesforce.backend.compiler"
def __init__(self, connection):
# not calling superclass constructor to maintain Django 1.3 support
self.connection = connection
self._cache = None
def connection_init(self):
pass
def sql_flush(self, style, tables, sequences):
return []
def quote_name(self, name):
return name
def value_to_db_datetime(self, value):
"""
We let the JSON serializer handle dates for us.
"""
return value
def last_insert_id(self, cursor, db_table, db_column):
return cursor.lastrowid
|
Add line break code at end of marked custom parser result
|
import marked from 'marked';
import htmlclean from 'htmlclean';
import he from 'he';
const renderer = new marked.Renderer();
renderer.listitem = (text) => {
if (/<input[^>]+type="checkbox"/.test(text)) {
return `<li class="task-list-item">${text}</li>\n`;
}
return `<li>${text}</li>\n`;
};
renderer.code = (code, language) => {
const escapedCode = he.escape(code);
return `<pre${language ? ` data-language="${language}"` : ''}>${escapedCode}</pre>\n`;
};
renderer.paragraph = (text) => `<div>${text}</div>\n`;
renderer.blockquote = (text) => {
return `<blockquote>${text.replace(/\n$/, '').split('\n').join('<br />')}</blockquote>\n`;
};
marked.setOptions({
gfm: true,
smartLists: true,
xhtml: true,
renderer
});
const markdownToHTML = (markdown) => htmlclean(marked(markdown));
export default markdownToHTML;
|
import marked from 'marked';
import htmlclean from 'htmlclean';
import he from 'he';
const renderer = new marked.Renderer();
renderer.listitem = (text) => {
if (/<input[^>]+type="checkbox"/.test(text)) {
return `<li class="task-list-item">${text}</li>\n`;
}
return `<li>${text}</li>\n`;
};
renderer.code = (code, language) => {
const escapedCode = he.escape(code);
return `<pre${language ? ` data-language="${language}"` : ''}>${escapedCode}</pre>`;
};
renderer.paragraph = (text) => `<div>${text}</div>\n`;
renderer.blockquote = (text) => {
return `<blockquote>${text.replace(/\n$/, '').split('\n').join('<br />')}</blockquote>`;
};
marked.setOptions({
gfm: true,
smartLists: true,
xhtml: true,
renderer
});
const markdownToHTML = (markdown) => htmlclean(marked(markdown));
export default markdownToHTML;
|
CRM-6171: Prepare correct DQL query for fetching contacts
- Change order of email and phone titles for Contact
|
<?php
namespace Oro\Component\MessageQueue\Consumption;
use Oro\Component\MessageQueue\Transport\MessageInterface;
use Oro\Component\MessageQueue\Transport\SessionInterface;
interface MessageProcessorInterface
{
/**
* Use this constant when the message is processed successfully and the message could be removed from the queue.
*/
const ACK = 'oro.message_queue.consumption.ack';
/**
* Use this constant when the message is not valid or could not be processed
* The message is removed from the queue
*/
const REJECT = 'oro.message_queue.consumption.reject';
/**
* Use this constant when the message is not valid or could not be processed right now but we can try again later
* The original message is removed from the queue but a copy is published to the queue again.
*/
const REQUEUE = 'oro.message_queue.consumption.requeue';
/**
* @param MessageInterface $message
* @param SessionInterface $session
*
* @return string
*/
public function process(MessageInterface $message, SessionInterface $session);
}
|
<?php
namespace Oro\Component\MessageQueue\Consumption;
use Oro\Component\MessageQueue\Transport\MessageInterface;
use Oro\Component\MessageQueue\Transport\SessionInterface;
interface MessageProcessorInterface
{
/**
* Use this constant when the message is processed successfully and the message could be removed from the queue.
*/
const ACK = 'oro.message_queue.consumption.ack';
/**
* Use this constant when the message is not valid or could not be processed
* The message is removed from the queue
*/
const REJECT = 'oro.message_queue.consumption.reject';
/**
* Use this constant when the message is not valid or could not be processed right now but we can try again later
* The original message is removed from the queue but a copy is publsihed to the queue again.
*/
const REQUEUE = 'oro.message_queue.consumption.requeue';
/**
* @param MessageInterface $message
* @param SessionInterface $session
*
* @return string
*/
public function process(MessageInterface $message, SessionInterface $session);
}
|
Remove recently published test for pending events
|
package au.gov.ga.geodesy.domain.model.event;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
public class EventRepositoryImpl implements EventRepositoryCustom {
@PersistenceContext(unitName = "geodesy")
private EntityManager entityManager;
// TODO: move out of custom
public List<Event> getPendingEvents() {
String queryString = "select e from Event e "
+ "where e.timeHandled is null and (e.retries is null or e.retries < " + Event.MAX_RETRIES + ") and (e.timePublished is null)";
TypedQuery<Event> query = entityManager.createQuery(queryString, Event.class);
return query.getResultList();
}
}
|
package au.gov.ga.geodesy.domain.model.event;
import java.time.Instant;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
public class EventRepositoryImpl implements EventRepositoryCustom {
@PersistenceContext(unitName = "geodesy")
private EntityManager entityManager;
public List<Event> getPendingEvents() {
// TODO: try to remove oneMinuteAgo
String queryString = "select e from Event e "
+ "where e.timeHandled is null and (e.retries is null or e.retries < " + Event.MAX_RETRIES + ") and (e.timePublished is null or e.timePublished < :oneMinuteAgo)";
TypedQuery<Event> query = entityManager.createQuery(queryString, Event.class);
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, -1);
query.setParameter("oneMinuteAgo", c.getTime());
return query.getResultList();
}
}
|
Return moment object after parsing
|
import moment from 'moment-timezone';
import AbstractFormat from './abstract';
export default class DateFormat extends AbstractFormat {
format(dateValue, dateFormat, locale, timezone) {
locale = locale || this._locale();
timezone = timezone || this._timezone();
return this
.moment(dateValue, locale, timezone)
.format(dateFormat);
}
moment(dateValue, locale, timezone) {
locale = locale || this._locale();
timezone = timezone || this._timezone();
return moment(dateValue)
.locale(locale)
.tz(timezone);
}
parse(dateValue, dateFormat, locale, timezone) {
locale = locale || this._locale();
timezone = timezone || this._timezone();
return moment.tz(
dateValue,
dateFormat,
locale,
true,
timezone
);
}
}
|
import moment from 'moment-timezone';
import AbstractFormat from './abstract';
export default class DateFormat extends AbstractFormat {
format(dateValue, dateFormat, locale, timezone) {
locale = locale || this._locale();
timezone = timezone || this._timezone();
return this
.moment(dateValue, locale, timezone)
.format(dateFormat);
}
moment(dateValue, locale, timezone) {
locale = locale || this._locale();
timezone = timezone || this._timezone();
return moment(dateValue)
.locale(locale)
.tz(timezone);
}
parse(dateValue, dateFormat, locale, timezone) {
locale = locale || this._locale();
timezone = timezone || this._timezone();
const result = moment.tz(
dateValue,
dateFormat,
locale,
true,
timezone
);
return result.isValid() === true ? result.toDate() : null;
}
}
|
Change env('APP_ENV') to $app->environment() to prevent .env reading again
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
if ($this->app->environment("local")) {
\DB::connection()->enableQueryLog();
}
if ($this->app->environment("local")) {
\Event::listen('kernel.handled', function ($request, $response) {
if ( $request->has('sql-debug') ) {
$queries = \DB::getQueryLog();
dd($queries);
}
});
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
}
|
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
if (env('APP_ENV') === 'local') {
\DB::connection()->enableQueryLog();
}
if (env('APP_ENV') === 'local') {
\Event::listen('kernel.handled', function ($request, $response) {
if ( $request->has('sql-debug') ) {
$queries = \DB::getQueryLog();
dd($queries);
}
});
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
}
|
Check and fast return if object can't move
|
function isArrived(object, target) {
return object.x === target.x && object.y === target.y;
}
function getC(a, b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
function getBeta(b, c) {
return Math.asin(b / c);
}
function getB(c, beta) {
return c * Math.sin(beta);
}
function getAlpha(a, c) {
return Math.asin(a / c);
}
function getA(c, alpha) {
return c * Math.sin(alpha);
}
function round(number) {
if (number < 0) {
return Math.floor(number);
}
return Math.ceil(number);
}
module.exports = function getMove(object, target) {
if (isArrived(object, target)) {
return {
x: 0,
y: 0,
};
}
if (object.speed === 0) {
return {
x: 0,
y: 0,
};
}
const a = target.y - object.y;
const b = target.x - object.x;
const c = getC(a, b);
if (c <= object.speed) {
return {
x: b,
y: a,
};
}
return {
x: round(getB(object.speed, getBeta(b, c))),
y: round(getA(object.speed, getAlpha(a, c))),
};
};
|
function isArrived(object, target) {
return object.x === target.x && object.y === target.y;
}
function getC(a, b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
function getBeta(b, c) {
return Math.asin(b / c);
}
function getB(c, beta) {
return c * Math.sin(beta);
}
function getAlpha(a, c) {
return Math.asin(a / c);
}
function getA(c, alpha) {
return c * Math.sin(alpha);
}
function round(number) {
if (number < 0) {
return Math.floor(number);
}
return Math.ceil(number);
}
module.exports = function getMove(object, target) {
if (isArrived(object, target)) {
return {
x: 0,
y: 0,
};
}
const a = target.y - object.y;
const b = target.x - object.x;
const c = getC(a, b);
if (c <= object.speed) {
return {
x: b,
y: a,
};
}
return {
x: round(getB(object.speed, getBeta(b, c))),
y: round(getA(object.speed, getAlpha(a, c))),
};
};
|
Use Node's `inspect` for error message formation
|
'use strict';
var nodeUtils = require('util');
var REASONS = {
'values' : 'Given objects are not equal',
'types' : 'Given objects are of different types',
'prototypes' : 'Given objects has different prototypes',
'object_property_amounts' : 'Given objects has different key amounts',
'object_property_names' : 'Given objects has different key sets',
'date_timestamps' : 'Given Date objects has different timestamps',
};
function Report(context, actual, expected, reason) {
this.context = context;
this.actual = actual;
this.expected = expected;
this.reason = reason;
if (!REASONS.hasOwnProperty(this.reason)) {
throw Error('Unknown reason for the report: ' +
nodeUtils.inspect(this.reason));
}
}
Report.prototype.toString = function toString() {
var result = '',
index,
path = this.context.path,
length = path.length;
result += REASONS[this.reason];
if (length > 0) {
result += ' at ';
for (index = 0; index < length; index += 1) {
result += '[' + JSON.stringify(path[index]) + ']';
}
}
result +=
' (actual: ' + nodeUtils.inspect(this.actual) +
', expected: ' + nodeUtils.inspect(this.expected) + ')';
return result;
}
module.exports = Report;
|
'use strict';
var nodeUtils = require('util');
var REASONS = {
'values' : 'Given objects are not equal',
'types' : 'Given objects are of different types',
'prototypes' : 'Given objects has different prototypes',
'object_property_amounts' : 'Given objects has different key amounts',
'object_property_names' : 'Given objects has different key sets',
'date_timestamps' : 'Given Date objects has different timestamps',
};
function Report(context, actual, expected, reason) {
this.context = context;
this.actual = actual;
this.expected = expected;
this.reason = reason;
if (!REASONS.hasOwnProperty(this.reason)) {
throw Error('Unknown reason for the report: ' + JSON.stringify(this.reason));
}
}
Report.prototype.toString = function toString() {
var result = '',
index,
path = this.context.path,
length = path.length;
result += REASONS[this.reason];
if (length > 0) {
result += ' at ';
for (index = 0; index < length; index += 1) {
result += '[' + JSON.stringify(path[index]) + ']';
}
}
result +=
' (actual: ' + nodeUtils.inspect(this.actual) +
', expected: ' + nodeUtils.inspect(this.expected) + ')';
return result;
}
module.exports = Report;
|
Change getGenerator method protected to public
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Drupal\AppConsole\Command;
use Drupal\AppConsole\Generator\Generator;
abstract class GeneratorCommand extends ContainerAwareCommand
{
private $generator;
// only useful for unit tests
public function setGenerator(Generator $generator)
{
$this->generator = $generator;
}
abstract protected function createGenerator();
public function getGenerator()
{
if (null === $this->generator) {
$this->generator = $this->createGenerator();
$this->generator->setSkeletonDirs($this->getSkeletonDirs());
$this->generator->setTranslator($this->translator);
}
$this->addMessage('application.console.messages.completed');
return $this->generator;
}
protected function getSkeletonDirs()
{
$skeletonDirs = array();
$skeletonDirs[] = __DIR__.'/../Resources/skeleton';
$skeletonDirs[] = __DIR__.'/../Resources';
return $skeletonDirs;
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Drupal\AppConsole\Command;
use Drupal\AppConsole\Generator\Generator;
abstract class GeneratorCommand extends ContainerAwareCommand
{
private $generator;
// only useful for unit tests
public function setGenerator(Generator $generator)
{
$this->generator = $generator;
}
abstract protected function createGenerator();
protected function getGenerator()
{
if (null === $this->generator) {
$this->generator = $this->createGenerator();
$this->generator->setSkeletonDirs($this->getSkeletonDirs());
$this->generator->setTranslator($this->translator);
}
$this->addMessage('application.console.messages.completed');
return $this->generator;
}
protected function getSkeletonDirs()
{
$skeletonDirs = array();
$skeletonDirs[] = __DIR__.'/../Resources/skeleton';
$skeletonDirs[] = __DIR__.'/../Resources';
return $skeletonDirs;
}
}
|
Add generic types to traversable implementations
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Adapter;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;
// Help opcache.preload discover always-needed symbols
class_exists(CacheItem::class);
/**
* Interface for adapters managing instances of Symfony's CacheItem.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
interface AdapterInterface extends CacheItemPoolInterface
{
/**
* {@inheritdoc}
*
* @return CacheItem
*/
public function getItem($key);
/**
* {@inheritdoc}
*
* @return \Traversable<string, CacheItem>
*/
public function getItems(array $keys = []);
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = '');
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Cache\Adapter;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;
// Help opcache.preload discover always-needed symbols
class_exists(CacheItem::class);
/**
* Interface for adapters managing instances of Symfony's CacheItem.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
interface AdapterInterface extends CacheItemPoolInterface
{
/**
* {@inheritdoc}
*
* @return CacheItem
*/
public function getItem($key);
/**
* {@inheritdoc}
*
* @return \Traversable|CacheItem[]
*/
public function getItems(array $keys = []);
/**
* {@inheritdoc}
*
* @return bool
*/
public function clear(string $prefix = '');
}
|
Use subprocess instead of os.system to git clone.
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.vcs
----------------
Helper functions for working with version control systems.
"""
import logging
import os
import shutil
import subprocess
import sys
from .prompt import query_yes_no
def git_clone(repo, checkout=None):
"""
Clone a git repo to the current directory.
:param repo: Git repo URL ending with .git.
:param checkout: The branch, tag or commit ID to checkout after clone
"""
# Return repo dir
tail = os.path.split(repo)[1]
repo_dir = tail.rsplit('.git')[0]
logging.debug('repo_dir is {0}'.format(repo_dir))
if os.path.isdir(repo_dir):
ok_to_delete = query_yes_no(
"You've cloned {0} before. Is it okay to delete and re-clone it?".format(repo_dir),
default="yes"
)
if ok_to_delete:
shutil.rmtree(repo_dir)
else:
sys.exit()
subprocess.check_call(['git', 'clone', repo], cwd='.')
if checkout is not None:
subprocess.check_call(['git', 'checkout', checkout], cwd=repo_dir)
return repo_dir
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
cookiecutter.vcs
----------------
Helper functions for working with version control systems.
"""
import logging
import os
import shutil
import subprocess
import sys
from .prompt import query_yes_no
def git_clone(repo, checkout=None):
"""
Clone a git repo to the current directory.
:param repo: Git repo URL ending with .git.
:param checkout: The branch, tag or commit ID to checkout after clone
"""
# Return repo dir
tail = os.path.split(repo)[1]
repo_dir = tail.rsplit('.git')[0]
logging.debug('repo_dir is {0}'.format(repo_dir))
if os.path.isdir(repo_dir):
ok_to_delete = query_yes_no(
"You've cloned {0} before. Is it okay to delete and re-clone it?".format(repo_dir),
default="yes"
)
if ok_to_delete:
shutil.rmtree(repo_dir)
else:
sys.exit()
os.system('git clone {0}'.format(repo))
if checkout is not None:
subprocess.check_call(['git', 'checkout', checkout], cwd=repo_dir)
return repo_dir
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.