text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Add hybrid (XEP-0126 & XEP-0186) service to initial presence test.
|
"""
Tests setting your own presence before calling Connect(), allowing the user to
sign in as Busy/Invisible/whatever rather than available.
"""
from twisted.words.xish import domish
from gabbletest import exec_test
from servicetest import EventPattern, assertEquals, assertNotEquals
import ns
import constants as cs
from invisible_helper import ValidInvisibleListStream, Xep0186Stream, \
Xep0186AndValidInvisibleListStream
def test(q, bus, conn, stream):
props = conn.Properties.GetAll(cs.CONN_IFACE_SIMPLE_PRESENCE)
assertNotEquals({}, props['Statuses'])
conn.SimplePresence.SetPresence("away", "watching bees")
conn.Connect()
_, presence = q.expect_many(
EventPattern('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]),
EventPattern('stream-presence'),
)
children = list(presence.stanza.elements())
assertEquals('show', children[0].name)
assertEquals('away', children[0].children[0])
assertEquals('status', children[1].name)
assertEquals('watching bees', children[1].children[0])
if __name__ == '__main__':
exec_test(test)
for protocol in [ValidInvisibleListStream, Xep0186Stream,
Xep0186AndValidInvisibleListStream]:
exec_test(test, protocol=protocol)
|
"""
Tests setting your own presence before calling Connect(), allowing the user to
sign in as Busy/Invisible/whatever rather than available.
"""
from twisted.words.xish import domish
from gabbletest import exec_test
from servicetest import EventPattern, assertEquals, assertNotEquals
import ns
import constants as cs
from invisible_helper import ValidInvisibleListStream, Xep0186XmlStream
def test(q, bus, conn, stream):
props = conn.Properties.GetAll(cs.CONN_IFACE_SIMPLE_PRESENCE)
assertNotEquals({}, props['Statuses'])
conn.SimplePresence.SetPresence("away", "watching bees")
conn.Connect()
_, presence = q.expect_many(
EventPattern('dbus-signal', signal='StatusChanged',
args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]),
EventPattern('stream-presence'),
)
children = list(presence.stanza.elements())
assertEquals('show', children[0].name)
assertEquals('away', children[0].children[0])
assertEquals('status', children[1].name)
assertEquals('watching bees', children[1].children[0])
if __name__ == '__main__':
exec_test(test)
exec_test(test, protocol=ValidInvisibleListStream)
exec_test(test, protocol=Xep0186XmlStream)
|
Remove "Duration -" from duration string.
Remove leading zero on hour in duration string.
|
/*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
function getCallStatusText (agent) {
switch(agent.callStatus) {
case CallAgent.CallStatusNoCall:
if (agent.error) {
return qsTr("Error");
} else {
return qsTr("No Call");
}
break;
case CallAgent.CallStatusIncomingCall:
return qsTr("Incoming");
break;
case CallAgent.CallStatusConnecting:
return qsTr("Connecting");
break;
case CallAgent.CallStatusRinging:
return qsTr("Ringing");
break;
case CallAgent.CallStatusTalking:
// Qt has no way to get the time separator
return Qt.formatTime(window.callAgent.elapsedTime(), "h:mm:ss");
break;
case CallAgent.CallStatusHeld:
return qsTr("On Hold");
break;
case CallAgent.CallStatusHangingUp:
return qsTr("Hanging up");
break;
default:
return qsTr("Unknown");
}
}
|
/*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
function getCallStatusText (agent) {
switch(agent.callStatus) {
case CallAgent.CallStatusNoCall:
if (agent.error) {
return qsTr("Error");
} else {
return qsTr("No Call");
}
break;
case CallAgent.CallStatusIncomingCall:
return qsTr("Incoming");
break;
case CallAgent.CallStatusConnecting:
return qsTr("Connecting");
break;
case CallAgent.CallStatusRinging:
return qsTr("Ringing");
break;
case CallAgent.CallStatusTalking:
// Qt has no way to get the time separator
return qsTr("Duration - ") + Qt.formatTime(window.callAgent.elapsedTime(), "HH:mm:ss");
break;
case CallAgent.CallStatusHeld:
return qsTr("On Hold");
break;
case CallAgent.CallStatusHangingUp:
return qsTr("Hanging up");
break;
default:
return qsTr("Unknown");
}
}
|
Add new lines here because they are added by some editors(vim for
example)
|
package com.nikolavp.approval.reporters;
import com.nikolavp.approval.Approval;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
import java.awt.*;
import java.nio.file.FileSystems;
/**
*
* User: nikolavp
* Date: 26/02/14
* Time: 14:28
*/
@Ignore
public class ReportersExamplesIT {
@Test
public void testGvimApprovalProcess() throws Exception {
Assume.assumeTrue(Desktop.isDesktopSupported());
Approval approval = new Approval(Reporters.gvim());
approval.verify("some test content\n".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGvimApprovalProcess.txt"));
}
@Test
public void testConsoleApprovalProcess() throws Exception {
Assume.assumeTrue(Desktop.isDesktopSupported());
Approval approval = new Approval(Reporters.console());
approval.verify("some test content\n".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testConsoleApprovalProcess.txt"));
}
@Test
public void testGeditApprovalProcess() throws Exception {
Assume.assumeTrue(Desktop.isDesktopSupported());
Approval approval = new Approval(Reporters.gedit());
approval.verify("some test content\n".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGeditApprovalProcess.txt"));
}
}
|
package com.nikolavp.approval.reporters;
import com.nikolavp.approval.Approval;
import org.junit.Assume;
import org.junit.Test;
import java.awt.*;
import java.nio.file.FileSystems;
/**
*
* User: nikolavp
* Date: 26/02/14
* Time: 14:28
*/
public class ReportersExamplesIT {
@Test
public void testGvimApprovalProcess() throws Exception {
Assume.assumeTrue(Desktop.isDesktopSupported());
Approval approval = new Approval(Reporters.gvim());
approval.verify("some test content".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGvimApprovalProcess.txt"));
}
@Test
public void testConsoleApprovalProcess() throws Exception {
Assume.assumeTrue(Desktop.isDesktopSupported());
Approval approval = new Approval(Reporters.console());
approval.verify("some test content".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testConsoleApprovalProcess.txt"));
}
@Test
public void testGeditApprovalProcess() throws Exception {
Assume.assumeTrue(Desktop.isDesktopSupported());
Approval approval = new Approval(Reporters.gedit());
approval.verify("some test content".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGeditApprovalProcess.txt"));
}
}
|
Fix bug not letting default values through in ${} templates
|
(function registerStackProcessor() {
widget.parser.register( 'stack', {
prefix: '$',
doc: {
name: "${<i>variable</i>}"
},
recursive: true,
processor: decode
});
function decode( token, context )
{
var sep = token.indexOf( ',' );
var path;
if( sep > -1 )
{
var dbName = token.substring( 0, sep );
path = token.substring( sep+1 ).split( '|', 2 );
return widget.util.get( dbName, path[0], path[1] );
}
else
{
context = context || (widget.util.getStack() || [])[0];
path = token.split( '|', 2 );
return widget.get( context, path[0], path[1] ) || "${" + token + "}";
}
}
})();
|
(function registerStackProcessor() {
widget.parser.register( 'stack', {
prefix: '$',
doc: {
name: "${<i>variable</i>}"
},
recursive: true,
processor: decode
});
function decode( token, context )
{
var sep = token.indexOf( ',' );
if( sep > -1 )
{
var dbName = token.substring( 0, sep );
var path = token.substring( sep+1 ).split( '|', 2 );
if( path.length > 1 )
return widget.util.get( dbName, path[0], path[1] );
else
return widget.util.get( dbName, path[0] );
}
else
{
context = context || (widget.util.getStack() || [])[0];
return widget.get( context, token ) || "${" + token + "}";
}
}
})();
|
Update control panel test for fetch
|
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout retrieved"}',
status=201,
)
response = ControlPanel.fetch_payment_session_timeout()
self.assertTrue(response['status'])
|
import httpretty
from paystackapi.tests.base_test_case import BaseTestCase
from paystackapi.cpanel import ControlPanel
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.get,
self.endpoint_url("/integration/payment_session_timeout"),
content_type='text/json',
body='{"status": true, "message": "Payment session timeout retrieved"}',
status=201,
)
response = ControlPanel.fetch_payment_session_timeout()
self.assertTrue(response['status'])
|
[minor] Use ~ operator to check for -1
This is mainly a style change as other expressjs modules use this.
Performance is mostly indifferent.
However, this tests specifically for -1.
|
module.exports = compressible
compressible.specs =
compressible.specifications = require('./specifications.json')
compressible.regex =
compressible.regexp = /json|text|javascript|dart|ecmascript|xml/
compressible.get = get
function compressible(type) {
if (!type || typeof type !== "string") return false
var i = type.indexOf(';')
, spec = compressible.specs[~i ? type.slice(0, i) : type]
return spec ? spec.compressible : compressible.regex.test(type)
}
function get(type) {
if (!type || typeof type !== "string") return {
compressible: false,
sources: [],
notes: "Invalid type."
}
var spec = compressible.specs[type.split(';')[0]]
return spec ? spec : {
compressible: compressible.regex.test(type),
sources: ["compressible.regex"],
notes: "Automatically generated via regex."
}
}
|
module.exports = compressible
compressible.specs =
compressible.specifications = require('./specifications.json')
compressible.regex =
compressible.regexp = /json|text|javascript|dart|ecmascript|xml/
compressible.get = get
function compressible(type) {
if (!type || typeof type !== "string") return false
var i = type.indexOf(';')
, spec = compressible.specs[i < 0 ? type : type.slice(0, i)]
return spec ? spec.compressible : compressible.regex.test(type)
}
function get(type) {
if (!type || typeof type !== "string") return {
compressible: false,
sources: [],
notes: "Invalid type."
}
var spec = compressible.specs[type.split(';')[0]]
return spec ? spec : {
compressible: compressible.regex.test(type),
sources: ["compressible.regex"],
notes: "Automatically generated via regex."
}
}
|
refactor: Remove old imports from main
|
#! /usr/bin/env python
import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
|
#! /usr/bin/env python
import os
import time
from slackclient import SlackClient
import pyrebase
import linkatos.parser as parser
import linkatos.confirmation as confirmation
import linkatos.printer as printer
import linkatos.utils as utils
import linkatos.firebase as fb
# starterbot environment variables
BOT_ID = os.environ.get("BOT_ID")
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
# instantiate Slack clients
slack_client = SlackClient(SLACK_BOT_TOKEN)
# firebase environment variables
FB_API_KEY = os.environ.get("FB_API_KEY")
FB_USER = os.environ.get("FB_USER")
FB_PASS = os.environ.get("FB_PASS")
# initialise firebase
project_name = 'coses-acbe6'
firebase = fb.initialise(FB_API_KEY, project_name)
# Main
if __name__ == '__main__':
READ_WEBSOCKET_DELAY = 1 # 1 second delay between reading from firehose
# verify linkatos connection
if slack_client.rtm_connect():
expecting_confirmation = False
url = None
while True:
(expecting_confirmation, url) = do.keep_wanted_urls(expecting_confirmation, url)
else:
print("Connection failed. Invalid Slack token or bot ID?")
|
Switch to use database for image ui
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from flask import render_template, Blueprint, json
from zhihudaily.cache import cache
from zhihudaily.models import Zhihudaily
from zhihudaily.utils import Date
image_ui = Blueprint('image_ui', __name__, template_folder='templates')
@image_ui.route('/withimage')
@cache.cached(timeout=900)
def with_image():
"""The page for 图片 UI."""
day = Date()
news = Zhihudaily.select().where(Zhihudaily.date == int(day.today)).get()
return render_template('with_image.html',
lists=json.loads(news.json_news),
display_date=news.display_date,
day_before=day.day_before,
is_today=True)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
from flask import render_template, Blueprint
from zhihudaily.utils import make_request
from zhihudaily.cache import cache
image_ui = Blueprint('image_ui', __name__, template_folder='templates')
@image_ui.route('/withimage')
@cache.cached(timeout=900)
def with_image():
"""The page for 图片 UI."""
r = make_request('http://news.at.zhihu.com/api/1.2/news/latest')
(display_date, date, news_list) = get_news_info(r)
news_list = handle_image(news_list)
day_before = (
datetime.datetime.strptime(date, '%Y%m%d') - datetime.timedelta(1)
).strftime('%Y%m%d')
return render_template('with_image.html', lists=news_list,
display_date=display_date,
day_before=day_before,
is_today=True)
|
Remove active key since is deprecated
|
# -*- coding: utf-8 -*-
#
#
# Copyright (C) 2013-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
{
'name': "Sale line description",
'version': '1.0',
'category': 'Sales Management',
'author': "Agile Business Group, Odoo Community Association (OCA)",
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
"depends": [
'sale',
],
"data": [
'security/sale_security.xml',
'res_config_view.xml',
],
"installable": True
}
|
# -*- coding: utf-8 -*-
#
#
# Copyright (C) 2013-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
{
'name': "Sale line description",
'version': '1.0',
'category': 'Sales Management',
'author': "Agile Business Group, Odoo Community Association (OCA)",
'website': 'http://www.agilebg.com',
'license': 'AGPL-3',
"depends": [
'sale',
],
"data": [
'security/sale_security.xml',
'res_config_view.xml',
],
"active": False,
"installable": True
}
|
Add import path for sass files on Mac OS
|
<?php
/**
*
* PHP.Gt (http://php.gt)
* @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
* @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
*/
namespace Gt\ClientSide;
use \Gt\Core\Path;
use \Gt\Response\Response;
use \scssc as ScssParser;
class Compiler {
/**
* Parses a source file and returns its compiled content, or the original
* content if no compilation is necessary/possible.
*
* @param string $inputFile Absolute path of input file
*
* @return string Content of file to write to public directory
*/
public static function parse($inputFile) {
$ext = strtolower(pathinfo($inputFile, PATHINFO_EXTENSION));
$content = file_get_contents($inputFile);
switch ($ext) {
case "scss":
$scss = new ScssParser();
$scss->addImportPath(Path::get(Path::STYLE));
$content = $scss->compile($content);
break;
default:
break;
}
return $content;
}
}#
|
<?php
/**
*
* PHP.Gt (http://php.gt)
* @copyright Copyright Ⓒ 2014 Bright Flair Ltd. (http://brightflair.com)
* @license Apache Version 2.0, January 2004. http://www.apache.org/licenses
*/
namespace Gt\ClientSide;
use \Gt\Response\Response;
use \scssc as ScssParser;
class Compiler {
/**
* Parses a source file and returns its compiled content, or the original
* content if no compilation is necessary/possible.
*
* @param string $inputFile Absolute path of input file
*
* @return string Content of file to write to public directory
*/
public static function parse($inputFile) {
$ext = strtolower(pathinfo($inputFile, PATHINFO_EXTENSION));
$content = file_get_contents($inputFile);
switch ($ext) {
case "scss":
$scss = new ScssParser();
$content = $scss->compile($content);
break;
default:
break;
}
return $content;
}
}#
|
Add a requires on python-six 1.4.0 ( for add_metaclass )
This also mean that this doesn't run on RHEL 7 as of today.
|
#!/usr/bin/env python
import sys
from ansible import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print("Ansible now needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install setuptools).")
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author='Michael DeHaan',
author_email='michael@ansible.com',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6', 'six >= 1.4.0'],
# package_dir={ '': 'lib' },
# packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1', 'modules/extras/windows/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
# 'bin/ansible-pull',
# 'bin/ansible-doc',
# 'bin/ansible-galaxy',
# 'bin/ansible-vault',
],
data_files=[],
)
|
#!/usr/bin/env python
import sys
from ansible import __version__
try:
from setuptools import setup, find_packages
except ImportError:
print("Ansible now needs setuptools in order to build. Install it using"
" your package manager (usually python-setuptools) or via pip (pip"
" install setuptools).")
sys.exit(1)
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author='Michael DeHaan',
author_email='michael@ansible.com',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
# package_dir={ '': 'lib' },
# packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1', 'modules/extras/windows/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
# 'bin/ansible-pull',
# 'bin/ansible-doc',
# 'bin/ansible-galaxy',
# 'bin/ansible-vault',
],
data_files=[],
)
|
Fix url to use new homepage
|
from setuptools import setup, find_packages
import sys, os
from applib import __version__
setup(name='applib',
version=__version__,
description="Cross-platform application utilities",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Sridhar Ratnakumar',
author_email='srid@nearfar.org',
url='http://bitbucket.org/srid/applib',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
from setuptools import setup, find_packages
import sys, os
from applib import __version__
setup(name='applib',
version=__version__,
description="Cross-platform application utilities",
long_description="""\
""",
classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
keywords='',
author='Sridhar Ratnakumar',
author_email='srid@nearfar.org',
url='http://firefly.activestate.com/sridharr/applib',
license='MIT',
packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
include_package_data=True,
zip_safe=True,
install_requires=[
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
|
Fix airflow.utils deprecation warning code being Python 3 incompatible
See https://docs.python.org/3.0/whatsnew/3.0.html#operators-and-special-methods
|
# -*- coding: utf-8 -*-
#
# 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
import warnings
from .decorators import apply_defaults as _apply_defaults
def apply_defaults(func):
warnings.warn_explicit(
"""
You are importing apply_defaults from airflow.utils which
will be deprecated in a future version.
Please use :
from airflow.utils.decorators import apply_defaults
""",
category=PendingDeprecationWarning,
filename=func.__code__.co_filename,
lineno=func.__code__.co_firstlineno + 1
)
return _apply_defaults(func)
|
# -*- coding: utf-8 -*-
#
# 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
import warnings
from .decorators import apply_defaults as _apply_defaults
def apply_defaults(func):
warnings.warn_explicit(
"""
You are importing apply_defaults from airflow.utils which
will be deprecated in a future version.
Please use :
from airflow.utils.decorators import apply_defaults
""",
category=PendingDeprecationWarning,
filename=func.func_code.co_filename,
lineno=func.func_code.co_firstlineno + 1
)
return _apply_defaults(func)
|
Fix bug with alloy deployed to dialog
|
import React, {Component, PropTypes} from 'react';
import AlloyEditor from 'alloyeditor';
export default class AlloyEditorComponent extends Component {
componentDidMount() {
this._editor = AlloyEditor.editable(this.props.container, this.props.alloyEditorConfig);
this._nativeEditor = this._editor.get('nativeEditor');
var _this = this;
this._nativeEditor.on('change', function () {
_this.props.onContentChange(_this._nativeEditor.getData());
});
}
componentWillUnmount() {
if (this._editor && this._editor.document) {
this._editor.destroy();
}
}
shouldComponentUpdate(newProps) {
if (newProps.content != this.props.content) {
return false;
}
return true;
}
render() {
return (
<div id={this.props.container} dangerouslySetInnerHTML={{__html: this.props.content}} className="form-control" style={{minHeight: '100px', height: 'auto'}}></div>
);
}
}
|
import React, {Component, PropTypes} from 'react';
import AlloyEditor from 'alloyeditor';
export default class AlloyEditorComponent extends Component {
componentDidMount() {
this._editor = AlloyEditor.editable(this.props.container, this.props.alloyEditorConfig);
this._nativeEditor = this._editor.get('nativeEditor');
var _this = this;
this._nativeEditor.on('change', function () {
_this.props.onContentChange(_this._nativeEditor.getData());
});
}
componentWillUnmount() {
this._editor.destroy();
}
shouldComponentUpdate(newProps) {
if (newProps.content != this.props.content) {
return false;
}
return true;
}
render() {
return (
<div id={this.props.container} dangerouslySetInnerHTML={{__html: this.props.content}} className="form-control" style={{minHeight: '100px', height: 'auto'}}></div>
);
}
}
|
Add exception for definitions ending in etc.
Fixes wordset/wordset#64
|
import Ember from 'ember';
import Base from 'ember-validations/validators/base';
export default Base.extend({
call: function() {
var prop = this.model.get(this.property);
var backtick = "`";
var endingPunctuation = [".", "?", "!"];
if (Ember.isBlank(prop)) {
this.errors.pushObject("We need something here!");
} else if (prop[0] === prop[0].toUpperCase()) {
this.errors.pushObject("Start your definition with a lowercase letter.");
} else if (endingPunctuation.contains(prop[prop.length - 1])) {
if (prop.substr(prop.length - 4) == "etc.") {
console.log("wheee")
}
else {
this.errors.pushObject("Don't finish your definition with punctuation.");
}
} else if (!Ember.isBlank(prop) && prop.indexOf(backtick) !== -1){
this.errors.pushObject("No need for backticks.");
}
}
});
|
import Ember from 'ember';
import Base from 'ember-validations/validators/base';
export default Base.extend({
call: function() {
var prop = this.model.get(this.property);
var backtick = "`";
var endingPunctuation = [".", "?", "!"];
if (Ember.isBlank(prop)) {
this.errors.pushObject("We need something here!");
} else if (prop[0] === prop[0].toUpperCase()) {
this.errors.pushObject("Start your definition with a lowercase letter.");
} else if (endingPunctuation.contains(prop[prop.length - 1])) {
this.errors.pushObject("Don't finish your definition with punctuation.");
} else if (!Ember.isBlank(prop) && prop.indexOf(backtick) !== -1){
this.errors.pushObject("No need for backticks.");
}
}
});
|
Add reference tests for created objects
|
import {load} from "Injector";
import A from "example/A";
import D from "example/D";
import assert from "./assert";
import Context from "./di/Context";
const d = load(D, {name:'injected instance'});
const context = new Context({[D]: d});
const a1 = load(A, context);
const a2 = load(A, context);
const a3 = load(A, {[D]: 'test'});
assert.equal(a1, a2);
assert.equal(a1.d, a2.d);
assert.equal(a1.b, a2.b);
assert.equal(a1.c, a2.c);
assert.equal(a1.b.c.d, a2.b.c.d);
assert.notEqual(a1, a3);
assert.notEqual(a1.d, a3.d);
assert.notEqual(a1.b, a3.b);
assert.notEqual(a1.c, a3.c);
assert.notEqual(a1.b.c.d, a3.b.c.d);
|
import {load} from "Injector";
import A from "example/A";
import D from "example/D";
import assert from "./assert";
import Context from "./di/Context";
const d = load(D, {name:'injected instance'});
const context = new Context({[D]: d});
const a1 = load(A, context);
const a2 = load(A, context);
const a3 = load(A, {[D]: 'test'});
assert.equal(a1.d, a2.d);
assert.equal(a1.b, a2.b);
assert.equal(a1.c, a2.c);
assert.equal(a1.b.c.d, a2.b.c.d);
assert.notEqual(a1.d, a3.d);
assert.notEqual(a1.b, a3.b);
assert.notEqual(a1.c, a3.c);
assert.notEqual(a1.b.c.d, a3.b.c.d);
|
Make the enum element comparison strict
The current check is matching numeric strings that are not equal ( like "604.1" == "604.10" because of PHP's == behavior that converts numeric strings to numbers and then performs a numeric comparison), even if type is checked before the comparison, the value should be identic
|
<?php
/*
* This file is part of the JsonSchema package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JsonSchema\Constraints;
/**
* The Enum Constraints, validates an element against a given set of possibilities
*
* @author Robert Schönthal <seroscho@googlemail.com>
* @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
*/
class Enum extends Constraint
{
/**
* {@inheritDoc}
*/
public function check($element, $schema = null, $path = null, $i = null)
{
// Only validate enum if the attribute exists
if ($element instanceof Undefined && (!isset($schema->required) || !$schema->required)) {
return;
}
foreach ($schema->enum as $enum) {
if ((gettype($element) === gettype($enum)) && ($element === $enum)) {
return;
}
}
$this->addError($path, "does not have a value in the enumeration " . print_r($schema->enum, true));
}
}
|
<?php
/*
* This file is part of the JsonSchema package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JsonSchema\Constraints;
/**
* The Enum Constraints, validates an element against a given set of possibilities
*
* @author Robert Schönthal <seroscho@googlemail.com>
* @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
*/
class Enum extends Constraint
{
/**
* {@inheritDoc}
*/
public function check($element, $schema = null, $path = null, $i = null)
{
// Only validate enum if the attribute exists
if ($element instanceof Undefined && (!isset($schema->required) || !$schema->required)) {
return;
}
foreach ($schema->enum as $enum) {
if ((gettype($element) === gettype($enum)) && ($element == $enum)) {
return;
}
}
$this->addError($path, "does not have a value in the enumeration " . print_r($schema->enum, true));
}
}
|
Fix locales for windows and unix
Signed-off-by: Josua Grawitter <c028c213ed5efcf30c3f4fc7361dbde0c893c5b7@greyage.org>
|
<?php
require_once('config.inc.php');
require_once('misc.inc.php');
require_once('db.inc.php');
require_once('html.inc.php');
date_default_timezone_set('Europe/Berlin');
setlocale(LC_TIME, 'de_DE.utf8', 'deu');
session_start();
// Actual content generation:
$db = new db();
switch ($_GET['view']) {
case 'print':
authenticate(VIEW_PRINT, 'index.php?view=print');
if (isset($_GET['date'])) {
$source = new ovp_print($db, $_GET['date']);
} else {
$source = new ovp_print($db);
}
break;
case 'author':
authenticate(VIEW_AUTHOR, 'index.php?view=author');
$source = new ovp_author($db);
break;
case 'admin':
authenticate(VIEW_ADMIN, 'index.php?view=admin');
$source = new ovp_admin($db);
break;
case 'login':
$source = new ovp_login($db);
break;
case 'public':
default:
authenticate(VIEW_PUBLIC, 'index.php?view=public');
$source = new ovp_public($db);
}
$page = new ovp_page($source);
exit($page->get_html());
?>
|
<?php
require_once('config.inc.php');
require_once('misc.inc.php');
require_once('db.inc.php');
require_once('html.inc.php');
date_default_timezone_set('Europe/Berlin');
setlocale(LC_TIME, 'deu');
session_start();
// Actual content generation:
$db = new db();
switch ($_GET['view']) {
case 'print':
authenticate(VIEW_PRINT, 'index.php?view=print');
if (isset($_GET['date'])) {
$source = new ovp_print($db, $_GET['date']);
} else {
$source = new ovp_print($db);
}
break;
case 'author':
authenticate(VIEW_AUTHOR, 'index.php?view=author');
$source = new ovp_author($db);
break;
case 'admin':
authenticate(VIEW_ADMIN, 'index.php?view=admin');
$source = new ovp_admin($db);
break;
case 'login':
$source = new ovp_login($db);
break;
case 'public':
default:
authenticate(VIEW_PUBLIC, 'index.php?view=public');
$source = new ovp_public($db);
}
$page = new ovp_page($source);
exit($page->get_html());
?>
|
Allow one field payload on method links.
|
var $ = require('jquery');
$(document).ready(function() {
var $body = $('body');
// Allow links to specify a HTTP method using `data-method`
$('[data-method]').on('click', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var method = $(this).data('method');
var formItem = $(this).data('form-item');
var formValue = $(this).data('form-value');
var csrfToken = $('meta[name=csrf-token]').attr('content');
var $form = $('<form method="post" action="' + url + '"></form>');
var metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';
if (csrfToken !== undefined) {
metadataInput += '<input name="_token" value="' + csrfToken + '" type="hidden" />';
}
if (formItem !== undefined && formValue !== undefined) {
metadataInput += '<input name="' + formItem + '" value="' + formValue + '" type="hidden" />';
}
$form.hide().append(metadataInput);
$body.append($form);
$form.submit();
});
});
|
var $ = require('jquery');
$(document).ready(function() {
var $body = $('body');
// Allow links to specify a HTTP method using `data-method`
$('[data-method]').on('click', function(event) {
event.preventDefault();
var url = $(this).attr('href');
var method = $(this).data('method');
var csrfToken = $('meta[name=csrf-token]').attr('content');
var $form = $('<form method="post" action="' + url + '"></form>');
var metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';
if (csrfToken !== undefined) {
metadataInput += '<input name="_token" value="' + csrfToken + '" type="hidden" />';
}
$form.hide().append(metadataInput);
$body.append($form);
$form.submit();
});
});
|
FIX css path in treeForVendor
|
/* jshint node: true */
'use strict';
var path = require('path');
var fs = require('fs');
var Funnel = require('broccoli-funnel');
process.setMaxListeners(0);
module.exports = {
name: 'ember-enterprise-core',
included: function(app) {
this._super.included(app);
var useScss = app.options['emberEnterprise.useScss'];
if (!useScss) {
app.import(path.join('vendor/compiled_css/bootstrap-theme.css'));
app.import(path.join('vendor/compiled_css/material-theme.css'));
}
var faPath = path.join(app.bowerDirectory, 'font-awesome');
var fontsPath = path.join(faPath, 'fonts');
// Import all files in the fonts folder when option not defined or enabled
fs.readdirSync(fontsPath).forEach(function(fontFilename){
app.import(
path.join(fontsPath, fontFilename),
{ destDir:'/fonts' }
);
});
},
treeForVendor: function(tree) {
var cssPath = 'node_modules/ember-enterprise-core/css';
if (this.isDevelopingAddon()) {
cssPath = 'css';
}
tree = new Funnel(cssPath, { destDir: 'compiled_css' });
return this._super.treeForVendor.call(this, tree);
}
};
|
/* jshint node: true */
'use strict';
var path = require('path');
var fs = require('fs');
var Funnel = require('broccoli-funnel');
var log = require('broccoli-stew').log;
process.setMaxListeners(0);
module.exports = {
name: 'ember-enterprise-core',
included: function(app) {
this._super.included(app);
var useScss = app.options['emberEnterprise.useScss'];
if (!useScss) {
app.import(path.join('vendor/compiled_css/bootstrap-theme.css'));
app.import(path.join('vendor/compiled_css/material-theme.css'));
}
var faPath = path.join(app.bowerDirectory, 'font-awesome');
var fontsPath = path.join(faPath, 'fonts');
// Import all files in the fonts folder when option not defined or enabled
fs.readdirSync(fontsPath).forEach(function(fontFilename){
app.import(
path.join(fontsPath, fontFilename),
{ destDir:'/fonts' }
);
});
},
treeForVendor: function(tree) {
tree = new Funnel('node_modules/ember-enterprise-core/css', { destDir: 'compiled_css' });
var loggedApp = log(tree, { name: 'vendor tree' });
return this._super.treeForVendor.call(this, loggedApp);
}
};
|
Add defer to ensure that logger will be called after serve http.
|
package mux
import (
"log"
"net/http"
"time"
)
type WrapperFunc func(handlerFunc http.Handler) http.Handler
// Wraps handler func with slice of wrapper functions one by one.
func Wrap(h http.Handler, wrappers ...WrapperFunc) http.Handler {
for _, w := range wrappers {
h = w(h)
}
return h
}
// Logs requests
func Logger(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer log.Printf(
"%s\t%s\t%s",
r.Method,
r.RequestURI,
time.Since(start),
)
h.ServeHTTP(w, r)
})
}
// Creates wrapper functions that adds timeout to requests
func Timeout(timeout time.Duration) WrapperFunc {
return func(h http.Handler) http.Handler {
return http.TimeoutHandler(h, timeout, "timeout exceed")
}
}
|
package mux
import (
"log"
"net/http"
"time"
)
type WrapperFunc func(handlerFunc http.Handler) http.Handler
// Wraps handler func with slice of wrapper functions one by one.
func Wrap(h http.Handler, wrappers ...WrapperFunc) http.Handler {
for _, w := range wrappers {
h = w(h)
}
return h
}
// Logs requests
func Logger(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
h.ServeHTTP(w, r)
log.Printf(
"%s\t%s\t%s",
r.Method,
r.RequestURI,
time.Since(start),
)
})
}
// Creates wrapper functions that adds timeout to requests
func Timeout(timeout time.Duration) WrapperFunc {
return func(h http.Handler) http.Handler {
return http.TimeoutHandler(h, timeout, "timeout exceed")
}
}
|
Fix link click handling - some regular links were erroneously caught
|
debug_log("Creating click handler");
$("body").on("click", "a", function(event) {
debug_log("Click handler activated.")
var url = $(this).prop("href");
debug_log("URL: "+url)
if (ExtensionConfig.handle_magnets) {
debug_log("Handling magnets enabled");
if (url.indexOf("magnet:") == 0) {
debug_log("Detected link as magnet");
event.stopPropagation();
event.preventDefault();
debug_log("Captured magnet link "+url);
chrome.runtime.sendMessage(
{
"method": "add_torrent_from_magnet",
"url": url
}
);
debug_log("Link sent to Deluge.")
}
}
if (ExtensionConfig.handle_torrents) {
debug_log("Handling torrents enabled");
if (url.search(/\.torrent$/) > 0) {
debug_log("Detected link as a torrent");
event.stopPropagation();
event.preventDefault();
debug_log("Captured .torrent link "+url)
chrome.runtime.sendMessage(
{
"method": "add_torrent_from_url",
"url": url
}
);
debug_log("Link sent to Deluge.")
}
}
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
debug_log(request.msg);
});
|
debug_log("Creating click handler");
$("body").on("click", "a", function(event) {
debug_log("Click handler activated.")
var url = $(this).prop("href");
debug_log("URL: "+url)
if (ExtensionConfig.handle_magnets) {
debug_log("Handling magnets enabled");
if (url.indexOf("magnet:") == 0) {
debug_log("Detected link as magnet");
event.stopPropagation();
event.preventDefault();
debug_log("Captured magnet link "+url);
chrome.runtime.sendMessage(
{
"method": "add_torrent_from_magnet",
"url": url
}
);
debug_log("Link sent to Deluge.")
}
}
if (ExtensionConfig.handle_torrents) {
debug_log("Handling torrents enabled");
if (url.indexOf(".torrent") > -1) {
debug_log("Detected link as a torrent");
event.stopPropagation();
event.preventDefault();
debug_log("Captured .torrent link "+url)
chrome.runtime.sendMessage(
{
"method": "add_torrent_from_url",
"url": url
}
);
debug_log("Link sent to Deluge.")
}
}
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
debug_log(request.msg);
});
|
Insert Script Tag at Foot of the `<head>` Tag
Ensures we're less likely to inflict damage to people's performance due
to tag ordering.
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-trackjs',
contentFor: function (type, config) {
var trackOpts;
var trackConfig;
var trackConfiguration;
var trackBoilerPlate;
var addonConfig;
if (type === 'head-footer') {
trackOpts = config.trackJs || {};
trackConfig = trackOpts.config || {};
trackConfiguration = '<script type="text/javascript" id="trackjs-configuration">window._trackJs = ' + JSON.stringify(trackConfig) + ';</script>';
if (trackOpts.url) {
trackBoilerPlate = '<script type="text/javascript" id="trackjs-boilerplate" src="' + trackOpts.url + '" crossorigin="anonymous"></script>';
}
return [trackConfiguration, trackBoilerPlate].join('\n');
}
},
included: function (app) {
this._super.included(app);
var options = app.options['ember-cli-trackjs'];
if (!(options && options.cdn)) {
app.import(app.bowerDirectory + '/trackjs/tracker.js');
}
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-trackjs',
contentFor: function (type, config) {
var trackOpts;
var trackConfig;
var trackConfiguration;
var trackBoilerPlate;
var addonConfig;
if (type === 'head') {
trackOpts = config.trackJs || {};
trackConfig = trackOpts.config || {};
trackConfiguration = '<script type="text/javascript" id="trackjs-configuration">window._trackJs = ' + JSON.stringify(trackConfig) + ';</script>';
if (trackOpts.url) {
trackBoilerPlate = '<script type="text/javascript" id="trackjs-boilerplate" src="' + trackOpts.url + '" crossorigin="anonymous"></script>';
}
return [trackConfiguration, trackBoilerPlate].join('\n');
}
},
included: function (app) {
this._super.included(app);
var options = app.options['ember-cli-trackjs'];
if (!(options && options.cdn)) {
app.import(app.bowerDirectory + '/trackjs/tracker.js');
}
}
};
|
Allow to override progress property of backdrop-content
|
import Ember from "ember";
const {
Component,
computed,
String: { htmlSafe },
computed: { oneWay },
inject: { service },
get,
} = Ember;
export default Component.extend({
sideMenu: service(),
progress: oneWay("sideMenu.progress"),
attributeBindings: ["style"],
classNames: ["content-backdrop"],
style: computed("progress", function () {
const progress = get(this, "progress");
const opacity = progress / 100;
const visibility = progress === 0 ? "hidden" : "visible";
let transition = "none";
if (progress === 100) {
transition = "opacity 0.2s ease-out";
} else if (progress === 0) {
transition = "visibility 0s linear 0.2s, opacity 0.2s ease-out";
}
return htmlSafe(
`opacity: ${opacity}; visibility: ${visibility}; transition: ${transition}`
);
}),
click() {
get(this, "sideMenu").close();
},
});
|
import Ember from "ember";
const {
Component,
computed,
String: { htmlSafe },
computed: { alias },
inject: { service },
get,
} = Ember;
export default Component.extend({
sideMenu: service(),
progress: alias("sideMenu.progress"),
attributeBindings: ["style"],
classNames: ["content-backdrop"],
style: computed("progress", function () {
const progress = get(this, "progress");
const opacity = progress / 100;
const visibility = progress === 0 ? "hidden" : "visible";
let transition = "none";
if (progress === 100) {
transition = "opacity 0.2s ease-out";
} else if (progress === 0) {
transition = "visibility 0s linear 0.2s, opacity 0.2s ease-out";
}
return htmlSafe(
`opacity: ${opacity}; visibility: ${visibility}; transition: ${transition}`
);
}),
click() {
get(this, "sideMenu").close();
},
});
|
Make sure current date is late enough
|
integration_test = True
timeout = 2
SLEEP_INTERVAL = int(100e6)
MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC
def check_state(state):
import re
from functools import partial
from operator import is_not
r = re.compile('^(\d+) \[.*\] Hello World!')
lines = map(r.match, state.console.split('\n'))
lines = filter(partial(is_not, None), lines)
times = map(lambda m: int(m.group(1)), lines)
times = list(times)
min_times = (timeout - 1) * int(1e9) // SLEEP_INTERVAL
assert len(times) >= min_times, "Expected at least {0} hello worlds".format(min_times)
prev = 0
for t in times:
diff = t - prev
assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTERVAL)
assert t >= MIN_TIME, "Time must be after {0}".format(MIN_TIME)
prev = diff
|
integration_test = True
timeout = 2
SLEEP_INTERVAL = int(100e6)
def check_state(state):
import re
from functools import partial
from operator import is_not
r = re.compile('^(\d+) \[.*\] Hello World!')
lines = map(r.match, state.console.split('\n'))
lines = filter(partial(is_not, None), lines)
times = map(lambda m: int(m.group(1)), lines)
times = list(times)
min_times = (timeout - 1) * int(1e9) // SLEEP_INTERVAL
assert len(times) >= min_times, "Expected at least {0} hello worlds".format(min_times)
prev = 0
for t in times:
diff = t - prev
assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTERVAL)
prev = diff
|
Fix test config import issues
|
"use strict";
let path = require('path'),
fs = require('fs');
// ========================================
// Load global modules
// ========================================
global._ = require('lodash');
global.winston = require('winston');
// ========================================
// Load configuration values
// ========================================
try {
// can't use async here, doing it the ugly way...
let configPath = path.join(__dirname, '../config.json');
fs.accessSync(configPath, fs.R_OK);
global.appconfig = require(configPath);
} catch(err) {
// Use default test values
let dataPath = (process.env.HOME) ? path.join(process.env.HOME, './requarksdata/') : path.join(__dirname, './tempdata/');
global.appconfig = {
"db": {
"connstr": "mongodb://localhost/requarks"
},
"storage": {
"local": {
"path": dataPath
},
"provider": "local"
},
"redis": {
"config": "noauth",
"host": "localhost",
"port": "6379"
},
"auth0": {},
"title": "Requarks",
"host": "http://localhost",
"setup": true,
"sessionSecret": "1234567890abcdefghijklmnopqrstuvxyz"
}
fs.mkdirSync(dataPath);
}
// ========================================
// Run Tests
// ========================================
require('./setup-db.js');
|
"use strict";
let path = require('path'),
fs = require('fs');
// ========================================
// Load global modules
// ========================================
global._ = require('lodash');
global.winston = require('winston');
// ========================================
// Load configuration values
// ========================================
fs.access('../config.json', fs.R_OK, (err) => {
if(err) {
// Use default test values
global.appconfig = {
"db": {
"connstr": "mongodb://localhost/requarks"
},
"storage": {
"local": {
"path": path.join(process.env.HOME, './requarksdata/')
},
"provider": "local"
},
"redis": {
"config": "noauth",
"host": "localhost",
"port": "6379"
},
"auth0": {},
"title": "Requarks",
"host": "http://localhost",
"setup": true,
"sessionSecret": "1234567890abcdefghijklmnopqrstuvxyz"
}
fs.mkdirSync(appconfig.storage.local.path);
} else {
// Use current values
global.appconfig = require('../config.json');
}
// ========================================
// Run Tests
// ========================================
require('./setup-db.js');
});
|
Change Auth\Guard to use Guard Contract
|
<?php namespace GeneaLabs\LaravelMixpanel\Providers;
use GeneaLabs\LaravelMixpanel\LaravelMixpanel;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelEventHandler;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelUserObserver;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Event;
use Illuminate\HTTP\Request;
use Illuminate\Support\ServiceProvider;
class LaravelMixpanelServiceProvider extends ServiceProvider
{
protected $defer = false;
public function boot(Request $request, Guard $guard, LaravelMixpanel $mixPanel)
{
include __DIR__ . '/../Http/routes.php';
$this->app->make(config('auth.model'))->observe(new LaravelMixpanelUserObserver($request, $mixPanel));
$eventHandler = new LaravelMixpanelEventHandler($request, $guard, $mixPanel);
Event::subscribe($eventHandler);
}
public function register()
{
$this->app->singleton(LaravelMixpanel::class);
}
/**
* @return array
*/
public function provides()
{
return ['laravel-mixpanel'];
}
}
|
<?php namespace GeneaLabs\LaravelMixpanel\Providers;
use GeneaLabs\LaravelMixpanel\LaravelMixpanel;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelEventHandler;
use GeneaLabs\LaravelMixpanel\Listeners\LaravelMixpanelUserObserver;
use Illuminate\Auth\Guard;
use Illuminate\Support\Facades\Event;
use Illuminate\HTTP\Request;
use Illuminate\Support\ServiceProvider;
class LaravelMixpanelServiceProvider extends ServiceProvider
{
protected $defer = false;
public function boot(Request $request, Guard $guard, LaravelMixpanel $mixPanel)
{
include __DIR__ . '/../Http/routes.php';
$this->app->make(config('auth.model'))->observe(new LaravelMixpanelUserObserver($request, $mixPanel));
$eventHandler = new LaravelMixpanelEventHandler($request, $guard, $mixPanel);
Event::subscribe($eventHandler);
}
public function register()
{
$this->app->singleton(LaravelMixpanel::class);
}
/**
* @return array
*/
public function provides()
{
return ['laravel-mixpanel'];
}
}
|
[Federation] Fix the comments on FederationNameAnnotation
|
/*
Copyright 2017 The Kubernetes Authors.
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 federation
// FederationNameAnnotation is the annotation which holds the name of
// the federation that a federation control plane component is associated
// with. It must be applied to all the API types that represent that federations
// control plane's components in the host cluster and in joining clusters.
const FederationNameAnnotation = "federation.alpha.kubernetes.io/federation-name"
// ClusterNameAnnotation is the annotation which holds the name of
// the cluster that an object is associated with. If the object is
// not associated with any cluster, then this annotation is not
// required.
const ClusterNameAnnotation = "federation.alpha.kubernetes.io/cluster-name"
|
/*
Copyright 2016 The Kubernetes Authors.
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 federation
// FederationNameAnnotation is the annotation which holds the name of
// the federation that an object is associated with. It must be
// applied to all API objects associated with that federation.
const FederationNameAnnotation = "federation.alpha.kubernetes.io/federation-name"
// ClusterNameAnnotation is the annotation which holds the name of
// the cluster that an object is associated with. If the object is
// not associated with any cluster, then this annotation is not
// required.
const ClusterNameAnnotation = "federation.alpha.kubernetes.io/cluster-name"
|
Remove exit from start event payload
|
'use strict';
const { mapValues, omit, pSetTimeout } = require('../utilities');
const { logEvent } = require('../log');
const { getDefaultDuration } = require('../perf');
// Create event when all protocol-specific servers have started
const emitStartEvent = async function ({ protocols, config, measures }) {
const message = 'Server is ready';
const params = getEventParams({ protocols, measures });
// Let other events finish first
await pSetTimeout(0, { unref: false });
await logEvent({
event: 'start',
phase: 'startup',
message,
params,
config,
});
return { startPayload: params };
};
// Remove some properties from event payload as they are not serializable,
// or should not be made immutable
const getEventParams = function ({ protocols, measures }) {
const protocolsA = mapValues(
protocols,
protocol => omit(protocol, ['server', 'protocolAdapter']),
);
const duration = getDefaultDuration({ measures });
return { protocols: protocolsA, duration };
};
module.exports = {
emitStartEvent,
};
|
'use strict';
const { mapValues, omit, pSetTimeout } = require('../utilities');
const { logEvent } = require('../log');
const { getDefaultDuration } = require('../perf');
// Create event when all protocol-specific servers have started
const emitStartEvent = async function ({
protocols,
config,
gracefulExit,
measures,
}) {
const message = 'Server is ready';
const params = getEventParams({ protocols, gracefulExit, measures });
// Let other events finish first
await pSetTimeout(0, { unref: false });
await logEvent({
event: 'start',
phase: 'startup',
message,
params,
config,
});
return { startPayload: params };
};
// Remove some properties from event payload as they are not serializable,
// or should not be made immutable
const getEventParams = function ({ protocols, gracefulExit, measures }) {
const protocolsA = mapValues(
protocols,
protocol => omit(protocol, ['server', 'protocolAdapter']),
);
const duration = getDefaultDuration({ measures });
return { protocols: protocolsA, exit: gracefulExit, duration };
};
module.exports = {
emitStartEvent,
};
|
Add real XP value to ChracterStatusDialog.
Still need real MaxXP
|
ui.CharacterStatusDialog = function(template, character) {
ui.Dialog.call(this, template);
this.name = ui.label(this, '.label.name');
this.hp = ui.progressbar(this, '.progressbar.health');
this.mp = ui.progressbar(this, '.progressbar.mana');
this.xp = ui.progressbar(this, '.progressbar.exp');
if (character) {
this.setCharacter(character);
}
}
ui.CharacterStatusDialog.prototype = Object.create(ui.Dialog.prototype);
ui.CharacterStatusDialog.prototype._character = null;
ui.CharacterStatusDialog.prototype.setCharacter = function(character) {
this._character = character;
this._update();
};
ui.CharacterStatusDialog.prototype._update = function() {
this.name.text(this._character.name);
this.hp.max(this._character.stats.getMaxHp());
this.hp.value(this._character.hp);
this.mp.max(this._character.stats.getMaxMp());
this.mp.value(this._character.mp);
this.xp.max(1000); // TODO: Real max xp
this.xp.value(this._character.xp);
};
ui.characterStatusDialog = function(character) {
return new ui.CharacterStatusDialog('#dlgCharacterStatus', character);
};
|
ui.CharacterStatusDialog = function(template, character) {
ui.Dialog.call(this, template);
this.name = ui.label(this, '.label.name');
this.hp = ui.progressbar(this, '.progressbar.health');
this.mp = ui.progressbar(this, '.progressbar.mana');
this.xp = ui.progressbar(this, '.progressbar.exp');
if (character) {
this.setCharacter(character);
}
}
ui.CharacterStatusDialog.prototype = Object.create(ui.Dialog.prototype);
ui.CharacterStatusDialog.prototype._character = null;
ui.CharacterStatusDialog.prototype.setCharacter = function(character) {
this._character = character;
this._update();
};
ui.CharacterStatusDialog.prototype._update = function() {
this.name.text(this._character.name);
// TODO: real hp values
this.hp.min(0);
this.hp.max(this._character.stats.getMaxHp());
this.hp.value(this._character.hp);
// TODO real mp values
this.mp.min(0);
this.mp.max(this._character.stats.getMaxMp());
this.mp.value(this._character.mp);
// TODO real xp values
this.xp.min(0);
this.xp.max(100);
this.xp.value(10);
};
ui.characterStatusDialog = function(character) {
return new ui.CharacterStatusDialog('#dlgCharacterStatus', character);
};
|
Fix mari pointing to dead dir
|
/*
* itsjoke.js - It's Joke!.
*
* Contributed by Capuccino and Ovyerus.
*/
/* eslint-env node */
const fs = require('fs');
const files = fs.readdirSync(`${__baseDir}/assets/itsjoke`);
exports.commands = [
'mari'
];
exports.mari = {
desc: "It's joke!",
longDesc: "Send a random picture of the it's joke meme.",
main(bot, ctx) {
return new Promise((resolve, reject) => {
ctx.channel.sendTyping();
let fileName = files[Math.floor(Math.random() * files.length)];
let file = fs.readFileSync(`${__baseDir}/assets/itsjoke/${fileName}`);
ctx.createMessage('', {file, name: fileName}).then(resolve).catch(reject);
});
}
};
|
/*
* itsjoke.js - It's Joke!.
*
* Contributed by Capuccino and Ovyerus.
*/
/* eslint-env node */
const fs = require('fs');
const files = fs.readdirSync(`${__baseDir}/res/itsjoke`);
exports.commands = [
'mari'
];
exports.mari = {
desc: "It's joke!",
longDesc: "Send a random picture of the it's joke meme.",
main(bot, ctx) {
return new Promise((resolve, reject) => {
ctx.channel.sendTyping();
let fileName = files[Math.floor(Math.random() * files.length)];
let file = fs.readFileSync(`${__baseDir}/assets/itsjoke/${fileName}`);
ctx.createMessage('', {file, name: fileName}).then(resolve).catch(reject);
});
}
};
|
Add way to debug lambda function end 2 end
|
"""
Entry point for lambda
"""
from _ebcf_alexa import interaction_model, incoming_types, speechlet
import logging
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG)
ALEXA_SKILL_ID = 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'
def lambda_handler(event_dict: dict, context) -> dict:
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
LOG.debug(repr(event_dict))
event = incoming_types.LambdaEvent(event_dict)
LOG.info("Start Lambda Event for event.session.application.applicationId=%s",
event.session.application.application_id)
# This is the official application id
if event.session.application.application_id != ALEXA_SKILL_ID:
raise ValueError("Invalid Application ID: %s" % event.session.application.application_id)
return interaction_model.handle_event(event).dict()
if __name__ == '__main__':
logging.basicConfig(format='%(levelname)s %(filename)s-%(funcName)s-%(lineno)d: %(message)s', level=logging.DEBUG)
import json
import sys
import pprint
import pdb
import traceback
try:
pprint.pprint(lambda_handler(json.load(sys.stdin), None))
except Exception:
traceback.print_exc()
pdb.post_mortem()
raise
|
"""
Entry point for lambda
"""
from _ebcf_alexa import interaction_model, incoming_types, speechlet
import logging
LOG = logging.getLogger()
LOG.setLevel(logging.DEBUG)
ALEXA_SKILL_ID = 'amzn1.ask.skill.d6f2f7c4-7689-410d-9c35-8f8baae37969'
def lambda_handler(event_dict: dict, context) -> dict:
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
LOG.debug(repr(event_dict))
event = incoming_types.LambdaEvent(event_dict)
LOG.info("Start Lambda Event for event.session.application.applicationId=%s",
event.session.application.application_id)
# This is the official application id
if event.session.application.application_id != ALEXA_SKILL_ID:
raise ValueError("Invalid Application ID: %s" % event.session.application.application_id)
return interaction_model.handle_event(event).dict()
|
Clean up runloop now that it's always on
|
import {
TICK,
} from './ActionTypes';
class RunLoop {
constructor() {
this.store = null;
this._listeners = [];
this._lastTickMs = Date.now();
window.requestAnimationFrame(this._runLoop.bind(this));
}
_runLoop() {
const now = Date.now();
const dt = now - this._lastTickMs;
this._lastTickMs = now;
this.store.dispatch({
type: TICK,
dt,
});
this._listeners.forEach((listener) => listener());
window.requestAnimationFrame(this._runLoop.bind(this));
}
setStore(store) {
this.store = store;
}
subscribe(listener) {
this._listeners.push(listener);
}
unsubscribe(listener) {
const idx = this._listeners.indexOf(listener);
if (idx === -1) {
throw new Error('tried to unsubscribe listener that wasn\'t subscribed');
}
this._listeners.splice(idx, 1);
}
}
const runLoop = new RunLoop();
export default runLoop;
|
import {
TICK,
} from './ActionTypes';
class RunLoop {
constructor() {
this.store = null;
this._listeners = [];
let prev = Date.now();
let runLoop = () => {
const now = Date.now();
const dt = now - prev;
prev = now;
this.store.dispatch({
type: TICK,
dt,
});
this._listeners.forEach((listener) => listener());
window.requestAnimationFrame(runLoop);
};
this.unsetPlaybackRunLoop = () => {
runLoop = () => {};
};
window.requestAnimationFrame(runLoop);
}
setStore(store) {
this.store = store;
}
subscribe(listener) {
this._listeners.push(listener);
}
unsubscribe(listener) {
const idx = this._listeners.indexOf(listener);
if (idx === -1) {
throw new Error('tried to unsubscribe listener that wasn\'t subscribed');
}
this._listeners.splice(idx, 1);
}
}
const runLoop = new RunLoop();
export default runLoop;
|
Add that nifty closing parenthesis
|
var _ = require('lodash');
if (process.env.NODE_ENV === 'production') {
var twilio = require('twilio')(process.env.TWILIO_ACCOUNT_ID, process.env.TWILIO_AUTH_TOKEN);
var phoneNumber = process.env.TWILIO_PHONE_NUMBER;
module.exports = {
send: function (number, message) {
var messages = [];
messages.concat(message);
console.log(messages);
messages.forEach(function (message) {
twilio.sms.messages.create({
body: message,
to: number,
from: phoneNumber
}, function(err, response) {
if (err) console.log(err);
console.log('Sent:', response.sid, number, message);
});
});
}
};
} else {
module.exports = {
send: function (number, message) {
messages.concat(message);
messages.forEach(function (message) {
console.log('Sent:', message);
});
}
};
}
|
var _ = require('lodash');
if (process.env.NODE_ENV === 'production') {
var twilio = require('twilio')(process.env.TWILIO_ACCOUNT_ID, process.env.TWILIO_AUTH_TOKEN);
var phoneNumber = process.env.TWILIO_PHONE_NUMBER;
module.exports = {
send: function (number, message) {
var messages = [];
messages.concat(message);
console.log(messages);
messages.forEach(function (message) {
twilio.sms.messages.create({
body: message,
to: number,
from: phoneNumber
}, function(err, response) {
if (err) console.log(err);
console.log('Sent:', response.sid, number, message);
});
});
}
};
} else {
module.exports = {
send: function (number, message) {
messages.concat(message);
messages.forEach(function (message) {
console.log('Sent:', message);
};
}
};
}
|
Fix Checkstyle issues: First sentence should end with a period.
git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1352225 13f79535-47bb-0310-9956-ffa450edef68
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.example;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;
/**
* Simply changed the last modification time of the given file.
*/
public class ChangeLastModificationTime
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
return;
}
FileObject fo = VFS.getManager().resolveFile(args[0]);
long setTo = System.currentTimeMillis();
System.err.println("set to: " + setTo);
fo.getContent().setLastModifiedTime(setTo);
System.err.println("after set: " + fo.getContent().getLastModifiedTime());
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.example;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.VFS;
/**
* Simply changed the last modification time of the given file
*/
public class ChangeLastModificationTime
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
{
System.err.println("Please pass the name of a file as parameter.");
return;
}
FileObject fo = VFS.getManager().resolveFile(args[0]);
long setTo = System.currentTimeMillis();
System.err.println("set to: " + setTo);
fo.getContent().setLastModifiedTime(setTo);
System.err.println("after set: " + fo.getContent().getLastModifiedTime());
}
}
|
Add more to test for selection in create hook.
|
var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var checkboxHTML = `
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
<span class="checkbox-label-span"></span>
</label>
`,
checkbox = d3.component("div", "form-check")
.create(function (selection){
selection.html(checkboxHTML);
})
.render(function (selection, props){
if(props && props.label){
selection.select(".checkbox-label-span")
.text(props.label);
}
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox);
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
tape("Render should have access to selection content from create hook.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox, { label: "My Checkbox"});
test.equal(div.select(".checkbox-label-span").text(), "My Checkbox");
test.end();
});
|
var tape = require("tape"),
jsdom = require("jsdom"),
d3 = Object.assign(require("../"), require("d3-selection"));
/*************************************
************ Components *************
*************************************/
// Leveraging create hook with selection as first argument.
var checkboxHTML = `
<label class="form-check-label">
<input type="checkbox" class="form-check-input">
<span class="checkbox-label-span"></span>
</label>
`,
checkbox = d3.component("div", "form-check")
.create(function (selection){
selection.html(checkboxHTML);
})
.render(function (selection, props){
});
/*************************************
************** Tests ****************
*************************************/
tape("Create hook should pass selection on enter.", function(test) {
var div = d3.select(jsdom.jsdom().body).append("div");
div.call(checkbox);
test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`);
test.end();
});
|
Add missing implementation in StaticAccessControl
|
<?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
use Imbo\Auth\AccessControl\Adapter\AdapterInterface,
Imbo\Auth\AccessControl\Adapter\AbstractAdapter,
Imbo\Auth\AccessControl\UserQuery,
Imbo\Auth\AccessControl\GroupQuery;
/**
* Use a custom user lookup implementation
*/
class StaticAccessControl extends AbstractAdapter implements AdapterInterface {
public function hasAccess($publicKey, $resource, $user = null) {
return $publicKey === 'public';
}
public function getPrivateKey($publicKey) {
return 'private';
}
public function getUsers(UserQuery $query = null) {
return ['public'];
}
public function getGroups(GroupQuery $query = null) {
return [];
}
public function getGroup($groupName) {
return false;
}
public function userExists($publicKey) {
return $publicKey === 'public';
}
public function publicKeyExists($publicKey) {
return $publicKey === 'public';
}
public function getAccessListForPublicKey($publicKey) {
return [];
}
public function getAccessRule($publicKey, $accessRuleId) {
return null;
}
}
return [
'accessControl' => new StaticAccessControl(),
];
|
<?php
/**
* This file is part of the Imbo package
*
* (c) Christer Edvartsen <cogo@starzinger.net>
*
* For the full copyright and license information, please view the LICENSE file that was
* distributed with this source code.
*/
use Imbo\Auth\AccessControl\Adapter\AdapterInterface,
Imbo\Auth\AccessControl\Adapter\AbstractAdapter,
Imbo\Auth\AccessControl\UserQuery,
Imbo\Auth\AccessControl\GroupQuery;
/**
* Use a custom user lookup implementation
*/
class StaticAccessControl extends AbstractAdapter implements AdapterInterface {
public function hasAccess($publicKey, $resource, $user = null) {
return $publicKey === 'public';
}
public function getPrivateKey($publicKey) {
return 'private';
}
public function getUsers(UserQuery $query = null) {
return ['public'];
}
public function getGroups(GroupQuery $query = null) {
return [];
}
public function getGroup($groupName) {
return false;
}
public function userExists($publicKey) {
return $publicKey === 'public';
}
public function publicKeyExists($publicKey) {
return $publicKey === 'public';
}
public function getAccessListForPublicKey($publicKey) {
return [];
}
}
return [
'accessControl' => new StaticAccessControl(),
];
|
Update guide url to shuup-guide.readthedocs.io
Refs SHUUP-3188
|
# 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.
#: ReadtheDocs API URL
#:
#: URL for fetching search results via ReadtheDocs API.
SHUUP_GUIDE_API_URL = "https://readthedocs.org/api/v2/search/?project=shoop-guide&version=latest&"
#: ReadtheDocs link URL
#:
#: URL for manually linking search query link. Query parameters are
#: added to end of URL when constructing link.
SHUUP_GUIDE_LINK_URL = "http://shuup-guide.readthedocs.io/en/latest/search.html?check_keywords=yes&area=default&"
#: Whether or not to fetch search results from ReadtheDocs
#:
#: If true, fetch results via the ReadtheDocs API, otherwise only
#: display a link to RTD search page.
SHUUP_GUIDE_FETCH_RESULTS = True
#: Timeout limit for fetching search results
#:
#: Time limit in seconds before a search result request should
#: timeout, so as not to block search results in case of slow response.
SHUUP_GUIDE_TIMEOUT_LIMIT = 2
|
# 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.
#: ReadtheDocs API URL
#:
#: URL for fetching search results via ReadtheDocs API.
SHUUP_GUIDE_API_URL = "https://readthedocs.org/api/v2/search/?project=shoop-guide&version=latest&"
#: ReadtheDocs link URL
#:
#: URL for manually linking search query link. Query parameters are
#: added to end of URL when constructing link.
SHUUP_GUIDE_LINK_URL = "http://shoop-guide.readthedocs.io/en/latest/search.html?check_keywords=yes&area=default&"
#: Whether or not to fetch search results from ReadtheDocs
#:
#: If true, fetch results via the ReadtheDocs API, otherwise only
#: display a link to RTD search page.
SHUUP_GUIDE_FETCH_RESULTS = True
#: Timeout limit for fetching search results
#:
#: Time limit in seconds before a search result request should
#: timeout, so as not to block search results in case of slow response.
SHUUP_GUIDE_TIMEOUT_LIMIT = 2
|
Rename alg value for easybox/secretbox
|
'use strict';
var _ = require('lodash');
var algos = {
'eddsa': 'eddsa',
'curve25519': 'curve25519',
'triplesec-v3': 'triplesec-v3',
'scrypt': 'scrypt',
'nacl easybox': 'easybox',
'nacl secretbox': 'secretbox',
};
algos.name = function(b) {
b = ''+b; // coerce to string
var found = _.findKey(algos, function(val) {
return val === b.toLowerCase();
});
if (found) {
return found;
}
throw new Error('unrecognized algo');
};
algos.value = function(key) {
var algo = algos[key.toString().toLowerCase()];
if (algo) {
return algo;
}
throw new Error('unrecognized algo');
};
module.exports = algos;
|
'use strict';
var _ = require('lodash');
var algos = {
'eddsa': 'eddsa',
'curve25519': 'curve25519',
'triplesec-v3': 'triplesec-v3',
'scrypt': 'scrypt',
'nacl easybox': 'nacl-easybox',
'nacl secretbox': 'nacl-secretbox',
};
algos.name = function(b) {
b = ''+b; // coerce to string
var found = _.findKey(algos, function(val) {
return val === b.toLowerCase();
});
if (found) {
return found;
}
throw new Error('unrecognized algo');
};
algos.value = function(key) {
var algo = algos[key.toString().toLowerCase()];
if (algo) {
return algo;
}
throw new Error('unrecognized algo');
};
module.exports = algos;
|
Fix typo retrieving vendor prefix
Properly get the OSCAR_SAGEPAY_TX_CODE_PREFIX from the project settings
|
from django.conf import settings
VPS_PROTOCOL = getattr(settings, 'OSCAR_SAGEPAY_VPS_PROTOCOL', '3.0')
VENDOR = settings.OSCAR_SAGEPAY_VENDOR
TEST_MODE = getattr(settings, 'OSCAR_SAGEPAY_TEST_MODE', True)
if TEST_MODE:
VPS_REGISTER_URL = 'https://test.sagepay.com/Simulator/VSPDirectGateway.asp'
VPS_AUTHORISE_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorAuthoriseTx'
VPS_REFUND_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorRefundTx'
VPS_VOID_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorVoidTx'
else:
VPS_REGISTER_URL = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp'
VPS_AUTHORISE_URL = VPS_REFUND_URL = VPS_REGISTER_URL = VPS_VOID_URL
VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEPAY_TX_CODE_PREFIX",
"oscar")
|
from django.conf import settings
VPS_PROTOCOL = getattr(settings, 'OSCAR_SAGEPAY_VPS_PROTOCOL', '3.0')
VENDOR = settings.OSCAR_SAGEPAY_VENDOR
TEST_MODE = getattr(settings, 'OSCAR_SAGEPAY_TEST_MODE', True)
if TEST_MODE:
VPS_REGISTER_URL = 'https://test.sagepay.com/Simulator/VSPDirectGateway.asp'
VPS_AUTHORISE_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorAuthoriseTx'
VPS_REFUND_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorRefundTx'
VPS_VOID_URL = 'https://test.sagepay.com/Simulator/VSPServerGateway.asp?Service=VendorVoidTx'
else:
VPS_REGISTER_URL = 'https://live.sagepay.com/gateway/service/vspdirect-register.vsp'
VPS_AUTHORISE_URL = VPS_REFUND_URL = VPS_REGISTER_URL = VPS_VOID_URL
VENDOR_TX_CODE_PREFIX = getattr(settings, "OSCAR_SAGEOAY_TX_CODE_PREFIX",
"oscar")
|
Test exception on queue plugin manager validation
|
<?php
namespace SlmQueueTest\Queue;
use PHPUnit_Framework_TestCase as TestCase;
use SlmQueue\Queue\QueuePluginManager;
use SlmQueueTest\Util\ServiceManagerFactory;
use Zend\ServiceManager\ServiceManager;
class QueuePluginManagerTest extends TestCase
{
/**
* @var ServiceManager
*/
protected $serviceManager;
public function setUp()
{
parent::setUp();
$this->serviceManager = ServiceManagerFactory::getServiceManager();
}
public function testCanRetrievePluginManagerWithServiceManager()
{
$queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');
$this->assertInstanceOf('SlmQueue\Queue\QueuePluginManager', $queuePluginManager);
}
public function testAskingTwiceTheSameQueueReturnsTheSameInstance()
{
$queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');
$firstInstance = $queuePluginManager->get('basic-queue');
$secondInstance = $queuePluginManager->get('basic-queue');
$this->assertSame($firstInstance, $secondInstance);
}
public function testPluginValidation()
{
$manager = new QueuePluginManager();
$queue = new \stdClass();
$this->setExpectedException('SlmQueue\Queue\Exception\RuntimeException');
$manager->validatePlugin($queue);
}
}
|
<?php
namespace SlmQueueTest\Queue;
use PHPUnit_Framework_TestCase as TestCase;
use SlmQueueTest\Util\ServiceManagerFactory;
use Zend\ServiceManager\ServiceManager;
class QueuePluginManagerTest extends TestCase
{
/**
* @var ServiceManager
*/
protected $serviceManager;
public function setUp()
{
parent::setUp();
$this->serviceManager = ServiceManagerFactory::getServiceManager();
}
public function testCanRetrievePluginManagerWithServiceManager()
{
$queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');
$this->assertInstanceOf('SlmQueue\Queue\QueuePluginManager', $queuePluginManager);
}
public function testAskingTwiceTheSameQueueReturnsTheSameInstance()
{
$queuePluginManager = $this->serviceManager->get('SlmQueue\Queue\QueuePluginManager');
$firstInstance = $queuePluginManager->get('basic-queue');
$secondInstance = $queuePluginManager->get('basic-queue');
$this->assertSame($firstInstance, $secondInstance);
}
}
|
Exclude Proxy code from production build
|
import { DEBUG } from '@glimmer/env';
let exportedWindow;
let _setCurrentHandler;
if (DEBUG) {
// this Proxy handler will be used to preserve the unaltered behavior of the window global by default
const doNothingHandler = {
get(target, prop) {
const value = Reflect.get(target, prop);
// make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
if (typeof value === 'function') {
return new Proxy(value, {
apply(t, _thisArg, argumentsList) {
return Reflect.apply(value, target, argumentsList);
}
});
}
return value;
},
set: Reflect.set,
has: Reflect.has,
deleteProperty: Reflect.deleteProperty
}
let currentHandler = doNothingHandler;
// private function to replace the default handler in tests
_setCurrentHandler = (handler = doNothingHandler) => currentHandler = handler;
const proxyHandler = {
get() {
return currentHandler.get(...arguments);
},
set() {
return currentHandler.set(...arguments);
},
has() {
return currentHandler.has(...arguments);
},
deleteProperty() {
return currentHandler.deleteProperty(...arguments);
},
}
exportedWindow = new Proxy(window, proxyHandler);
} else {
exportedWindow = window;
}
export default exportedWindow;
export { _setCurrentHandler };
|
// this Proxy handler will be used to preserve the unaltered behavior of the window global by default
const doNothingHandler = {
get(target, prop) {
const value = Reflect.get(target, prop);
// make sure the function receives the original window as the this context! (e.g. alert will throw an invalid invocation error)
if (typeof window[prop] === 'function') {
return new Proxy(value, {
apply(t, _thisArg, argumentsList) {
return Reflect.apply(value, target, argumentsList);
}
});
}
return value;
},
set: Reflect.set,
has: Reflect.has,
deleteProperty: Reflect.deleteProperty
}
let currentHandler = doNothingHandler;
// private function to replace the default handler in tests
export function _setCurrentHandler(handler = doNothingHandler) {
currentHandler = handler;
}
const proxyHandler = {
get() {
return currentHandler.get(...arguments);
},
set() {
return currentHandler.set(...arguments);
},
has() {
return currentHandler.has(...arguments);
},
deleteProperty() {
return currentHandler.deleteProperty(...arguments);
},
}
export default new Proxy(window, proxyHandler);
|
Add some explanation of logging options.
|
"""Configuration file for harness.py
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
The main configuration options are for logging. By changing _debug to 1 (default
is 0) much more debugging information will be added to the log files.
The overall logging level can also be set using the LOGLEVEL variable. This
level can be overridden using command line options to the scripts.
"""
import logging
##################################################
# debug logging control
# 0 for off, 1 for on
##################################################
_debug = 1
#This is the default log level which can be overridden in run_config.
# The logging level changes how much is saved to logging files.
# Choose from logging.DEBUG, .INFO, .WARN, .ERROR, .CRITICAL in decreasing order of verbosity
LOGLEVEL = logging.INFO
# Directory structure
# Change the names of various directories
#Change to using the base run directory with bin, pyflation, scripts immediately below.
CODEDIRNAME = "."
RUNDIRNAME = "runs"
RESULTSDIRNAME = "results"
LOGDIRNAME = "applogs"
QSUBSCRIPTSDIRNAME = "qsubscripts"
QSUBLOGSDIRNAME = "qsublogs"
RUNCONFIGTEMPLATE = "run_config.template"
#Name of provenance file which records the code revisions and results files added
provenancefilename = "provenance.log"
# Compression type to be used with PyTables:
# PyTables stores results in HDF5 files. The compression it uses can be
# selected here. For maximum compatibility with other HDF5 utilities use "zlib".
# For maximum efficiency in both storage space and recall time use "blosc".
hdf5complib = "blosc"
hdf5complevel = 2
|
"""Configuration file for harness.py
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
"""
import logging
##################################################
# debug logging control
# 0 for off, 1 for on
##################################################
_debug = 1
#This is the default log level which can be overridden in run_config.
# The logging level changes how much is saved to logging files.
# Choose from logging.DEBUG, .INFO, .WARN, .ERROR, .CRITICAL in decreasing order of verbosity
LOGLEVEL = logging.INFO
# Directory structure
# Change the names of various directories
#Change to using the base run directory with bin, pyflation, scripts immediately below.
CODEDIRNAME = "."
RUNDIRNAME = "runs"
RESULTSDIRNAME = "results"
LOGDIRNAME = "applogs"
QSUBSCRIPTSDIRNAME = "qsubscripts"
QSUBLOGSDIRNAME = "qsublogs"
RUNCONFIGTEMPLATE = "run_config.template"
#Name of provenance file which records the code revisions and results files added
provenancefilename = "provenance.log"
# Compression type to be used with PyTables:
# PyTables stores results in HDF5 files. The compression it uses can be
# selected here. For maximum compatibility with other HDF5 utilities use "zlib".
# For maximum efficiency in both storage space and recall time use "blosc".
hdf5complib = "blosc"
hdf5complevel = 2
|
Clean the sandbox after the last test
Otherwise there can be some weird test pollution
|
(function(){
function mochaSinon(sinon){
if (typeof beforeEach !== "function") {
throw "mocha-sinon relies on mocha having been loaded.";
}
beforeEach(function() {
if (null == this.sinon) {
if (sinon.createSandbox) {
// Sinon 2+ (sinon.sandbox.create triggers a deprecation warning in Sinon 5)
this.sinon = sinon.createSandbox();
} else {
this.sinon = sinon.sandbox.create();
}
} else {
this.sinon.restore();
}
});
after(function() {
// avoid test pollution for the last test that runs
if (this.sinon) {
this.sinon.restore();
}
});
}
(function(plugin){
if (
typeof window === "object"
&& typeof window.sinon === "object"
) {
plugin(window.sinon);
} else if (typeof require === "function") {
var sinon = require('sinon');
module.exports = function () {
plugin(sinon);
};
plugin(sinon);
} else {
throw "We could not find sinon through a supported module loading technique. Pull requests are welcome!";
}
})(mochaSinon);
})();
|
(function(){
function mochaSinon(sinon){
if (typeof beforeEach !== "function") {
throw "mocha-sinon relies on mocha having been loaded.";
}
beforeEach(function() {
if (null == this.sinon) {
if (sinon.createSandbox) {
// Sinon 2+ (sinon.sandbox.create triggers a deprecation warning in Sinon 5)
this.sinon = sinon.createSandbox();
} else {
this.sinon = sinon.sandbox.create();
}
} else {
this.sinon.restore();
}
});
}
(function(plugin){
if (
typeof window === "object"
&& typeof window.sinon === "object"
) {
plugin(window.sinon);
} else if (typeof require === "function") {
var sinon = require('sinon');
module.exports = function () {
plugin(sinon);
};
plugin(sinon);
} else {
throw "We could not find sinon through a supported module loading technique. Pull requests are welcome!";
}
})(mochaSinon);
})();
|
Move logic for fetching md files to it's own function
* wqflask/wqflask/markdown_routes.py
(render_markdown): New function.
(glossary): use render_markdown function.
|
"""Markdown routes
Render pages from github, or if they are unavailable, look for it else where
"""
import os
import requests
import mistune
from flask import Blueprint
from flask import render_template
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
def render_markdown(file_name):
"""Try to fetch the file name from Github and if that fails, try to
look for it inside the file system
"""
markdown_url = (f"https://raw.githubusercontent.com"
f"/genenetwork/genenetwork2/"
f"wqflask/wqflask/static/"
f"{file_name}")
md_content = requests.get(markdown_url)
if md_content.status_code == 200:
return mistune.html(md_content.content.decode("utf-8"))
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),
f"static/markdown/{file_name}")) as md_file:
markdown = md_file.read()
return mistune.html(markdown)
@glossary_blueprint.route('/')
def glossary():
return render_template(
"glossary.html",
rendered_markdown=render_markdown("glossary.md")), 200
|
"""Markdown routes
Render pages from github, or if they are unavailable, look for it else where
"""
import requests
import mistune
from flask import Blueprint
from flask import render_template
glossary_blueprint = Blueprint('glossary_blueprint', __name__)
@glossary_blueprint.route('/')
def glossary():
markdown_url = ("https://raw.githubusercontent.com"
"/genenetwork/genenetwork2/"
"wqflask/wqflask/static"
"/glossary.md")
md_content = requests.get(markdown_url)
if md_content.status_code == 200:
return render_template(
"glossary_html",
rendered_markdown=mistune.html(
md_content.content.decode("utf-8"))), 200
return render_template(
"glossary.html",
rendered_markdown=mistune.html("# Github Down!")), 200
|
Fix fake db service API
|
'use strict';
function FakeDatabaseService() {
}
module.exports = FakeDatabaseService;
FakeDatabaseService.prototype = {
run: function(query, callback) {
return callback(null, {});
},
createCacheTable: function(node, callback) {
return callback(null, true);
},
registerAnalysisInCatalog: function(analysis, callback) {
return callback(null);
},
getMetadataFromAffectedTables: function(node, skip, callback) {
return callback(null, {
last_update: 0,
affected_tables: []
});
},
queueAnalysisOperations: function(analysis, callback) {
return callback(null);
},
trackAnalysis: function(analysis, callback) {
return callback(null);
},
getColumnNames: function(query, callback) {
return callback(null, []);
},
getColumns: function(query, callback) {
return callback(null, []);
},
enqueue: function(query, callback) {
return callback(null, {status: 'ok'});
}
};
|
'use strict';
function FakeDatabaseService() {
}
module.exports = FakeDatabaseService;
FakeDatabaseService.prototype = {
run: function(query, callback) {
return callback(null, {});
},
createCacheTable: function(node, callback) {
return callback(null, true);
},
registerAnalysisInCatalog: function(analysis, callback) {
return callback(null);
},
getMetadataFromAffectedTables: function(node, skip, callback) {
return callback(null, 0);
},
queueAnalysisOperations: function(analysis, callback) {
return callback(null);
},
trackAnalysis: function(analysis, callback) {
return callback(null);
},
getColumnNames: function(query, callback) {
return callback(null, []);
},
getColumns: function(query, callback) {
return callback(null, []);
},
enqueue: function(query, callback) {
return callback(null, {status: 'ok'});
}
};
|
Add valid key for .map'd FeaturedGene components
|
import React from "react"
import PropTypes from "prop-types"
import styled from "styled-components"
import FeaturedGene from "./FeaturedGene"
const propTypes = {
featuredGeneLinks: PropTypes.array,
}
const Layout = styled.div`
display: none;
@media (min-width: 768px) {
display: block;
padding-top: 1em;
column-count: 3;
column-gap: 2em;
}
`
const FeaturedGenes = ({ featuredGeneLinks }) => {
return (
<Layout>
{featuredGeneLinks &&
featuredGeneLinks.length > 0 &&
featuredGeneLinks
.map(featuredGene => (
<FeaturedGene key={featuredGene.href} {...featuredGene} />
))
.slice(0, 3)}
</Layout>
)
}
FeaturedGenes.propTypes = propTypes
export default FeaturedGenes
|
import React from "react"
import PropTypes from "prop-types"
import styled from "styled-components"
import FeaturedGene from "./FeaturedGene"
const propTypes = {
featuredGeneLinks: PropTypes.array,
}
const Layout = styled.div`
display: none;
@media (min-width: 768px) {
display: block;
padding-top: 1em;
column-count: 3;
column-gap: 2em;
}
`
const FeaturedGenes = ({ featuredGeneLinks }) => {
return (
<Layout>
{featuredGeneLinks &&
featuredGeneLinks.length > 0 &&
featuredGeneLinks
.map(featuredGene => (
<FeaturedGene key={featuredGene.id} {...featuredGene} />
))
.slice(0, 3)}
</Layout>
)
}
FeaturedGenes.propTypes = propTypes
export default FeaturedGenes
|
Tweak PHPDocs in the extension configuration files
|
<?php
namespace Symfony\Bundle\DoctrineMigrationsBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* DoctrineMigrationsExtension configuration structure.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
class Configuration
{
/**
* Generates the configuration tree.
*
* @return \Symfony\Component\Config\Definition\ArrayNode The config tree
*/
public function getConfigTree()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('doctrine_migrations', 'array');
$rootNode
->children()
->scalarNode('dir_name')->defaultValue('%kernel.root_dir%/DoctrineMigrations')->cannotBeEmpty()->end()
->scalarNode('namespace')->defaultValue('Application\Migrations')->cannotBeEmpty()->end()
->scalarNode('table_name')->defaultValue('migration_versions')->cannotBeEmpty()->end()
->scalarNode('name')->defaultValue('Application Migrations')->end()
->end()
;
return $treeBuilder->buildTree();
}
}
|
<?php
namespace Symfony\Bundle\DoctrineMigrationsBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
/**
* DoctrineMigrationsExtension configuration structure.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
class Configuration
{
/**
* Generates the configuration tree.
*
* @return NodeInterface
*/
public function getConfigTree()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('doctrine_migrations', 'array');
$rootNode
->children()
->scalarNode('dir_name')->defaultValue('%kernel.root_dir%/DoctrineMigrations')->cannotBeEmpty()->end()
->scalarNode('namespace')->defaultValue('Application\Migrations')->cannotBeEmpty()->end()
->scalarNode('table_name')->defaultValue('migration_versions')->cannotBeEmpty()->end()
->scalarNode('name')->defaultValue('Application Migrations')->end()
->end()
;
return $treeBuilder->buildTree();
}
}
|
Check that expected title exists in the actual title, not the other way round
|
# (c) Crown Owned Copyright, 2016. Dstl.
import os
import unittest
from splinter import Browser
class TestLoginPage (unittest.TestCase):
def setUp(self):
self.browser = Browser('phantomjs')
def test_login_page_appears(self):
# This needs to come from an environment variable at some point
# For now, this will only pass if the lighthouse-app-server host is
# running.
url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST']
title = 'Lighthouse'
self.browser.visit(url)
self.assertEqual(self.browser.url, url)
self.assertEqual(self.browser.status_code.code, 200)
self.assertIn(title, self.browser.title)
self.assertIn('Login with ID.', self.browser.html)
|
# (c) Crown Owned Copyright, 2016. Dstl.
import os
import unittest
from splinter import Browser
class TestLoginPage (unittest.TestCase):
def setUp(self):
self.browser = Browser('phantomjs')
def test_login_page_appears(self):
# This needs to come from an environment variable at some point
# For now, this will only pass if the lighthouse-app-server host is
# running.
url = "http://%s/login" % os.environ['LIGHTHOUSE_HOST']
title = 'Lighthouse'
self.browser.visit(url)
self.assertEqual(self.browser.url, url)
self.assertEqual(self.browser.status_code.code, 200)
self.assertIn(self.browser.title, title)
self.assertIn('Login with ID.', self.browser.html)
|
Add assertion for issue gh-1089
|
import os
from .. import run_nbgrader
from .base import BaseTestApp
class TestNbGraderGenerateConfig(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["generate_config", "--help-all"])
def test_generate_config(self):
"""Is the config file properly generated?"""
# it already exists, because we create it in conftest.py
os.remove("nbgrader_config.py")
# try recreating it
run_nbgrader(["generate_config"])
assert os.path.isfile("nbgrader_config.py")
with open("nbgrader_config.py") as f:
contents = f.read()
# This was missing in issue #1089
assert "AssignLatePenalties" in contents
# does it fail if it already exists?
run_nbgrader(["generate_config"], retcode=1)
|
import os
from .. import run_nbgrader
from .base import BaseTestApp
class TestNbGraderGenerateConfig(BaseTestApp):
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["generate_config", "--help-all"])
def test_generate_config(self):
"""Is the config file properly generated?"""
# it already exists, because we create it in conftest.py
os.remove("nbgrader_config.py")
# try recreating it
run_nbgrader(["generate_config"])
assert os.path.isfile("nbgrader_config.py")
# does it fail if it already exists?
run_nbgrader(["generate_config"], retcode=1)
|
Return the config, don't hit the callback
|
var http = require('http');
var yaml = require('js-yaml');
var fs = require('fs');
var spawn = require('child_process').spawn;
var chimneypot = require('chimneypot');
(function() {
function readConfig() {
var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));
if (doc.config !== undefined && doc.config.port !== undefined &&
doc.config.path !== undefined && doc.config.secret !== undefined) {
return doc.config;
}
}
readConfig(function(err, data) {
if (err) {
console.log(err);
} else {
var pot = new chimneypot({
port: data.port,
path: data.path,
secret: data.secret
});
pot.route('push', function (event) {
spawn('sh', ['pull.sh']);
});
pot.listen();
}
});
})();
|
var http = require('http');
var yaml = require('js-yaml');
var fs = require('fs');
var spawn = require('child_process').spawn;
var chimneypot = require('chimneypot');
(function() {
function readConfig(callback) {
var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));
if (doc.config !== undefined && doc.config.port !== undefined &&
doc.config.path !== undefined && doc.config.secret !== undefined) {
callback(undefined, doc.config);
} else {
callback("Malformed .deploy.yml.", undefined);
}
}
readConfig(function(err, data) {
if (err) {
console.log(err);
} else {
var pot = new chimneypot({
port: data.port,
path: data.path,
secret: data.secret
});
pot.route('push', function (event) {
spawn('sh', ['pull.sh']);
});
pot.listen();
}
});
})();
|
Fix `APP_ENV` not set in some runtime contexts
|
<?php
namespace Outlandish\Wpackagist\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
// Let Symfony's default error tracing happen in dev.
if ($_SERVER['APP_ENV'] === 'dev') {
return;
}
$message = 'Something went wrong.';
$exception = $event->getThrowable();
$response = new Response();
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
if ($exception->getStatusCode() === 404) {
$message = 'The requested page could not be found.';
}
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
$response->setContent($message);
$event->setResponse($response);
}
}
|
<?php
namespace Outlandish\Wpackagist\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
// Let Symfony's default error tracing happen in dev.
if (getenv('APP_ENV') === 'dev') {
return;
}
$message = 'Something went wrong.';
$exception = $event->getThrowable();
$response = new Response();
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
if ($exception->getStatusCode() === 404) {
$message = 'The requested page could not be found.';
}
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
$response->setContent($message);
$event->setResponse($response);
}
}
|
Add one more if to speed up
|
# Remove Element https://oj.leetcode.com/problems/remove-element/
# Given an array and a value, remove all instances of that value in place and return the new length.
# The order of elements can be changed. It doesn't matter what you leave beyond the new length.
#Arrays
# Xilin SUN
# Jan 8 2015
# Don't forget to return 0 if A == [].
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
if len(A) == 0:
return 0
else:
k=0
for i in range(0, len(A)):
if A[i] != elem:
if i!= k:
A[k] = A[i]
k += 1
return k
|
# Remove Element https://oj.leetcode.com/problems/remove-element/
# Given an array and a value, remove all instances of that value in place and return the new length.
# The order of elements can be changed. It doesn't matter what you leave beyond the new length.
#Arrays
# Xilin SUN
# Jan 8 2015
# Don't forget to return 0 if A == [].
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
if len(A) == 0:
return 0
else:
k=0
for i in range(0, len(A)):
if A[i] != elem:
A[k] = A[i]
k += 1
return k
|
Add a backref from Link to LinkAttribute
|
# Copyright (c) 2014 Lukas Lalinsky, Wieland Hoffmann
# License: MIT, see LICENSE for details
from mbdata.models import Area, Artist, Label, LinkAttribute, Recording, ReleaseGroup, Work
from sqlalchemy import exc as sa_exc
from sqlalchemy.orm import relationship
from warnings import simplefilter
# Ignore SQLAlchemys warnings that we're overriding some attributes
simplefilter(action="ignore", category=sa_exc.SAWarning)
class CustomArea(Area):
aliases = relationship("AreaAlias")
class CustomArtist(Artist):
aliases = relationship("ArtistAlias")
area = relationship('CustomArea', foreign_keys=[Artist.area_id])
begin_area = relationship('CustomArea', foreign_keys=[Artist.begin_area_id])
end_area = relationship('CustomArea', foreign_keys=[Artist.end_area_id])
class CustomLabel(Label):
aliases = relationship("LabelAlias")
class CustomRecording(Recording):
tracks = relationship("Track")
class CustomReleaseGroup(ReleaseGroup):
releases = relationship("Release")
class CustomWork(Work):
aliases = relationship("WorkAlias")
artist_links = relationship("LinkArtistWork")
class CustomLinkAttribute(LinkAttribute):
link = relationship('Link', foreign_keys=[LinkAttribute.link_id], innerjoin=True,
backref="attributes")
|
# Copyright (c) 2014 Lukas Lalinsky, Wieland Hoffmann
# License: MIT, see LICENSE for details
from mbdata.models import Area, Artist, Label, Recording, ReleaseGroup, Work
from sqlalchemy import exc as sa_exc
from sqlalchemy.orm import relationship
from warnings import simplefilter
# Ignore SQLAlchemys warnings that we're overriding some attributes
simplefilter(action="ignore", category=sa_exc.SAWarning)
class CustomArea(Area):
aliases = relationship("AreaAlias")
class CustomArtist(Artist):
aliases = relationship("ArtistAlias")
area = relationship('CustomArea', foreign_keys=[Artist.area_id])
begin_area = relationship('CustomArea', foreign_keys=[Artist.begin_area_id])
end_area = relationship('CustomArea', foreign_keys=[Artist.end_area_id])
class CustomLabel(Label):
aliases = relationship("LabelAlias")
class CustomRecording(Recording):
tracks = relationship("Track")
class CustomReleaseGroup(ReleaseGroup):
releases = relationship("Release")
class CustomWork(Work):
aliases = relationship("WorkAlias")
artist_links = relationship("LinkArtistWork")
|
Return instance of Client rather than ClientBuilder
|
<?php
namespace Orphans\ElasticSearch\App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use Elasticsearch\ClientBuilder;
class ElasticSearchServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('elasticsearch', function($app){
$es = new ClientBuilder;
$client = $es->create()->build();
$this->app->instance('elasticsearch', $client);
return $client;
});
}
}
|
<?php
namespace Orphans\ElasticSearch\App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use Elasticsearch\ClientBuilder;
class ElasticSearchServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('elasticsearch', function($app){
$es = new ClientBuilder;
$this->app->instance('elasticsearch', $es->create()->build());
return $es;
});
}
}
|
Rename tests with more sensible names
|
package fgis.server.support.geojson;
import org.geolatte.geom.Geometry;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public final class GjGeometryTest
extends AbstractGjElementTest
{
@Test
public void basic()
throws Exception
{
final Geometry geometry = fromWkT( "POINT (1 1)" );
final GjGeometry e = new GjGeometry( geometry, null, null, null );
assertEquals( e.getGeometry(), geometry );
assertPropertyAllowed( e, "X" );
assertPropertyNotAllowed( e, "coordinates" );
}
@SuppressWarnings( "ConstantConditions" )
@Test
public void nullGeometry()
throws Exception
{
try
{
new GjGeometry( null, null, null, null );
}
catch ( final IllegalArgumentException e )
{
return;
}
fail( "Expected to fail when passing null geometry" );
}
@SuppressWarnings( "ConstantConditions" )
@Test
public void geometryCollectionPassedAsGeometryShouldFail()
throws Exception
{
try
{
new GjGeometry( fromWkT( "GEOMETRYCOLLECTION(POINT (1 1))" ), null, null, null );
}
catch ( final IllegalArgumentException e )
{
return;
}
fail( "Expected to fail when passing null geometry" );
}
}
|
package fgis.server.support.geojson;
import org.geolatte.geom.Geometry;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public final class GjGeometryTest
extends AbstractGjElementTest
{
@Test
public void geometry()
throws Exception
{
final Geometry geometry = fromWkT( "POINT (1 1)" );
final GjGeometry e = new GjGeometry( geometry, null, null, null );
assertEquals( e.getGeometry(), geometry );
assertPropertyAllowed( e, "X" );
assertPropertyNotAllowed( e, "coordinates" );
}
@SuppressWarnings( "ConstantConditions" )
@Test
public void nullGeometryPassedToGeometry()
throws Exception
{
try
{
new GjGeometry( null, null, null, null );
}
catch ( final IllegalArgumentException e )
{
return;
}
fail( "Expected to fail when passing null geometry" );
}
@SuppressWarnings( "ConstantConditions" )
@Test
public void geometryCollectionPassedToGeometryShouldFail()
throws Exception
{
try
{
new GjGeometry( fromWkT( "GEOMETRYCOLLECTION(POINT (1 1))" ), null, null, null );
}
catch ( final IllegalArgumentException e )
{
return;
}
fail( "Expected to fail when passing null geometry" );
}
}
|
Change list copy to list()
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = list(inputL)
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
"""
Solution to code eval interrupted bubble sort:
https://www.codeeval.com/open_challenges/158/
"""
import sys
def bubble_sort(inputL):
"""One iteration of bubble sort."""
for num in xrange(len(inputL)-1):
if inputL[num+1] < inputL[num]:
inputL[num+1], inputL[num] = inputL[num], inputL[num+1]
return inputL
def interrupted_bs(line):
"""Parse input line and preform bubble sort X times.
X is defined as the integer after '|' on line."""
temp = line.split('|')
num = int(temp[1].rstrip())
temp[0] = temp[0].rstrip()
inputL = [int(x) for x in temp[0].split(' ')]
for x in xrange(num):
old = inputL[:]
inputL = bubble_sort(inputL)
# check if sorted
if old == inputL:
break
# convert back to string
print ' '.join(map(str, inputL))
def main(filename):
"""Open file and perform bubble_sort on each line."""
with open(filename, 'r') as file_handle:
for line in file_handle:
interrupted_bs(line)
if __name__ == '__main__':
filename = sys.argv[1]
main(filename)
|
Clean up config in constructor
|
'use strict';
const colors = require('ansicolors');
const fs = require('fs');
const pluralize = require('pluralize');
const CLIEngine = require('eslint').CLIEngine;
class ESLinter {
constructor(brunchConfig) {
this.config = (brunchConfig && brunchConfig.plugins && brunchConfig.plugins.eslint) || {};
this.warnOnly = (this.config.warnOnly === true);
this.pattern = this.config.pattern || /^app[\/\\].*\.js?$/;
const engineConfig = {};
this.linter = new CLIEngine(engineConfig);
}
lint(data, path) {
const result = this.linter.executeOnText(data, path).results[0];
const errorCount = result.errorCount;
if (errorCount === 0) {
return Promise.resolve();
}
const errorMsg = result.messages.map(error => {
return `${colors.blue(error.message)} (${error.line}:${error.column})`;
});
errorMsg.unshift(`ESLint detected ${errorCount} ${(pluralize('problem', errorCount))}:`);
let msg = errorMsg.join('\n');
if (this.warnOnly) {
msg = `warn: ${msg}`;
}
return (msg ? Promise.reject(msg) : Promise.resolve());
}
}
ESLinter.prototype.brunchPlugin = true;
ESLinter.prototype.type = 'javascript';
ESLinter.prototype.extension = 'js';
module.exports = ESLinter;
|
'use strict';
const colors = require('ansicolors');
const fs = require('fs');
const pluralize = require('pluralize');
const CLIEngine = require('eslint').CLIEngine;
class ESLinter {
constructor(brunchConfig) {
this.config = brunchConfig || {};
const config = brunchConfig.plugins && brunchConfig.plugins.eslint || {};
this.warnOnly = config.warnOnly != null ? config.warnOnly : true;
this.pattern = config.pattern || /^app[\/\\].*\.js?$/;
const engineConfig = {};
this.linter = new CLIEngine(engineConfig);
}
lint(data, path) {
const result = this.linter.executeOnText(data, path).results[0];
const errorCount = result.errorCount;
if (errorCount === 0) {
return Promise.resolve();
}
const errorMsg = result.messages.map(error => {
return `${colors.blue(error.message)} (${error.line}:${error.column})`;
});
errorMsg.unshift(`ESLint detected ${errorCount} ${(pluralize('problem', errorCount))}:`);
let msg = errorMsg.join('\n');
if (this.warnOnly) {
msg = `warn: ${msg}`;
}
return (msg ? Promise.reject(msg) : Promise.resolve());
}
}
ESLinter.prototype.brunchPlugin = true;
ESLinter.prototype.type = 'javascript';
ESLinter.prototype.extension = 'js';
module.exports = ESLinter;
|
Fix polymorphic type handling when loading test data.
|
package poussecafe.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import poussecafe.domain.EntityAttributes;
import poussecafe.exception.PousseCafeException;
public class JsonDataReader {
public JsonDataReader() {
objectMapper = new ObjectMapper();
objectMapper.enableDefaultTypingAsProperty(DefaultTyping.OBJECT_AND_NON_CONCRETE, "@class");
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.registerModule(new JavaTimeModule());
}
public <K, D extends EntityAttributes<K>> void readJson(D dataImplementation,
JsonNode dataJson) {
try {
objectMapper.readerForUpdating(dataImplementation).readValue(dataJson);
} catch (IOException e) {
throw new PousseCafeException("Unable to load data implementation", e);
}
}
private ObjectMapper objectMapper;
}
|
package poussecafe.test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import poussecafe.domain.EntityAttributes;
import poussecafe.exception.PousseCafeException;
public class JsonDataReader {
public JsonDataReader() {
objectMapper = new ObjectMapper();
objectMapper.enableDefaultTypingAsProperty(DefaultTyping.JAVA_LANG_OBJECT, "@class");
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.registerModule(new JavaTimeModule());
}
public <K, D extends EntityAttributes<K>> void readJson(D dataImplementation,
JsonNode dataJson) {
try {
objectMapper.readerForUpdating(dataImplementation).readValue(dataJson);
} catch (IOException e) {
throw new PousseCafeException("Unable to load data implementation", e);
}
}
private ObjectMapper objectMapper;
}
|
Change toString() serializations for debug
|
package ru.agentlab.maia.event;
import java.util.Objects;
import ru.agentlab.maia.IEvent;
public abstract class Event<T> implements IEvent<T> {
protected final T payload;
public Event(T payload) {
this.payload = payload;
}
@Override
public T getPayload() {
return payload;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof IEvent<?>) {
IEvent<?> other = (IEvent<?>) obj;
return (payload == other.getPayload()) && (this.getType() == other.getType());
} else {
return false;
}
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + payload.toString();
}
@Override
public int hashCode() {
return Objects.hash(getType(), payload);
}
}
|
package ru.agentlab.maia.event;
import java.util.Objects;
import ru.agentlab.maia.IEvent;
public abstract class Event<T> implements IEvent<T> {
protected final T payload;
public Event(T payload) {
this.payload = payload;
}
@Override
public T getPayload() {
return payload;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj instanceof IEvent<?>) {
IEvent<?> other = (IEvent<?>) obj;
return (payload == other.getPayload()) && (this.getType() == other.getType());
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(getType(), payload);
}
}
|
Correct version number for sk-video
|
# -*- coding: utf-8 -*-
"""
image analysis group tools
"""
from setuptools import setup
setup(
name='image-analysis',
version='0.0.1',
url='https://github.com/CoDaS-Lab/image-analysis',
license='BSD',
author='CoDaSLab http://shaftolab.com/',
author_email='s@sophiaray.info',
description='A small but fast and easy to use stand-alone template '
'engine written in pure python.',
long_description=__doc__,
zip_safe=False,
classifiers=[
'Programming Language :: Python :: 3.5',
],
packages=['image-analysis'],
install_requires=['scipy >= 0.18.1','scikit-learn>=0.17', 'ffmpeg>=3.2.2',
'sk-video>=1.1.7', 'scikit-image>=0.12.0'],
extras_require=None,
include_package_data=True
)
|
# -*- coding: utf-8 -*-
"""
image analysis group tools
"""
from setuptools import setup
setup(
name='image-analysis',
version='0.0.1',
url='https://github.com/CoDaS-Lab/image-analysis',
license='BSD',
author='CoDaSLab http://shaftolab.com/',
author_email='s@sophiaray.info',
description='A small but fast and easy to use stand-alone template '
'engine written in pure python.',
long_description=__doc__,
zip_safe=False,
classifiers=[
'Programming Language :: Python :: 3.5',
],
packages=['image-analysis'],
install_requires=['scipy >= 0.18.1','scikit-learn>=0.17', 'ffmpeg>=3.2.2',
'sk-video>=1.17', 'scikit-image>=0.12.0'],
extras_require=None,
include_package_data=True
)
|
Add dummy user with known credentials, some of the seed objects will be randomly assigned to it
|
<?php
use Illuminate\Database\Seeder;
use Bdgt\Resources\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker\Factory::create();
User::create([
'id' => null,
'username' => "admin",
'email' => "admin@example.com",
'password' => Hash::make("admin")
]);
for ($i = 0; $i < 29; $i++) {
User::create([
'id' => null,
'username' => $faker->userName(),
'email' => $faker->email(),
'password' => $faker->md5()
]);
}
}
}
|
<?php
use Illuminate\Database\Seeder;
use Bdgt\Resources\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker\Factory::create();
for ($i = 0; $i < 30; $i++) {
User::create([
'id' => null,
'username' => $faker->userName(),
'email' => $faker->email(),
'password' => $faker->md5()
]);
}
}
}
|
Fix static path in production
|
// Static file helpers
import { canUseDOM } from 'react/lib/ExecutionEnvironment';
const PRODUCTION_STATIC_ROOT = 'http://static.tonikarttunen.com/static/';
const DEVELOPMENT_STATIC_ROOT = 'http://127.0.0.1:8888/';
const getStaticRootUrl = () => {
if (canUseDOM) {
const HOST_BASE_URL =
window.location.origin || /* Modern browsers */
window.location.protocol + '//' + window.location.hostname +
(window.location.port ? ':' + window.location.port : ''); /* IE */
return (HOST_BASE_URL.includes('tonikarttunen.com') ?
PRODUCTION_STATIC_ROOT :
DEVELOPMENT_STATIC_ROOT);
} else {
const DEVELOPMENT = process.env.NODE_ENV !== 'production';
return DEVELOPMENT ? DEVELOPMENT_STATIC_ROOT : PRODUCTION_STATIC_ROOT;
}
};
export default {
PRODUCTION_STATIC_ROOT: PRODUCTION_STATIC_ROOT,
DEVELOPMENT_STATIC_ROOT: DEVELOPMENT_STATIC_ROOT,
staticPath: (path) => {
return getStaticRootUrl() + path;
}
};
|
// Static file helpers
import { canUseDOM } from 'react/lib/ExecutionEnvironment';
const os = require('os');
const PRODUCTION_STATIC_ROOT = 'http://static.tonikarttunen.com/static/';
const DEVELOPMENT_STATIC_ROOT = 'http://127.0.0.1:8888/';
const getStaticRootUrl = () => {
if (canUseDOM) {
const HOST_BASE_URL =
window.location.origin || /* Modern browsers */
window.location.protocol + '//' + window.location.hostname +
(window.location.port ? ':' + window.location.port : ''); /* IE */
return (HOST_BASE_URL.includes('tonikarttunen.com') ?
PRODUCTION_STATIC_ROOT :
DEVELOPMENT_STATIC_ROOT);
} else {
return (os.hostname().includes('tonikarttunen.com') ?
PRODUCTION_STATIC_ROOT :
DEVELOPMENT_STATIC_ROOT);
}
};
export default {
PRODUCTION_STATIC_ROOT: PRODUCTION_STATIC_ROOT,
DEVELOPMENT_STATIC_ROOT: DEVELOPMENT_STATIC_ROOT,
staticPath: (path) => {
return getStaticRootUrl() + path;
}
};
|
Revert "Allow only name, url keys for win32."
This reverts commit 9ea03c29ffc1dac7f04f094433c9e47c2ba1c5ad.
|
var spawn = require('child_process').spawn;
var path = require('path');
module.exports = function (options) {
options = options || {};
options.url = options.url || 'http://nodejs.org';
options.name = options.name || 'nodejs';
var client;
switch (process.platform) {
case 'win32':
client = path.resolve(__dirname + '/cefclient/cefclient');
break;
case 'linux':
client = path.resolve(__dirname + '/build/default/topcube');
break;
default:
console.warn('');
return null;
break;
}
var args = [];
for (var key in options) args.push('--' + key + '=' + options[key]);
var child = spawn(client, args);
child.on('exit', function(code) {
process.exit(code);
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
return child;
};
|
var spawn = require('child_process').spawn;
var path = require('path');
module.exports = function (options) {
options = options || {};
options.url = options.url || 'http://nodejs.org';
options.name = options.name || 'nodejs';
var client;
switch (process.platform) {
case 'win32':
client = path.resolve(__dirname + '/cefclient/cefclient');
break;
case 'linux':
client = path.resolve(__dirname + '/build/default/topcube');
break;
default:
console.warn('');
return null;
break;
}
var args = [];
for (var key in options) {
// Omit keys besides name & url for now until options
// parsing bugs are resolved.
if (process.platform === 'win32' &&
(key !== 'name' || key !== 'url')) continue;
args.push('--' + key + '=' + options[key]);
}
var child = spawn(client, args);
child.on('exit', function(code) {
process.exit(code);
});
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
return child;
};
|
Fix no id property for RadioStation
|
import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time.sleep(1)
return
def stop(self):
self.call_handler.stop()
self.__program_handler.stop()
pass
def __init__(self, station, db, logger):
self.logger = logger
self.db = db
self.station = station
self.id = station.id
self.__program_handler = ProgramHandler(self)
self.call_handler = CallHandler(self)
self.__community_handler = CommunityMenu(self)
self.logger.info("Starting up station {0}".format(self.station.name))
return
|
import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time.sleep(1)
return
def stop(self):
self.call_handler.stop()
self.__program_handler.stop()
pass
def __init__(self, station, db, logger):
self.logger = logger
self.db = db
self.station = station
self.__program_handler = ProgramHandler(self)
self.call_handler = CallHandler(self)
self.__community_handler = CommunityMenu(self)
self.logger.info("Starting up station {0}".format(self.station.name))
return
|
Remove this test for now
|
"""geohash unit tests."""
import unittest
import os
import json
import gtfs
class TestGTFSReader(unittest.TestCase):
test_gtfs = os.path.join('examples', 'sample-feed.zip')
def test_readcsv(self):
expect = {
'stop_lat': '36.425288',
'zone_id': '',
'stop_lon': '-117.133162',
'stop_url': '',
'stop_id': 'FUR_CREEK_RES',
'stop_desc': '',
'stop_name': 'Furnace Creek Resort (Demo)'
}
f = gtfs.GTFSReader(self.test_gtfs)
stops = f.readcsv('stops.txt')
found = filter(lambda x:x['stop_id'] == expect['stop_id'], stops)[0]
for k in expect:
assert expect[k] == found[k]
if __name__ == '__main__':
unittest.main()
|
"""geohash unit tests."""
import unittest
import os
import json
import gtfs
class TestGTFSReader(unittest.TestCase):
test_gtfs = os.path.join('examples', 'sample-feed.zip')
def test_readcsv(self):
expect = {
'stop_lat': '36.425288',
'zone_id': '',
'stop_lon': '-117.133162',
'stop_url': '',
'stop_id': 'FUR_CREEK_RES',
'stop_desc': '',
'stop_name': 'Furnace Creek Resort (Demo)'
}
f = gtfs.GTFSReader(self.test_gtfs)
stops = f.readcsv('stops.txt')
found = filter(lambda x:x['stop_id'] == expect['stop_id'], stops)[0]
for k in expect:
assert expect[k] == found[k]
def test_stops_centroid(self):
f = gtfs.GTFSReader(self.test_gtfs)
centroid = f.stops_centroid()
expect = (-116.7720483, 36.8196683)
self.assertAlmostEqual(centroid[0], expect[0])
self.assertAlmostEqual(centroid[1], expect[1])
def test_stops_geohash(self):
f = gtfs.GTFSReader(self.test_gtfs)
g = f.stops_geohash()
assert g == '9qs'
if __name__ == '__main__':
unittest.main()
|
Resolve promises with one argument
|
import url from "url";
import mixin from "merge-descriptors";
import wildcard from "wildcard-named";
export default {
callbacks : {},
when( uri ) {
return new Promise( resolve => {
this.callbacks[ url.resolve( this.base, uri ) ] = resolve;
} );
},
check( uri, req, res ) {
for ( const index in this.callbacks ) {
const requested = wildcard( uri, index );
const callback = this.callbacks[ index ];
if ( uri === index || requested ) {
mixin( req.params, requested || {} );
callback( { req, res, uri } );
}
}
}
};
|
import url from "url";
import mixin from "merge-descriptors";
import wildcard from "wildcard-named";
export default {
callbacks : {},
when( uri ) {
return new Promise( resolve => {
this.callbacks[ url.resolve( this.base, uri ) ] = resolve;
} );
},
check( uri, req, res ) {
for ( const index in this.callbacks ) {
const requested = wildcard( uri, index );
const callback = this.callbacks[ index ];
if ( uri === index || requested ) {
mixin( req.params, requested || {} );
callback( req, res, uri );
}
}
}
};
|
Add protractor test function to click after an element is loaded
|
"use strict";
var UserPages = require("./UserPages.js");
var MailParser = require("mailparser").MailParser;
var fs = require("fs");
var EC = protractor.ExpectedConditions;
var restUrl = "http://localhost:9080/";
var hasClass = function (element, cls) {
return element.getAttribute("class").then(function (classes) {
return classes.split(" ").indexOf(cls) !== -1;
});
};
var parseEmail = function(filename, callback) {
var mailparser = new MailParser();
mailparser.on("end", callback);
mailparser.write(fs.readFileSync(filename));
mailparser.end();
};
var waitAndClick = function(element) {
var isClickable = EC.elementToBeClickable(element);
browser.wait(isClickable, 5000);
element.click();
}
module.exports = {
restUrl: restUrl,
register: UserPages.register,
login: UserPages.login,
logout: UserPages.logout,
isLoggedIn: UserPages.isLoggedIn,
loginParticipant: UserPages.loginParticipant,
participantName: UserPages.participantName,
loginOtherParticipant: UserPages.loginOtherParticipant,
hasClass: hasClass,
parseEmail: parseEmail,
waitAndClick: waitAndClick
}
|
"use strict";
var UserPages = require("./UserPages.js");
var MailParser = require("mailparser").MailParser;
var fs = require("fs");
var restUrl = "http://localhost:9080/";
var hasClass = function (element, cls) {
return element.getAttribute("class").then(function (classes) {
return classes.split(" ").indexOf(cls) !== -1;
});
};
var parseEmail = function(filename, callback) {
var mailparser = new MailParser();
mailparser.on("end", callback);
mailparser.write(fs.readFileSync(filename));
mailparser.end();
};
module.exports = {
restUrl: restUrl,
register: UserPages.register,
login: UserPages.login,
logout: UserPages.logout,
isLoggedIn: UserPages.isLoggedIn,
loginParticipant: UserPages.loginParticipant,
participantName: UserPages.participantName,
loginOtherParticipant: UserPages.loginOtherParticipant,
hasClass: hasClass,
parseEmail: parseEmail
}
|
Add watched-canvases api in mirage
|
export default function sharedConfig() { // eslint-ignore-line no-empty-function
}
export function testConfig() {
this.namespace = '/v1';
this.get('/account', _ => {
return this.create('account');
});
this.get('/teams', schema => {
return schema.teams.all();
});
this.get('/comments', schema => {
return schema.comments.all();
});
this.post('/tokens', schema => {
return schema.create('token');
});
this.get('/watched-canvases', schema => {
return schema.watchedCanvases.all();
});
this.get('/ui-dismissals', schema => {
return schema.uiDismissals.all();
});
this.get('/teams/:domain', (schema, req) => {
return schema.teams.findBy({ domain: req.params.domain });
});
this.get('/teams/:id/user', (schema, req) => {
const team = schema.teams.find(req.params.id);
return team.users.models[0];
});
}
|
export default function sharedConfig() { // eslint-ignore-line no-empty-function
}
export function testConfig() {
this.namespace = '/v1';
this.get('/account', _ => {
return this.create('account');
});
this.get('/teams', schema => {
return schema.teams.all();
});
this.get('/comments', schema => {
return schema.comments.all();
});
this.post('/tokens', schema => {
return schema.create('token');
});
this.get('/ui-dismissals', schema => {
return schema.uiDismissals.all();
});
this.get('/teams/:domain', (schema, req) => {
return schema.teams.findBy({ domain: req.params.domain });
});
this.get('/teams/:id/user', (schema, req) => {
const team = schema.teams.find(req.params.id);
return team.users.models[0];
});
}
|
Use new way of defining phonegap plugins.
|
cordova.define("cordova/plugin/applicationpreferences", function(require, exports, module) {
var exec = require("cordova/exec");
var AppPreferences = function () {};
var AppPreferencesError = function(code, message) {
this.code = code || null;
this.message = message || '';
};
AppPreferencesError.NO_PROPERTY = 0;
AppPreferencesError.NO_PREFERENCE_ACTIVITY = 1;
AppPreferences.prototype.get = function(key,success,fail) {
cordova.exec(success,fail,"applicationPreferences","get",[key]);
};
AppPreferences.prototype.set = function(key,value,success,fail) {
cordova.exec(success,fail,"applicationPreferences","set",[key, value]);
};
AppPreferences.prototype.load = function(success,fail) {
cordova.exec(success,fail,"applicationPreferences","load",[]);
};
AppPreferences.prototype.show = function(activity,success,fail) {
cordova.exec(success,fail,"applicationPreferences","show",[activity]);
};
var appPreferences = new AppPreferences();
module.exports = appPreferences;
});
|
var AppPreferences = function () {};
var AppPreferencesError = function(code, message) {
this.code = code || null;
this.message = message || '';
};
AppPreferencesError.NO_PROPERTY = 0;
AppPreferencesError.NO_PREFERENCE_ACTIVITY = 1;
AppPreferences.prototype.get = function(key,success,fail) {
cordova.exec(success,fail,"applicationPreferences","get",[key]);
};
AppPreferences.prototype.set = function(key,value,success,fail) {
cordova.exec(success,fail,"applicationPreferences","set",[key, value]);
};
AppPreferences.prototype.load = function(success,fail) {
cordova.exec(success,fail,"applicationPreferences","load",[]);
};
AppPreferences.prototype.show = function(activity,success,fail) {
cordova.exec(success,fail,"applicationPreferences","show",[activity]);
};
if(!window.plugins) {
window.plugins = {};
}
if (!window.plugins.applicationPreferences) {
window.plugins.applicationPreferences = new AppPreferences();
}
|
Change access modifier for builder attributes.
Made fields protected so it can be accessed by subclasses. This is for if a custom subclass of SimpleAdapter is needed.
Signed-off-by: Jhun Mag-atas <81e4780f037db3a872190957a49473577f0839d0@teamcodeflux.com>
|
/*
* Copyright 2011 CodeFlux, Inc <info@teamcodeflux.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.teamcodeflux.android.adapter;
import android.content.Context;
import android.widget.SimpleAdapter;
import java.util.List;
import java.util.Map;
public abstract class AbstractSimpleAdapterBuilder<T> implements SimpleAdapterBuilder {
protected Context context;
protected List<T> data;
public AbstractSimpleAdapterBuilder(final Context context, final List<T> data) {
this.context = context;
this.data = data;
}
@Override
public SimpleAdapter build() {
return new SimpleAdapter(context, data(data), resource(), from(), to());
}
protected abstract List<? extends Map<String, ?>> data(List<T> data);
protected abstract int resource();
protected abstract String[] from();
protected abstract int[] to();
}
|
/*
* Copyright 2011 CodeFlux, Inc <info@teamcodeflux.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.teamcodeflux.android.adapter;
import android.content.Context;
import android.widget.SimpleAdapter;
import java.util.List;
import java.util.Map;
public abstract class AbstractSimpleAdapterBuilder<T> implements SimpleAdapterBuilder {
private Context context;
private List<T> data;
public AbstractSimpleAdapterBuilder(final Context context, final List<T> data) {
this.context = context;
this.data = data;
}
@Override
public SimpleAdapter build() {
return new SimpleAdapter(context, data(data), resource(), from(), to());
}
protected abstract List<? extends Map<String, ?>> data(List<T> data);
protected abstract int resource();
protected abstract String[] from();
protected abstract int[] to();
}
|
Move RedisSessionFactory into its own module
|
#!/usr/bin/env python
from twisted.web.server import Site
from webtest.session_factory import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
logger = log.get_logger()
class RedisSite(Site):
sessionFactory = RedisSessionFactory
requestFactory = RedisRequest
def makeSession(self):
"""
Generate a new Session instance
"""
uid = self._mkuid()
return self.sessionFactory.retrieve(uid, reactor=self._reactor)
def getSession(self, uid):
"""
Get a previously generated session, by its unique ID.
This raises a KeyError if the session is not found.
"""
return self.sessionFactory.retrieve(uid, reactor=self._reactor)
|
#!/usr/bin/env python
from twisted.web.server import Site
from webtest.session import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
logger = log.get_logger()
class RedisSite(Site):
sessionFactory = RedisSessionFactory
requestFactory = RedisRequest
def makeSession(self):
"""
Generate a new Session instance
"""
uid = self._mkuid()
return self.sessionFactory.retrieve(uid, reactor=self._reactor)
def getSession(self, uid):
"""
Get a previously generated session, by its unique ID.
This raises a KeyError if the session is not found.
"""
return self.sessionFactory.retrieve(uid, reactor=self._reactor)
|
Check http origin for Websocket
|
package websocket
import (
"net/http"
"github.com/gorilla/websocket"
"github.com/spring1843/chat-server/src/chat"
"github.com/spring1843/chat-server/src/shared/logs"
)
var (
chatServerInstance *chat.Server
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: checkOrigin,
}
)
// TODO validate CORS headers here
func checkOrigin(r *http.Request) bool {
return true
}
// Handler is a http handler function that implements WebSocket
func Handler(w http.ResponseWriter, r *http.Request) {
logs.Infof("Call to websocket /wp form %s", r.RemoteAddr)
chatConnection := NewChatConnection()
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logs.ErrIfErrf(err, "Error upgrading websocket connection.")
return
}
chatConnection.Connection = conn
go chatServerInstance.ReceiveConnection(chatConnection)
go chatConnection.writePump()
chatConnection.readPump()
logs.Infof("End of call to websocket /wp form %s", r.RemoteAddr)
}
// SetWebSocket sets the chat server instance
func SetWebSocket(chatServerParam *chat.Server) {
chatServerInstance = chatServerParam
}
|
package websocket
import (
"net/http"
"github.com/gorilla/websocket"
"github.com/spring1843/chat-server/src/chat"
"github.com/spring1843/chat-server/src/shared/logs"
)
var (
chatServerInstance *chat.Server
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
// Handler is a http handler function that implements WebSocket
func Handler(w http.ResponseWriter, r *http.Request) {
logs.Infof("Call to websocket /wp form %s", r.RemoteAddr)
chatConnection := NewChatConnection()
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logs.ErrIfErrf(err, "Error upgrading websocket connection.")
return
}
chatConnection.Connection = conn
go chatServerInstance.ReceiveConnection(chatConnection)
go chatConnection.writePump()
chatConnection.readPump()
logs.Infof("End of call to websocket /wp form %s", r.RemoteAddr)
}
// SetWebSocket sets the chat server instance
func SetWebSocket(chatServerParam *chat.Server) {
chatServerInstance = chatServerParam
}
|
Change clean by isClean in check_clamav task
|
from __future__ import absolute_import
from celery import shared_task
from documents.models import Document
import clamd
@shared_task
def compile_tex(document_id):
document = Document.objects.get(pk=document_id)
print(document)
@shared_task
def check_clamav(document_id):
document = Document.objects.get(pk=document_id)
clam = clamd.ClamdUnixSocket(settings.CLAMAV_SOCKET)
status, sig = clam.scan(absolute_path_to_pdf)[absolute_path_to_pdf]
if status == 'OK':
document.isClean = True
elif status == 'FOUND':
document.isClean = False
print("Signature found", sig)
else:
# unknown state
document.isClean = False
print("Unknown return of clamav", status, sig)
document.save()
|
from __future__ import absolute_import
from celery import shared_task
from documents.models import Document
import clamd
@shared_task
def compile_tex(document_id):
document = Document.objects.get(pk=document_id)
print(document)
@shared_task
def check_clamav(document_id):
document = Document.objects.get(pk=document_id)
clam = clamd.ClamdUnixSocket(settings.CLAMAV_SOCKET)
status, sig = clam.scan(absolute_path_to_pdf)[absolute_path_to_pdf]
if status == 'OK':
document.clean = True
elif status == 'FOUND':
document.clean = False
print("Signature found", sig)
else:
# unknown state
document.clean = False
print("Unknown return of clamav", status, sig)
document.save()
|
Add some topics for next deploy
|
import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='sumproduct',
version='0.0.1',
description='The sum-product algorithm. Belief propagation (message passing) for factor graphs',
long_description=(read('README.rst')),
url='http://github.com/ilyakava/sumproduct/',
license='MIT',
author='Ilya Kavalerov',
author_email='ilyakavalerov@gmail.com',
packages=find_packages(exclude=['tests*']),
py_modules=['sumproduct'],
include_package_data=True,
classifiers=[
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
import os
from setuptools import setup, find_packages
def read(*paths):
"""Build a file path from *paths* and return the contents."""
with open(os.path.join(*paths), 'r') as f:
return f.read()
setup(
name='sumproduct',
version='0.0.1',
description='The sum-product algorithm. Belief propagation (message passing) for factor graphs',
long_description=(read('README.rst')),
url='http://github.com/ilyakava/sumproduct/',
license='MIT',
author='Ilya Kavalerov',
author_email='ilyakavalerov@gmail.com',
packages=find_packages(exclude=['tests*']),
py_modules=['sumproduct'],
include_package_data=True,
classifiers=[
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Remove giphy since it doesn't work
|
'use strict';
var mongoose = require('mongoose');
var slack = require('./slack.js');
var Rejection = mongoose.model('Rejection');
exports.help = help;
exports.reject = reject;
function help(args, message) {
var channel = slack.getChannelGroupOrDMByID(message.channel);
channel.send('I\'m codybot! \n\n\
Usage: `@codybot: <command>`\n\n\
Commands: \n\
reject <comanyName> - Records that you were rejected from that company. \n\
help - Prints this prompt \
');
}
function reject(args, message) {
var channel = slack.getChannelGroupOrDMByID(message.channel);
var companyName = args[0];
var rejection = new Rejection({
companyName: companyName,
user: message.user,
timestamp: { type: Date, default: Date.now }
});
Rejection.find({
companyName: companyName,
user: message.user
}).exec(function (err, rejections) {
if(rejections.length > 0) {
channel.send('This information is already in my database. Thanks for reminding me though.');
} else {
rejection.save(function (err, rejection) {
if (err) {
return console.error(err);
}
channel.send('Sounds like you\'re too awesome for ' + rejection.companyName + ' anyways!');
});
}
});
}
|
'use strict';
var mongoose = require('mongoose');
var slack = require('./slack.js');
var Rejection = mongoose.model('Rejection');
exports.help = help;
exports.reject = reject;
function help(args, message) {
var channel = slack.getChannelGroupOrDMByID(message.channel);
channel.send('I\'m codybot! \n\n\
Usage: `@codybot: <command>`\n\n\
Commands: \n\
reject <comanyName> - Records that you were rejected from that company. \n\
help - Prints this prompt \
');
}
function reject(args, message) {
var channel = slack.getChannelGroupOrDMByID(message.channel);
var companyName = args[0];
var rejection = new Rejection({
companyName: companyName,
user: message.user,
timestamp: { type: Date, default: Date.now }
});
Rejection.find({
companyName: companyName,
user: message.user
}).exec(function (err, rejections) {
if(rejections.length > 0) {
channel.send('This information is already in my database. Thanks for reminding me though.');
} else {
rejection.save(function (err, rejection) {
if (err) {
return console.error(err);
}
channel.send('Sounds like you\'re too awesome for ' + rejection.companyName + ' anyways!');
channel.send('/giphy celebrate');
});
}
});
}
|
Change this test to not expect an error.
|
import unittest
from flask import Flask
from flask_selfdoc import Autodoc
class TestErrorHandling(unittest.TestCase):
def test_app_not_initialized(self):
app = Flask(__name__)
autodoc = Autodoc()
with app.app_context():
self.assertRaises(RuntimeError, lambda: autodoc.html())
def test_app_not_initialized_json(self):
"""
If we don't get an exception, no reason
to enforce that we get any specific exception.
"""
app = Flask(__name__)
autodoc = Autodoc()
with app.app_context():
autodoc.json()
def test_app_initialized_by_ctor(self):
app = Flask(__name__)
autodoc = Autodoc(app)
with app.app_context():
autodoc.html()
def test_app_initialized_by_init_app(self):
app = Flask(__name__)
autodoc = Autodoc()
autodoc.init_app(app)
with app.app_context():
autodoc.html()
|
import unittest
from flask import Flask
from flask_selfdoc import Autodoc
class TestErrorHandling(unittest.TestCase):
def test_app_not_initialized(self):
app = Flask(__name__)
autodoc = Autodoc()
with app.app_context():
self.assertRaises(RuntimeError, lambda: autodoc.html())
def test_app_not_initialized_json(self):
app = Flask(__name__)
autodoc = Autodoc()
with app.app_context():
self.assertRaises(RuntimeError, lambda: autodoc.json())
def test_app_initialized_by_ctor(self):
app = Flask(__name__)
autodoc = Autodoc(app)
with app.app_context():
autodoc.html()
def test_app_initialized_by_init_app(self):
app = Flask(__name__)
autodoc = Autodoc()
autodoc.init_app(app)
with app.app_context():
autodoc.html()
|
Make sure to match pre and textarea without any attributes
|
<?php // @codeCoverageIgnoreStart
/*
* This file is part of HtmlCompress.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\HtmlCompress;
/**
* Class Patterns
*
* @package WyriHaximus\HtmlCompress
*/
class Patterns
{
const MATCH_PRE = '!(<pre>|<pre[^>]*>?)(.*?)(</pre>)!is';
const MATCH_TEXTAREA = '!(<textarea>|<textarea[^>]*>?)(.*?)(</textarea>)!is';
const MATCH_STYLE = '!(<style>|<style[^>]*>?)(.*?)(</style>)!is';
// @codingStandardsIgnoreStart
const MATCH_JSCRIPT = '!(<script>|<script[^>]*type="text/javascript"[^>]*>|<script[^>]*type=\'text/javascript\'[^>]*>)(.*?)(</script>)!is';
// @codingStandardsIgnoreEnd
const MATCH_SCRIPT = '!(<script[^>]*>?)(.*?)(</script>)!is';
const MATCH_NOCOMPRESS = '!(<nocompress>)(.*?)(</nocompress>)!is';
}
|
<?php // @codeCoverageIgnoreStart
/*
* This file is part of HtmlCompress.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace WyriHaximus\HtmlCompress;
/**
* Class Patterns
*
* @package WyriHaximus\HtmlCompress
*/
class Patterns
{
const MATCH_PRE = '!(<pre[^>]*>?)(.*?)(</pre>)!is';
const MATCH_TEXTAREA = '!(<textarea[^>]*>?)(.*?)(</textarea>)!is';
const MATCH_STYLE = '!(<style>|<style[^>]*>?)(.*?)(</style>)!is';
// @codingStandardsIgnoreStart
const MATCH_JSCRIPT = '!(<script>|<script[^>]*type="text/javascript"[^>]*>|<script[^>]*type=\'text/javascript\'[^>]*>)(.*?)(</script>)!is';
// @codingStandardsIgnoreEnd
const MATCH_SCRIPT = '!(<script[^>]*>?)(.*?)(</script>)!is';
const MATCH_NOCOMPRESS = '!(<nocompress>)(.*?)(</nocompress>)!is';
}
|
Add glob for test-specific configuration files
|
<?php
use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfiguration;
use CdliTwoStageSignupTest\Framework\TestCase;
chdir(__DIR__);
$previousDir = '.';
while (!file_exists('config/application.config.php')) {
$dir = dirname(getcwd());
if($previousDir === $dir) {
throw new RuntimeException(
'Unable to locate "config/application.config.php":'
. ' is CdliTwoStageSignup in a subdir of your application skeleton?'
);
}
$previousDir = $dir;
chdir($dir);
}
if (!include('vendor/autoload.php')) {
throw new RuntimeException(
'vendor/autoload.php could not be found. '
. 'Did you run php composer.phar install in your application skeleton?'
);
}
// Get application stack configuration
$configuration = include 'config/application.config.php';
$configuration['module_listener_options']['config_glob_paths'][] = __DIR__ . '/config/{,*.}{global,local}.php';
// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$config = $serviceManager->get('Configuration');
TestCase::setServiceLocator($serviceManager);
|
<?php
use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfiguration;
use CdliTwoStageSignupTest\Framework\TestCase;
chdir(__DIR__);
$previousDir = '.';
while (!file_exists('config/application.config.php')) {
$dir = dirname(getcwd());
if($previousDir === $dir) {
throw new RuntimeException(
'Unable to locate "config/application.config.php":'
. ' is CdliTwoStageSignup in a subdir of your application skeleton?'
);
}
$previousDir = $dir;
chdir($dir);
}
if (!include('vendor/autoload.php')) {
throw new RuntimeException(
'vendor/autoload.php could not be found. '
. 'Did you run php composer.phar install in your application skeleton?'
);
}
// Get application stack configuration
$configuration = include 'config/application.config.php';
// Setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfiguration($configuration['service_manager']));
$serviceManager->setService('ApplicationConfiguration', $configuration);
$config = $serviceManager->get('Configuration');
TestCase::setServiceLocator($serviceManager);
|
Use put instead of add
Updated setKeyValue to use put instead of add (was crashing), with some other minor updates.
|
package com.ccsoft.plugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
import com.parse.ParseInstallation;
public class CordovaParse extends CordovaPlugin {
private final String TAG = "CordovaParse";
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
Log.i(TAG, "action:" + action);
if (action.equals("getInstallationId")) {
String id = ParseInstallation.getCurrentInstallation().getInstallationId();
Log.i(TAG, "Installation Id: " + id);
callbackContext.success(id);
return true;
}
if (action.equals("setKeyValue")) {
if(args.length() >= 2) {
ParseInstallation inst = ParseInstallation.getCurrentInstallation();
String key = args.getString(0);
String value = args.getString(1);
inst.put(key, value);
inst.saveEventually();
Log.i(TAG, "Saved key: " + key + " and value: " + value);
callbackContext.success("");
} else {
callbackContext.error("invalid number of params passed");
}
return true;
}
return false;
}
}
|
package com.ccsoft.plugin;
import java.util.Dictionary;
import java.util.Hashtable;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
import com.parse.ParseInstallation;
public class CordovaParse extends CordovaPlugin {
private final String TAG = "CordovaParse";
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
Log.i(TAG, "action:" + action);
if (action.equals("getInstallationId")) {
String id = ParseInstallation.getCurrentInstallation().getInstallationId();
Log.d("Parse.com Plugin", "Installation Id: " + id);
callbackContext.success(id);
return true;
}
if (action.equals("setKeyValue")) {
if(args.length() >= 2) {
ParseInstallation inst = ParseInstallation.getCurrentInstallation();
String key = args.getString(0);
String value = args.getString(1);
inst.add(key, value);
inst.saveEventually();
Log.d("Parse.com Plugin", "Saved key: " + key + " and value: " + value);
callbackContext.success("");
return true;
}
}
return false;
}
}
|
Check for the existence of document before accessing it.
Since document is referenced within getDefaultProps which unlike
componentDidMount is run in both browser and node environments we need
to make sure we check it exists before accessing it.
|
import React from './react-es6';
export default = {
propTypes: {
container: React.PropTypes.object.isRequired
},
getDefaultProps: function () {
return {
container: typeof document !== 'undefined' ? document.body : null
};
},
componentWillUnmount: function () {
this._unrenderOverlay();
this.getContainerDOMNode()
.removeChild(this._overlayTarget);
this._overlayTarget = null;
},
componentDidUpdate: function () {
this._renderOverlay();
},
componentDidMount: function () {
this._renderOverlay();
},
_mountOverlayTarget: function () {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode()
.appendChild(this._overlayTarget);
},
_renderOverlay: function () {
if (!this._overlayTarget) {
this._mountOverlayTarget();
}
// Save reference to help testing
this._overlayInstance = React.renderComponent(this.renderOverlay(), this._overlayTarget);
},
_unrenderOverlay: function () {
React.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
},
getOverlayDOMNode: function() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
return this._overlayInstance.getDOMNode();
},
getContainerDOMNode: function() {
return React.isValidComponent(this.props.container) ?
this.props.container.getDOMNode() : this.props.container;
}
};
|
import React from './react-es6';
export default = {
propTypes: {
container: React.PropTypes.object.isRequired
},
getDefaultProps: function () {
return {
container: document.body
};
},
componentWillUnmount: function () {
this._unrenderOverlay();
this.getContainerDOMNode()
.removeChild(this._overlayTarget);
this._overlayTarget = null;
},
componentDidUpdate: function () {
this._renderOverlay();
},
componentDidMount: function () {
this._renderOverlay();
},
_mountOverlayTarget: function () {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode()
.appendChild(this._overlayTarget);
},
_renderOverlay: function () {
if (!this._overlayTarget) {
this._mountOverlayTarget();
}
// Save reference to help testing
this._overlayInstance = React.renderComponent(this.renderOverlay(), this._overlayTarget);
},
_unrenderOverlay: function () {
React.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
},
getOverlayDOMNode: function() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
return this._overlayInstance.getDOMNode();
},
getContainerDOMNode: function() {
return React.isValidComponent(this.props.container) ?
this.props.container.getDOMNode() : this.props.container;
}
};
|
Remove jsondata variable to simplify the code
|
# coding=utf-8
import urllib2
import json
import re
# album_url = 'http://www.ximalaya.com/7712455/album/6333174'
album_url = 'http://www.ximalaya.com/7712455/album/4474664'
headers = {'User-Agent': 'Safari/537.36'}
resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers))
ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',')
for ind, f in enumerate(ids):
url = 'http://www.ximalaya.com/tracks/{}.json'.format(f)
resp = urllib2.urlopen(urllib2.Request(url, headers=headers))
data = json.loads(resp.read())
output = data['title'] + data['play_path_64'][-4:]
print output, data['play_path_64']
with open(output, 'wb') as local:
local.write(urllib2.urlopen(data['play_path_64']).read())
|
# coding=utf-8
import urllib2
import json
import re
# album_url = 'http://www.ximalaya.com/7712455/album/6333174'
album_url = 'http://www.ximalaya.com/7712455/album/4474664'
headers = {'User-Agent': 'Safari/537.36'}
resp = urllib2.urlopen(urllib2.Request(album_url, headers=headers))
ids = re.search('sound_ids=\"(.*)\"', resp.read()).group(1).split(',')
for ind, f in enumerate(ids):
url = 'http://www.ximalaya.com/tracks/{}.json'.format(f)
resp = urllib2.urlopen(urllib2.Request(url, headers=headers))
jsondata = resp.read()
data = json.loads(jsondata)
output = data['title'] + data['play_path_64'][-4:]
print output, data['play_path_64']
with open(output, 'wb') as local:
local.write(urllib2.urlopen(data['play_path_64']).read())
|
Change from rpc to amqp backend
Otherwise retrieving result are problematic
|
from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
CELERY_RESULT_BACKEND='amqp://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
imputation_exchange = Exchange('imputation', type='direct')
ancestry_exchange = Exchange('ancestry',type='direct')
riskprediction_exchange = Exchange('riskprediction',type='direct')
CELERY_QUEUES = (
Queue('imputation', imputation_exchange, routing_key='imputation'),
Queue('ancestry', ancestry_exchange, routing_key='ancestry'),
Queue('riskprediction',riskprediction_exchange,routing_key='riskprediction')
)
CELERY_ROUTES = {
'thehonestgenepipeline.imputation.test':{'queue':'imputation'},
'thehonestgenepipeline.imputation.imputation':{'queue':'imputation'},
'thehonestgenepipeline.imputation.convert':{'queue':'imputation'},
'thehonestgenepipeline.imputation.impute':{'queue':'imputation'},
'thehonestgenepipeline.ancestry.analysis':{'queue':'ancestry'},
'thehonestgenepipeline.riskprediction.run':{'queue':'riskprediction'}
}
|
from kombu import Exchange, Queue
import os
BROKER_URL = os.environ['CELERY_BROKER']
CELERY_RESULT_BACKEND='rpc://'
CELERY_RESULT_PERSISTENT = True
CELERY_DISABLE_RATE_LIMITS = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
imputation_exchange = Exchange('imputation', type='direct')
ancestry_exchange = Exchange('ancestry',type='direct')
riskprediction_exchange = Exchange('riskprediction',type='direct')
CELERY_QUEUES = (
Queue('imputation', imputation_exchange, routing_key='imputation'),
Queue('ancestry', ancestry_exchange, routing_key='ancestry'),
Queue('riskprediction',riskprediction_exchange,routing_key='riskprediction')
)
CELERY_ROUTES = {
'thehonestgenepipeline.imputation.test':{'queue':'imputation'},
'thehonestgenepipeline.imputation.imputation':{'queue':'imputation'},
'thehonestgenepipeline.imputation.convert':{'queue':'imputation'},
'thehonestgenepipeline.imputation.impute':{'queue':'imputation'},
'thehonestgenepipeline.ancestry.analysis':{'queue':'ancestry'},
'thehonestgenepipeline.riskprediction.run':{'queue':'riskprediction'}
}
|
Set tocify scrollTo property to offset top banner
|
/**
* User: powerumc
* Date: 2014. 5. 18.
*/
$(function() {
$(function () {
$.ajax({
url: "README.md",
type: "GET",
success: function (data) {
var html = marked(data);
$("#preview").html(html);
var toc = $("#toc").tocify({
context: "#preview",
selectors: "h1, h2, h3, h4, h5, h6",
showEffect: "slideDown",
hideEffect: "slideUp",
scrollTo: 55,
theme: "jqueryui",
hashGenerator: "pretty",
highlightOffset: 40});
$("code").addClass("prettyprint");
prettyPrint();
$(document).ready(function () {
$('[data-toggle=offcanvas]').click(function () {
$('.row-offcanvas').toggleClass('active');
});
});
$("#title").text($("#preview h1:first").text());
}
});
});
});
|
/**
* User: powerumc
* Date: 2014. 5. 18.
* Time: ������ 8:39
*/
$(function() {
$(function () {
$.ajax({
url: "README.md",
type: "GET",
success: function (data) {
var html = marked(data);
$("#preview").html(html);
var toc = $("#toc").tocify({
context: "#preview",
selectors: "h1, h2, h3, h4, h5, h6",
showEffect: "slideDown",
hideEffect: "slideUp",
theme: "jqueryui",
hashGenerator: "pretty",
highlightOffset: 40});
$("code").addClass("prettyprint");
prettyPrint();
$(document).ready(function () {
$('[data-toggle=offcanvas]').click(function () {
$('.row-offcanvas').toggleClass('active');
});
});
$("#title").text($("#preview h1:first").text());
}
});
});
});
|
Return error message and print stack trace via try/catch
|
import generateFramework from '../generators/framework/generateFramework';
import generateTemplateEngine from '../generators/template-engine/generateTemplateEngine';
import generateCssFramework from '../generators/css-framework/generateCssFramework';
import generateCssPreprocessor from '../generators/css-preprocessor/generateCssPreprocessor';
import generateCssBuildOptions from '../generators/css-build-options/generateCssBuildOptions';
import generateDatabase from '../generators/database/generateDatabase';
import generateAuthentication from '../generators/authentication/generateAuthentication';
import generateJsFramework from '../generators/js-framework/generateJsFramework';
import { walkAndRemoveComments, prepare, cleanup } from '../generators/utils';
async function download(req, res) {
let params = await prepare(req.body);
try {
await generateFramework(params);
await generateTemplateEngine(params);
await generateCssFramework(params);
await generateCssPreprocessor(params);
await generateCssBuildOptions(params);
await generateDatabase(params);
await generateAuthentication(params);
await generateJsFramework(params);
await walkAndRemoveComments(params);
res.end();
} catch (err) {
console.info(err.stack);
console.info(params);
res.status(500).send(err.message);
}
}
export default download;
|
import generateFramework from '../generators/framework/generateFramework';
import generateTemplateEngine from '../generators/template-engine/generateTemplateEngine';
import generateCssFramework from '../generators/css-framework/generateCssFramework';
import generateCssPreprocessor from '../generators/css-preprocessor/generateCssPreprocessor';
import generateCssBuildOptions from '../generators/css-build-options/generateCssBuildOptions';
import generateDatabase from '../generators/database/generateDatabase';
import generateAuthentication from '../generators/authentication/generateAuthentication';
import generateJsFramework from '../generators/js-framework/generateJsFramework';
import { walkAndRemoveComments, prepare, cleanup } from '../generators/utils';
async function download(req, res) {
let params = await prepare(req.body);
try {
await generateFramework(params);
await generateTemplateEngine(params);
await generateCssFramework(params);
await generateCssPreprocessor(params);
await generateCssBuildOptions(params);
await generateDatabase(params);
await generateAuthentication(params);
await generateJsFramework(params);
await walkAndRemoveComments(params);
} catch (e) {
throw Error(e);
}
res.end();
}
export default download;
|
Handle the weird field names from the new version of the API
As part of the switch to cordova, we moved to a newer version of the google
play API. Unfortunately, this meant that the weird field names for the
confidence and type changed to a different set of weird field names. We should
really use a standard wrapper class for this on android as well to avoid such
silent breakages in the future.
https://github.com/e-mission/e-mission-data-collection/issues/80
|
import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
else:
data.confidence = entry.data.zzaEh
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
data.type = ecwa.MotionTypes(entry.data.agb).value
data.confidence = entry.data.agc
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
Add link to vpc in console
|
class Resource {
constructor(region, id, tagMap) {
this._region = region;
this._id = id;
this._tagMap = tagMap || new Map();
}
get region() { return this._region; }
get id() { return this._id; }
get tagMap() { return this._tagMap; }
get title() { return null; }
get link() { return null; }
}
class Ec2Instance extends Resource {
get title() {
const name = this.tagMap.get('Name');
return `:ec2: Instance ${this.id}` + (name ? ` (${name})` : '');
}
get link() {
return `https://console.aws.amazon.com/ec2/v2/home?region=${this.region}#Instances:instanceId=${this.id}`;
}
}
class RdsDbCluster extends Resource {
get title() {
return `:rds: RDS ${this.id}`;
}
}
class Vpc extends Resource {
get title() {
const name = this.tagMap.get('Name');
return `:vpc: VPC ${this.id}` + (name ? ` (${name})` : '');
}
get link() {
return `https://console.aws.amazon.com/vpc/home?region=${this.region}#vpcs:filter=${this.id}`;
}
}
export default Resource;
export {
Ec2Instance,
RdsDbCluster,
Vpc,
};
|
class Resource {
constructor(region, id, tagMap) {
this._region = region;
this._id = id;
this._tagMap = tagMap || new Map();
}
get region() { return this._region; }
get id() { return this._id; }
get tagMap() { return this._tagMap; }
get title() { return null; }
get link() { return null; }
}
class Ec2Instance extends Resource {
get title() {
const name = this.tagMap.get('Name');
return `:ec2: Instance ${this.id}` + (name ? ` (${name})` : '');
}
get link() {
return `https://console.aws.amazon.com/ec2/v2/home?region=${this.region}#Instances:instanceId=${this.id}`;
}
}
class RdsDbCluster extends Resource {
get title() {
return `:rds: RDS ${this.id}`;
}
}
class Vpc extends Resource {
get title() {
const name = this.tagMap.get('Name');
return `:vpc: VPC ${this.id}` + (name ? ` (${name})` : '');
}
}
export default Resource;
export {
Ec2Instance,
RdsDbCluster,
Vpc,
};
|
Allow for path to renderer to be provided instead of just the classname. Removed headers set before rendering, instead they should be handled in the renderer
|
<?php
define('DOCROOT', rtrim(dirname(__FILE__), '\\/'));
define('DOMAIN', rtrim(rtrim($_SERVER['HTTP_HOST'], '\\/') . dirname($_SERVER['PHP_SELF']), '\\/'));
require(DOCROOT . '/symphony/bundle.php');
function renderer($handle){
if(file_exists(realpath($handle))){
$path = realpath($handle);
}
elseif(file_exists(LIB . "/class.{$handle}.php")){
$path = LIB . "/class.{$handle}.php";
}
else{
throw new Exception('Invalid Symphony renderer handle specified.');
}
$classname = require_once($path);
return call_user_func("{$classname}::instance");
}
$handle = (isset($_GET['symphony-renderer'])
? $_GET['symphony-renderer']
: 'frontend');
$output = renderer($handle)->display(getCurrentPage());
header(sprintf('Content-Length: %d', strlen($output)));
echo $output;
exit();
|
<?php
define('DOCROOT', rtrim(dirname(__FILE__), '\\/'));
define('DOMAIN', rtrim(rtrim($_SERVER['HTTP_HOST'], '\\/') . dirname($_SERVER['PHP_SELF']), '\\/'));
require(DOCROOT . '/symphony/bundle.php');
function renderer($handle){
if(!file_exists(LIB . "/class.{$handle}.php")){
throw new Exception('Invalid Symphony renderer handle specified.');
}
$classname = require_once(LIB . "/class.{$handle}.php");
return call_user_func("{$classname}::instance");
}
$handle = (isset($_GET['symphony-renderer'])
? $_GET['symphony-renderer']
: 'frontend');
header('Expires: Mon, 12 Dec 1982 06:14:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$output = renderer($handle)->display(getCurrentPage());
header(sprintf('Content-Length: %d', strlen($output)));
echo $output;
exit();
|
Fix hostname answer issue in catalog
https://github.com/rancher/rancher/issues/17058
|
import Component from '@ember/component';
import { get, set, observer } from '@ember/object'
import layout from './template';
import { inject as service } from '@ember/service';
import C from 'shared/utils/constants';
export default Component.extend({
settings: service(),
layout,
value: '',
mode: 'automatic',
init() {
this._super(...arguments);
const xip = get(this, `settings.${ C.SETTING.INGRESS_IP_DOMAIN }`);
const host = get(this, 'value');
if ( host && host === xip ) {
set(this, 'mode', 'automatic');
} else {
set(this, 'mode', 'manual');
}
},
modeChanged: observer('mode', function() {
const mode = get(this, 'mode');
const xip = get(this, `settings.${ C.SETTING.INGRESS_IP_DOMAIN }`);
if ( mode === 'automatic' ) {
set(this, 'value', xip);
} else {
if ( get(this, 'value') === xip ) {
set(this, 'value', '');
}
}
}),
});
|
import Component from '@ember/component';
import { next } from '@ember/runloop';
import { get, set, observer } from '@ember/object'
import layout from './template';
import { inject as service } from '@ember/service';
import C from 'shared/utils/constants';
export default Component.extend({
settings: service(),
layout,
value: '',
mode: 'automatic',
init() {
this._super(...arguments);
const xip = get(this, `settings.${ C.SETTING.INGRESS_IP_DOMAIN }`);
const host = get(this, 'value');
if ( host && host === xip ) {
set(this, 'mode', 'automatic');
} else if ( host ) {
set(this, 'mode', 'manual');
}
next(() => {
this.modeChanged();
});
},
modeChanged: observer('mode', function() {
const mode = get(this, 'mode');
const xip = get(this, `settings.${ C.SETTING.INGRESS_IP_DOMAIN }`);
if ( mode === 'automatic' ) {
set(this, 'value', xip);
} else {
if ( get(this, 'value') === xip ) {
set(this, 'value', '');
}
}
}),
});
|
Revert "Revert "🐛 Fix issues with mobx and class properties""
This reverts commit 3f24504d9d5e61efff40ea18c3b6d9e06dffee8a.
|
module.exports = function (context, opts = {}) {
const env = process.env.BABEL_ENV || process.env.NODE_ENV
const isDevelopment = env === 'development'
return {
presets: [
// Browsers are taken from the browserslist field in package.json
[require('@babel/preset-env').default, {
modules: false,
useBuiltIns: 'usage',
}],
[require('@babel/preset-react').default, {
// Adds component stack to warning messages
// Adds __self attribute to JSX which React will use for some warnings
development: isDevelopment,
}],
[require('@babel/preset-stage-0').default, {
// Enable loose mode to use assignment instead of defineProperty
// in the @babel/plugin-proposal-class-properties
// See discussion in https://github.com/facebook/create-react-app/issues/4263
loose: true,
}],
],
plugins: [
require('babel-plugin-lodash'),
require('babel-plugin-macros'),
],
}
}
|
module.exports = function (context, opts = {}) {
const env = process.env.BABEL_ENV || process.env.NODE_ENV
const isDevelopment = env === 'development'
return {
presets: [
// Browsers are taken from the browserslist field in package.json
[require('@babel/preset-env').default, {
modules: false,
useBuiltIns: 'usage',
}],
[require('@babel/preset-react').default, {
// Adds component stack to warning messages
// Adds __self attribute to JSX which React will use for some warnings
development: isDevelopment,
}],
require('@babel/preset-stage-0').default,
],
plugins: [
require('babel-plugin-lodash'),
require('babel-plugin-macros'),
],
}
}
|
Clear local Storage on cancel
|
function something()
{
var x = window.localStorage.getItem('bbb');
x = x * 1 + 1;
window.localStorage.setItem('bbb', x);
alert(x);
}
function add_to_cart(id)
{
var key = 'product_' + id;
var x = window.localStorage.getItem(key);
x = x * 1 + 1;
window.localStorage.setItem(key, x);
update_orders_input();
update_orders_button();
}
function update_orders_input()
{
var orders = cart_get_orders();
$('#orders_input').val(orders);
}
function update_orders_button()
{
var text = 'Cart ('+ list_all_Items() +')';
$('#orders_button').val(text);
}
function list_all_Items()
{
total = 0;
$.each(localStorage, function(key, value){
total += value * 1;
});
return total;
}
function cart_get_orders()
{
var orders = '';
for(var i = 0; i < window.localStorage.length; i++)
{
var key = window.localStorage.key(i); // get key
var value = window.localStorage.getItem(key); // get value by key from hash
if(key.indexOf('product_') == 0)
{
orders = orders + key + '=' + value + ',';
}
}
return orders;
}
function cancel_order()
{
window.localStorage.clear();
update_orders_input();
update_orders_button();
return false;
}
|
function something()
{
var x = window.localStorage.getItem('bbb');
x = x * 1 + 1;
window.localStorage.setItem('bbb', x);
alert(x);
}
function add_to_cart(id)
{
var key = 'product_' + id;
var x = window.localStorage.getItem(key);
x = x * 1 + 1;
window.localStorage.setItem(key, x);
update_orders_input();
update_orders_button();
}
function update_orders_input()
{
var orders = cart_get_orders();
$('#orders_input').val(orders);
}
function update_orders_button()
{
var text = 'Cart ('+ list_all_Items() +')';
$('#orders_button').val(text);
}
function list_all_Items()
{
total = 0;
$.each(localStorage, function(key, value){
total += value * 1;
});
return total;
}
function cart_get_orders()
{
var orders = '';
for(var i = 0; i < window.localStorage.length; i++)
{
var key = window.localStorage.key(i); // get key
var value = window.localStorage.getItem(key); // get value by key from hash
if(key.indexOf('product_') == 0)
{
orders = orders + key + '=' + value + ',';
}
}
return orders;
}
function cancel_order()
{
alert('aaa');
return false;
}
|
[bug] Fix bug on cartridge handler
|
var builder = require('focus').component.builder;
var React = require('react');
var applicationStore = require('focus').application.builtInStore();
var cartridgeMixin = {
getDefaultProps: function getCartridgeDefaultProps(){
return {
style: {}
};
},
/** @inheriteddoc */
getInitialState: function getCartridgeInitialState() {
return this._getStateFromStore();
},
/** @inheriteddoc */
componentWillMount: function cartridgeWillMount() {
applicationStore.addCartridgeComponentChangeListener(this._handleComponentChange);
},
/** @inheriteddoc */
componentWillUnMount: function cartridgeWillUnMount(){
applicationStore.removeCartridgeComponentChangeListener(this._handleComponentChange);
},
_getStateFromStore: function getCartridgeStateFromStore(){
return {cartridgeComponent: applicationStore.getCartridgeComponent() || {component: 'div', props: {}}};
},
_handleComponentChange: function _handleComponentChange(){
this.setState(this._getStateFromStore());
},
/** @inheriteddoc */
render: function renderCartridge() {
var className = `cartridge ${this.props.style.className}`;
return (
<div className={className} data-focus='cartridge'>
<this.state.cartridgeComponent.component {...this.state.cartridgeComponent.props}/>
</div>
);
}
};
module.exports = builder(cartridgeMixin);
|
var builder = require('focus').component.builder;
var React = require('react');
var applicationStore = require('focus').application.builtInStore();
var cartridgeMixin = {
getDefaultProps: function getCartridgeDefaultProps(){
return {
style: {}
};
},
/** @inheriteddoc */
getInitialState: function getCartridgeInitialState() {
return this._getStateFromStore();
},
/** @inheriteddoc */
componentWillMount: function cartridgeWillMount() {
applicationStore.addCartridgeComponentChangeListener(this._handleComponentChange);
},
/** @inheriteddoc */
componentWillUnMount: function cartridgeWillUnMount(){
applicationStore.removeCartridgeComponentChangeListener(this._onComponentChange);
},
_getStateFromStore: function getCartridgeStateFromStore(){
return {cartridgeComponent: applicationStore.getCartridgeComponent() || {component: 'div', props: {}}};
},
_handleComponentChange: function _handleComponentChange(){
this.setState(this._getStateFromStore());
},
/** @inheriteddoc */
render: function renderCartridge() {
var className = `cartridge ${this.props.style.className}`;
return (
<div className={className} data-focus='cartridge'>
<this.state.cartridgeComponent.component {...this.state.cartridgeComponent.props}/>
</div>
);
}
};
module.exports = builder(cartridgeMixin);
|
Change my email to avoid Yahoo, which decided to brake my scraper script recently.
|
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from setuptools import setup
setup(
name = 'TracMasterTickets',
version = '2.1.1',
packages = ['mastertickets'],
package_data = { 'mastertickets': ['templates/*.html', 'htdocs/*.js', 'htdocs/*.css' ] },
author = "Noah Kantrowitz",
author_email = "noah@coderanger.net",
description = "Provides support for ticket dependencies and master tickets.",
license = "BSD",
keywords = "trac plugin ticket dependencies master",
url = "http://trac-hacks.org/wiki/MasterTicketsPlugin",
classifiers = [
'Framework :: Trac',
],
install_requires = ['Trac', 'Genshi >= 0.5.dev-r698,==dev'],
entry_points = {
'trac.plugins': [
'mastertickets.web_ui = mastertickets.web_ui',
'mastertickets.api = mastertickets.api',
]
}
)
|
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from setuptools import setup
setup(
name = 'TracMasterTickets',
version = '2.1.1',
packages = ['mastertickets'],
package_data = { 'mastertickets': ['templates/*.html', 'htdocs/*.js', 'htdocs/*.css' ] },
author = "Noah Kantrowitz",
author_email = "coderanger@yahoo.com",
description = "Provides support for ticket dependencies and master tickets.",
license = "BSD",
keywords = "trac plugin ticket dependencies master",
url = "http://trac-hacks.org/wiki/MasterTicketsPlugin",
classifiers = [
'Framework :: Trac',
],
install_requires = ['Trac', 'Genshi >= 0.5.dev-r698,==dev'],
entry_points = {
'trac.plugins': [
'mastertickets.web_ui = mastertickets.web_ui',
'mastertickets.api = mastertickets.api',
]
}
)
|
Align Exception test to coding style for test suite
|
<?php
/**
* League.Csv (https://csv.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LeagueTest\Csv;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception as BaseException;
use League\Csv\InvalidArgument;
use League\Csv\SyntaxError;
use League\Csv\UnavailableFeature;
use PHPUnit\Framework\TestCase;
class ExceptionsTest extends TestCase
{
public function testExceptionsExtendBaseClass()
{
self::assertInstanceOf(BaseException::class, new UnavailableFeature());
self::assertInstanceOf(BaseException::class, new CannotInsertRecord());
self::assertInstanceOf(BaseException::class, new InvalidArgument());
self::assertInstanceOf(BaseException::class, new SyntaxError());
}
}
|
<?php
/**
* League.Csv (https://csv.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LeagueTest\Csv;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception as BaseException;
use League\Csv\InvalidArgument;
use League\Csv\SyntaxError;
use League\Csv\UnavailableFeature;
use PHPUnit\Framework\TestCase;
class ExceptionsTest extends TestCase
{
public function testExceptionsExtendBaseClass()
{
$this->assertInstanceOf(BaseException::class, new UnavailableFeature());
$this->assertInstanceOf(BaseException::class, new CannotInsertRecord());
$this->assertInstanceOf(BaseException::class, new InvalidArgument());
$this->assertInstanceOf(BaseException::class, new SyntaxError());
}
}
|
Add Draft of Karma Handler.
|
package main
import (
"fmt"
"github.com/danryan/hal"
_ "github.com/danryan/hal/adapter/slack"
_ "github.com/danryan/hal/store/memory"
"os"
)
var canYouHandler = hal.Hear("(Tim|tim).*can you.*", func(res *hal.Response) error {
return res.Send("on it!")
})
var karmaHandler = hal.Hear(".*(\\w+)(\\+\\+|\\-\\-).*", func(res *hal.Response) error {
var format string
if res.Match[2] == "++" {
format = "%s just gained a level (%s: %d)"
} else {
format = "%s just lost a life (%s: %d)"
}
thing := res.Match[1]
return res.Reply(fmt.Sprintf(format, thing, thing, 1))
})
var echoHandler = hal.Respond(`echo (.+)`, func(res *hal.Response) error {
return res.Reply(res.Match[1])
})
func run() int {
robot, err := hal.NewRobot()
if err != nil {
hal.Logger.Error(err)
return 1
}
robot.Handle(
canYouHandler,
echoHandler,
karmaHandler,
)
if err := robot.Run(); err != nil {
hal.Logger.Error(err)
return 1
}
return 0
}
func main() {
os.Exit(run())
}
|
package main
import (
"github.com/danryan/hal"
_ "github.com/danryan/hal/adapter/shell"
_ "github.com/danryan/hal/adapter/slack"
_ "github.com/danryan/hal/store/memory"
"os"
)
var canYouHandler = hal.Hear("(Tim|tim).*can you.*", func(res *hal.Response) error {
return res.Send("on it!")
})
var echoHandler = hal.Respond(`echo (.+)`, func(res *hal.Response) error {
return res.Reply(res.Match[1])
})
func run() int {
robot, err := hal.NewRobot()
if err != nil {
hal.Logger.Error(err)
return 1
}
robot.Handle(
canYouHandler,
echoHandler,
)
if err := robot.Run(); err != nil {
hal.Logger.Error(err)
return 1
}
return 0
}
func main() {
os.Exit(run())
}
|
Set defaults for karma server
|
module.exports = function(config){
config.set({
basePath : '../',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
hostname: process.env.IP || 'localhost',
port: process.env.PORT || '9876',
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter',
'karma-phantomjs-launcher'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
},
});
};
|
module.exports = function(config){
config.set({
basePath : '../',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
hostname: process.env.IP,
port: process.env.PORT,
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter',
'karma-phantomjs-launcher'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
},
});
};
|
Handle missing INCAR files gracefully
|
from django.shortcuts import render_to_response
from django.template import RequestContext
import os
from qmpy.models import Calculation
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculation = Calculation.objects.get(pk=calculation_id)
data = get_globals()
data['calculation'] = calculation
data['stdout'] = ''
data['stderr'] = ''
if os.path.exists(os.path.join(calculation.path, 'stdout.txt')):
with open(os.path.join(calculation.path, 'stdout.txt')) as fr:
data['stdout'] = fr.read()
if os.path.exists(os.path.join(calculation.path, 'stderr.txt')):
with open(os.path.join(calculation.path, 'stderr.txt')) as fr:
data['stderr'] = fr.read()
try:
data['incar'] = ''.join(calculation.read_incar())
except FileNotFoundError:
data['incar'] = 'Could not read INCAR'
if not calculation.dos is None:
script, div = components(calculation.dos.bokeh_plot)
data['dos'] = script
data['dosdiv'] = div
return render_to_response('analysis/calculation.html',
data, RequestContext(request))
|
from django.shortcuts import render_to_response
from django.template import RequestContext
import os.path
from qmpy.models import Calculation
from ..tools import get_globals
from bokeh.embed import components
def calculation_view(request, calculation_id):
calculation = Calculation.objects.get(pk=calculation_id)
data = get_globals()
data['calculation'] = calculation
data['stdout'] = ''
data['stderr'] = ''
if os.path.exists(calculation.path+'/stdout.txt'):
data['stdout'] = open(calculation.path+'/stdout.txt').read()
if os.path.exists(calculation.path+'/stderr.txt'):
data['stderr'] = open(calculation.path+'/stderr.txt').read()
#if not calculation.dos is None:
# data['dos'] = calculation.dos.plot.get_flot_script()
if not calculation.dos is None:
script, div = components(calculation.dos.bokeh_plot)
data['dos'] = script
data['dosdiv'] = div
## Get exact INCAR settings from INCAR file
data['incar'] = ''.join(calculation.read_incar())
return render_to_response('analysis/calculation.html',
data, RequestContext(request))
|
Remove commented developer tools code
|
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 870,
height: 475,
icon: __dirname + '/logo.png'
});
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`);
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference window object
mainWindow = null;
});
}
// Called when Electron has finished initialization.
app.on('ready', createWindow);
ipcMain.on('renderData', function(event, arg) {
var dataWindow = new BrowserWindow({
width: 1000,
height: 500
});
// Load options page
dataWindow.loadURL(`file://${__dirname}/data.html`);
dataWindow.on('closed', function() {
// Dereference window object
dataWindow = null;
});
});
|
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const ipcMain = electron.ipcMain;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 870,
height: 475,
icon: __dirname + '/logo.png'
});
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`);
// Uncomment to open dev tools (Inspect Element) automatically
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference window object
mainWindow = null;
});
}
// Called when Electron has finished initialization.
app.on('ready', createWindow);
ipcMain.on('renderData', function(event, arg) {
var dataWindow = new BrowserWindow({
width: 1000,
height: 500
});
// Load options page
dataWindow.loadURL(`file://${__dirname}/data.html`);
dataWindow.on('closed', function() {
// Dereference window object
dataWindow = null;
});
});
|
Add the original body field to the replies table.
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRepliesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('replies', function(Blueprint $table)
{
$table->increments('id');
$table->text('body');
$table->text('body_original');
$table->integer('user_id')->index();
$table->integer('topic_id')->index();
$table->integer('vote_count')->default(0)-index();
$table->boolean('blocked')->default(false)->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('replies');
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRepliesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('replies', function(Blueprint $table)
{
$table->increments('id');
$table->text('body');
$table->integer('user_id')->index();
$table->integer('topic_id')->index();
$table->integer('vote_count')->default(0)-index();
$table->boolean('blocked')->default(false)->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('replies');
}
}
|
CHANGE number max of posts
Add argument to the function to allow 9 posts per page
|
<?php
/**
* Template Name: Gallery
* The template for displaying the galleries.
*
* @package Pu-ente
*/
get_header(); ?>
<!-- page-gallery.php -->
<div id="primary" class="content-area">
<main id="main" class="site-main clear" role="main">
<?php
global $post;
$slug = get_post( $post )->post_name;
$args = array( 'numberposts' => 9, 'category_name' => $slug, 'order' => 'ASC' );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<li class="project-container">
<div class="project">
<div class="project-description">
<p><?php the_title(); ?></p>
<?php $posttags = get_the_tags();
if ($posttags) {
echo "<p>";
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
echo "</p>";
}
?>
</div>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( $size, $attr ); ?>
</a>
</div>
</li>
<?php endforeach; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
<?php
/**
* Template Name: Gallery
* The template for displaying the galleries.
*
* @package Pu-ente
*/
get_header(); ?>
<!-- page-gallery.php -->
<div id="primary" class="content-area">
<main id="main" class="site-main clear" role="main">
<?php
global $post;
$slug = get_post( $post )->post_name;
$args = array( 'category_name' => $slug, 'order' => 'ASC' );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<li class="project-container">
<div class="project">
<div class="project-description">
<p><?php the_title(); ?></p>
<?php $posttags = get_the_tags();
if ($posttags) {
echo "<p>";
foreach($posttags as $tag) {
echo $tag->name . ' ';
}
echo "</p>";
}
?>
</div>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( $size, $attr ); ?>
</a>
</div>
</li>
<?php endforeach; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.