text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
fix(set): Fix django-pipeline configuration for development/test
|
import os
import sys
# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')
# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')
# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# django-pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
if 'test' in sys.argv:
STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'
STATICFILES_FINDERS = (
'pipeline.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
'pipeline.compilers.stylus.StylusCompiler',
)
# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
'--include {path}/common/static/styl', # Expose common styl lib dir
'--use kouto-swiss',
]).format(path=BASE_DIR)
# Packaging specs for CSS
PIPELINE_CSS = {
'app': {
'source_filenames': [
# ...
],
'output_filename': 'css/app.css',
}
}
# Packaging specs for JavaScript
PIPELINE_JS = {
}
|
import os
import sys
# Disable django-pipeline when in test mode
PIPELINE_ENABLED = 'test' not in sys.argv
# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')
# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')
# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# django-pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_FINDERS = (
'pipeline.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
'pipeline.compilers.stylus.StylusCompiler',
)
# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
'--include {path}/common/static/styl', # Expose common styl lib dir
'--use kouto-swiss',
]).format(path=BASE_DIR)
# Packaging specs for CSS
PIPELINE_CSS = {
'app': {
'source_filenames': [
# ...
],
'output_filename': 'css/app.css',
}
}
# Packaging specs for JavaScript
PIPELINE_JS = {
}
|
Throw an error if the XML is invalid.
|
var sax = require('sax')
var parser = {}
parser.stream = function () {
return sax.createStream({
trim: true,
normalize: true,
lowercase: true
})
}
parser.capture = function (stream) {
return new Promise(function (resolve, reject) {
var frames = [{}]
stream.on('opentagstart', (node) => frames.push({}))
stream.on('attribute', (node) => frames[frames.length - 1][node.name] = node.value)
stream.on('text', (text) => text.trim().length && (frames[frames.length - 1] = text.trim()))
stream.on('closetag', (name) => frames[frames.length - 2][name] = []
.concat(frames[frames.length - 2][name] || [])
.concat(frames.pop()))
stream.on('end', () => resolve(frames.pop()))
stream.on('error', reject)
})
}
module.exports = parser
|
var sax = require('sax')
var parser = {}
parser.stream = function () {
return sax.createStream({
trim: true,
normalize: true,
lowercase: true
})
}
parser.capture = function (stream) {
return new Promise(function (resolve, reject) {
var frames = [{}]
stream.on('opentagstart', (node) => frames.push({}))
stream.on('attribute', (node) => frames[frames.length - 1][node.name] = node.value)
stream.on('text', (text) => text.trim().length && (frames[frames.length - 1] = text.trim()))
stream.on('closetag', (name) => frames[frames.length - 2][name] = []
.concat(frames[frames.length - 2][name] || [])
.concat(frames.pop()))
stream.on('end', () => resolve(frames.pop()))
})
}
module.exports = parser
|
Change project name to avoid pypi conflict
|
#!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""
install_requires = [
'beautifulsoup4==4.4.1',
'requests==2.9.1',
]
setup(
name='pypimirror-simple',
version='0.1.0a0',
description='A simple pypimirror',
long_description=long_description,
author='wilypomegranate',
author_email='wilypomegranate@users.noreply.github.com>',
packages=find_packages(),
test_suite='py.test',
tests_require=['pytest'],
install_requires=install_requires,
entry_points={
'console_scripts': [
'pypimirror = pypimirror.__main__:main',
]
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Systems Administration',
],
)
|
#!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""
install_requires = [
'beautifulsoup4==4.4.1',
'requests==2.9.1',
]
setup(
name='pypimirror',
version='0.1.0a',
description='pypimirror',
long_description=long_description,
author='wilypomegranate',
author_email='wilypomegranate@users.noreply.github.com>',
packages=find_packages(),
test_suite='py.test',
tests_require=['pytest'],
install_requires=install_requires,
entry_points={
'console_scripts': [
'pypimirror = pypimirror.__main__:main',
]
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: Unix',
'Operating System :: POSIX',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Systems Administration',
],
)
|
Update KMS per 2021-06-17 changes
|
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
class ReplicaKey(AWSObject):
resource_type = "AWS::KMS::ReplicaKey"
props = {
"Description": (str, False),
"Enabled": (boolean, False),
"KeyPolicy": (dict, True),
"PendingWindowInDays": (integer, False),
"PrimaryKeyArn": (str, True),
"Tags": (Tags, False),
}
|
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
|
Convert some skips to expected failures.
|
import unittest
from ..utils import TranspileTestCase
class SequenceTests(TranspileTestCase):
def test_unpack_sequence(self):
self.assertCodeExecution("""
x = [1, 2, 3]
a, b, c = x
print(a)
print(b)
print(c)
""")
@unittest.expectedFailure
def test_unpack_sequence_overflow(self):
self.assertCodeExecution("""
x = [1, 2, 3]
a, b = x
print(a)
print(b)
""")
@unittest.expectedFailure
def test_unpack_sequence_underflow(self):
self.assertCodeExecution("""
x = [1, 2]
a, b, c = x
print(a)
print(b)
print(c)
""")
|
import unittest
from ..utils import TranspileTestCase
class SequenceTests(TranspileTestCase):
def test_unpack_sequence(self):
self.assertCodeExecution("""
x = [1, 2, 3]
a, b, c = x
print(a)
print(b)
print(c)
""")
@unittest.skip('Feature not yet implemented')
def test_unpack_sequence_overflow(self):
self.assertCodeExecution("""
x = [1, 2, 3]
a, b = x
print(a)
print(b)
""")
@unittest.skip('Feature not yet implemented')
def test_unpack_sequence_underflow(self):
self.assertCodeExecution("""
x = [1, 2]
a, b, c = x
print(a)
print(b)
print(c)
""")
|
Update method should use KConfig instead of ArrayObject as parameter.
|
<?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Pattern
* @subpackage Observer
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://www.koowa.org
*/
/**
* Abstract observer class to implement the observer design pattern
*
* @author Johan Janssens <johan@koowa.org>
* @category Koowa
* @package Koowa_Pattern
* @subpackage Observer
*/
interface KPatternObserver
{
/**
* Event received in case the observables states has changed
*
* @param object An associative array of arguments
* @return mixed
*/
public function update(KConfig $args);
/**
* This function returns an unique identifier for the object. This id can be used as
* a hash key for storing objects or for identifying an object
*
* @return string A string that is unique
*/
public function getHandle();
}
|
<?php
/**
* @version $Id$
* @category Koowa
* @package Koowa_Pattern
* @subpackage Observer
* @copyright Copyright (C) 2007 - 2010 Johan Janssens and Mathias Verraes. All rights reserved.
* @license GNU GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
* @link http://www.koowa.org
*/
/**
* Abstract observer class to implement the observer design pattern
*
* @author Johan Janssens <johan@koowa.org>
* @category Koowa
* @package Koowa_Pattern
* @subpackage Observer
*/
interface KPatternObserver
{
/**
* Event received in case the observables states has changed
*
* @param object An associative array of arguments
* @return mixed
*/
public function update(ArrayObject $args);
/**
* This function returns an unique identifier for the object. This id can be used as
* a hash key for storing objects or for identifying an object
*
* @return string A string that is unique
*/
public function getHandle();
}
|
Allow to disable deviceCapabilities adapter (i.e. use none)
|
<?php
class CM_Model_DeviceCapabilities extends CM_Model_Abstract {
const TYPE = 20;
/**
* @param string $userAgent
*/
public function __construct($userAgent) {
$userAgent = (string) $userAgent;
$this->_setCacheLocal();
$this->_construct(array('id' => (string) $userAgent));
}
/**
* @return string
*/
public function getUserAgent() {
return $this->getId();
}
/**
* @return boolean
*/
public function isMobile() {
return $this->_get('mobile');
}
/**
* @return boolean
*/
public function isTablet() {
return $this->_get('tablet');
}
/**
* @return boolean
*/
public function hasTouchscreen() {
return $this->_get('hasTouchscreen');
}
protected function _loadData() {
$default = array('mobile' => false, 'tablet' => false, 'hasTouchscreen' => false);
$adapterClass = self::_getConfig()->adapter;
if (!$adapterClass) {
return $default;
}
/** @var CM_DeviceCapabilitiesAdapter_Abstract $adapter */
$adapter = new $adapterClass($this->getUserAgent());
$capabilities = $adapter->getCapabilities();
if (null === $capabilities) {
return $default;
}
return $capabilities;
}
}
|
<?php
class CM_Model_DeviceCapabilities extends CM_Model_Abstract {
const TYPE = 20;
/**
* @param string $userAgent
*/
public function __construct($userAgent) {
$userAgent = (string) $userAgent;
$this->_setCacheLocal();
$this->_construct(array('id' => (string) $userAgent));
}
/**
* @return string
*/
public function getUserAgent() {
return $this->getId();
}
/**
* @return boolean
*/
public function isMobile() {
return $this->_get('mobile');
}
/**
* @return boolean
*/
public function isTablet() {
return $this->_get('tablet');
}
/**
* @return boolean
*/
public function hasTouchscreen() {
return $this->_get('hasTouchscreen');
}
protected function _loadData() {
$adapterClass = self::_getConfig()->adapter;
/** @var CM_DeviceCapabilitiesAdapter_Abstract $adapter */
$adapter = new $adapterClass($this->getUserAgent());
$capabilities = $adapter->getCapabilities();
if (is_null($capabilities)) {
$capabilities = array('mobile' => false, 'tablet' => false, 'hasTouchscreen' => false);
}
return $capabilities;
}
}
|
Make it a single test case
|
from models import AuthenticationError,AuthenticationRequired
from trello import Trello
import unittest
import os
class TrelloTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
self.assertEquals(
len(self._trello.list_boards()),
int(os.environ['TRELLO_TEST_BOARD_COUNT']))
def test10_board_attrs(self):
boards = self._trello.list_boards()
for b in boards:
self.assertIsNotNone(b['_id'], msg="_id not provided")
self.assertIsNotNone(b['name'], msg="name not provided")
self.assertIsNotNone(b['closed'], msg="closed not provided")
if __name__ == "__main__":
unittest.main()
|
from models import AuthenticationError,AuthenticationRequired
from trello import Trello
import unittest
import os
class BoardTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
print "list boards"
self.assertEquals(
len(self._trello.list_boards()),
int(os.environ['TRELLO_TEST_BOARD_COUNT']))
def test02_board_attrs(self):
print "board attrs"
boards = self._trello.list_boards()
for b in boards:
self.assertIsNotNone(b['_id'], msg="_id not provided")
self.assertIsNotNone(b['name'], msg="name not provided")
self.assertIsNotNone(b['closed'], msg="closed not provided")
class CardTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
if __name__ == "__main__":
unittest.main()
|
Make the const properties enumerable.
|
import _ from 'lodash';
export function defineConstProperties(obj, properties) {
_.forEach(properties, (v, k) => defineConstProperty(obj, k, v));
return obj;
}
export function defineConstProperty(obj, name, value) {
return Object.defineProperty(obj, name, {
value,
enumerable: true,
configurable: false,
writable: false
});
}
export function defineGeneratedProperties(obj, properties) {
_.forEach(properties, (v, k) => defineGeneratedProperty(obj, k, v));
return obj;
}
export function defineGeneratedProperty(obj, name, generator) {
return Object.defineProperty(obj, name, {
configurable: true,
get() {
const value = generator.call(this);
defineConstProperty(this, name, value);
return value;
}
});
}
export function defineStagingProperty(obj, name, value, resolver) {
return Object.defineProperty(obj, name, {
configurable: true,
get() {
const v = resolver.call(this, value);
if (_.isUndefined(v)) {
return value;
} else {
defineConstProperty(obj, name, v);
return v;
}
}
});
}
|
import _ from 'lodash';
export function defineConstProperties(obj, properties) {
_.forEach(properties, (v, k) => defineConstProperty(obj, k, v));
return obj;
}
export function defineConstProperty(obj, name, value) {
return Object.defineProperty(obj, name, {
value,
configurable: false,
writable: false
});
}
export function defineGeneratedProperties(obj, properties) {
_.forEach(properties, (v, k) => defineGeneratedProperty(obj, k, v));
return obj;
}
export function defineGeneratedProperty(obj, name, generator) {
return Object.defineProperty(obj, name, {
configurable: true,
get() {
const value = generator.call(this);
defineConstProperty(this, name, value);
return value;
}
});
}
export function defineStagingProperty(obj, name, value, resolver) {
return Object.defineProperty(obj, name, {
configurable: true,
get() {
const v = resolver.call(this, value);
if (_.isUndefined(v)) {
return value;
} else {
defineConstProperty(obj, name, v);
return v;
}
}
});
}
|
Add functions for retrieving the view center and position
|
function Annotation(id, viewPos, dataPos, dataPosProj) {
this.id = id;
this.minX = viewPos[0];
this.maxX = viewPos[1];
this.minY = viewPos[2];
this.maxY = viewPos[3];
this.cX = (this.maxX - this.minX) / 2;
this.cY = (this.maxY - this.minY) / 2;
this.minXData = dataPos[0];
this.maxXData = dataPos[1];
this.minYData = dataPos[2];
this.maxYData = dataPos[3];
this.minXDataProj = dataPosProj[0];
this.maxXDataProj = dataPosProj[1];
this.minYDataProj = dataPosProj[2];
this.maxYDataProj = dataPosProj[3];
this.importance = 0;
}
Annotation.prototype.getViewPosition = function getViewPosition() {
return [
this.minX,
this.maxX,
this.minY,
this.maxY,
];
};
Annotation.prototype.getViewPositionCenter = function getViewPositionCenter() {
return [
this.cX,
this.cY,
];
};
Annotation.prototype.getDataPosition = function getDataPosition() {
return [
this.minXData,
this.maxXData,
this.minYData,
this.maxYData,
];
};
Annotation.prototype.getImportance = function getImportance() {
return this.importance;
};
Annotation.prototype.setImportance = function setImportance(importance) {
this.importance = importance;
};
export default Annotation;
|
function Annotation(id, viewPos, dataPos, dataPosProj) {
this.id = id;
this.minX = viewPos[0];
this.maxX = viewPos[1];
this.minY = viewPos[2];
this.maxY = viewPos[3];
this.cX = (this.maxX - this.minX) / 2;
this.cY = (this.maxY - this.minY) / 2;
this.minXData = dataPos[0];
this.maxXData = dataPos[1];
this.minYData = dataPos[2];
this.maxYData = dataPos[3];
this.minXDataProj = dataPosProj[0];
this.maxXDataProj = dataPosProj[1];
this.minYDataProj = dataPosProj[2];
this.maxYDataProj = dataPosProj[3];
this.importance = 0;
}
Annotation.prototype.getDataPosition = function getDataPosition() {
return [
this.minXData,
this.maxXData,
this.minYData,
this.maxYData,
];
};
Annotation.prototype.getImportance = function getImportance() {
return this.importance;
};
Annotation.prototype.setImportance = function setImportance(importance) {
this.importance = importance;
};
export default Annotation;
|
Return WorldPay instance from Service Provider
|
<?php namespace PhilipBrown\WorldPay;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
class WorldPayServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('philipbrown/worldpay');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['worldpay'] = $this->app->share(function($app)
{
$wp = new WorldPay;
$wp->setConfig(Config::get('worldpay'));
return $wp;
});
$this->app->booting(function()
{
$loader = AliasLoader::getInstance();
$loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('WorldPay');
}
}
|
<?php namespace PhilipBrown\WorldPay;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
class WorldPayServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('philipbrown/worldpay');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['worldpay'] = $this->app->share(function($app)
{
$wp = new WorldPay;
$wp->setConfig(Config::get('worldpay'));
});
$this->app->booting(function()
{
$loader = AliasLoader::getInstance();
$loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay');
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('WorldPay');
}
}
|
Fix documentation for method getLastError
|
<?php
namespace Gelf\Transport;
use Gelf\MessageInterface as Message;
/**
* A wrapper for any AbstractTransport to ignore any kind of errors
* @package Gelf\Transport
*/
class IgnoreErrorTransportWrapper extends AbstractTransport
{
/**
* @var AbstractTransport
*/
private $transport;
/**
* @var \Exception|null
*/
private $lastError = null;
/**
* IgnoreErrorTransportWrapper constructor.
*
* @param AbstractTransport $transport
*/
public function __construct(AbstractTransport $transport)
{
$this->transport = $transport;
}
/**
* Sends a Message over this transport.
*
* @param Message $message
*
* @return int the number of bytes sent
*/
public function send(Message $message)
{
try {
return $this->transport->send($message);
} catch (\Exception $e) {
$this->lastError = $e;
return 0;
}
}
/**
* Returns the last error
* @return \Exception|null
*/
public function getLastError()
{
return $this->lastError;
}
}
|
<?php
namespace Gelf\Transport;
use Gelf\MessageInterface as Message;
/**
* A wrapper for any AbstractTransport to ignore any kind of errors
* @package Gelf\Transport
*/
class IgnoreErrorTransportWrapper extends AbstractTransport
{
/**
* @var AbstractTransport
*/
private $transport;
/**
* @var \Exception|null
*/
private $lastError = null;
/**
* IgnoreErrorTransportWrapper constructor.
*
* @param AbstractTransport $transport
*/
public function __construct(AbstractTransport $transport)
{
$this->transport = $transport;
}
/**
* Sends a Message over this transport.
*
* @param Message $message
*
* @return int the number of bytes sent
*/
public function send(Message $message)
{
try {
return $this->transport->send($message);
} catch (\Exception $e) {
$this->lastError = $e;
return 0;
}
}
/**
* Returns the last error
* @return \Exception
*/
public function getLastError()
{
return $this->lastError;
}
}
|
Add a dismiss button to the alert
|
@extends('larapress.layouts.master')
@section('head.extension')
{{ HTML::style('larapress/assets/css/pages/home/login.css') }}
@stop
@section('body')
<div id="wrapper">
<div id="login-box">
<img src="{{ asset('larapress/assets/png/logo.png') }}">
{{-- Messages --}}
@if ( Session::has('error') )
<div class="alert alert-danger alert-dismissable fade in">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>@lang('messages.Error')!</strong>
@lang('messages.' . Session::get('error'))
</div>
@endif
@yield('content')
</div>
<p id="copyright">
© {{{ $now->year }}} <a href="http://kontakt.hettiger.com" target="_blank">Martin Hettiger</a> |
Powered by <a href="http://laravel.com" target="_blank">Laravel</a>
</p>
</div>
@stop
|
@extends('larapress.layouts.master')
@section('head.extension')
{{ HTML::style('larapress/assets/css/pages/home/login.css') }}
@stop
@section('body')
<div id="wrapper">
<div id="login-box">
<img src="{{ asset('larapress/assets/png/logo.png') }}">
{{-- Messages --}}
@if ( Session::has('error') )
<div class="alert alert-danger">
<strong>@lang('messages.Error')!</strong>
@lang('messages.' . Session::get('error'))
</div>
@endif
@yield('content')
</div>
<p id="copyright">
© {{{ $now->year }}} <a href="http://kontakt.hettiger.com" target="_blank">Martin Hettiger</a> |
Powered by <a href="http://laravel.com" target="_blank">Laravel</a>
</p>
</div>
@stop
|
Add a missing (string) cast to repository.query
Summary: The method returns a PhutilURI object, which json_encode() encodes as "{}" since all the properties are private.
Test Plan:
Examined the output of "repository.query" more carefully:
"0" : {
"name" : "Phabricator",
"callsign" : "P",
"vcs" : "git",
"uri" : "http:\/\/local.aphront.com:8080\/diffusion\/P\/",
"remoteURI" : "git:\/\/github.com\/facebook\/phabricator.git",
"tracking" : true
},
Reviewers: csilvers, btrahan, vrana, jungejason
Reviewed By: csilvers
CC: aran
Differential Revision: https://secure.phabricator.com/D2402
|
<?php
/*
* Copyright 2012 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.
*/
/**
* @group conduit
*/
abstract class ConduitAPI_repository_Method extends ConduitAPIMethod {
protected function buildDictForRepository(PhabricatorRepository $repository) {
return array(
'name' => $repository->getName(),
'callsign' => $repository->getCallsign(),
'vcs' => $repository->getVersionControlSystem(),
'uri' => PhabricatorEnv::getProductionURI($repository->getURI()),
'remoteURI' => (string)$repository->getPublicRemoteURI(),
'tracking' => $repository->getDetail('tracking-enabled'),
);
}
}
|
<?php
/*
* Copyright 2012 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.
*/
/**
* @group conduit
*/
abstract class ConduitAPI_repository_Method extends ConduitAPIMethod {
protected function buildDictForRepository(PhabricatorRepository $repository) {
return array(
'name' => $repository->getName(),
'callsign' => $repository->getCallsign(),
'vcs' => $repository->getVersionControlSystem(),
'uri' => PhabricatorEnv::getProductionURI($repository->getURI()),
'remoteURI' => $repository->getPublicRemoteURI(),
'tracking' => $repository->getDetail('tracking-enabled'),
);
}
}
|
Use fopen r+ instead of rw to fix hhvm tests
|
<?php
namespace ZBateson\MailMimeParser;
use PHPUnit_Framework_TestCase;
/**
* Description of MailMimeParserTest
*
* @group MailMimeParser
* @group Base
* @covers ZBateson\MailMimeParser\MailMimeParser
* @author Zaahid Bateson
*/
class MailMimeParserTest extends PHPUnit_Framework_TestCase
{
public function testConstructMailMimeParser()
{
$mmp = new MailMimeParser();
$this->assertNotNull($mmp);
}
public function testParseFromHandle()
{
$mmp = new MailMimeParser();
$handle = fopen('php://memory', 'r+');
fwrite($handle, 'This is a test');
rewind($handle);
$ret = $mmp->parse($handle);
$this->assertNotNull($ret);
$this->assertInstanceOf('ZBateson\MailMimeParser\Message', $ret);
}
public function testParseFromString()
{
$mmp = new MailMimeParser();
$ret = $mmp->parse('This is a test');
$this->assertNotNull($ret);
$this->assertInstanceOf('ZBateson\MailMimeParser\Message', $ret);
}
}
|
<?php
namespace ZBateson\MailMimeParser;
use PHPUnit_Framework_TestCase;
/**
* Description of MailMimeParserTest
*
* @group MailMimeParser
* @group Base
* @covers ZBateson\MailMimeParser\MailMimeParser
* @author Zaahid Bateson
*/
class MailMimeParserTest extends PHPUnit_Framework_TestCase
{
public function testConstructMailMimeParser()
{
$mmp = new MailMimeParser();
$this->assertNotNull($mmp);
}
public function testParseFromHandle()
{
$mmp = new MailMimeParser();
$handle = fopen('php://memory', 'rw');
fwrite($handle, 'This is a test');
rewind($handle);
$ret = $mmp->parse($handle);
$this->assertNotNull($ret);
$this->assertInstanceOf('ZBateson\MailMimeParser\Message', $ret);
}
public function testParseFromString()
{
$mmp = new MailMimeParser();
$ret = $mmp->parse('This is a test');
$this->assertNotNull($ret);
$this->assertInstanceOf('ZBateson\MailMimeParser\Message', $ret);
}
}
|
Make a point about CoffeeScript.
|
module.exports = normalize
var isValid = require("./is_valid")
var fixer = require("./fixer")
var fieldsToFix = ['name','version','description','repository'
,'files','bin','man','keywords','readme']
var otherThingsToFix = ['dependencies','people']
var thingsToFix = fieldsToFix.map(function(fieldName) {
return ucFirst(fieldName) + "Field"
})
// two ways to do this in CoffeeScript on only one line, sub-70 chars:
// thingsToFix = fieldsToFix.map (name) -> ucFirst(name) + "Field"
// thingsToFix = (ucFirst(name) + "Field" for name in fieldsToFix)
thingsToFix = thingsToFix.concat(otherThingsToFix)
function normalize (data, warn) {
if(!warn) warn = function(msg) { /* noop */ }
isValid(data, warn) // don't care if it's valid, we'll make it valid
if (data.scripts &&
data.scripts.install === "node-gyp rebuild" &&
!data.scripts.preinstall) {
data.gypfile = true
}
fixer.warn = warn
thingsToFix.forEach(function(thingName) {
fixer["fix" + ucFirst(thingName)](data)
})
data._id = data.name + "@" + data.version
if (data.modules) delete data.modules // modules field is deprecated
}
function ucFirst (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
|
module.exports = normalize
var isValid = require("./is_valid")
var fixer = require("./fixer")
var fieldsToFix = ['name','version','description','repository'
,'files','bin','man','keywords','readme']
var otherThingsToFix = ['dependencies','people']
var thingsToFix = fieldsToFix.map(function(fieldName) {
return ucFirst(fieldName) + "Field"
})
thingsToFix = thingsToFix.concat(otherThingsToFix)
function normalize (data, warn) {
if(!warn) warn = function(msg) { /* noop */ }
isValid(data, warn) // don't care if it's valid, we'll make it valid
if (data.scripts &&
data.scripts.install === "node-gyp rebuild" &&
!data.scripts.preinstall) {
data.gypfile = true
}
fixer.warn = warn
thingsToFix.forEach(function(thingName) {
fixer["fix" + ucFirst(thingName)](data)
})
data._id = data.name + "@" + data.version
if (data.modules) delete data.modules // modules field is deprecated
}
function ucFirst (string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
|
Fix some deprecated things for NC 14
|
<?php
/**
* Nextcloud - Phone Sync
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Loic Blot <loic.blot@unix-experience.fr>
* @copyright Loic Blot 2014-2017
*/
namespace OCA\OcSms\AppInfo;
if (class_exists('\OCP\AppFramework\App')) {
\OC::$server->getNavigationManager()->add(array(
// the string under which your app will be referenced in owncloud
'id' => 'ocsms',
// sorting weight for the navigation. The higher the number, the higher
// will it be listed in the navigation
'order' => 10,
// the route that will be shown on startup
'href' => \OC::$server->getURLGenerator()->linkToRoute('ocsms.sms.index'),
// the icon that will be shown in the navigation
// this file needs to exist in img/
'icon' => \OC::$server->getURLGenerator()->imagePath('ocsms', 'app.svg'),
// the title of your application. This will be used in the
// navigation or on the settings page of your app
'name' => \OCP\Util::getL10N('ocsms')->t('Phone Sync')
));
} else {
$msg = 'Can not enable the OcSms app because the App Framework App is disabled';
\OC::$server->getLogger()->error($msg, array('ocsms'));
}
|
<?php
/**
* Nextcloud - Phone Sync
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Loic Blot <loic.blot@unix-experience.fr>
* @copyright Loic Blot 2014-2017
*/
namespace OCA\OcSms\AppInfo;
if (class_exists('\OCP\AppFramework\App')) {
\OC::$server->getNavigationManager()->add(array(
// the string under which your app will be referenced in owncloud
'id' => 'ocsms',
// sorting weight for the navigation. The higher the number, the higher
// will it be listed in the navigation
'order' => 10,
// the route that will be shown on startup
'href' => \OCP\Util::linkToRoute('ocsms.sms.index'),
// the icon that will be shown in the navigation
// this file needs to exist in img/
'icon' => \OCP\Util::imagePath('ocsms', 'app.svg'),
// the title of your application. This will be used in the
// navigation or on the settings page of your app
'name' => \OCP\Util::getL10N('ocsms')->t('Phone Sync')
));
} else {
$msg = 'Can not enable the OcSms app because the App Framework App is disabled';
\OCP\Util::writeLog('ocsms', $msg, \OCP\Util::ERROR);
}
|
Update reshapeNewsData to use allNewsSelector and pass state to it
|
/* NewsFeedContainer.js
* Container for our NewsFeed as a view
* Dependencies: ActionTypes
* Modules: NewsActions, and NewsFeed
* Author: Tiffany Tse
* Created: July 29, 2017
*/
//import dependencie
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
//import modules
import { loadNews } from '../actions/NewsActions.js';
import NewsFeed from '../component/NewsFeed.js';
import { reshapeNewsData } from '../util/DataTransformations.js';
import { allNewsSelector } from '../selectors/NewsSelectors.js';
//create state for mapStateToProps which exposes state tree's news property as a prop
//to NewsFeed called news
const mapStateToProps = state ({
news: allNewsSelector(state);
});
//create the dispatcher for actions as a prop
const mapDispatchToProps = dispatch => (
bindActionCreators({ loadNews}, dispatch)
);
//export mapStateToProps and mapDispatchToProps as props to to newsFeed
export default connect(mapStateToProps, mapDispatchToProps)(NewsFeed);
|
/* NewsFeedContainer.js
* Container for our NewsFeed as a view
* Dependencies: ActionTypes
* Modules: NewsActions, and NewsFeed
* Author: Tiffany Tse
* Created: July 29, 2017
*/
//import dependencie
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
//import modules
import { loadNews } from '../actions/NewsActions.js';
import NewsFeed from '../component/NewsFeed.js';
import { reshapeNewsData } from '../util/DataTransformations.js';
import { allNewsSelector } from '../selectors/NewsSelectors.js';
//create state for mapStateToProps which exposes state tree's news property as a prop
//to NewsFeed called news
const mapStateToProps = state ({
news: reshapeNewsData(state.news);
});
//create the dispatcher for actions as a prop
const mapDispatchToProps = dispatch => (
bindActionCreators({ loadNews}, dispatch)
);
//export mapStateToProps and mapDispatchToProps as props to to newsFeed
export default connect(mapStateToProps, mapDispatchToProps)(NewsFeed);
|
Use global request context, because None url_rule sometimes
|
""" Session interface switcher """
from flask.sessions import SecureCookieSessionInterface, SessionMixin
from dockci.util import is_api_request
class FakeSession(dict, SessionMixin):
""" Transient session-like object """
pass
class SessionSwitchInterface(SecureCookieSessionInterface):
"""
Session interface that uses ``SecureCookieSessionInterface`` methods,
unless there's no session cookie and it's an API request
"""
def __init__(self, app):
self.app = app
def open_session(self, app, request):
session_id = request.cookies.get(self.app.session_cookie_name)
if not session_id and is_api_request():
return FakeSession()
return super(SessionSwitchInterface, self).open_session(
app, request,
)
def save_session(self, app, session, response):
if isinstance(session, FakeSession):
return
return super(SessionSwitchInterface, self).save_session(
app, session, response,
)
|
""" Session interface switcher """
from flask.sessions import SecureCookieSessionInterface, SessionMixin
from dockci.util import is_api_request
class FakeSession(dict, SessionMixin):
""" Transient session-like object """
pass
class SessionSwitchInterface(SecureCookieSessionInterface):
"""
Session interface that uses ``SecureCookieSessionInterface`` methods,
unless there's no session cookie and it's an API request
"""
def __init__(self, app):
self.app = app
def open_session(self, app, request):
session_id = request.cookies.get(self.app.session_cookie_name)
if not session_id and is_api_request(request):
return FakeSession()
return super(SessionSwitchInterface, self).open_session(
app, request,
)
def save_session(self, app, session, response):
if isinstance(session, FakeSession):
return
return super(SessionSwitchInterface, self).save_session(
app, session, response,
)
|
Remove bad argument to enqueue to prevent strict error.
|
<?php
/*
* This file is part of WPCore project.
*
* (c) Louis-Michel Raynauld <louismichel@pweb.ca>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WPCore;
/**
* WP style admin
*
* @author Louis-Michel Raynauld <louismichel@pweb.ca>
*/
class WPstyleAdmin extends WPstyle
{
protected $admin_page = array();
public function __construct($admin_page, $handle, $src = "", $deps = array(),$ver = false, $media = 'all')
{
parent::__construct($handle, $src, $deps, $ver, $media);
if(!is_array($admin_page))
{
$this->admin_page[] = $admin_page;
}
else
{
$this->admin_page = $admin_page;
}
}
public function is_needed($page)
{
if(empty($this->admin_page)) return true;
return in_array($page, $this->admin_page);
}
public function enqueue()
{
$page = func_get_arg(0);
if($this->is_needed($page))
{
parent::enqueue();
}
}
}
|
<?php
/*
* This file is part of WPCore project.
*
* (c) Louis-Michel Raynauld <louismichel@pweb.ca>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WPCore;
/**
* WP style admin
*
* @author Louis-Michel Raynauld <louismichel@pweb.ca>
*/
class WPstyleAdmin extends WPstyle
{
protected $admin_page = array();
public function __construct($admin_page, $handle, $src = "", $deps = array(),$ver = false, $media = 'all')
{
parent::__construct($handle, $src, $deps, $ver, $media);
if(!is_array($admin_page))
{
$this->admin_page[] = $admin_page;
}
else
{
$this->admin_page = $admin_page;
}
}
public function is_needed($page)
{
if(empty($this->admin_page)) return true;
return in_array($page, $this->admin_page);
}
public function enqueue($page)
{
if($this->is_needed($page))
{
parent::enqueue();
}
}
}
|
Replace HTML-encoded & with &
|
import _ from 'lodash';
function extractHrefs(htmlBody) {
const matchHref = /href="([^\"]*)"/g;
let results = [];
let match;
while (match = matchHref.exec(htmlBody)) {
results.push(match[1]);
}
return results;
}
function toMatchInfo(hrefs) {
const matchHistoryUrl = _.find(hrefs, href => {
return href.search(/matchhistory/i) !== -1;
});
const replayUrl = _.find(hrefs, href => {
return href.search(/replay.gg\/\?r=/i) !== -1;
});
const replayUnsubscribeUrl = _.find(hrefs, href => {
return href.search(/replay.gg\/\?remove=/i) !== -1;
});
if (matchHistoryUrl && replayUrl && replayUnsubscribeUrl) {
const matchId = parseInt(matchHistoryUrl.match(/\/(\d+)\//)[1], 10);
return {
matchId,
matchHistoryUrl,
replayUrl,
replayUnsubscribeUrl: replayUnsubscribeUrl.replace('&', '&'),
};
}
}
export default function parseReplaygg(emailBody) {
const matchInfo = toMatchInfo(extractHrefs(emailBody));
if (!matchInfo) {
console.error(`ERROR, Could not parse email:\n${emailBody}`);
}
return matchInfo;
}
|
import _ from 'lodash';
function extractHrefs(htmlBody) {
const matchHref = /href="([^\"]*)"/g;
let results = [];
let match;
while (match = matchHref.exec(htmlBody)) {
results.push(match[1]);
}
return results;
}
function toMatchInfo(hrefs) {
const matchHistoryUrl = _.find(hrefs, href => {
return href.search(/matchhistory/i) !== -1;
});
const replayUrl = _.find(hrefs, href => {
return href.search(/replay.gg\/\?r=/i) !== -1;
});
const replayUnsubscribeUrl = _.find(hrefs, href => {
return href.search(/replay.gg\/\?remove=/i) !== -1;
});
if (matchHistoryUrl && replayUrl && replayUnsubscribeUrl) {
const matchId = parseInt(matchHistoryUrl.match(/\/(\d+)\//)[1], 10);
return {
matchId,
matchHistoryUrl,
replayUrl,
replayUnsubscribeUrl,
};
}
}
export default function parseReplaygg(emailBody) {
const matchInfo = toMatchInfo(extractHrefs(emailBody));
if (!matchInfo) {
console.error(`ERROR, Could not parse email:\n${emailBody}`);
}
return matchInfo;
}
|
Add test for trimming leading/trailing whitespace
|
var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
it('should add string to trie', function() {
expect(trie.add('test')).to.be.undefined;
});
it('should correctly find an added string', function() {
trie.add('test');
expect(trie.find('test')).to.be.true;
});
it('should trim leading/trailing spaces when adding a string', function() {
trie.add(' test ');
expect(trie.find('test')).to.be.true;
});
});
|
var Trie = require('../app/trie');
describe('Trie', function() {
var trie;
beforeEach(function() {
trie = new Trie();
});
it('should be an object', function() {
expect(trie).to.be.ok;
});
it('should have a root', function() {
expect(trie.root).to.be.ok;
});
it('should have add method', function() {
expect(trie.add).to.be.an.instanceof(Function);
});
it('should have search method', function() {
expect(trie.search).to.be.an.instanceof(Function);
});
it('should have find method', function() {
expect(trie.find).to.be.an.instanceof(Function);
});
it('should add string to trie', function() {
expect(trie.add('test')).to.be.undefined;
});
it('should correctly find an added string', function() {
trie.add('test');
expect(trie.find('test')).to.be.true;
});
});
|
Raise an exception when setting a construct's type to None.
|
from django.db import models
from tmapi.exceptions import ModelConstraintException
from construct import Construct
class Typed (Construct, models.Model):
"""Indicates that a Topic Maps construct is typed. `Association`s,
`Role`s, `Occurrence`s, and `Name`s are typed."""
type = models.ForeignKey('Topic', related_name='typed_%(class)ss')
class Meta:
abstract = True
app_label = 'tmapi'
def get_type (self):
"""Returns the type of this construct.
:rtype: the `Topic` that represents the type
"""
return self.type
def set_type (self, construct_type):
"""Sets the type of this construct. Any previous type is overridden.
:param construct_type: the `Topic` that should define the
nature of this construct
"""
if construct_type is None:
raise ModelConstraintException
self.type = construct_type
self.save()
|
from django.db import models
from construct import Construct
class Typed (Construct, models.Model):
"""Indicates that a Topic Maps construct is typed. `Association`s,
`Role`s, `Occurrence`s, and `Name`s are typed."""
type = models.ForeignKey('Topic', related_name='typed_%(class)ss')
class Meta:
abstract = True
app_label = 'tmapi'
def get_type (self):
"""Returns the type of this construct.
:rtype: the `Topic` that represents the type
"""
return self.type
def set_type (self, construct_type):
"""Sets the type of this construct. Any previous type is overridden.
:param construct_type: the `Topic` that should define the
nature of this construct
"""
self.type = construct_type
self.save()
|
Use `fs.access` instead of `fs.existsSync`
|
'use strict'
const github = require('octonode')
const https = require('https')
const path = require('path')
const fs = require('fs')
const basePath = path.join(__dirname, '..', '..', 'locale', 'en', 'blog', 'weekly-updates')
const repo = github.client().repo('nodejs/evangelism')
/* Currently proof-of-concept work. Outstanding:
* ================
* - [ ] gulpify
* - [ ] add to local boot process or trigger at key times
* - [ ] support other content patterns (meeting notes, release notes, etc.)
* - [ ] support similar patterns for other locales
* - [ ] prepend predictable markdown metadata on download
*/
function checkOrFetchFile (file) {
const filePath = path.join(basePath, file.name)
fs.access(filePath, function (err) {
if (!err) {
console.log(`Weekly Update ${filePath} exists. (No SHA check, yet.)`)
return
}
console.log(`Weekly Update ${filePath} does not exist. Downloading.`)
https.get(file.download_url, function (response) {
console.log(`Weekly Update ${filePath} downloaded.`)
response.pipe(fs.createWriteStream(filePath))
})
})
}
repo.contents('weekly-updates', function (err, files) {
if (err) { throw err }
files.forEach(checkOrFetchFile)
})
|
'use strict'
var github = require('octonode')
var client = github.client()
var evRepo = client.repo('nodejs/evangelism')
var https = require('https')
var path = require('path')
var fs = require('fs')
/* Currently proof-of-concept work. Outstanding:
* ================
* - [ ] gulpify
* - [ ] add to local boot process or trigger at key times
* - [ ] support other content patterns (meeting notes, release notes, etc.)
* - [ ] support similar patterns for other locales
* - [ ] prepend predictable markdown metadata on download
*/
function checkOrFetchFile (file) {
let name = file.name
let downloadUrl = file.download_url
let localPath = path.join(__dirname, '..', '..', 'locale', 'en', 'blog', 'weekly-updates', name)
if (fs.existsSync(localPath)) {
console.log(`Weekly Update ${name} exists. (No SHA check, yet.)`)
return
}
console.log(`Weekly Update ${name} does not exist. Downloading.`)
var outputFile = fs.createWriteStream(localPath)
https.get(downloadUrl, function (response) {
response.pipe(outputFile)
})
}
evRepo.contents('weekly-updates', function (err, files) {
if (err) { throw err }
files.forEach(checkOrFetchFile)
})
|
Refactor of comma separated list to selectbox & other inputs.
|
// Take the comma separated list for {field} from {item}.{field} and populate the select#{field} box
// Any of the values in the comma separated list for {field} that doesn't have an option in select#{field}
// Get stuffed into {field}Other as it's own comma separated list.
function setupDisplayFieldsEducationTab(item, field) {
if (item[field] != '' && $('select#'+field)[0] != undefined) {
var itemOptions = item[field].split(',');
$('select#'+field+' option').each(function() {
if ($.inArray($(this).val(),itemOptions) !== -1) {
$(this).attr('selected',true);
}
});
var selectOptions = $('select#'+field+' option').map(function() { return this.value });
var otherOptions = [];
for (i in itemOptions) {
if ($.inArray(itemOptions[i], selectOptions) === -1) {
otherOptions.push(itemOptions[i]);
}
}
if (otherOptions.length > 0) {
$('#'+field+'Other').attr('value',otherOptions.join(','));
}
}
}
|
function setupDisplayFieldsEducationTab(TempObject, selectBox){
// This code is needed to merge the multiselect field and the "other" input field per
if (typeof TempObject[selectBox] != 'undefined') {
if (TempObject[selectBox] != "") {
var optionsToSelect = TempObject[selectBox];
var select = document.getElementById( [selectBox] );
for ( var i = 0, l = select.options.length, o; i < l; i++ ){
o = select.options[i];
var tempO = o;
if ( optionsToSelect.toLowerCase().indexOf( tempO.text.toLowerCase() ) != -1 ) {
o.selected = true;
optionsToSelect = optionsToSelect.replace(o.text,"");
optionsToSelect = optionsToSelect.replace(/,,/g,",");
optionsToSelect = optionsToSelect.replace(/^,/g,"");
}
else document.getElementById( [selectBox]+'Other' ).value = optionsToSelect;
}
}
}
}
|
Use the remote getter call only on objects with an object_type.
|
# -*- coding: utf-8 -*-
class Manager(object):
# should be re-defined in a subclass
state_name = None
object_type = None
def __init__(self, api):
self.api = api
# shortcuts
@property
def state(self):
return self.api.state
@property
def queue(self):
return self.api.queue
class AllMixin(object):
def all(self, filt=None):
return list(filter(filt, self.state[self.state_name]))
class GetByIdMixin(object):
def get_by_id(self, obj_id, only_local=False):
"""
Finds and returns the object based on its id.
"""
for obj in self.state[self.state_name]:
if obj['id'] == obj_id or obj.temp_id == str(obj_id):
return obj
if not only_local and self.object_type is not None:
getter = getattr(self.api, 'get_%s' % self.object_type)
return getter(obj_id)
return None
class SyncMixin(object):
"""
Syncs this specific type of objects.
"""
def sync(self):
return self.api.sync()
|
# -*- coding: utf-8 -*-
class Manager(object):
# should be re-defined in a subclass
state_name = None
object_type = None
def __init__(self, api):
self.api = api
# shortcuts
@property
def state(self):
return self.api.state
@property
def queue(self):
return self.api.queue
class AllMixin(object):
def all(self, filt=None):
return list(filter(filt, self.state[self.state_name]))
class GetByIdMixin(object):
def get_by_id(self, obj_id, only_local=False):
"""
Finds and returns the object based on its id.
"""
for obj in self.state[self.state_name]:
if obj['id'] == obj_id or obj.temp_id == str(obj_id):
return obj
if not only_local:
getter = getattr(self.api, 'get_%s' % self.object_type)
return getter(obj_id)
return None
class SyncMixin(object):
"""
Syncs this specific type of objects.
"""
def sync(self):
return self.api.sync()
|
Remove EsLint preloader from tests
|
process.env.NODE_ENV = 'test';
const path = require('path');
const DefinePlugin = require('webpack/lib/DefinePlugin')
var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js'));
webpackConfig.devtool = 'inline-source-map';
webpackConfig.plugins.push(new DefinePlugin({
DOMAIN: JSON.stringify('apiary.dev')
}));
webpackConfig.module.preLoaders = [];
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['src/**/iframe/**/**.test.js', 'src/**/JsAgent/**/**.test.js'],
exclude: [],
preprocessors: { 'src/**/**.test.js': ['webpack', 'sourcemap'] },
webpack: webpackConfig,
reporters: ['mocha', 'junit'],
junitReporter: {
outputDir: `${process.env.CIRCLE_TEST_REPORTS || '.'}/unit/iframe`,
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'Firefox'],
singleRun: true,
concurrency: 1,
});
}
|
process.env.NODE_ENV = 'test';
const path = require('path');
const DefinePlugin = require('webpack/lib/DefinePlugin')
var webpackConfig = require(path.join(__dirname, './node_modules/react-scripts/config/webpack.config.dev.js'));
webpackConfig.devtool = 'inline-source-map';
webpackConfig.plugins.push(new DefinePlugin({
DOMAIN: JSON.stringify('apiary.dev')
}));
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['src/**/iframe/**/**.test.js', 'src/**/JsAgent/**/**.test.js'],
exclude: [],
preprocessors: { 'src/**/**.test.js': ['webpack', 'sourcemap'] },
webpack: webpackConfig,
reporters: ['mocha', 'junit'],
junitReporter: {
outputDir: `${process.env.CIRCLE_TEST_REPORTS || '.'}/unit/iframe`,
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'Firefox'],
singleRun: true,
concurrency: 1,
});
}
|
Fix issue with confirm group order
|
Template.callButton.events({
'click .call-button': function (event, template) {
$(event.target)
.data('working-text', 'Working...')
.button('working')
.prop('disabled', true);
if (typeof template.data.buttonMethodArgs === 'string' || template.data.buttonMethodArgs instanceof String) {
if(template.data.buttonMethodArgs.match(/\(\)$/)) {
args = [eval(template.data.buttonMethodArgs)];
} else {
args = template.data.buttonMethodArgs;
}
} else {
args = template.data.buttonMethodArgs;
}
Meteor.apply(template.data.buttonMethod, args, function(error, result) {
$(event.target).button('reset').prop('disabled', false);;
if (error) {
$('#error-modal').modal();
console.log(error)
Session.set('call-button-error', error.message)
} else {
if (typeof template.data.buttonOnSuccess === "function") {
template.data.buttonOnSuccess(result);
}
}
});
}
});
Template.callButton.helpers({
style: function() {
return this.buttonStyle?this.buttonStyle:'success'
}
});
|
Template.callButton.events({
'click .call-button': function (event, template) {
$(event.target)
.data('working-text', 'Working...')
.button('working')
.prop('disabled', true);
if(template.data.buttonMethodArgs.match(/\(\)$/)) {
args = [eval(template.data.buttonMethodArgs)];
} else {
args = template.data.buttonMethodArgs;
}
Meteor.apply(template.data.buttonMethod, args, function(error, result) {
$(event.target).button('reset').prop('disabled', false);;
if (error) {
$('#error-modal').modal();
console.log(error)
Session.set('call-button-error', error.message)
} else {
if (typeof template.data.buttonOnSuccess === "function") {
template.data.buttonOnSuccess(result);
}
}
});
}
});
Template.callButton.helpers({
style: function() {
return this.buttonStyle?this.buttonStyle:'success'
}
});
|
Enable passing in a callback in promise constructors
|
var Class = require('./Class'),
invokeWith = require('./invokeWith'),
slice = require('./slice'),
each = require('./each'),
bind = require('./bind')
module.exports = Class(function() {
this.init = function(callback) {
this._dependants = []
this._fulfillment = null
if (callback) { this.add(callback) }
}
this.add = function(callback) {
if (this._fulfillment) { callback.apply(this, this._fulfillment) }
else { this._dependants.push(callback) }
}
this.fulfill = function(/* arg1, arg2, ...*/) {
if (this._fulfillment) { throw new Error('Promise fulfilled twice') }
this._fulfillment = slice(arguments)
each(this._dependants, invokeWith.apply(this, this._fulfillment))
delete this._dependants
}
this.nextTickAdd = function(callback) {
setTimeout(bind(this, this.add, callback), 0)
}
})
|
var Class = require('./Class'),
invokeWith = require('./invokeWith'),
slice = require('./slice'),
each = require('./each'),
bind = require('./bind')
module.exports = Class(function() {
this.init = function() {
this._dependants = []
this._fulfillment = null
}
this.add = function(callback) {
if (this._fulfillment) { callback.apply(this, this._fulfillment) }
else { this._dependants.push(callback) }
}
this.fulfill = function(/* arg1, arg2, ...*/) {
if (this._fulfillment) { throw new Error('Promise fulfilled twice') }
this._fulfillment = slice(arguments)
each(this._dependants, invokeWith.apply(this, this._fulfillment))
delete this._dependants
}
this.nextTickAdd = function(callback) {
setTimeout(bind(this, this.add, callback), 0)
}
})
|
Remove final modifier from UUID so games can alter it if needed
|
package com.bitdecay.jump.level;
import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.annotation.CantInspect;
import com.bitdecay.jump.geom.BitPointInt;
import com.bitdecay.jump.geom.BitRectangle;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public abstract class LevelObject {
@CantInspect
public BitRectangle rect;
@CantInspect
public String uuid = UUID.randomUUID().toString();
public LevelObject() {
// Here for JSON
}
public LevelObject(BitRectangle rect) {
this.rect = rect;
}
@JsonIgnore
public abstract BitBody buildBody();
public abstract String name();
public boolean selects(BitPointInt point) {
return rect.contains(point);
}
public boolean selects(BitRectangle selectionRect) {
return selectionRect.contains(rect);
}
}
|
package com.bitdecay.jump.level;
import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.annotation.CantInspect;
import com.bitdecay.jump.geom.BitPointInt;
import com.bitdecay.jump.geom.BitRectangle;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public abstract class LevelObject {
@CantInspect
public BitRectangle rect;
@CantInspect
public final String uuid = UUID.randomUUID().toString();
public LevelObject() {
// Here for JSON
}
public LevelObject(BitRectangle rect) {
this.rect = rect;
}
@JsonIgnore
public abstract BitBody buildBody();
public abstract String name();
public boolean selects(BitPointInt point) {
return rect.contains(point);
}
public boolean selects(BitRectangle selectionRect) {
return selectionRect.contains(rect);
}
}
|
Move input event processing to its own method
|
package screens
import (
"groggy/world"
"github.com/nsf/termbox-go"
"groggy/widgets"
)
func mainMapProcessInput(worldState *world.WorldState, event termbox.Event) {
level := worldState.CurrentLevel
player := worldState.PlayerCharacter
switch event.Key {
case termbox.KeyArrowLeft:
if player.MapEntity.X > 0 {
player.MapEntity.X -= 1
}
case termbox.KeyArrowRight:
if player.MapEntity.X < level.Width - 1 {
player.MapEntity.X += 1
}
case termbox.KeyArrowUp:
if player.MapEntity.Y > 0 {
player.MapEntity.Y -= 1
}
case termbox.KeyArrowDown:
if player.MapEntity.Y < level.Height - 1 {
player.MapEntity.Y += 1
}
}
}
func MainMapLoop(worldState *world.WorldState) {
for {
widgets.DrawMainMap(0, 2, worldState)
widgets.DrawStatusBar(0, 23, worldState)
termbox.Flush()
event := termbox.PollEvent()
if event.Key == termbox.KeyEsc {
break
}
mainMapProcessInput(worldState, event)
}
}
|
package screens
import (
"groggy/world"
"github.com/nsf/termbox-go"
"groggy/widgets"
)
func MainMapLoop(worldState *world.WorldState) {
level := worldState.CurrentLevel
player := worldState.PlayerCharacter
for {
widgets.DrawMainMap(0, 2, worldState)
widgets.DrawStatusBar(0, 23, worldState)
termbox.Flush()
event := termbox.PollEvent()
if event.Key == termbox.KeyEsc {
termbox.HideCursor()
break
}
switch event.Key {
case termbox.KeyArrowLeft:
if player.MapEntity.X > 0 {
player.MapEntity.X -= 1
}
case termbox.KeyArrowRight:
if player.MapEntity.X < level.Width - 1 {
player.MapEntity.X += 1
}
case termbox.KeyArrowUp:
if player.MapEntity.Y > 0 {
player.MapEntity.Y -= 1
}
case termbox.KeyArrowDown:
if player.MapEntity.Y < level.Height - 1 {
player.MapEntity.Y += 1
}
}
}
}
|
Add info about csv fields
|
# csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('csv', help="""CSV file to convert. Fields are : Index,Illumina_SNP_Name,Alternative_SNP_Name,Chromosome,Build36_Position,Build37_Position,new_rsname,Strand,TopAlleles,ForwardAlleles,DesignAlleles
""")
parser.add_argument('map', help='MAP file to create')
args = parser.parse_args()
# read the csv file and convert it into a MAP file
with open(args.csv, 'r') as fdr:
with open(args.map, 'w') as fdw:
for line in fdr:
line_split = line.split(',')
fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])]))
fdw.close()
fdr.close()
if __name__ == "__main__":
main()
|
# csv2map.py -- Convert .csv into a .map format
# Description of MAP format: http://pngu.mgh.harvard.edu/~purcell/plink/data.shtml#map
#
# jean-daniel.granet@mines-paristech.fr
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description='Convert .csv to .map')
parser.add_argument('csv', help='CSV file to convert')
parser.add_argument('map', help='MAP file to create')
args = parser.parse_args()
# read the csv file and convert it into a MAP file
with open(args.csv, 'r') as fdr:
with open(args.map, 'w') as fdw:
for line in fdr:
line_split = line.split(',')
fdw.write("%s\n" % "\n".join(["%s %s 0 %s" % (line_split[3], line_split[2], line_split[5])]))
fdw.close()
fdr.close()
if __name__ == "__main__":
main()
|
Set open_basedir to restrict file access to the current directory
|
<?php
use App\Bootstrap\ViewComposer;
use App\Controllers;
use DI\Container;
use DI\Bridge\Slim\Bridge;
use Dotenv\Dotenv;
use PHLAK\Config\Config;
use Slim\Views\Twig;
require __DIR__ . '/vendor/autoload.php';
/** Set some restrictions */
ini_set('open_basedir', __DIR__);
/** Initialize environment variable handler */
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();
/** Create the container */
$container = new Container();
/** Register dependencies */
$container->set(Config::class, new Config('app/config'));
$container->set(Twig::class, function (Config $config) {
return new Twig("app/themes/{$config->get('theme')}", [
'cache' => $config->get('view_cache', 'app/cache/views')
]);
});
/** Configure the view handler */
$container->call(ViewComposer::class);
/** Create the application */
$app = Bridge::create($container);
/** Register routes */
$app->get('/[{path:.*}]', Controllers\DirectoryController::class);
/** Enagage! */
$app->run();
|
<?php
use App\Bootstrap\ViewComposer;
use App\Controllers;
use DI\Container;
use DI\Bridge\Slim\Bridge;
use Dotenv\Dotenv;
use PHLAK\Config\Config;
use Slim\Views\Twig;
require __DIR__ . '/vendor/autoload.php';
/** Initialize environment variable handler */
$dotenv = Dotenv::create(__DIR__);
$dotenv->load();
/** Create the container */
$container = new Container();
/** Register dependencies */
$container->set(Config::class, new Config('app/config'));
$container->set(Twig::class, function (Config $config) {
return new Twig("app/themes/{$config->get('theme')}", [
'cache' => $config->get('view_cache', 'app/cache/views')
]);
});
/** Configure the view handler */
$container->call(ViewComposer::class);
/** Create the application */
$app = Bridge::create($container);
/** Register routes */
$app->get('/[{path:.*}]', Controllers\DirectoryController::class);
/** Enagage! */
$app->run();
|
atests: Fix getting Windows system encoding on non-ASCII envs
|
from os.path import abspath, dirname, join, normpath
import locale
import os
import subprocess
import robot
__all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING',
'CONSOLE_ENCODING']
ROBOTPATH = dirname(abspath(robot.__file__))
ROBOT_VERSION = robot.version.get_version()
DATADIR = normpath(join(dirname(abspath(__file__)), '..', 'testdata'))
SYSTEM_ENCODING = locale.getpreferredencoding(False)
# Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding.
if os.name == 'nt':
output = subprocess.check_output('chcp', shell=True, encoding='ASCII',
errors='ignore')
CONSOLE_ENCODING = 'cp' + output.split()[-1]
else:
CONSOLE_ENCODING = locale.getdefaultlocale()[-1]
|
from os.path import abspath, dirname, join, normpath
import locale
import os
import subprocess
import robot
__all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING',
'CONSOLE_ENCODING']
ROBOTPATH = dirname(abspath(robot.__file__))
ROBOT_VERSION = robot.version.get_version()
DATADIR = normpath(join(dirname(abspath(__file__)), '..', 'testdata'))
SYSTEM_ENCODING = locale.getpreferredencoding(False)
# Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding.
if os.name == 'nt':
output = subprocess.check_output('chcp', shell=True, encoding='ASCII')
CONSOLE_ENCODING = 'cp' + output.split()[-1]
else:
CONSOLE_ENCODING = locale.getdefaultlocale()[-1]
|
Fix menu view not refactored
|
import {inject} from 'aurelia-framework';
import {LayoutService} from './services/layout-service';
import type {RouterConfiguration, Router} from 'aurelia-router';
@inject(LayoutService)
export class App {
router: Router;
layoutService: LayoutService;
constructor(layoutService: LayoutService) {
this.layoutService = layoutService;
}
configureRouter(config: RouterConfiguration, router: Router) {
config.title = 'Bridge calculator';
config.options.pushState = !location.host.includes('github'); // GitHub does not support push state
config.map([
{ route: '', name: 'menu', moduleId: './menu/menu' },
{ route: '/entry', name: 'entry', moduleId: './entry/entry', title: 'New Game' }
]);
this.router = router;
}
showHelp() {
}
back() {
this.router.navigateToRoute('menu');
}
}
|
import {inject} from 'aurelia-framework';
import {LayoutService} from './services/layout-service';
import type {RouterConfiguration, Router} from 'aurelia-router';
@inject(LayoutService)
export class App {
router: Router;
layoutService: LayoutService;
constructor(layoutService: LayoutService) {
this.layoutService = layoutService;
}
configureRouter(config: RouterConfiguration, router: Router) {
config.title = 'Bridge calculator';
config.options.pushState = !location.host.includes('github'); // GitHub does not support push state
config.map([
{ route: '', name: 'menu', moduleId: './menu' },
{ route: '/entry', name: 'entry', moduleId: './entry/entry', title: 'New Game' }
]);
this.router = router;
}
showHelp() {
}
back() {
this.router.navigateToRoute('menu');
}
}
|
Set paymenttype correctly when selecting an account to pay to
|
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { SELECT_PAYMENT_TYPE } from '../actiontypes';
function Paymenttypes(props) {
const { id, className } = props;
const paymentTypeId = useSelector(state => state.transactionTypeId);
const paymenttypes = useSelector(state => state.paymenttypes);
const dispatch = useDispatch();
return (
<select id={id} className={className} onChange={e => dispatch(SELECT_PAYMENT_TYPE(parseInt(e.target.value)))} value={paymentTypeId}>
<option key="-1" value="-1" />
{paymenttypes.map((val) => <option key={val.id} value={val.id}>{val.transactionTypeName}</option>)}
</select>
);
}
export default Paymenttypes;
|
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { SELECT_PAYMENT_TYPE } from '../actiontypes';
function Paymenttypes(props) {
const { id, className } = props;
const paymentTypeId = useSelector(state => state.paymentTypeId);
const paymenttypes = useSelector(state => state.paymenttypes);
const dispatch = useDispatch();
return (
<select id={id} className={className} onChange={e => dispatch(SELECT_PAYMENT_TYPE(parseInt(e.target.value)))} value={paymentTypeId}>
<option key="-1" value="-1" />
{paymenttypes.map((val) => <option key={val.id} value={val.id}>{val.transactionTypeName}</option>)}
</select>
);
}
export default Paymenttypes;
|
fix: Send general alert when update is not available
|
import { ipcMain } from 'electron';
import { autoUpdater } from 'electron-updater';
import {
ON_ACCEPT_UPDATE,
SEND_CHECKING_FOR_UPDATES,
SEND_ERROR,
SEND_GENERAL_ALERT,
SEND_NEEDS_UPDATE
} from '../events';
export default function updater(win) {
const platform = process.platform;
if (platform === 'linux') return;
const log = require('electron-log');
log.transports.file.level = 'info';
autoUpdater.logger = log;
autoUpdater.autoDownload = false;
autoUpdater.checkForUpdates();
autoUpdater.on('checking-for-update', () => {
notify(SEND_CHECKING_FOR_UPDATES);
});
autoUpdater.on('update-not-available', () => {
notify(SEND_GENERAL_ALERT, 'You are currently up-to-date.');
});
autoUpdater.on('update-available', (info) => {
notify(SEND_NEEDS_UPDATE, info.version);
});
autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall();
});
autoUpdater.on('error', () => {
notify(SEND_ERROR, 'Something went wrong while trying to look for updates.');
});
ipcMain.on(ON_ACCEPT_UPDATE, () => {
autoUpdater.downloadUpdate();
});
function notify(channel, message) {
win.webContents.send(channel, message);
}
}
|
import { ipcMain } from 'electron';
import { autoUpdater } from 'electron-updater';
import {
ON_ACCEPT_UPDATE,
SEND_CHECKING_FOR_UPDATES,
SEND_ERROR,
SEND_NEEDS_UPDATE
} from '../events';
export default function updater(win) {
const platform = process.platform;
if (platform === 'linux') return;
const log = require('electron-log');
log.transports.file.level = 'info';
autoUpdater.logger = log;
autoUpdater.autoDownload = false;
autoUpdater.checkForUpdates();
autoUpdater.on('checking-for-update', () => {
notify(SEND_CHECKING_FOR_UPDATES);
});
autoUpdater.on('update-available', (info) => {
notify(SEND_NEEDS_UPDATE, info.version);
});
autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall();
});
autoUpdater.on('error', () => {
notify(SEND_ERROR, 'Something went wrong while trying to look for updates.');
});
ipcMain.on(ON_ACCEPT_UPDATE, () => {
autoUpdater.downloadUpdate();
});
function notify(channel, message) {
win.webContents.send(channel, message);
}
}
|
Add the voodoo object constructions
|
<?php
// run the callback a lot, return average run time in ms
function clock(\Closure $callback, $iterations = 10000) {
$begin = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$callback();
}
$end = microtime(true) - $begin;
return ($end / $iterations)*1000;
}
// nicely show me how long the name ran, and percent increase/decrease over last
function report($name, $time) {
static $last = null;
printf("%-12s: %.8fms", $name, $time);
if (null !== $last) {
printf(", %.1f%%", (($time - $last)/$last)*100);
}
echo PHP_EOL;
$last = $time;
}
// fixtures
$a = str_repeat('a', 2<<8);
class O {
public function strcmp($a) {
strcmp($a, $a);
}
}
// do it
report('direct call', clock(function () use ($a) { strcmp($a, $a); }));
report('object call', clock(function () use ($a) { $o = new O(); $o->strcmp($a); }));
report('voodoo call', clock(function () use ($a) { $o = unserialize('O:1:"O":0:{}'); $o->strcmp($a); }));
|
<?php
// run the callback a lot, return average run time in ms
function clock(\Closure $callback, $iterations = 10000) {
$begin = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$callback();
}
$end = microtime(true) - $begin;
return ($end / $iterations)*1000;
}
// nicely show me how long the name ran, and percent increase/decrease over last
function report($name, $time) {
static $last = null;
printf("%-12s: %.8fms", $name, $time);
if (null !== $last) {
printf(", %.1f%%", (($time - $last)/$last)*100);
}
echo PHP_EOL;
$last = $time;
}
// fixtures
$a = str_repeat('a', 2<<8);
class O {
public function strcmp($a) {
strcmp($a, $a);
}
}
// do it
report('direct call', clock(function () use ($a) { strcmp($a, $a); }));
report('object call', clock(function () use ($a) { $o = new O(); $o->strcmp($a); }));
|
Add version numbers to dependencies
|
from setuptools import setup, find_packages
setup(
name='django-mininews',
version='0.1',
packages=find_packages(exclude=['example_project']),
license='MIT',
description='Boilerplate for creating publishable lists of objects',
long_description=open('README.rst').read(),
install_requires=[
'django-model-utils==2.0.3',
'factory-boy==2.3.1',
],
url='https://github.com/richardbarran/django-mininews',
author='Richard Barran',
author_email='richard@arbee-design.co.uk',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import setup, find_packages
setup(
name='django-mininews',
version='0.1',
packages=find_packages(exclude=['example_project']),
license='MIT',
description='Boilerplate for creating publishable lists of objects',
long_description=open('README.rst').read(),
install_requires=[
'django-model-utils',
'factory-boy',
],
url='https://github.com/richardbarran/django-mininews',
author='Richard Barran',
author_email='richard@arbee-design.co.uk',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Change the "name" to django-auth_mac
|
#from distutils.core import setup
from setuptools import setup
setup(
name='django-auth_mac',
version='0.1',
description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01",
author='Nicholas Devenish',
author_email='n.devenish@gmail.com',
packages=['auth_mac', 'auth_mac.tests'],
license=open('LICENSE.txt').read(),
long_description=open('README.rst').read(),
url='https://github.com/ndevenish/auth_mac',
keywords = ['django', 'authorization', 'MAC'],
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: MIT License",
"Framework :: Django",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Software Development :: Libraries :: Python Modules",
],
install_requires=['django', 'south'],
zip_safe=False,
)
|
#from distutils.core import setup
from setuptools import setup
setup(
name='auth_mac',
version='0.1',
description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01",
author='Nicholas Devenish',
author_email='n.devenish@gmail.com',
packages=['auth_mac', 'auth_mac.tests'],
license=open('LICENSE.txt').read(),
long_description=open('README.rst').read(),
url='https://github.com/ndevenish/auth_mac',
keywords = ['django', 'authorization', 'MAC'],
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"License :: OSI Approved :: MIT License",
"Framework :: Django",
"Operating System :: OS Independent",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Development Status :: 2 - Pre-Alpha",
"Topic :: Software Development :: Libraries :: Python Modules",
],
install_requires=['django', 'south'],
zip_safe=False,
)
|
Remove prin on save_model PublishableAdmin
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
print request.user, request.user.id
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
|
Update to match new framework
|
package dk.statsbiblioteket.medieplatform.newspaper.ninestars;
import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.EventStorer;
import dk.statsbiblioteket.medieplatform.autonomous.EventTrigger;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.RunnableComponent;
import java.util.Properties;
public class MockComponent implements RunnableComponent {
public MockComponent(Properties properties) {
}
@Override
public String getComponentName() {
return "MockComponent";
}
@Override
public String getComponentVersion() {
return getClass().getPackage().getImplementationVersion();
}
@Override
public String getEventID() {
return "Mock_Event";
}
@Override
public void doWorkOnBatch(Batch batch,
ResultCollector resultCollector)
throws
Exception {
return;
}
@Override
public EventTrigger getEventTrigger() {
return null;
}
@Override
public EventStorer getEventStorer() {
return null;
}
}
|
package dk.statsbiblioteket.medieplatform.newspaper.ninestars;
import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.RunnableComponent;
import java.util.Properties;
public class MockComponent implements RunnableComponent {
public MockComponent(Properties properties) {
}
@Override
public String getComponentName() {
return "MockComponent";
}
@Override
public String getComponentVersion() {
return getClass().getPackage().getImplementationVersion();
}
@Override
public String getEventID() {
return "Mock_Event";
}
@Override
public void doWorkOnBatch(Batch batch,
ResultCollector resultCollector)
throws
Exception {
return;
}
}
|
Make /mcnotify match the process of the other commands for getting the
mcMMOPlayer object.
|
package com.gmail.nossr50.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager;
public class McnotifyCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName());
if (mcMMOPlayer.useChatNotifications()) {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.Off"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.On"));
}
mcMMOPlayer.toggleChatNotifications();
return true;
default:
return false;
}
}
}
|
package com.gmail.nossr50.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager;
public class McnotifyCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
switch (args.length) {
case 0:
McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);
if (mcMMOPlayer.useChatNotifications()) {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.Off"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Notifications.On"));
}
mcMMOPlayer.toggleChatNotifications();
return true;
default:
return false;
}
}
}
|
Fix for failing demo setup
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.examples.bpmn.servicetask;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.el.Expression;
/**
* @author Frederik Heremans
*/
public class ToUpperCaseSetterInjected implements JavaDelegate {
private Expression text;
private boolean setterInvoked = false;
public void execute(DelegateExecution execution) {
if(!setterInvoked) {
throw new RuntimeException("Setter was not invoked");
}
execution.setVariable("setterVar", ((String)text.getValue(execution)).toUpperCase());
}
public void setText(Expression text) {
setterInvoked = true;
this.text = text;
}
}
|
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.examples.bpmn.servicetask;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.impl.el.Expression;
import org.junit.Assert;
/**
* @author Frederik Heremans
*/
public class ToUpperCaseSetterInjected implements JavaDelegate {
private Expression text;
private boolean setterInvoked = false;
public void execute(DelegateExecution execution) {
if(!setterInvoked) {
Assert.fail("Setter was not invoked");
}
execution.setVariable("setterVar", ((String)text.getValue(execution)).toUpperCase());
}
public void setText(Expression text) {
setterInvoked = true;
this.text = text;
}
}
|
Make the class public to use from other packages
|
package org.realityforge.gwt.eventsource.client;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import javax.annotation.Nonnull;
public final class TestEventSource
extends EventSource
{
static class Factory
implements EventSource.Factory
{
@Override
public EventSource newEventSource()
{
return new TestEventSource( new SimpleEventBus() );
}
}
public TestEventSource( final EventBus eventBus )
{
super( eventBus );
}
@Override
public void open( @Nonnull final String url, final boolean withCredentials )
{
}
@Override
public boolean subscribeTo( @Nonnull final String messageType )
throws IllegalStateException
{
return false;
}
@Override
public boolean unsubscribeFrom( @Nonnull final String messageType )
throws IllegalStateException
{
return false;
}
@Override
@Nonnull
public String getURL()
{
return "";
}
@Override
public boolean getWithCredentials()
{
return false;
}
@Override
public void close()
{
}
@Nonnull
@Override
public ReadyState getReadyState()
{
return ReadyState.CLOSED;
}
}
|
package org.realityforge.gwt.eventsource.client;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import javax.annotation.Nonnull;
final class TestEventSource
extends EventSource
{
static class Factory
implements EventSource.Factory
{
@Override
public EventSource newEventSource()
{
return new TestEventSource( new SimpleEventBus() );
}
}
TestEventSource( final EventBus eventBus )
{
super( eventBus );
}
@Override
public void open( @Nonnull final String url, final boolean withCredentials )
{
}
@Override
public boolean subscribeTo( @Nonnull final String messageType )
throws IllegalStateException
{
return false;
}
@Override
public boolean unsubscribeFrom( @Nonnull final String messageType )
throws IllegalStateException
{
return false;
}
@Override
@Nonnull
public String getURL()
{
return "";
}
@Override
public boolean getWithCredentials()
{
return false;
}
@Override
public void close()
{
}
@Nonnull
@Override
public ReadyState getReadyState()
{
return ReadyState.CLOSED;
}
}
|
Add missing import statement for igor translator
|
from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import igor_ibw
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
|
from . import be_odf
from . import be_odf_relaxation
from . import beps_ndf
from . import general_dynamic_mode
from . import gmode_iv
from . import gmode_line
from . import image
from . import ndata_translator
from . import numpy_translator
from . import oneview
from . import ptychography
from . import sporc
from . import time_series
from . import translator
from . import utils
from . import df_utils
from .be_odf import BEodfTranslator
from .be_odf_relaxation import BEodfRelaxationTranslator
from .beps_ndf import BEPSndfTranslator
from .general_dynamic_mode import GDMTranslator
from .gmode_iv import GIVTranslator
from .gmode_line import GLineTranslator
from .igor_ibw import IgorIBWTranslator
from .image import ImageTranslator
from .ndata_translator import NDataTranslator
from .numpy_translator import NumpyTranslator
from .oneview import OneViewTranslator
from .ptychography import PtychographyTranslator
from .sporc import SporcTranslator
from .time_series import MovieTranslator
from .translator import Translator
__all__ = ['Translator', 'BEodfTranslator', 'BEPSndfTranslator', 'BEodfRelaxationTranslator',
'GIVTranslator', 'GLineTranslator', 'GDMTranslator', 'PtychographyTranslator',
'SporcTranslator', 'MovieTranslator', 'IgorIBWTranslator', 'NumpyTranslator',
'OneViewTranslator', 'ImageTranslator', 'NDataTranslator']
|
Modify parent filter to return variants and self
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import Q
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from shop_catalog.models import Product
class ProductParentListFilter(SimpleListFilter):
title = _('Parent')
parameter_name = 'parent'
def lookups(self, request, model_admin):
lookups = ()
for product in Product.objects.all():
if product.is_group:
lookups += (product.pk, product.get_name()),
return lookups
def queryset(self, request, queryset):
if self.value():
queryset = queryset.filter(
Q(pk=self.value()) | Q(parent_id=self.value()))
return queryset
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.admin import SimpleListFilter
from django.utils.translation import ugettext_lazy as _
from shop_catalog.models import Product
class ProductParentListFilter(SimpleListFilter):
title = _('Parent')
parameter_name = 'parent'
def lookups(self, request, model_admin):
lookups = ()
for product in Product.objects.all():
if product.is_group:
lookups += (product.pk, product.get_name()),
return lookups
def queryset(self, request, queryset):
if self.value():
try:
return queryset.get(pk=self.value()).variants.all()
except Product.DoesNotExist:
pass
return queryset
|
Fix stupid nltk data download thing
|
# Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
nltk.download("punkt")
# DB
db = boto3.resource("dynamodb",
region_name=app.config["DYNAMO_REGION"],
endpoint_url=app.config["DYNAMO_DATABASE_URI"])
s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"])
from app import models
models.initialize()
# Initialize the controllers
from app import controllers
# Initialize app w/SocketIO
socketio.init_app(app)
# HTTP error handling
@app.errorhandler(404)
def not_found(error):
return render_template("404.html"), 404
|
# Gevent needed for sockets
from gevent import monkey
monkey.patch_all()
# Imports
import os
from flask import Flask, render_template
from flask_socketio import SocketIO
import boto3
# Configure app
socketio = SocketIO()
app = Flask(__name__)
app.config.from_object(os.environ["APP_SETTINGS"])
import nltk
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download("punkt")
# DB
db = boto3.resource("dynamodb",
region_name=app.config["DYNAMO_REGION"],
endpoint_url=app.config["DYNAMO_DATABASE_URI"])
s3 = boto3.resource("s3", region_name=app.config["DYNAMO_REGION"])
from app import models
models.initialize()
# Initialize the controllers
from app import controllers
# Initialize app w/SocketIO
socketio.init_app(app)
# HTTP error handling
@app.errorhandler(404)
def not_found(error):
return render_template("404.html"), 404
|
Return dict object from sentry processor regardless of setting existence
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if not SENTRY_PUBLIC_DSN:
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
|
import os
import logging
from django.conf import settings
log = logging.getLogger(__name__)
def static(request):
"Shorthand static URLs. In debug mode, the JavaScript is not minified."
static_url = settings.STATIC_URL
prefix = 'src' if settings.DEBUG else 'min'
return {
'CSS_URL': os.path.join(static_url, 'stylesheets/css'),
'IMAGES_URL': os.path.join(static_url, 'images'),
'JAVASCRIPT_URL': os.path.join(static_url, 'scripts/javascript', prefix),
}
def alamut(request):
return {
'ALAMUT_URL': settings.ALAMUT_URL,
}
def sentry(request):
SENTRY_PUBLIC_DSN = getattr(settings, 'SENTRY_PUBLIC_DSN', None)
if SENTRY_PUBLIC_DSN:
return {
'SENTRY_PUBLIC_DSN': SENTRY_PUBLIC_DSN
}
log.warning('SENTRY_PUBLIC_DSN not defined in settings.')
|
Create mongoose model after static methods are defined
|
var mongoose = require('mongoose');
// Create a new schema for tweets
var schema = new mongoose.Schema({
twid : String,
active : Boolean,
author : String,
avatar : String,
body : String,
date : Date,
screenname : String
});
// Return tweets from the database
schema.statics.getTweets = function(page, skip, callback) {
var tweets = [];
var start = (page * 10) + (skip * 1);
// Query the database (use skip and limit to achieve page chunks)
Tweet.find(
{},
'twid active author avatar body date screenname',
{ skip: start, limit: 10 }
)
.sort({ date: 'desc' })
.exec(function(err, docs) {
if (!err) {
tweets = docs;
tweets.forEach(function(tweet) {
tweet.active = true;
});
}
callback(tweets);
});
};
var Tweet = mongoose.model('Tweet', schema);
module.exports = Tweet;
|
var mongoose = require('mongoose');
// Create a new schema for tweets
var schema = new mongoose.Schema({
twid : String,
active : Boolean,
author : String,
avatar : String,
body : String,
date : Date,
screenname : String
});
var Tweet = mongoose.model('Tweet', schema);
// Return tweets from the database
schema.statics.getTweets = function(page, skip, callback) {
var tweets = [];
var start = (page * 10) + (skip * 1);
// Query the database (use skip and limit to achieve page chunks)
Tweet.find(
{},
'twid active author avatar body date screenname',
{ skip: start, limit: 10 }
)
.sort({ date: 'desc' })
.exec(function(err, docs) {
if (!err) {
tweets = docs;
tweets.forEach(function(tweet) {
tweet.active = true;
});
}
callback(tweets);
});
};
module.exports = Tweet;
|
Enhance get_stain_matrix to take any desired number of vectors
|
import numpy
from .stain_color_map import stain_color_map
def get_stain_vector(args, index):
"""Get the stain corresponding to args.stain_$index and
args.stain_$index_vector. If the former is not "custom", the
latter must be None.
"""
args = vars(args)
stain = args['stain_' + str(index)]
stain_vector = args['stain_' + str(index) + '_vector']
if stain == 'custom':
if stain_vector is None:
raise ValueError('If "custom" is chosen for a stain, '
'a stain vector must be provided.')
return stain_vector
else:
if stain_vector is None:
return stain_color_map[stain]
raise ValueError('Unless "custom" is chosen for a stain, '
'no stain vector may be provided.')
def get_stain_matrix(args, count=3):
"""Get the stain matrix corresponding to the args.stain_$index and
args.stain_$index_vector arguments for values of index 1 to count.
Return a numpy array of column vectors.
"""
return numpy.array([get_stain_vector(args, i+1) for i in range(count)]).T
__all__ = (
'get_stain_vector',
)
|
import numpy
from .stain_color_map import stain_color_map
def get_stain_vector(args, index):
"""Get the stain corresponding to args.stain_$index and
args.stain_$index_vector. If the former is not "custom", the
latter must be None.
"""
args = vars(args)
stain = args['stain_' + str(index)]
stain_vector = args['stain_' + str(index) + '_vector']
if stain == 'custom':
if stain_vector is None:
raise ValueError('If "custom" is chosen for a stain, '
'a stain vector must be provided.')
return stain_vector
else:
if stain_vector is None:
return stain_color_map[stain]
raise ValueError('Unless "custom" is chosen for a stain, '
'no stain vector may be provided.')
def get_stain_matrix(args):
"""Get the stain matrix corresponding to the args.stain_$index and
args.stain_$index_vector arguments for values of index 1, 2, 3.
Return a numpy array of column vectors.
"""
return numpy.array([get_stain_vector(args, i) for i in 1, 2, 3]).T
__all__ = (
'get_stain_vector',
)
|
Remove previous handler when listener unsubscribed
|
import { Linking } from 'react-native'; // eslint-disable-line import/no-unresolved, max-len
let previousOnLinkChange;
export const dance = (authUrl) => {
if (previousOnLinkChange) {
Linking.removeEventListener('url', previousOnLinkChange);
}
return Linking.openURL(authUrl)
.then(() => new Promise((resolve, reject) => {
const handleUrl = (url) => {
if (!url || url.indexOf('fail') > -1) {
reject(url);
} else {
resolve(url);
}
};
const onLinkChange = ({ url }) => {
Linking.removeEventListener('url', onLinkChange);
previousOnLinkChange = undefined;
handleUrl(url);
};
Linking.addEventListener('url', onLinkChange);
previousOnLinkChange = onLinkChange;
}));
};
export const request = fetch;
|
import { Linking } from 'react-native'; // eslint-disable-line import/no-unresolved, max-len
let previousOnLinkChange;
export const dance = (authUrl) => {
if (previousOnLinkChange) {
Linking.removeEventListener('url', previousOnLinkChange);
}
return Linking.openURL(authUrl)
.then(() => new Promise((resolve, reject) => {
const handleUrl = (url) => {
if (!url || url.indexOf('fail') > -1) {
reject(url);
} else {
resolve(url);
}
};
const onLinkChange = ({ url }) => {
Linking.removeEventListener('url', onLinkChange);
handleUrl(url);
};
Linking.addEventListener('url', onLinkChange);
previousOnLinkChange = onLinkChange;
}));
};
export const request = fetch;
|
Add comments for types and functions to be published
|
package acgen
import (
"fmt"
"io"
"sync"
)
// A Command represents a command which has flags.
type Command struct {
Name string
Flags []*Flag
}
// A Flag represents the information of a flag.
type Flag struct {
Short []string // short options
Long []string // long options
Arg string // argument's name
Description string // help message
}
// A Generator writes a completion for command to w.
type Generator func(w io.Writer, c *Command) error
var (
generatorsMu sync.Mutex
generators = make(map[string]Generator)
)
// RegisterGenerator makes a completion generator available
// by the provided name.
func RegisterGenerator(name string, g Generator) {
generatorsMu.Lock()
defer generatorsMu.Unlock()
if _, dup := generators[name]; dup {
panic("RegisterGenerator called twice for generator " + name)
}
generators[name] = g
}
// LookGenerator returns a completion generator
// specified by its completion generator name.
func LookGenerator(name string) (g Generator, err error) {
generatorsMu.Lock()
defer generatorsMu.Unlock()
if _, ok := generators[name]; !ok {
return nil, fmt.Errorf("%s: is not supported", name)
}
return generators[name], nil
}
|
package acgen
import (
"fmt"
"io"
"sync"
)
type Command struct {
Name string
Flags []*Flag
}
type Flag struct {
Short []string
Long []string
Arg string
Description string
}
type Generator func(w io.Writer, c *Command) error
var (
generatorsMu sync.Mutex
generators = make(map[string]Generator)
)
func RegisterGenerator(name string, g Generator) {
generatorsMu.Lock()
defer generatorsMu.Unlock()
if _, dup := generators[name]; dup {
panic("RegisterGenerator called twice for generator " + name)
}
generators[name] = g
}
func LookGenerator(name string) (g Generator, err error) {
generatorsMu.Lock()
defer generatorsMu.Unlock()
if _, ok := generators[name]; !ok {
return nil, fmt.Errorf("%s: is not supported", name)
}
return generators[name], nil
}
|
Set the isNew flag when finding a feed
|
'use strict';
const request = require('request'),
trans = require('trans'),
chalk = require('chalk');
module.exports = (state, opts, cb) => {
const url = state.conf('api:url'),
existing = state.feed.id,
newCount = state.posts.length,
postCount = Object.keys(state.postGuids).length + newCount;
let dates = trans(state.postGuids).array().pluck('value.date').value();
dates = dates.concat(trans(state.posts).pluck('date').value());
dates = trans(dates).sort(':desc').value();
state.feed.postCount = postCount;
state.feed.lastPostDate = dates[0];
state.log.info(`saving feed ${chalk.green(state.feed.uri)} (${chalk.magenta(newCount)}/${chalk.blue(postCount)})`);
request({
url: existing ? `${url}/feeds/${state.feed.id}` : `${url}/feeds`,
method: existing ? 'PUT' : 'POST',
body: state.feed,
json: true
}, (err, _, body) => {
if (err) {
state.log.error(`failed to update feed ${state.feed.uri}`);
cb(err);
} else {
state.feed = body;
state.feed.isNew = !existing;
cb();
}
});
};
|
'use strict';
const request = require('request'),
trans = require('trans'),
chalk = require('chalk');
module.exports = (state, opts, cb) => {
const url = state.conf('api:url'),
existing = state.feed.id,
newCount = state.posts.length,
postCount = Object.keys(state.postGuids).length + newCount;
let dates = trans(state.postGuids).array().pluck('value.date').value();
dates = dates.concat(trans(state.posts).pluck('date').value());
dates = trans(dates).sort(':desc').value();
state.feed.postCount = postCount;
state.feed.lastPostDate = dates[0];
state.log.info(`saving feed ${chalk.green(state.feed.uri)} (${chalk.magenta(newCount)}/${chalk.blue(postCount)})`);
request({
url: existing ? `${url}/feeds/${state.feed.id}` : `${url}/feeds`,
method: existing ? 'PUT' : 'POST',
body: state.feed,
json: true
}, (err, _, body) => {
if (err) {
state.log.error(`failed to update feed ${state.feed.uri}`);
cb(err);
} else {
state.feed = body;
cb();
}
});
};
|
Add borderRadius to the box prop list
|
import omit from 'lodash.omit';
import pick from 'lodash.pick';
const boxProps = [
'alignContent',
'alignItems',
'alignSelf',
'borderWidth',
'borderBottomWidth',
'borderColor',
'borderLeftWidth',
'borderRightWidth',
'borderTint',
'borderTopWidth',
'borderRadius',
'boxSizing',
'className',
'display',
'element',
'flex',
'flexBasis',
'flexDirection',
'flexGrow',
'flexShrink',
'flexWrap',
'justifyContent',
'margin',
'marginHorizontal',
'marginVertical',
'marginBottom',
'marginLeft',
'marginRight',
'marginTop',
'order',
'overflow',
'overflowX',
'overflowY',
'padding',
'paddingHorizontal',
'paddingVertical',
'paddingBottom',
'paddingLeft',
'paddingRight',
'paddingTop',
'textAlign',
];
const omitBoxProps = props => omit(props, boxProps);
const pickBoxProps = props => pick(props, boxProps);
export default boxProps;
export { omitBoxProps, pickBoxProps };
|
import omit from 'lodash.omit';
import pick from 'lodash.pick';
const boxProps = [
'alignContent',
'alignItems',
'alignSelf',
'borderWidth',
'borderBottomWidth',
'borderColor',
'borderLeftWidth',
'borderRightWidth',
'borderTint',
'borderTopWidth',
'boxSizing',
'className',
'display',
'element',
'flex',
'flexBasis',
'flexDirection',
'flexGrow',
'flexShrink',
'flexWrap',
'justifyContent',
'margin',
'marginHorizontal',
'marginVertical',
'marginBottom',
'marginLeft',
'marginRight',
'marginTop',
'order',
'overflow',
'overflowX',
'overflowY',
'padding',
'paddingHorizontal',
'paddingVertical',
'paddingBottom',
'paddingLeft',
'paddingRight',
'paddingTop',
'textAlign',
];
const omitBoxProps = props => omit(props, boxProps);
const pickBoxProps = props => pick(props, boxProps);
export default boxProps;
export { omitBoxProps, pickBoxProps };
|
Make exception messages more descriptive
|
"""This module defines error classes for typedjsonrpc."""
class Error(Exception):
"""Base class for all errors."""
code = 0
message = None
data = None
def __init__(self, data=None):
super(Error, self).__init__(self.code, self.message, data)
self.data = data
def as_error_object(self):
"""Turns the error into an error object."""
return {
"code": self.code,
"message": self.message,
"data": self.data
}
class ParseError(Error):
"""Invalid JSON was received by the server / JSON could not be parsed."""
code = -32700
message = "Parse error"
class InvalidRequestError(Error):
"""The JSON sent is not a valid request object."""
code = -32600
message = "Invalid request"
class MethodNotFoundError(Error):
"""The method does not exist."""
code = -32601
message = "Method not found"
class InvalidParamsError(Error):
"""Invalid method parameter(s)."""
code = -32602
message = "Invalid params"
class InternalError(Error):
"""Internal JSON-RPC error."""
code = -32603
message = "Internal error"
class ServerError(Error):
"""Something else went wrong."""
code = -32000
message = "Server error"
|
"""This module defines error classes for typedjsonrpc."""
class Error(Exception):
"""Base class for all errors."""
code = 0
message = None
data = None
def __init__(self, data=None):
super(Error, self).__init__()
self.data = data
def as_error_object(self):
"""Turns the error into an error object."""
return {
"code": self.code,
"message": self.message,
"data": self.data
}
class ParseError(Error):
"""Invalid JSON was received by the server / JSON could not be parsed."""
code = -32700
message = "Parse error"
class InvalidRequestError(Error):
"""The JSON sent is not a valid request object."""
code = -32600
message = "Invalid request"
class MethodNotFoundError(Error):
"""The method does not exist."""
code = -32601
message = "Method not found"
class InvalidParamsError(Error):
"""Invalid method parameter(s)."""
code = -32602
message = "Invalid params"
class InternalError(Error):
"""Internal JSON-RPC error."""
code = -32603
message = "Internal error"
class ServerError(Error):
"""Something else went wrong."""
code = -32000
message = "Server error"
|
[completion] Fix sign overflow when comparing matchingDegree
GitOrigin-RevId: eab238ccd73bbb90590e64477d896cec3194c934
|
package com.intellij.codeInsight.completion.impl;
import com.intellij.codeInsight.completion.CompletionService;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import com.intellij.codeInsight.lookup.WeighingContext;
import org.jetbrains.annotations.NotNull;
/**
* @author Peter
*/
public class RealPrefixMatchingWeigher extends LookupElementWeigher {
public RealPrefixMatchingWeigher() {
super("prefix", false, true);
}
@Override
public Comparable weigh(@NotNull LookupElement element, @NotNull WeighingContext context) {
return getBestMatchingDegree(element, CompletionService.getItemMatcher(element, context));
}
public static int getBestMatchingDegree(LookupElement element, PrefixMatcher matcher) {
int max = Integer.MIN_VALUE;
for (String lookupString : element.getAllLookupStrings()) {
max = Math.max(max, matcher.matchingDegree(lookupString));
}
return max == Integer.MIN_VALUE ? Integer.MAX_VALUE : -max;
}
}
|
package com.intellij.codeInsight.completion.impl;
import com.intellij.codeInsight.completion.CompletionService;
import com.intellij.codeInsight.completion.PrefixMatcher;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementWeigher;
import com.intellij.codeInsight.lookup.WeighingContext;
import org.jetbrains.annotations.NotNull;
/**
* @author Peter
*/
public class RealPrefixMatchingWeigher extends LookupElementWeigher {
public RealPrefixMatchingWeigher() {
super("prefix", false, true);
}
@Override
public Comparable weigh(@NotNull LookupElement element, @NotNull WeighingContext context) {
return getBestMatchingDegree(element, CompletionService.getItemMatcher(element, context));
}
public static int getBestMatchingDegree(LookupElement element, PrefixMatcher matcher) {
int max = Integer.MIN_VALUE;
for (String lookupString : element.getAllLookupStrings()) {
max = Math.max(max, matcher.matchingDegree(lookupString));
}
return -max;
}
}
|
Fix compilation issue due to bug in 'old' jdk 'Inference fails for type variable return constraint'
See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954
|
package com.google.sitebricks.options;
import java.lang.reflect.Type;
import java.util.Set;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.sitebricks.conversion.MvelTypeConverter;
import com.google.sitebricks.conversion.TypeConverter;
/**
* Hacky wrapper of MvelTypeConverter to support sets.
*
* @author jochen@pedesis.org (Jochen Bekmann)
*/
public class OptionTypeConverter implements TypeConverter {
@Inject
MvelTypeConverter converter;
@Override
@SuppressWarnings("unchecked")
public <T> T convert(Object source, Type type) {
if (Set.class == type && String.class == source.getClass()) {
Set<String> set = Sets.newHashSet();
for (String s : ((String) source).split(","))
set.add(s.trim());
return (T) set;
}
return (T) converter.convert(source, type);
}
}
|
package com.google.sitebricks.options;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.sitebricks.conversion.MvelTypeConverter;
import com.google.sitebricks.conversion.TypeConverter;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Hacky wrapper of MvelTypeConverter to support sets.
*
* @author jochen@pedesis.org (Jochen Bekmann)
*/
public class OptionTypeConverter implements TypeConverter {
@Inject
MvelTypeConverter converter;
@Override
@SuppressWarnings("unchecked")
public <T> T convert(Object source, Type type) {
if (Set.class == type && String.class == source.getClass()) {
Set<String> set = Sets.newHashSet();
for (String s : ((String) source).split(","))
set.add(s.trim());
return (T) set;
}
return converter.convert(source, type);
}
}
|
Disable the STATE parameter - it doesn't play nice with the SurveyMonkey App Directory links
|
"""
SurveyMonkey OAuth2 backend, docs at:
https://developer.surveymonkey.com/api/v3/#authentication
"""
from .oauth import BaseOAuth2
class SurveyMonkeyOAuth2(BaseOAuth2):
"""SurveyMonkey OAuth2 authentication backend"""
name = 'surveymonkey'
AUTHORIZATION_URL = 'https://api.surveymonkey.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://api.surveymonkey.com/oauth/token'
ACCESS_TOKEN_METHOD = 'POST'
USER_DATA_URL = '/v3/users/me'
STATE_PARAMETER = False
REDIRECT_STATE = False
EXTRA_DATA = [
('access_url', 'access_url'),
]
def get_user_details(self, response):
"""Return user details from a SurveyMonkey /users/me response"""
response["name"] = response['first_name'] + ' ' + response['last_name']
return response
def user_data(self, access_token, *args, **kwargs):
"""Loads user data information from service"""
base_url = kwargs["response"]["access_url"]
return self.get_json(base_url + self.USER_DATA_URL, headers={
'Authorization': 'bearer ' + access_token
})
|
"""
SurveyMonkey OAuth2 backend, docs at:
https://developer.surveymonkey.com/api/v3/#authentication
"""
from .oauth import BaseOAuth2
class SurveyMonkeyOAuth2(BaseOAuth2):
"""SurveyMonkey OAuth2 authentication backend"""
name = 'surveymonkey'
AUTHORIZATION_URL = 'https://api.surveymonkey.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://api.surveymonkey.com/oauth/token'
ACCESS_TOKEN_METHOD = 'POST'
USER_DATA_URL = '/v3/users/me'
EXTRA_DATA = [
('access_url', 'access_url'),
]
def get_user_details(self, response):
"""Return user details from a SurveyMonkey /users/me response"""
response["name"] = response['first_name'] + ' ' + response['last_name']
return response
def user_data(self, access_token, *args, **kwargs):
"""Loads user data information from service"""
base_url = kwargs["response"]["access_url"]
return self.get_json(base_url + self.USER_DATA_URL, headers={
'Authorization': 'bearer ' + access_token
})
|
Fix background color on OS X for histogram widget of ray.
|
"""
TrackingHistogramWidget
:Authors:
Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem
from ui.widgets import Style
class TrackingHistogramWidget(HistogramWidget):
"""
TrackingHistogramWidget
"""
updatePosition = Signal(float)
def __init__(self):
super(TrackingHistogramWidget, self).__init__()
self.nodeItem = None
Style.styleWidgetForTab(self)
def update(self):
super(TrackingHistogramWidget, self).update()
if not self.nodeItem:
return
self.nodeItem.update()
def setHistogram(self, histogram):
super(TrackingHistogramWidget, self).setHistogram(histogram)
if not self.nodeItem:
self.nodeItem = TrackingNodeItem()
self.scene().addItem(self.nodeItem)
self.nodeItem.setHistogramItem(self._histogramItem)
self.nodeItem.setPos(QPoint(0, 0))
self.nodeItem.setZValue(300)
self.nodeItem.delegate = self
def updatePos(self, position):
self.updatePosition.emit(position)
|
"""
TrackingHistogramWidget
:Authors:
Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem
class TrackingHistogramWidget(HistogramWidget):
"""
TrackingHistogramWidget
"""
updatePosition = Signal(float)
def __init__(self):
super(TrackingHistogramWidget, self).__init__()
self.nodeItem = None
def update(self):
super(TrackingHistogramWidget, self).update()
if not self.nodeItem:
return
self.nodeItem.update()
def setHistogram(self, histogram):
super(TrackingHistogramWidget, self).setHistogram(histogram)
if not self.nodeItem:
self.nodeItem = TrackingNodeItem()
self.scene().addItem(self.nodeItem)
self.nodeItem.setHistogramItem(self._histogramItem)
self.nodeItem.setPos(QPoint(0, 0))
self.nodeItem.setZValue(300)
self.nodeItem.delegate = self
def updatePos(self, position):
self.updatePosition.emit(position)
|
Fix another issue with signs
|
package tk.martijn_heil.kingdomessentials.signs;
import com.google.common.base.Preconditions;
import org.bukkit.ChatColor;
import org.bukkit.block.Sign;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
public class Signs
{
public static boolean isKingdomEssSign(@NotNull Sign s)
{
Preconditions.checkNotNull(s, "s can not be null.");
return s.getLine(0).equals(ChatColor.YELLOW + "[KingdomEss]");
}
@Contract(pure = true)
public static boolean isKingdomEssSign(@NotNull String firstLine)
{
Preconditions.checkNotNull(firstLine, "firstLine can not be null.");
return firstLine.equals(ChatColor.YELLOW + "[KingdomEss]");
}
@Contract(pure = true)
public static String getKingdomEssPrefix()
{
return ChatColor.YELLOW + "[KingdomEss]";
}
}
|
package tk.martijn_heil.kingdomessentials.signs;
import com.google.common.base.Preconditions;
import org.bukkit.ChatColor;
import org.bukkit.block.Sign;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
public class Signs
{
public static boolean isKingdomEssSign(@NotNull Sign s)
{
Preconditions.checkNotNull(s, "s can not be null.");
return s.getLine(0).equals(ChatColor.YELLOW + "[KingdomKits]");
}
@Contract(pure = true)
public static boolean isKingdomEssSign(@NotNull String firstLine)
{
Preconditions.checkNotNull(firstLine, "firstLine can not be null.");
return firstLine.equals(ChatColor.YELLOW + "[KingdomEss]");
}
@Contract(pure = true)
public static String getKingdomEssPrefix()
{
return ChatColor.YELLOW + "[KingdomEss]";
}
}
|
Make conditional rendering even shorter syntax
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './boardCard.css';
const BoardCard = ({
alt,
name,
role,
src,
description
}) => (
<div className={styles.boardCard}>
<img className={styles.img} src={src} alt={alt} />
<span className={styles.name}>
{name}
</span>
<hr className={styles.hr} />
<span className={styles.item}>
<span className={styles.upper}>Role: </span> {role}
{description && <p>{description}</p>}
</span>
</div>
);
BoardCard.propTypes = {
name: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
role: PropTypes.string.isRequired,
description: PropTypes.string
};
BoardCard.defaultProps = {
description: null
};
export default BoardCard;
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './boardCard.css';
const BoardCard = ({
alt,
name,
role,
src,
description
}) => (
<div className={styles.boardCard}>
<img className={styles.img} src={src} alt={alt} />
<span className={styles.name}>
{name}
</span>
<hr className={styles.hr} />
<span className={styles.item}>
<span className={styles.upper}>Role: </span> {role}
{description !== null && <p>{description}</p>}
</span>
</div>
);
BoardCard.propTypes = {
name: PropTypes.string.isRequired,
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
role: PropTypes.string.isRequired,
description: PropTypes.string
};
BoardCard.defaultProps = {
description: null
};
export default BoardCard;
|
Check separatorIndex is > -1 instead of truthiness
|
import { currentStoreView } from '@vue-storefront/core/lib/multistore'
import dayjs from 'dayjs'
import dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat'
import { once } from '../helpers';
once('__VUE_EXTEND_DAYJS_LOCALIZED_FORMAT__', () => {
dayjs.extend(dayjsLocalizedFormat)
})
/**
* Converts date to format provided as an argument or defined in config file (if argument not provided)
* @param {String} date
* @param {String} format
*/
export function date (date, format) {
const displayFormat = format || currentStoreView().i18n.dateFormat
let storeLocale = currentStoreView().i18n.defaultLocale.toLocaleLowerCase()
const separatorIndex = storeLocale.indexOf('-')
const languageCode = (separatorIndex > -1) ? storeLocale.substr(0, separatorIndex) : storeLocale
const isStoreLocale = dayjs().locale(storeLocale).locale()
const isLanguageLocale = dayjs().locale(languageCode).locale()
const locale = isStoreLocale || isLanguageLocale
if (locale) return dayjs(date).locale(languageCode).format(displayFormat)
return dayjs(date).format(displayFormat)
}
|
import { currentStoreView } from '@vue-storefront/core/lib/multistore'
import dayjs from 'dayjs'
import dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat'
import { once } from '../helpers';
once('__VUE_EXTEND_DAYJS_LOCALIZED_FORMAT__', () => {
dayjs.extend(dayjsLocalizedFormat)
})
/**
* Converts date to format provided as an argument or defined in config file (if argument not provided)
* @param {String} date
* @param {String} format
*/
export function date (date, format) {
const displayFormat = format || currentStoreView().i18n.dateFormat
let storeLocale = currentStoreView().i18n.defaultLocale.toLocaleLowerCase()
const separatorIndex = storeLocale.indexOf('-')
const languageCode = separatorIndex ? storeLocale.substr(0, separatorIndex) : storeLocale
const isStoreLocale = dayjs().locale(storeLocale).locale()
const isLanguageLocale = dayjs().locale(languageCode).locale()
const locale = isStoreLocale || isLanguageLocale
if (locale) return dayjs(date).locale(languageCode).format(displayFormat)
return dayjs(date).format(displayFormat)
}
|
Clean up, comments, liveness checking, robust data transfer
|
import random
import json
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if utilities.multiping(port, machines):
success = True
print "hey"
break
except Exception as e:
print "ouups"
attempted += 1
return success
|
import random
import json
import SocketExtend as SockExt
import config as conf
import parser as p
def ping(sock):
try:
rand = random.randint(1, 99999)
data = {'request':'ping', 'contents': {'value':rand}}
SockExt.send_msg(sock, json.dumps(data))
result = json.loads(SockExt.recv_msg(sock))
if result['return'] == rand:
return True
else:
return False
except Exception as e:
print "Exception while pinging: ", e
return False
def multiping(port, auths=[]):
result = True
for a_ip in auths:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.settimeout(120.0)
sock.connect((a_ip, int(port)))
if not ping(sock):
result = False
sock.shutdown(socket.SHUT_RDWR)
sock.close()
return result
def alive(port, machines=[]):
attempted = 0
success = False
while (attempted < conf.tries):
try:
if utilities.multiping(port, machines):
success = True
break
except Exception as e:
attempted += 1
return success
|
Add dummy tag buttons in the menu
|
package com.soofw.trk;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class ActionDialogFragment extends DialogFragment {
final static int EDIT = 0;
Main activity;
Task task;
public ActionDialogFragment(Task task) {
this.task = task;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] tags = this.task.getTags();
String[] actions = new String[tags.length + 1];
actions[0] = "Edit";
System.arraycopy(tags, 0, actions, 1, tags.length);
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == ActionDialogFragment.EDIT) {
new EditDialogFragment(ActionDialogFragment.this.task)
.show(ActionDialogFragment.this.activity.getSupportFragmentManager(), "tag!");
}
}
});
return builder.create();
}
}
|
package com.soofw.trk;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class ActionDialogFragment extends DialogFragment {
final static int EDIT = 0;
Main activity;
Task task;
public ActionDialogFragment(Task task) {
this.task = task;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.activity = (Main)this.getActivity();
String[] actions = new String[2];
actions[0] = "Edit";
actions[1] = "(complex tags here)";
AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
builder.setItems(actions, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == ActionDialogFragment.EDIT) {
new EditDialogFragment(ActionDialogFragment.this.task)
.show(ActionDialogFragment.this.activity.getSupportFragmentManager(), "tag!");
}
}
});
return builder.create();
}
}
|
Make it work with very small values
|
var _ = require('underscore');
var d3 = require('d3');
var format = {};
format.formatNumber = function (value, unit) {
if (!_.isNumber(value) || value === 0) {
return value;
}
var format = d3.format('.2s');
var p = 0;
var abs_v = Math.abs(value);
if (value > 1000) {
value = format(value) + (unit ? ' ' + unit : '');
return value;
}
if (abs_v > 100) {
p = 0;
} else if (abs_v > 10) {
p = 1;
} else if (abs_v > 1) {
p = 2;
} else if (abs_v > 0) {
p = Math.max(Math.ceil(Math.abs(Math.log(abs_v)/Math.log(10))) + 2,3);
}
value = value.toFixed(p);
var m = value.match(/(\.0+)$/);
if (m) {
value = value.replace(m[0], '');
}
return value;
};
format.formatDate = function (value) {
return d3.time.format('%Y-%m-%d')(value);
};
format.formatValue = function (value) {
if (_.isNumber(value)) {
return format.formatNumber(value);
}
if (_.isDate(value)) {
return format.formatDate(value);
}
return value;
};
module.exports = format;
|
var _ = require('underscore');
var d3 = require('d3');
var format = {};
format.formatNumber = function (value, unit) {
if (!_.isNumber(value) || value === 0) {
return value;
}
var format = d3.format('.2s');
var p = 0;
var abs_v = Math.abs(value);
if (value > 1000) {
value = format(value) + (unit ? ' ' + unit : '');
return value;
}
if (abs_v > 100) {
p = 0;
} else if (abs_v > 10) {
p = 1;
} else if (abs_v > 1) {
p = 2;
} else if (abs_v > 0) {
p = 3;
}
value = value.toFixed(p);
var m = value.match(/(\.0+)$/);
if (m) {
value = value.replace(m[0], '');
}
return value;
};
format.formatDate = function (value) {
return d3.time.format('%Y-%m-%d')(value);
};
format.formatValue = function (value) {
if (_.isNumber(value)) {
return format.formatNumber(value);
}
if (_.isDate(value)) {
return format.formatDate(value);
}
return value;
};
module.exports = format;
|
Convert background image example screen to using scroll view.
|
W.ImageBackground = function() {
var win = UI.Win({
title:'Background Images',
});
var scrollView = Ti.UI.createScrollView({
layout:'vertical',
contentWidth:'100%',
contentHeight:'auto',
showVerticalScrollIndicator:true,
showHorizontalScrollIndicator:false,
});
var label = Ti.UI.createLabel({
text:'It seems like background images for buttons and views are always stretched',
height:'auto',
width:'auto',
top:10
});
var button = Ti.UI.createButton({
title:'Stretched Button',
top:20,
width:200,
height:50,
backgroundImage:Ti.Filesystem.resourcesDirectory + 'images/sky.jpg',
borderRadius:10
});
var view = Ti.UI.createView({
top:20,
width:100,
height:100,
backgroundImage:Ti.Filesystem.resourcesDirectory + 'images/sky.jpg'
});
var viewRepeat = Ti.UI.createView({
top:20,
width:150,
height:150,
backgroundImage:Ti.Filesystem.resourcesDirectory + 'KS_nav_ui.png',
backgroundRepeat:true
});
scrollView.add(label);
scrollView.add(button);
scrollView.add(view);
scrollView.add(viewRepeat);
win.add(scrollView);
return win;
}
|
W.ImageBackground = function() {
var win = UI.Win({
title:'Background Images',
layout:'vertical'
});
var label = Ti.UI.createLabel({
text:'It seems like background images for buttons and views are always stretched',
height:'auto',
width:'auto',
top:10
});
var button = Ti.UI.createButton({
title:'Stretched Button',
top:20,
width:200,
height:50,
backgroundImage:Ti.Filesystem.resourcesDirectory + 'images/sky.jpg',
borderRadius:10
});
var view = Ti.UI.createView({
top:20,
width:100,
height:100,
backgroundImage:Ti.Filesystem.resourcesDirectory + 'images/sky.jpg'
});
var viewRepeat = Ti.UI.createView({
top:20,
width:150,
height:150,
backgroundImage:Ti.Filesystem.resourcesDirectory + 'KS_nav_ui.png',
backgroundRepeat:true
});
win.add(label);
win.add(button);
win.add(view);
win.add(viewRepeat);
return win;
}
|
Handle error in readdir() callback.
|
/*jslint node: true, nomen: true, white: true, unparam: true, todo: true*/
/*!
* Sitegear3
* Copyright(c) 2014 Ben New, Sitegear.org
* MIT Licensed
*/
(function (_, path, fs) {
"use strict";
module.exports = function (app, dirname) {
dirname = dirname || path.join(__dirname, '..', 'viewHelpers');
return function (request, response, next) {
app.locals.siteName = app.get('site name');
app.locals.baseUrl = request.secure ? app.get('https url') : app.get('http url');
app.locals.now = new Date();
fs.readdir(dirname, function (error, filenames) {
_.each(filenames, function (filename) {
if (/\.js$/.test(filename)) {
var name = path.basename(filename, '.js');
app.locals[name] = require('../viewHelpers/' + filename);
}
});
next(error);
});
};
};
}(require('lodash'), require('path'), require('fs')));
|
/*jslint node: true, nomen: true, white: true, unparam: true, todo: true*/
/*!
* Sitegear3
* Copyright(c) 2014 Ben New, Sitegear.org
* MIT Licensed
*/
(function (_, path, fs) {
"use strict";
module.exports = function (app, dirname) {
dirname = dirname || path.join(__dirname, '..', 'viewHelpers');
return function (request, response, next) {
app.locals.siteName = app.get('site name');
app.locals.baseUrl = request.secure ? app.get('https url') : app.get('http url');
app.locals.now = new Date();
fs.readdir(dirname, function (error, filenames) {
// TODO Handle error
_.each(filenames, function (filename) {
if (/\.js$/.test(filename)) {
var name = path.basename(filename, '.js');
app.locals[name] = require('../viewHelpers/' + filename);
}
});
next();
});
};
};
}(require('lodash'), require('path'), require('fs')));
|
Fix Attempted relative import beyond top-level package
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from survey.actions import make_published
from survey.models import Answer, Category, Question, Response, Survey
class QuestionInline(admin.TabularInline):
model = Question
ordering = ("order", "category")
extra = 1
class CategoryInline(admin.TabularInline):
model = Category
extra = 0
class SurveyAdmin(admin.ModelAdmin):
list_display = ("name", "is_published", "need_logged_user", "template")
list_filter = ("is_published", "need_logged_user")
inlines = [CategoryInline, QuestionInline]
actions = [make_published]
class AnswerBaseInline(admin.StackedInline):
fields = ("question", "body")
readonly_fields = ("question",)
extra = 0
model = Answer
class ResponseAdmin(admin.ModelAdmin):
list_display = ("interview_uuid", "survey", "created", "user")
list_filter = ("survey", "created")
date_hierarchy = "created"
inlines = [AnswerBaseInline]
# specifies the order as well as which fields to act on
readonly_fields = ("survey", "created", "updated", "interview_uuid", "user")
# admin.site.register(Question, QuestionInline)
# admin.site.register(Category, CategoryInline)
admin.site.register(Survey, SurveyAdmin)
admin.site.register(Response, ResponseAdmin)
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from survey.models import Answer, Category, Question, Response, Survey
from .actions import make_published
class QuestionInline(admin.TabularInline):
model = Question
ordering = ("order", "category")
extra = 1
class CategoryInline(admin.TabularInline):
model = Category
extra = 0
class SurveyAdmin(admin.ModelAdmin):
list_display = ("name", "is_published", "need_logged_user", "template")
list_filter = ("is_published", "need_logged_user")
inlines = [CategoryInline, QuestionInline]
actions = [make_published]
class AnswerBaseInline(admin.StackedInline):
fields = ("question", "body")
readonly_fields = ("question",)
extra = 0
model = Answer
class ResponseAdmin(admin.ModelAdmin):
list_display = ("interview_uuid", "survey", "created", "user")
list_filter = ("survey", "created")
date_hierarchy = "created"
inlines = [AnswerBaseInline]
# specifies the order as well as which fields to act on
readonly_fields = ("survey", "created", "updated", "interview_uuid", "user")
# admin.site.register(Question, QuestionInline)
# admin.site.register(Category, CategoryInline)
admin.site.register(Survey, SurveyAdmin)
admin.site.register(Response, ResponseAdmin)
|
Change modelId to type Integer
|
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
Integer modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public Integer getModelID() {
return modelID;
}
public void setModelID(Integer modelID) {
this.modelID = modelID;
}
}
|
package xyz.igorgee.imagecreator3d;
import java.io.File;
public class Model {
String name;
File location;
String modelID;
public Model(String name, File location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getLocation() {
return location;
}
public void setLocation(File location) {
this.location = location;
}
public String getModelID() {
return modelID;
}
public void setModelID(String modelID) {
this.modelID = modelID;
}
}
|
Make GroupedKatas a real ES6 class.
|
import {loadFileOnServer} from '../src/server/http-get.js';
export default class GroupedKata{
constructor(katasUrl){
this.katasUrl = katasUrl;
}
load(onError, onSuccess) {
function onLoaded(err, data) {
var parsed;
try {
parsed = JSON.parse(data);
} catch (jsonParseError) {
onError(jsonParseError);
}
if (err) {
onError(err);
} else if (!('groups' in parsed)) {
onError(new Error('No groups found in the data'));
} else {
onSuccess(parsed.groups);
}
}
loadFileOnServer(this.katasUrl, onLoaded);
}
}
|
var loadFileOnServer = require('../src/server/http-get.js');
function GroupedKata(katasUrl) {
this.load = function(onError, onSuccess) {
function onLoaded(err, data) {
var parsed;
try {
parsed = JSON.parse(data);
} catch (jsonParseError) {
onError(jsonParseError);
}
if (err) {
onError(err);
} else if (!('groups' in parsed)) {
onError(new Error('No groups found in the data'));
} else {
onSuccess(parsed.groups);
}
}
loadFileOnServer(katasUrl, onLoaded);
}
}
module.exports = GroupedKata;
|
Drop explicit archlist for now.
|
import logging
import subprocess
from hotness.cache import cache
log = logging.getLogger('fedmsg')
def get_version(package_name, yumconfig):
nvr_dict = build_nvr_dict(yumconfig)
return nvr_dict[package_name]
@cache.cache_on_arguments()
def build_nvr_dict(yumconfig):
cmdline = ["/usr/bin/repoquery",
"--config", yumconfig,
"--quiet",
#"--archlist=src",
"--all",
"--qf",
"%{name}\t%{version}\t%{release}"]
log.info("Running %r" % ' '.join(cmdline))
repoquery = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
(stdout, stderr) = repoquery.communicate()
log.debug("Done with repoquery.")
if stderr:
log.warn(stderr)
new_nvr_dict = {}
for line in stdout.split("\n"):
line = line.strip()
if line:
name, version, release = line.split("\t")
new_nvr_dict[name] = (version, release)
return new_nvr_dict
|
import logging
import subprocess
from hotness.cache import cache
log = logging.getLogger('fedmsg')
def get_version(package_name, yumconfig):
nvr_dict = build_nvr_dict(yumconfig)
return nvr_dict[package_name]
@cache.cache_on_arguments()
def build_nvr_dict(yumconfig):
cmdline = ["/usr/bin/repoquery",
"--config", yumconfig,
"--quiet",
"--archlist=src",
"--all",
"--qf",
"%{name}\t%{version}\t%{release}"]
log.info("Running %r" % ' '.join(cmdline))
repoquery = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
(stdout, stderr) = repoquery.communicate()
log.debug("Done with repoquery.")
if stderr:
log.warn(stderr)
new_nvr_dict = {}
for line in stdout.split("\n"):
line = line.strip()
if line:
name, version, release = line.split("\t")
new_nvr_dict[name] = (version, release)
return new_nvr_dict
|
[Discord] Handle package not found in pypi command
|
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Python())
class Python(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.command()
async def pep(self, ctx, number: int):
'''Generate Python Enhancement Proposal URL'''
await ctx.embed_reply(f"https://www.python.org/dev/peps/pep-{number:04}/")
@commands.command()
async def pypi(self, ctx, package: str):
'''Information about a package on PyPI'''
url = f"https://pypi.python.org/pypi/{package}/json"
async with ctx.bot.aiohttp_session.get(url) as resp:
if resp.status == 404:
return await ctx.embed_reply(f"{ctx.bot.error_emoji} Package not found")
data = await resp.json()
await ctx.embed_reply(title = data["info"]["name"], title_url = data["info"]["package_url"],
description = data["info"]["summary"], fields = (("Version", data["info"]["version"]),))
|
from discord.ext import commands
from utilities import checks
def setup(bot):
bot.add_cog(Python())
class Python(commands.Cog):
async def cog_check(self, ctx):
return await checks.not_forbidden().predicate(ctx)
@commands.command()
async def pep(self, ctx, number: int):
'''Generate Python Enhancement Proposal URL'''
await ctx.embed_reply(f"https://www.python.org/dev/peps/pep-{number:04}/")
@commands.command()
async def pypi(self, ctx, package: str):
'''Information about a package on PyPI'''
url = f"https://pypi.python.org/pypi/{package}/json"
async with ctx.bot.aiohttp_session.get(url) as resp:
data = await resp.json()
await ctx.embed_reply(title = data["info"]["name"], title_url = data["info"]["package_url"],
description = data["info"]["summary"], fields = (("Version", data["info"]["version"]),))
|
Set map type to satellite
|
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import './Harta.css';
const Participant = ({ text, color }) => {
return (
<div
style={color}
className="avatar-participant">
<span>{text}</span>
</div>
);
};
const createMapOptions = (maps) => {
return {
mapTypeId: maps.MapTypeId.SATELLITE
}
}
export default class Harta extends Component {
constructor(props) {
super(props);
this.state = {
culoriParticipanti: []
};
}
static defaultProps = {
center: {lat: 47.6401534, lng: 26.2572495},
zoom: 17,
participanti: {},
};
render() {
const participant = this.props.participanti.map((p, index) => {
return <Participant key={index}
lat={p.lastLocation.latitude}
lng={p.lastLocation.longitude}
text={p.id}
/>;
});
return (
<GoogleMapReact
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
options={createMapOptions}
>{participant}</GoogleMapReact>
);
}
}
|
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import './Harta.css';
const Participant = ({ text, color }) => {
return (
<div
style={color}
className="avatar-participant">
<span>{text}</span>
</div>
);
};
export default class Harta extends Component {
constructor(props) {
super(props);
this.state = {
culoriParticipanti: []
};
}
static defaultProps = {
center: {lat: 47.6401534, lng: 26.2572495},
zoom: 17,
participanti: {},
};
render() {
const participant = this.props.participanti.map((p, index) => {
return <Participant key={index}
lat={p.lastLocation.latitude}
lng={p.lastLocation.longitude}
text={p.id}
/>;
});
return (
<GoogleMapReact
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
>{participant}</GoogleMapReact>
);
}
}
|
Fix issue with Python bindings caused by introduction of CI20 platform
this adds ci20.c to the compile path for Python bindings, otherwise you
get the following:
ImportError:
/usr/lib/python3.4/site-packages/wiringX/gpio.cpython-34m.so: undefined
symbol: ci20Init
|
from distutils.core import setup
from distutils.core import Extension
from distutils.command.build_ext import build_ext as _build_ext
import sys
modules = [
Extension('wiringX.gpio', sources=['wiringX/wiringx.c', '../wiringX.c', '../hummingboard.c', '../bananapi.c', '../radxa.c', '../raspberrypi.c', '../ci20.c'], include_dirs=['../'], extra_compile_args=['-Wformat=0']),
]
setup(
name='wiringX',
version='0.6',
author='CurlyMo',
author_email='curlymoo1@gmail.com',
url='https://www.wiringx.org/',
license='GPLv2',
packages=['wiringX'],
description='Control GPIO and I2C',
classifiers=['Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Home Automation',
'Topic :: Software Development :: Embedded Systems'
],
ext_modules=modules
)
|
from distutils.core import setup
from distutils.core import Extension
from distutils.command.build_ext import build_ext as _build_ext
import sys
modules = [
Extension('wiringX.gpio', sources=['wiringX/wiringx.c', '../wiringX.c', '../hummingboard.c', '../bananapi.c', '../radxa.c', '../raspberrypi.c'], include_dirs=['../'], extra_compile_args=['-Wformat=0']),
]
setup(
name='wiringX',
version='0.5',
author='CurlyMo',
author_email='curlymoo1@gmail.com',
url='https://www.wiringx.org/',
license='GPLv2',
packages=['wiringX'],
description='Control GPIO and I2C',
classifiers=['Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Home Automation',
'Topic :: Software Development :: Embedded Systems'
],
ext_modules=modules
)
|
Fix for POP3 by disabling TLS explicitly.
based on this: http://moodle.org/mod/forum/discuss.php?d=1884
|
<?PHP // $Id$
// Authentication by looking up a POP3 server
function auth_user_login ($username, $password) {
// Returns true if the username and password work
// and false if they are wrong or don't exist.
global $CFG;
switch ($CFG->auth_pop3type) {
case "pop3":
$host = "{".$CFG->auth_pop3host.":$CFG->auth_pop3port/pop3/notls}INBOX";
break;
case "pop3cert":
$host = "{".$CFG->auth_pop3host.":$CFG->auth_pop3port/pop3/ssl/novalidate-cert}INBOX";
break;
}
error_reporting(0);
$connection = imap_open($host, $username, $password, OP_HALFOPEN);
error_reporting($CFG->debug);
if ($connection) {
imap_close($connection);
return true;
} else {
return false;
}
}
?>
|
<?PHP // $Id$
// Authentication by looking up a POP3 server
function auth_user_login ($username, $password) {
// Returns true if the username and password work
// and false if they are wrong or don't exist.
global $CFG;
switch ($CFG->auth_pop3type) {
case "pop3":
$host = "{".$CFG->auth_pop3host.":$CFG->auth_pop3port/pop3}INBOX";
break;
case "pop3cert":
$host = "{".$CFG->auth_pop3host.":$CFG->auth_pop3port/pop3/ssl/novalidate-cert}INBOX";
break;
}
error_reporting(0);
$connection = imap_open($host, $username, $password, OP_HALFOPEN);
error_reporting($CFG->debug);
if ($connection) {
imap_close($connection);
return true;
} else {
return false;
}
}
?>
|
Use alpha layer instead of window flag for dimming.
|
/*
* Copyright (c) 2014, 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.rating.view;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
/**
* @author Sky Kelsey
*/
public abstract class ApptentiveBaseDialog extends Dialog {
public ApptentiveBaseDialog(final Context context, int layout) {
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(layout); // This needs to be set before the window layout is messed with below.
// Let the dialog take up the whole device width.
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = ViewGroup.LayoutParams.FILL_PARENT;
params.height = ViewGroup.LayoutParams.FILL_PARENT;
params.gravity = Gravity.CENTER;
getWindow().setAttributes(params);
getWindow().setBackgroundDrawable(new ColorDrawable(0x7F000000));
}
}
|
/*
* Copyright (c) 2014, 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.rating.view;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
/**
* @author Sky Kelsey
*/
public abstract class ApptentiveBaseDialog extends Dialog {
public ApptentiveBaseDialog(final Context context, int layout) {
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(layout); // This needs to be set before the window layout is messed with below.
// Let the dialog take up the whole device width.
WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = ViewGroup.LayoutParams.FILL_PARENT;
params.height = ViewGroup.LayoutParams.FILL_PARENT;
params.gravity = Gravity.CENTER;
params.dimAmount = 0.5f;
getWindow().setAttributes(params);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
}
|
Remove the auth contenttypes thing for now, needs improvement
|
"""
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
# Is causing strange errors, removing for now (we might need to fix up orm first)
#if 'django.contrib.auth' in settings.INSTALLED_APPS:
#def create_permissions_compat(app, **kwargs):
#from django.db.models import get_app
#from django.contrib.auth.management import create_permissions
#create_permissions(get_app(app), (), 0)
#post_migrate.connect(create_permissions_compat)
|
"""
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a particular migration in a direction
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
if 'django.contrib.auth' in settings.INSTALLED_APPS:
def create_permissions_compat(app, **kwargs):
from django.db.models import get_app
from django.contrib.auth.management import create_permissions
create_permissions(get_app(app), (), 0)
post_migrate.connect(create_permissions_compat)
|
Fix a couple of PEP8 issues
|
import os
import csv
class CSVFile(object):
def __init__(self, path, values):
self.path = path
self.values = values
def write(self, results):
field_names = self.values.keys()
write_header = not os.path.exists(self.path)
with open(self.path, 'a') as output_file:
writer = csv.DictWriter(output_file, fieldnames=field_names)
if write_header:
writer.writeheader()
row = {}
for field in self.values:
row[field] = self.values[field](results)
writer.writerow(row)
|
import os
import csv
class CSVFile(object):
def __init__(self, path, values):
self.path = path
self.values = values
def write(self, results):
field_names = self.values.keys()
write_header = not os.path.exists(self.path)
with open(self.path, 'a') as output_file:
writer = csv.DictWriter(output_file, fieldnames=field_names)
if write_header:
writer.writeheader()
row = {}
for field in self.values:
row[field]= self.values[field](results)
writer.writerow(row)
|
Update policy names in test
|
import os
import shutil
from .datasets import Dataset
from mclearn.experiment import ActiveExperiment
class TestExperiment:
@classmethod
def setup_class(cls):
cls.data = Dataset('wine')
cls.policies = ['passive', 'margin', 'w-margin', 'confidence',
'w-confidence', 'entropy', 'w-entropy',
'qbb-margin', 'qbb-kl', 'thompson', 'ocucb', 'klucb',
'exp++', 'borda', 'geometric', 'schulze']
def test_experiment(self):
for policy in self.policies:
expt = ActiveExperiment(self.data.features, self.data.target,
'wine', policy, n_iter=1)
expt.run_policies()
@classmethod
def teardown_class(cls):
if os.path.exists('results'):
shutil.rmtree('results')
|
import os
import shutil
from .datasets import Dataset
from mclearn.experiment import ActiveExperiment
class TestExperiment:
@classmethod
def setup_class(cls):
cls.data = Dataset('wine')
cls.policies = ['passive', 'margin', 'weighted-margin', 'confidence',
'weighted-confidence', 'entropy', 'weighted-entropy',
'qbb-margin', 'qbb-kl', 'thompson', 'ocucb', 'klucb',
'exp++', 'borda', 'geometric', 'schulze']
def test_experiment(self):
for policy in self.policies:
expt = ActiveExperiment(self.data.features, self.data.target,
'wine', policy, n_iter=1)
expt.run_policies()
@classmethod
def teardown_class(cls):
if os.path.exists('results'):
shutil.rmtree('results')
|
Use ES2015 feature Set() to store unique robot names
|
import Robot from './robot-name';
describe('Robot', () => {
let robot;
beforeEach(() => {
robot = new Robot();
});
it('has a name', () => {
expect(robot.name).toMatch(/^[A-Z]{2}\d{3}$/);
});
xit('name is the same each time', () => {
expect(robot.name).toEqual(robot.name);
});
xit('different robots have different names', () => {
const NUMBER_OF_ROBOTS = 10000;
const usedNames = new Set();
for (let i = 0; i < NUMBER_OF_ROBOTS; i++) {
const newRobot = new Robot();
usedNames.add(newRobot.name);
}
expect(usedNames.size).toEqual(NUMBER_OF_ROBOTS);
});
xit('is able to reset the name', () => {
const originalName = robot.name;
robot.reset();
const newName = robot.name;
expect(newName).toMatch(/^[A-Z]{2}\d{3}$/);
expect(originalName).not.toEqual(newName);
});
xit('should set a unique name after reset', () => {
const NUMBER_OF_ROBOTS = 10000;
const usedNames = new Set();
usedNames.add(robot.name);
for (let i = 0; i < NUMBER_OF_ROBOTS; i++) {
robot.reset();
usedNames.add(robot.name);
}
expect(usedNames.size).toEqual(NUMBER_OF_ROBOTS + 1);
});
});
|
import Robot from './robot-name';
describe('Robot', () => {
let robot;
beforeEach(() => {
robot = new Robot();
});
it('has a name', () => {
expect(robot.name).toMatch(/^[A-Z]{2}\d{3}$/);
});
xit('name is the same each time', () => {
expect(robot.name).toEqual(robot.name);
});
xit('different robots have different names', () => {
const NUMBER_OF_ROBOTS = 10000;
let usedNames = {};
for (let i = 0; i < NUMBER_OF_ROBOTS; i++) {
let newRobot = new Robot();
usedNames[newRobot.name] = true;
}
expect(Object.keys(usedNames).length).toEqual(NUMBER_OF_ROBOTS);
});
xit('is able to reset the name', () => {
let originalName = robot.name;
robot.reset();
let newName = robot.name;
expect(newName).toMatch(/^[A-Z]{2}\d{3}$/);
expect(originalName).not.toEqual(newName);
});
xit('should set a unique name after reset', () => {
const NUMBER_OF_ROBOTS = 10000;
let usedNames = {};
usedNames[robot.name] = true;
for (let i = 0; i < NUMBER_OF_ROBOTS; i++) {
robot.reset();
usedNames[robot.name] = true;
}
expect(Object.keys(usedNames).length).toEqual(NUMBER_OF_ROBOTS + 1);
});
});
|
Remove prop-types import in production
|
'use strict'
const getBrowserslistConfig = require('./lib/getBrowserslistConfig')
const mergeByEnv = require('./lib/mergeByEnv')
module.exports = mergeByEnv({
presets: [
[
'babel-preset-env',
{
modules: false,
targets: {
browsers: getBrowserslistConfig()
},
useBuiltIns: true
}
],
'babel-preset-react'
],
plugins: [
'babel-plugin-react-css-modules',
'babel-plugin-syntax-dynamic-import',
'babel-plugin-transform-class-properties',
'babel-plugin-transform-object-rest-spread',
[
'babel-plugin-transform-react-jsx',
{
pragma: 'createElement'
}
]
],
env: {
production: {
plugins: [
'babel-plugin-transform-react-constant-elements',
'babel-plugin-transform-react-inline-elements',
['babel-plugin-transform-react-remove-prop-types', {removeImport: true}]
]
},
test: {
plugins: ['babel-plugin-istanbul']
},
development: {
plugins: ['babel-plugin-flow-react-proptypes', 'babel-plugin-tcomb']
}
}
})
|
'use strict'
const getBrowserslistConfig = require('./lib/getBrowserslistConfig')
const mergeByEnv = require('./lib/mergeByEnv')
module.exports = mergeByEnv({
presets: [
[
'babel-preset-env',
{
modules: false,
targets: {
browsers: getBrowserslistConfig()
},
useBuiltIns: true
}
],
'babel-preset-react'
],
plugins: [
'babel-plugin-react-css-modules',
'babel-plugin-syntax-dynamic-import',
'babel-plugin-transform-class-properties',
'babel-plugin-transform-object-rest-spread',
[
'babel-plugin-transform-react-jsx',
{
pragma: 'createElement'
}
]
],
env: {
production: {
plugins: [
'babel-plugin-transform-react-constant-elements',
'babel-plugin-transform-react-inline-elements',
'babel-plugin-transform-react-remove-prop-types'
]
},
test: {
plugins: ['babel-plugin-istanbul']
},
development: {
plugins: ['babel-plugin-flow-react-proptypes', 'babel-plugin-tcomb']
}
}
})
|
Add generation for spawn egg
|
package info.u_team.u_team_test.data.provider;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
public class TestItemModelsProvider extends CommonItemModelsProvider {
public TestItemModelsProvider(GenerationData data) {
super(data);
}
@Override
protected void registerModels() {
// Items
simpleGenerated(TestItems.BASIC.get());
simpleGenerated(TestItems.BASIC_FOOD.get());
simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld);
iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated);
spawnEgg(TestItems.TEST_LIVING_SPAWN_EGG.get());
// Blocks
simpleBlock(TestBlocks.BASIC.get());
simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
}
}
|
package info.u_team.u_team_test.data.provider;
import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
public class TestItemModelsProvider extends CommonItemModelsProvider {
public TestItemModelsProvider(GenerationData data) {
super(data);
}
@Override
protected void registerModels() {
// Items
simpleGenerated(TestItems.BASIC.get());
simpleGenerated(TestItems.BASIC_FOOD.get());
simpleGenerated(TestItems.BETTER_ENDERPEARL.get());
iterateItems(TestItems.BASIC_TOOL, this::simpleHandheld);
iterateItems(TestItems.BASIC_ARMOR, this::simpleGenerated);
// Blocks
simpleBlock(TestBlocks.BASIC.get());
simpleBlock(TestBlocks.BASIC_TILEENTITY.get());
simpleBlock(TestBlocks.BASIC_ENERGY_CREATOR.get());
simpleBlock(TestBlocks.BASIC_FLUID_INVENTORY.get());
}
}
|
Throw HTTP error 400 on misformerd URI.
|
package org.webbitserver.handler;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpHandler;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathMatchHandler implements HttpHandler {
private final Pattern pathPattern;
private final HttpHandler httpHandler;
public PathMatchHandler(Pattern pathPattern, HttpHandler httpHandler) {
this.pathPattern = pathPattern;
this.httpHandler = httpHandler;
}
public PathMatchHandler(String path, HttpHandler httpHandler) {
this(Pattern.compile(path), httpHandler);
}
@Override
public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control) throws Exception {
Matcher matcher;
try
{
String path = URI.create(request.uri()).getPath();
matcher = pathPattern.matcher(path);
}
catch(Exception e)
{
response.status(400);
response.header("Content-Type", "text/plain");
response.content("Internal server error. We are notified about the problem and will fix it. Sorry for any inconvenience.");
response.end();
return;
}
if(matcher.matches())
{
httpHandler.handleHttpRequest(request, response, control);
}
else
{
control.nextHandler();
}
}
}
|
package org.webbitserver.handler;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpHandler;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathMatchHandler implements HttpHandler {
private final Pattern pathPattern;
private final HttpHandler httpHandler;
public PathMatchHandler(Pattern pathPattern, HttpHandler httpHandler) {
this.pathPattern = pathPattern;
this.httpHandler = httpHandler;
}
public PathMatchHandler(String path, HttpHandler httpHandler) {
this(Pattern.compile(path), httpHandler);
}
@Override
public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control) throws Exception {
String path = URI.create(request.uri()).getPath();
Matcher matcher = pathPattern.matcher(path);
if (matcher.matches()) {
httpHandler.handleHttpRequest(request, response, control);
} else {
control.nextHandler();
}
}
}
|
Put the missing semicolon at the end of exports declaration
|
module.exports = function (db) {
db.set = set;
return db;
};
function set(path, obj, cb) {
var objs = [];
putObjBatch(path, obj, objs);
this.batch(objs, function (err) {
cb(err);
});
}
function putObjBatch(path, obj, objs) {
var keyPath = '';
if (path !== '/' && path.length > 1) {
keyPath = path.substr(1) + '/';
}
for (var objKey in obj) {
var objVal = obj[objKey];
if (typeof objVal === 'object') {
if (keyPath !== '' && keyPath.length > 1) {
putObjBatch('/' + keyPath + objKey, objVal, objs);
} else {
putObjBatch('/' + objKey, objVal, objs);
}
} else {
objs.push({ type: 'put', key: keyPath + objKey, value: objVal });
}
}
}
|
module.exports = function (db) {
db.set = set;
return db;
}
function set(path, obj, cb) {
var objs = [];
putObjBatch(path, obj, objs);
this.batch(objs, function (err) {
cb(err);
});
}
function putObjBatch(path, obj, objs) {
var keyPath = '';
if (path !== '/' && path.length > 1) {
keyPath = path.substr(1) + '/';
}
for (var objKey in obj) {
var objVal = obj[objKey];
if (typeof objVal === 'object') {
if (keyPath !== '' && keyPath.length > 1) {
putObjBatch('/' + keyPath + objKey, objVal, objs);
} else {
putObjBatch('/' + objKey, objVal, objs);
}
} else {
objs.push({ type: 'put', key: keyPath + objKey, value: objVal });
}
}
}
|
Remove vim header from source files
Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765
|
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import fixtures
from mox3 import mox
from mox3 import stubout
class MoxStubout(fixtures.Fixture):
"""Deal with code around mox and stubout as a fixture."""
def setUp(self):
super(MoxStubout, self).setUp()
self.mox = mox.Mox()
self.stubs = stubout.StubOutForTesting()
self.addCleanup(self.mox.UnsetStubs)
self.addCleanup(self.stubs.UnsetAll)
self.addCleanup(self.stubs.SmartUnsetAll)
self.addCleanup(self.mox.VerifyAll)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import fixtures
from mox3 import mox
from mox3 import stubout
class MoxStubout(fixtures.Fixture):
"""Deal with code around mox and stubout as a fixture."""
def setUp(self):
super(MoxStubout, self).setUp()
self.mox = mox.Mox()
self.stubs = stubout.StubOutForTesting()
self.addCleanup(self.mox.UnsetStubs)
self.addCleanup(self.stubs.UnsetAll)
self.addCleanup(self.stubs.SmartUnsetAll)
self.addCleanup(self.mox.VerifyAll)
|
Fix ExactlyXCard Selector pretarget bug
|
const BaseCardSelector = require('./BaseCardSelector.js');
class ExactlyXCardSelector extends BaseCardSelector {
constructor(numCards, properties) {
super(properties);
this.numCards = numCards;
}
defaultActivePromptTitle() {
if(this.cardType.length === 1) {
return this.numCards === 1 ? 'Choose a ' + this.cardType[0] : `Choose ${this.numCards} ${this.cardType[0]}`;
}
return this.numCards === 1 ? 'Select a card' : `Select ${this.numCards} cards`;
}
hasEnoughSelected(selectedCards) {
return selectedCards.length === this.numCards;
}
hasEnoughTargets(context, pretarget = false) {
let numMatchingCards = context.game.allCards.reduce((total, card) => {
if(this.canTarget(card, context, pretarget)) {
return total + 1;
}
return total;
}, 0);
return numMatchingCards >= this.numCards;
}
hasReachedLimit(selectedCards) {
return selectedCards.length >= this.numCards;
}
}
module.exports = ExactlyXCardSelector;
|
const BaseCardSelector = require('./BaseCardSelector.js');
class ExactlyXCardSelector extends BaseCardSelector {
constructor(numCards, properties) {
super(properties);
this.numCards = numCards;
}
defaultActivePromptTitle() {
if(this.cardType.length === 1) {
return this.numCards === 1 ? 'Choose a ' + this.cardType[0] : `Choose ${this.numCards} ${this.cardType[0]}`;
}
return this.numCards === 1 ? 'Select a card' : `Select ${this.numCards} cards`;
}
hasEnoughSelected(selectedCards) {
return selectedCards.length === this.numCards;
}
hasEnoughTargets(context) {
let numMatchingCards = context.game.allCards.reduce((total, card) => {
if(this.canTarget(card, context)) {
return total + 1;
}
return total;
}, 0);
return numMatchingCards >= this.numCards;
}
hasReachedLimit(selectedCards) {
return selectedCards.length >= this.numCards;
}
}
module.exports = ExactlyXCardSelector;
|
Remove default for director & jb ip in vsphere terraform template
- The defaults are now provided via the input generator.
[#152908821]
Signed-off-by: Genevieve LEsperance <1b6a7b865633211adcfeed81fa254bd2ba36f0db@pivotal.io>
|
package vsphere
import (
"fmt"
"github.com/cloudfoundry/bosh-bootloader/storage"
)
type TemplateGenerator struct{}
func NewTemplateGenerator() TemplateGenerator {
return TemplateGenerator{}
}
func (t TemplateGenerator) Generate(state storage.State) string {
return fmt.Sprintf(`
variable "vsphere_subnet" {}
variable "jumpbox_ip" {}
variable "internal_gw" {}
variable "network_name" {}
variable "vcenter_cluster" {}
variable "bosh_director_internal_ip" {}
output "internal_cidr" { value = "${var.vsphere_subnet}" }
output "internal_gw" { value = "${var.internal_gw}" }
output "network_name" { value = "${var.network_name}" }
output "vcenter_cluster" { value = "${var.vcenter_cluster}" }
output "jumpbox_url" { value = "${var.jumpbox_ip}:22" }
output "external_ip" { value = "${var.jumpbox_ip}" }
output "jumpbox_internal_ip" { value = "${var.jumpbox_ip}" }
output "bosh_director_internal_ip" { value = "${var.bosh_director_internal_ip}" }
`)
}
|
package vsphere
import (
"fmt"
"github.com/cloudfoundry/bosh-bootloader/storage"
)
type TemplateGenerator struct{}
func NewTemplateGenerator() TemplateGenerator {
return TemplateGenerator{}
}
func (t TemplateGenerator) Generate(state storage.State) string {
return fmt.Sprintf(`
variable "vsphere_subnet" {}
variable "jumpbox_ip" {
default = ""
}
variable "internal_gw" {}
variable "network_name" {}
variable "vcenter_cluster" {}
variable "bosh_director_internal_ip" {
default = ""
}
output "internal_cidr" { value = "${var.vsphere_subnet}" }
output "internal_gw" { value = "${var.internal_gw}" }
output "network_name" { value = "${var.network_name}" }
output "vcenter_cluster" { value = "${var.vcenter_cluster}" }
output "jumpbox_url" { value = "${var.jumpbox_ip}:22" }
output "external_ip" { value = "${var.jumpbox_ip}" }
output "jumpbox_internal_ip" { value = "${var.jumpbox_ip}" }
output "bosh_director_internal_ip" { value = "${var.bosh_director_internal_ip}" }
`)
}
|
Fix issue with wsgi and translations.
|
from pyramid.httpexceptions import HTTPNotFound
from pyramid.i18n import TranslationString as _
def get_or_create(session, model, **kw):
""" Django's get_or_create function
http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
"""
obj = session.query(model).filter_by(**kw).first()
if obj:
return obj
else:
obj = model(**kw)
session.add(obj)
session.flush()
return obj
def get_object_or_404(session, model, **kw):
""" Django's get_object_or_404 function
"""
obj = session.query(model).filter_by(**kw).first()
if obj is None:
raise HTTPNotFound(detail='No %s matches the given query.' % model.__name__)
return obj
def merge_session_with_post(session, post):
""" Basic function to merge data into an sql object.
This function doesn't work with relations.
"""
for key, value in post:
setattr(session, key, value)
return session
|
from pyramid.httpexceptions import HTTPNotFound
from pyramid.i18n import TranslationString as _
def get_or_create(session, model, **kw):
""" Django's get_or_create function
http://stackoverflow.com/questions/2546207/does-sqlalchemy-have-an-equivalent-of-djangos-get-or-create
"""
obj = session.query(model).filter_by(**kw).first()
if obj:
return obj
else:
obj = model(**kw)
session.add(obj)
session.flush()
return obj
def get_object_or_404(session, model, **kw):
""" Django's get_object_or_404 function
"""
obj = session.query(model).filter_by(**kw).first()
if obj is None:
raise HTTPNotFound(detail=_('No %s matches the given query.') % model.__name__)
return obj
def merge_session_with_post(session, post):
""" Basic function to merge data into an sql object.
This function doesn't work with relations.
"""
for key, value in post:
setattr(session, key, value)
return session
|
Use relative import to allow vendoring
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
from .__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
|
# Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, division, print_function
from packaging.__about__ import (
__author__, __copyright__, __email__, __license__, __summary__, __title__,
__uri__, __version__
)
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
|
Fix require das dependências externas (gulp)
|
var _ = require('lodash');
var chalk = require('chalk');
module.exports = function(options){
var defaultOptions = require('./defaults.js')();
options = _.defaultsDeep(options, defaultOptions);
var baseBuildName = chalk.bgWhite( chalk.black('[ ' + 'Base Build ' + chalk.red('Angular') + ' ]') );
/*
==========================
Read gulp files
==========================
*/
for(key in options.modules){
var value = options.modules[key];
var category = chalk.green(' external ');
if(value === defaultOptions.modulesData[key].defaultValue && key != 'gulp'){
category = chalk.cyan(' built-in ');
require(value)(options);
} else if(key === 'gulp') {
require(value);
} else {
require( process.cwd() + value );
}
console.log( baseBuildName + ' required' + category + chalk.magenta(value) + ' module');
}
}
|
var _ = require('lodash');
var chalk = require('chalk');
module.exports = function(options){
var defaultOptions = require('./defaults.js')();
options = _.defaultsDeep(options, defaultOptions);
var baseBuildName = chalk.bgWhite( chalk.black('[ ' + 'Base Build ' + chalk.red('Angular') + ' ]') );
/*
==========================
Read gulp files
==========================
*/
for(key in options.modules){
var value = options.modules[key];
var category = '';
if(value === defaultOptions.modulesData[key].defaultValue){
category = chalk.cyan(' default ');
require(value)(options);
} else if(key != 'gulp'){
category = chalk.blue(' external ');
require( process.cwd() + value )
}
console.log( baseBuildName + ' required' + category + chalk.magenta(value) + ' module');
}
}
|
Modify service_providers for dynamic columns
Refs SH-64
|
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from shuup.admin.utils.picotable import Column, TextFilter
from shuup.admin.utils.views import PicotableListView
from shuup.core.models import ServiceProvider
class ServiceProviderListView(PicotableListView):
model = ServiceProvider
default_columns = [
Column(
"name", _("Name"), sort_field="base_translations__name",
filter_config=TextFilter(
filter_field="base_translations__name",
placeholder=_("Filter by name..."))),
Column("type", _(u"Type"), display="get_type_display", sortable=False),
]
def get_type_display(self, instance):
return instance._meta.verbose_name.capitalize()
def get_object_abstract(self, instance, item):
return [
{"text": "%s" % instance, "class": "header"},
{"text": self.get_type_display(instance)},
]
|
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from shuup.admin.utils.picotable import Column, TextFilter
from shuup.admin.utils.views import PicotableListView
from shuup.core.models import ServiceProvider
class ServiceProviderListView(PicotableListView):
model = ServiceProvider
columns = [
Column(
"name", _("Name"), sort_field="base_translations__name",
filter_config=TextFilter(
filter_field="base_translations__name",
placeholder=_("Filter by name..."))),
Column("type", _(u"Type"), display="get_type_display", sortable=False),
]
def get_type_display(self, instance):
return instance._meta.verbose_name.capitalize()
def get_object_abstract(self, instance, item):
return [
{"text": "%s" % instance, "class": "header"},
{"text": self.get_type_display(instance)},
]
|
[major] Convert from es6 to es5
|
"use strict";
/**
* RegExp to find placeholders in the template
*
* http://regexr.com/3e1o7
* @type {RegExp}
*/
var _re = /{([0-9a-zA-Z]+?)}/g;
/**
* Micro template compiler
*
* @param {string} template
* @param {array|object} values
* @returns {string}
*/
var crouch = function ( template, values ) {
/*
* Default arguments
*/
var
template = template || "",
values = values || {};
var match;
/*
* Loop through all the placeholders that matched with regex
*/
while ( match = _re.exec( template ) ) {
var _value = values[ match[ 1 ] ];
if ( !_value ) _value = "";
/*
* Replace the placeholder with a real value.
*/
template = template.replace( match[ 0 ], _value )
}
/*
* Return the template with filled in values
*/
return template;
};
/*
* Export
*/
module.exports = crouch;
|
"use strict";
/**
* RegExp to find placeholders in the template
*
* http://regexr.com/3e1o7
* @type {RegExp}
*/
const _re = /{([0-9a-zA-Z]+?)}/g;
/**
* Micro template compiler
*
* @param {string} template
* @param {array|object} values
* @returns {string}
*/
const crouch = ( template, values ) => {
let match;
// Loop through all the placeholders that matched with regex
while ( match = _re.exec( template ) ) {
let _value = values[ match[ 1 ] ];
if ( !_value ) _value = "";
// Replace the placeholder with a real value.
template = template.replace( match[ 0 ], _value )
}
return template;
};
/*
* Export
*/
module.exports = crouch;
|
Define $bg_url variable for header
|
<?php
// get page thumbnail image if it is a page
$bg_url = '';
if ( is_home() ) {
$bg = mbtheme_get_option( 'header-bg-blog', array() );
$bg_url = $bg[ 'url' ];
} elseif ( is_page() ) {
$page_id = get_queried_object_id();
$bg_url = get_the_post_thumbnail_url( $page_id, 'full' );
}
// get default backgound image
if ( !$bg_url ) {
$bg = mbtheme_get_option( 'header-bg-default', array() );
$bg_url = $bg[ 'url' ];
}
// set bg style
$bg_style = ($bg_url) ? 'background-image: url("' . esc_url( $bg_url ) . '")' : '';
?>
<div class="site-header" style="<?php echo esc_attr( $bg_style ); ?>">
<div class="site-header-inner">
<?php do_action( 'mbtheme_site_header_inner' ); ?>
</div>
</div>
|
<?php
// get page thumbnail image if it is a page
if ( is_home() ) {
$bg = mbtheme_get_option( 'header-bg-blog', array() );
$bg_url = $bg[ 'url' ];
} elseif ( is_page() ) {
$page_id = get_queried_object_id();
$bg_url = get_the_post_thumbnail_url( $page_id, 'full' );
}
// get default backgound image
if ( !$bg_url ) {
$bg = mbtheme_get_option( 'header-bg-default', array() );
$bg_url = $bg[ 'url' ];
}
// set bg style
$bg_style = ($bg_url) ? 'background-image: url("' . esc_url( $bg_url ) . '")' : '';
?>
<div class="site-header" style="<?php echo esc_attr( $bg_style ); ?>">
<div class="site-header-inner">
<?php do_action( 'mbtheme_site_header_inner' ); ?>
</div>
</div>
|
FIX web_demo upload was not processing grayscale correctly
|
"""
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_270),
8: (Image.ROTATE_90,)
}
def open_oriented_im(im_path):
im = Image.open(im_path)
if hasattr(im, '_getexif'):
exif = im._getexif()
if exif is not None and 274 in exif:
orientation = exif[274]
im = apply_orientation(im, orientation)
img = np.asarray(im).astype(np.float32) / 255.
if img.ndim == 2:
img = img[:, :, np.newaxis]
img = np.tile(img, (1, 1, 3))
elif img.shape[2] == 4:
img = img[:, :, :3]
return img
def apply_orientation(im, orientation):
if orientation in ORIENTATIONS:
for method in ORIENTATIONS[orientation]:
im = im.transpose(method)
return im
|
"""
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_270),
8: (Image.ROTATE_90,)
}
def open_oriented_im(im_path):
im = Image.open(im_path)
if hasattr(im, '_getexif'):
exif = im._getexif()
if exif is not None and 274 in exif:
orientation = exif[274]
im = apply_orientation(im, orientation)
return np.asarray(im).astype(np.float32) / 255.
def apply_orientation(im, orientation):
if orientation in ORIENTATIONS:
for method in ORIENTATIONS[orientation]:
im = im.transpose(method)
return im
|
Fix onChatEvent to handle player null
|
package fr.epicanard.globalmarketchest.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import fr.epicanard.globalmarketchest.GlobalMarketChest;
import fr.epicanard.globalmarketchest.gui.InventoryGUI;
public class ChatListener implements Listener {
private Boolean isChatEditing(Player player) {
if (player != null) {
InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(player.getUniqueId());
return (inv != null && inv.getChatEditing());
}
return false;
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
if (this.isChatEditing(event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerBreakBlock(BlockBreakEvent event) {
if (this.isChatEditing(event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler
public void onChatEvent(AsyncPlayerChatEvent event) {
if (this.isChatEditing(event.getPlayer())) {
InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(event.getPlayer().getUniqueId());
inv.setChatReturn(event.getMessage());
event.setCancelled(true);
}
}
}
|
package fr.epicanard.globalmarketchest.listeners;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import fr.epicanard.globalmarketchest.GlobalMarketChest;
import fr.epicanard.globalmarketchest.gui.InventoryGUI;
public class ChatListener implements Listener {
private Boolean isChatEditing(Player player) {
if (player != null) {
InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(player.getUniqueId());
return (inv != null && inv.getChatEditing());
}
return false;
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
if (this.isChatEditing(event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerBreakBlock(BlockBreakEvent event) {
if (this.isChatEditing(event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler
public void onChatEvent(AsyncPlayerChatEvent event) {
InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(event.getPlayer().getUniqueId());
if (inv != null && inv.getChatEditing()) {
inv.setChatReturn(event.getMessage());
event.setCancelled(true);
}
}
}
|
Update to use assistant SID inline
Maintaining consistency with the auto-generated code samples for Understand, which
don't allow for our variable-named placeholder values
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
# Create a new intent named 'tell_a_joke'
# Replace 'UAXXX...' with your Assistant's unique SID https://www.twilio.com/console/assistant/list
intent = client.preview.understand \
.assistants('UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
.intents \
.create(unique_name='tell-a-joke')
# Provide actions for the new intent
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke intent to use this 'say' action.
client.preview.understand \
.assistants(assistant_sid) \
.intents(intent.sid) \
.intent_actions().update(joke_actions)
print(intent.sid)
|
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
assistant_sid = 'UAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Create a new intent named 'tell_a_joke'
intent = client.preview.understand \
.assistants(assistant_sid) \
.intents \
.create(unique_name='tell-a-joke')
# Provide actions for the new intent
joke_actions = {
'actions': [
{'say': 'I was going to look for my missing watch, but I could never find the time.'}
]
}
# Update the tell-a-joke intent to use this 'say' action.
client.preview.understand \
.assistants(assistant_sid) \
.intents(intent.sid) \
.intent_actions().update(joke_actions)
print(intent.sid)
|
Tag python-cephclient as beta instead of alpha
It's pretty much beyond alpha now.
|
from setuptools import setup
setup(
name='python-cephclient',
packages=['cephclient'],
version='0.1.0.5',
url='https://github.com/dmsimard/python-cephclient',
author='David Moreau Simard',
author_email='moi@dmsimard.com',
description='A client library in python for the Ceph REST API.',
long_description=open('README.rst', 'rt').read(),
license='Apache License, Version 2.0',
keywords='ceph rest api ceph-rest-api client library',
install_requires=['lxml>=3.2.5', 'requests>=2.2.1'],
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Information Technology',
'Programming Language :: Python :: 2.7',
'Topic :: Utilities'
]
)
|
from setuptools import setup
setup(
name='python-cephclient',
packages=['cephclient'],
version='0.1.0.5',
url='https://github.com/dmsimard/python-cephclient',
author='David Moreau Simard',
author_email='moi@dmsimard.com',
description='A client library in python for the Ceph REST API.',
long_description=open('README.rst', 'rt').read(),
license='Apache License, Version 2.0',
keywords='ceph rest api ceph-rest-api client library',
install_requires=['lxml>=3.2.5', 'requests>=2.2.1'],
classifiers=[
'License :: OSI Approved :: Apache Software License',
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Information Technology',
'Programming Language :: Python :: 2.7',
'Topic :: Utilities'
]
)
|
Fix bug with 'actionCard' property being reset improperly
|
export default class GameModelService {
constructor($log, $localStorage, _, gamesApi) {
'ngInject';
this.$log = $log.getInstance(this.constructor.name);
this._ = _;
this.gamesApi = gamesApi;
this.model = {};
}
endGame() {
let onSuccess = (res => {
this.$log.debug('onSuccess()', res, this);
this.update(res.data);
}),
onError = (err => {
this.$log.error(err);
});
this.$log.debug('endGame()', this);
this.gamesApi
.update(this.model.id, { isGameStarted: false })
.then(onSuccess, onError);
}
clear() {
angular.copy({}, this.model);
}
get() {
return this.gamesApi.get();
}
getByProp(prop) {
if (prop) {
return this.model[prop];
}
return this.model;
}
isGameStarted() {
return this.model.isGameStarted;
}
update(data) {
this.$log.debug('update()', data, this);
angular.extend(this.model, data);
if (data.actionCard === null) {
angular.copy(null, this.model.actionCard);
}
}
}
|
export default class GameModelService {
constructor($log, $localStorage, _, gamesApi) {
'ngInject';
this.$log = $log.getInstance(this.constructor.name);
this._ = _;
this.gamesApi = gamesApi;
this.model = {};
}
endGame() {
let onSuccess = (res => {
this.$log.debug('onSuccess()', res, this);
this.update(res.data);
}),
onError = (err => {
this.$log.error(err);
});
this.$log.debug('endGame()', this);
this.gamesApi
.update(this.model.id, { isGameStarted: false })
.then(onSuccess, onError);
}
clear() {
angular.copy({}, this.model);
}
get() {
return this.gamesApi.get();
}
getByProp(prop) {
if (prop) {
return this.model[prop];
}
return this.model;
}
isGameStarted() {
return this.model.isGameStarted;
}
update(data) {
this.$log.debug('update()', data, this);
angular.extend(this.model, data);
if (!data.actionCard) {
angular.copy(null, this.model.actionCard);
}
}
}
|
feat: Add Content-Language header, always 'en'
|
"use strict"
const express = require('express');
const HTTPStatus = require('http-status-codes');
var scraper = require('./app/routes/scraper');
const app = express();
// This middleware will be executed for every request to the app
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
res.header('Content-Language', 'en');
next();
});
app.use('/', scraper);
// Final catch any route middleware used to raise 404
app.get('*', (req, res, next) => {
const err = new Error();
err.statusCode = HTTPStatus.NOT_FOUND;
next(err);
});
// Error response handler
app.use((err, req, res, next) => {
res.status(err.statusCode);
res.send(err.message || HTTPStatus.getStatusText(err.statusCode));
});
app.listen(3000, function () {
console.log('Junkan server is running on port 3000!');
});
module.exports = app;
|
"use strict"
const express = require('express');
const HTTPStatus = require('http-status-codes');
var scraper = require('./app/routes/scraper');
const app = express();
// This middleware will be executed for every request to the app
// The api produces application/json only
app.use(function (req, res, next) {
res.header('Content-Type','application/json');
next();
});
app.use('/', scraper);
// Final catch any route middleware used to raise 404
app.get('*', (req, res, next) => {
const err = new Error();
err.statusCode = HTTPStatus.NOT_FOUND;
next(err);
});
// Error response handler
app.use((err, req, res, next) => {
res.status(err.statusCode);
res.send(err.message || HTTPStatus.getStatusText(err.statusCode));
});
app.listen(3000, function () {
console.log('Junkan server is running on port 3000!');
});
module.exports = app;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.