text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Update response to match swagger spec | 'use strict';
const url2Domain = require('./ext/url2domain');
const credibleSources = require('./data/credible');
const notCredibleSources = require('./data/notCredible');
module.exports.check = (event, context, callback) => {
const origin = (event.queryStringParameters) ? event.queryStringParameters.__amp_source_origin : '*';
const articleUrl = (event.queryStringParameters) ? event.queryStringParameters.url : '';
const domain = url2Domain(articleUrl);
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': origin,
'AMP-Access-Control-Allow-Source-Origin': origin,
'Access-Control-Expose-Headers': 'AMP-Access-Control-Allow-Source-Origin'
},
body: JSON.stringify({
url: articleUrl,
score: '¯\\_(ツ)_/¯', // TODO: implement score
criteria: {
opensources: {
flag: (notCredibleSources[domain]) ? true : false,
type: (notCredibleSources[domain]) ? notCredibleSources[domain].type : null,
credible: credibleSources.some(source => source.url === domain)
}
}
})
};
callback(null, response);
};
| 'use strict';
const url2Domain = require('./ext/url2domain');
const credibleSources = require('./data/credible');
const notCredibleSources = require('./data/notCredible');
module.exports.check = (event, context, callback) => {
const origin = (event.queryStringParameters) ? event.queryStringParameters.__amp_source_origin : '*';
const articleUrl = (event.queryStringParameters) ? event.queryStringParameters.url : '';
const domain = url2Domain(articleUrl);
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': origin,
'AMP-Access-Control-Allow-Source-Origin': origin,
'Access-Control-Expose-Headers': 'AMP-Access-Control-Allow-Source-Origin'
},
body: JSON.stringify({
url: articleUrl,
score: '¯\\_(ツ)_/¯',
meta: {
opensources: {
redFlag: (notCredibleSources[domain]) ? notCredibleSources[domain] : false,
credible: credibleSources.some(source => source.url === domain)
}
}
})
};
callback(null, response);
};
|
Fix backup view if spending password actived | 'use strict';
angular.module('copayApp.controllers').controller('backupWarningController', function($scope, $state, $timeout, $stateParams, $ionicModal) {
$scope.walletId = $stateParams.walletId;
$scope.fromState = $stateParams.from == 'onboarding' ? $stateParams.from + '.backupRequest' : $stateParams.from;
$scope.toState = $stateParams.from + '.backup';
$scope.openPopup = function() {
$ionicModal.fromTemplateUrl('views/includes/screenshotWarningModal.html', {
scope: $scope,
backdropClickToClose: true,
hardwareBackButtonClose: true
}).then(function(modal) {
$scope.warningModal = modal;
$scope.warningModal.show();
});
$scope.close = function() {
$scope.warningModal.remove();
$timeout(function() {
$state.go($scope.toState, {
walletId: $scope.walletId
});
}, 200);
};
}
$scope.goBack = function() {
$state.go($scope.fromState, {
walletId: $scope.walletId
});
};
});
| 'use strict';
angular.module('copayApp.controllers').controller('backupWarningController', function($scope, $state, $timeout, $stateParams, $ionicModal) {
$scope.walletId = $stateParams.walletId;
$scope.fromState = $stateParams.from == 'onboarding' ? $stateParams.from + '.backupRequest' : $stateParams.from;
$scope.toState = $stateParams.from + '.backup';
$scope.openPopup = function() {
$ionicModal.fromTemplateUrl('views/includes/screenshotWarningModal.html', {
scope: $scope,
backdropClickToClose: true,
hardwareBackButtonClose: true
}).then(function(modal) {
$scope.warningModal = modal;
$scope.warningModal.show();
});
$scope.close = function() {
$scope.warningModal.hide();
$scope.warningModal.remove();
$state.go($scope.toState, {
walletId: $scope.walletId
});
};
}
$scope.goBack = function() {
$state.go($scope.fromState, {
walletId: $scope.walletId
});
};
});
|
Put the original Monitor on statics | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ActionCreators } from './devTools';
export default function connectMonitor(Monitor) {
const ConnectedMonitor = connect(state => state, ActionCreators)(Monitor);
class DevTools extends Component {
static Monitor = Monitor;
static propTypes = {
store(props, propName, componentName) {
if (!props.store) {
return new Error('Required prop `store` was not specified in `' + componentName + '`.');
}
if (!props.store.devToolsStore) {
return new Error(
'Could not find the DevTools store inside the `store` prop passed to `' +
componentName +
'`. Have you applied the devTools() store enhancer?'
);
}
}
};
render() {
const { store } = this.props;
if (!store) {
return null;
}
const { devToolsStore } = store;
if (!devToolsStore) {
return null;
}
return <ConnectedMonitor {...this.props} store={devToolsStore} />;
}
}
return DevTools;
}
| import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ActionCreators } from './devTools';
export default function connectMonitor(Monitor) {
const ConnectedMonitor = connect(state => state, ActionCreators)(Monitor);
class DevTools extends Component {
static propTypes = {
store(props, propName, componentName) {
if (!props.store) {
return new Error('Required prop `store` was not specified in `' + componentName + '`.');
}
if (!props.store.devToolsStore) {
return new Error(
'Could not find the DevTools store inside the `store` prop passed to `' +
componentName +
'`. Have you applied the devTools() store enhancer?'
);
}
}
};
render() {
const { store } = this.props;
if (!store) {
return null;
}
const { devToolsStore } = store;
if (!devToolsStore) {
return null;
}
return <ConnectedMonitor {...this.props} store={devToolsStore} />;
}
}
return DevTools;
}
|
Add a DataHandler object as part of the interface | /*
* Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.example.lit.saving;
/**
* Created by Riley Dixon on 12/11/2017.
*/
public interface Saveable {
public DataHandler dataHandler;
abstract public boolean saveData();
abstract public boolean loadData();
}
| /*
* Copyright 2017 Max Schafer, Ammar Mahdi, Riley Dixon, Steven Weikai Lu, Jiaxiong Yang
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.example.lit.saving;
/**
* Created by Riley Dixon on 12/11/2017.
*/
public interface Saveable {
abstract public boolean saveData();
abstract public boolean loadData();
}
|
Make post creation work again. | (function(config, models, views, routers, utils, templates) {
views.NewPost = Backbone.View.extend({
id: 'new_post',
events: {
'submit #new_post_form': 'createPost'
},
createPost: function() {
var that = this;
var filename = this.$('.filename').val();
var title = this.$('.title').val();
var subtitle = this.$('.subtitle').val();
var metadata = {
title: title,
subtitle: subtitle,
published: false
};
savePost(app.state.user, app.state.repo, app.state.branch, app.state.path, filename, _.toYAML(metadata), '', 'Created ' +filename, function(err) {
router.navigate(app.state.user + '/' + app.state.repo + '/' + app.state.branch + '/' + app.state.path + '/' + filename, true);
});
return false;
},
initialize: function(options) {
},
render: function() {
$(this.el).html(templates.new_post(this.model));
return this;
}
});
}).apply(this, window.args);
| (function(config, models, views, routers, utils, templates) {
views.NewPost = Backbone.View.extend({
id: 'new_post',
events: {
'submit #new_post_form': 'createPost'
},
createPost: function() {
var that = this;
var filename = this.$('.filename').val();
var title = this.$('.title').val();
var subtitle = this.$('.subtitle').val();
// TODO: make this smart
// No assumptions on the repository layout should be made
var metadata = {
title: title,
category: 'blog',
subtitle: subtitle,
hidden: true
};
savePost(app.state.user, app.state.repo, app.state.branch, app.state.path, filename, metadata, '', 'Created ' +filename, function(err) {
router.navigate(app.state.user + '/' + app.state.repo + '/' + app.state.branch + '/' + app.state.path + '/' + filename, true);
});
return false;
},
initialize: function(options) {
},
render: function() {
$(this.el).html(templates.new_post(this.model));
return this;
}
});
}).apply(this, window.args);
|
Add the action required to fix the issue to the warning | # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root not in pytest_testdox.__file__:
warnings.warn(
'pytest-testdox was not imported from your repository. '
'You might be testing the wrong code. '
'Uninstall pytest-testdox to be able to run all test cases '
'-- More: https://github.com/renanivo/pytest-testdox/issues/13',
UserWarning
)
| # -*- coding: utf-8 -*-
import os
import warnings
import pytest
pytest_plugins = 'pytester'
@pytest.fixture(scope='session', autouse=True)
def verify_target_path():
import pytest_testdox
current_path_root = os.path.dirname(
os.path.dirname(os.path.realpath(__file__))
)
if current_path_root not in pytest_testdox.__file__:
warnings.warn(
'pytest-testdox was not imported from your repository. '
'You might be testing the wrong code '
'-- More: https://github.com/renanivo/pytest-testdox/issues/13',
UserWarning
)
|
Test fix for exit handler
PiperOrigin-RevId: 436937697 | # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Custom component for exit handler."""
from tfx.orchestration.kubeflow import decorators
from tfx.utils import io_utils
import tfx.v1 as tfx
@decorators.exit_handler
def test_exit_handler(final_status: tfx.dsl.components.Parameter[str],
file_dir: tfx.dsl.components.Parameter[str]):
io_utils.write_string_file(file_dir, final_status)
| # Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Custom component for exit handler."""
from tfx.orchestration.kubeflow.v2 import decorators
from tfx.utils import io_utils
import tfx.v1 as tfx
@decorators.exit_handler
def test_exit_handler(final_status: tfx.dsl.components.Parameter[str],
file_dir: tfx.dsl.components.Parameter[str]):
io_utils.write_string_file(file_dir, final_status)
|
Add getAlias for CMS routes | <?php
namespace AddressixAPI\App\Cms;
use AddressixAPI\App\Resource;
class UrlAlias extends Resource
{
protected $resource_uri = '/cms';
public function __construct($app)
{
parent::__construct($app);
$this->functions['get'] =
array(
'method' => 'GET',
'uri' => '/urlaliases/:id'
);
$this->functions['get_processed'] =
array(
'method' => 'GET',
'uri' => '/urlaliases/process'
);
$this->functions['get_alias'] =
array(
'method' => 'GET',
'uri' => '/urlaliases/process_alias'
);
}
public function getProcessed($siteid, $langcode, $alias)
{
$this->request('get_processed', array('site'=>$siteid, 'language'=>$langcode, 'alias'=>$alias));
return $this->data;
}
public function getAlias($siteid, $langcode, $path)
{
$this->request('get_alias', array('site'=>$siteid, 'language'=>$langcode, 'path'=>$path));
return $this->data;
}
} | <?php
namespace AddressixAPI\App\Cms;
use AddressixAPI\App\Resource;
class Article extends Resource
{
protected $resource_uri = '/cms';
public function __construct($app)
{
parent::__construct($app);
$this->functions['get'] =
array(
'method' => 'GET',
'uri' => '/articles/:id/:langcode'
);
$this->functions['get_processed'] =
array(
'method' => 'GET',
'uri' => '/urlaliases/process'
);
}
public function getProcessed($siteid, $langcode, $alias)
{
$this->request('get_processed', array('siteid'=>$siteid, 'language'=>$langcode, 'alias'=>$alias));
return $this->data;
}
} |
Handle the fact that a user can be removed but have feeds in queue | <?php
use Miniflux\Handler;
use Miniflux\Model;
use Miniflux\Session\SessionStorage;
use Pheanstalk\Pheanstalk;
require __DIR__.'/app/common.php';
if (php_sapi_name() !== 'cli') {
die('This script can run only from the command line.'.PHP_EOL);
}
$connection = new Pheanstalk(BEANSTALKD_HOST);
$session = SessionStorage::getInstance();
while ($job = $connection->reserveFromTube(BEANSTALKD_QUEUE)) {
$payload = unserialize($job->getData());
$start_time = microtime(true);
echo 'Processing feed_id=', $payload['feed_id'], ' for user_id=', $payload['user_id'];
$user = Model\User\get_user_by_id($payload['user_id']);
if (empty($user)) {
echo ', user not found (removed?)'.PHP_EOL;
} else {
$session->flush();
$session->setUser($user);
Handler\Feed\update_feed($payload['user_id'], $payload['feed_id']);
Model\Item\autoflush_read($payload['user_id']);
Model\Item\autoflush_unread($payload['user_id']);
echo ', duration='.(microtime(true) - $start_time).' seconds', PHP_EOL;
Miniflux\Helper\write_debug_file();
}
$connection->delete($job);
}
| <?php
use Miniflux\Handler;
use Miniflux\Model;
use Miniflux\Session\SessionStorage;
use Pheanstalk\Pheanstalk;
require __DIR__.'/app/common.php';
if (php_sapi_name() !== 'cli') {
die('This script can run only from the command line.'.PHP_EOL);
}
$connection = new Pheanstalk(BEANSTALKD_HOST);
$session = SessionStorage::getInstance();
while ($job = $connection->reserveFromTube(BEANSTALKD_QUEUE)) {
$payload = unserialize($job->getData());
$start_time = microtime(true);
echo 'Processing feed_id=', $payload['feed_id'], ' for user_id=', $payload['user_id'];
$session->flush();
$session->setUser(Model\User\get_user_by_id($payload['user_id']));
Handler\Feed\update_feed($payload['user_id'], $payload['feed_id']);
Model\Item\autoflush_read($payload['user_id']);
Model\Item\autoflush_unread($payload['user_id']);
echo ', duration='.(microtime(true) - $start_time).' seconds', PHP_EOL;
Miniflux\Helper\write_debug_file();
$connection->delete($job);
}
|
Add bucket to p command | package main
import (
"log"
"github.com/codegangsta/cli"
"github.com/headmade/backuper/config"
)
func providerAction(c *cli.Context) {
var providerConfig config.Provider
switch c.Command.Name {
case "AWS":
validateArgs(c, 3)
providerConfig = config.Provider{"bucket": c.Args()[0], "AWS_ACCESS_KEY_ID": c.Args()[1], "AWS_SECRET_ACCESS_KEY": c.Args()[2]}
case "encryption":
validateArgs(c, 1)
providerConfig = config.Provider{"pass": c.Args()[0]}
}
providerCommand(c.Command.Name, providerConfig)
}
func validateArgs(c *cli.Context, length int) {
if len(c.Args()) != length {
log.Fatal("Bad arguments")
}
}
func providerCommand(name string, providerConfig config.Provider) {
conf, err := config.New()
if err != nil {
log.Fatal(err)
}
if conf.Secret == nil {
conf.Secret = config.Providers{}
}
// conf.Secret[name] = providerConfig
if conf.Secret[name] == nil {
conf.Secret[name] = config.Provider{}
}
for k, v := range providerConfig {
conf.Secret[name][k] = v
}
conf.Write(conf.Secret)
}
| package main
import (
"log"
"github.com/codegangsta/cli"
"github.com/headmade/backuper/config"
)
func providerAction(c *cli.Context) {
var providerConfig config.Provider
switch c.Command.Name {
case "AWS":
validateArgs(c, 2)
providerConfig = config.Provider{"AWS_ACCESS_KEY_ID": c.Args()[0], "AWS_SECRET_ACCESS_KEY": c.Args()[1]}
case "encryption":
validateArgs(c, 1)
providerConfig = config.Provider{"pass": c.Args()[0]}
}
providerCommand(c.Command.Name, providerConfig)
}
func validateArgs(c *cli.Context, length int) {
if len(c.Args()) != length {
log.Fatal("Bad arguments")
}
}
func providerCommand(name string, providerConfig config.Provider) {
conf, err := config.New()
if err != nil {
log.Fatal(err)
}
if conf.Secret == nil {
conf.Secret = config.Providers{}
}
// conf.Secret[name] = providerConfig
if conf.Secret[name] == nil {
conf.Secret[name] = config.Provider{}
}
for k, v := range providerConfig {
conf.Secret[name][k] = v
}
conf.Write(conf.Secret)
}
|
Fix regression: No handlers could be found for logger when start
This change fixed a function regression on bug/1201562.
Closes-Bug: #1201562
Change-Id: I3994c97633f5d09cccf6defdf0eac3957d63304e
Signed-off-by: Zhi Yan Liu <98cb9f7b35c45309ab1e4c4eac6ba314b641cf7a@cn.ibm.com> | # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
print(ex, file=sys.stderr)
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
| # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
|
Use color configurations from config file | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
from tldr.config import get_config
def parse_page(page):
"""Parse the command man page."""
colors = get_config()['colors']
with open(page) as f:
lines = f.readlines()
for line in lines:
if line.startswith('#'):
continue
elif line.startswith('>'):
click.secho(line.replace('>', ' '), fg=colors['description'],
nl=False)
elif line.startswith('-'):
click.secho(line, fg=colors['usage'], nl=False)
elif line.startswith('`'):
click.secho(' ' + line.replace('`', ''), fg=colors['command'],
nl=False)
else:
click.secho(line, nl=False)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import click
def parse_page(page):
"""Parse the command man page."""
with open(page) as f:
lines = f.readlines()
for line in lines:
if line.startswith('#'):
continue
elif line.startswith('>'):
click.secho(line.replace('>', ' '), fg='blue', nl=False)
elif line.startswith('-'):
click.secho(line, fg='green', nl=False)
elif line.startswith('`'):
click.secho(' ' + line.replace('`', ''), fg='cyan', nl=False)
else:
click.secho(line, nl=False)
|
Correct the definitions of old-style classes | import numpy as np
from scipy.interpolate import PchipInterpolator
class UcPoly(object):
def __init__(self, coef):
self.p = np.poly1d(coef)
def machine_to_physics(self, machine_value):
return self.p(machine_value)
def physics_to_machine(self, physics_value):
roots = (self.p - physics_value).roots
positive_roots = [root for root in roots if root > 0]
if len(positive_roots) > 0:
return positive_roots[0]
else:
raise ValueError("No corresponding positive machine value:", roots)
class UcPchip(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.pp = PchipInterpolator(x, y)
def machine_to_physics(self, machine_value):
return self.pp(machine_value)
def physics_to_machine(self, physics_value):
pass
| import numpy as np
from scipy.interpolate import PchipInterpolator
class UcPoly():
def __init__(self, coef):
self.p = np.poly1d(coef)
def machine_to_physics(self, machine_value):
return self.p(machine_value)
def physics_to_machine(self, physics_value):
roots = (self.p - physics_value).roots
positive_roots = [root for root in roots if root > 0]
if len(positive_roots) > 0:
return positive_roots[0]
else:
raise ValueError("No corresponding positive machine value:", roots)
class UcPchip():
def __init__(self, x, y):
self.x = x
self.y = y
self.pp = PchipInterpolator(x, y)
def machine_to_physics(self, machine_value):
return self.pp(machine_value)
def physics_to_machine(self, physics_value):
pass
|
Update search index after deleting a page. | import db from 'src/pouchdb'
import { findVisits } from 'src/search/find-visits'
import { getEquivalentPages, updatePageSearchIndex } from 'src/search/find-pages'
export async function deleteVisitAndPage({visitId}) {
// Delete the visit object
const visit = await db.get(visitId)
const pageId = visit.page._id
await db.remove(visit)
// If this was the only visit linking to the page, also remove the page.
// (a simple choice for now; this behaviour may be changed in the future)
await deletePageIfOrphaned({pageId})
}
async function deletePageIfOrphaned({pageId}) {
// Because of deduplication, different page objects may redirect to this
// one, or this one may redirect to others. So we check for visits either
// referring to this page object or to any equivalent ones.
const pagesResult = await getEquivalentPages({pageId})
const visitsResult = await findVisits({pagesResult})
// If there are no visits to any of them, delete all these page objects.
// (otherwise, we leave them; it does not seem worth the effort to smartly
// prune some orphans among them already)
if (visitsResult.rows.length === 0) {
await db.bulkDocs(pagesResult.rows.map(
row => ({
_id: row.id,
_rev: row.value.rev,
_deleted: true,
})
))
await updatePageSearchIndex()
}
}
| import db from 'src/pouchdb'
import { findVisits } from 'src/search/find-visits'
import { getEquivalentPages } from 'src/search/find-pages'
export async function deleteVisitAndPage({visitId}) {
// Delete the visit object
const visit = await db.get(visitId)
const pageId = visit.page._id
await db.remove(visit)
// If this was the only visit linking to the page, also remove the page.
// (a simple choice for now; this behaviour may be changed in the future)
await deletePageIfOrphaned({pageId})
}
async function deletePageIfOrphaned({pageId}) {
// Because of deduplication, different page objects may redirect to this
// one, or this one may redirect to others. So we check for visits either
// referring to this page object or to any equivalent ones.
const pagesResult = await getEquivalentPages({pageId})
const visitsResult = await findVisits({pagesResult})
// If there are no visits to any of them, delete all these page objects.
// (otherwise, we leave them; it does not seem worth the effort to smartly
// prune some orphans among them already)
if (visitsResult.rows.length === 0) {
await db.bulkDocs(pagesResult.rows.map(
row => ({
_id: row.id,
_rev: row.value.rev,
_deleted: true,
})
))
}
}
|
Add last event of the day | import React from 'react'
import Chronodex from './src/Chronodex.jsx'
let events = [
[9, 10, 'Email'],
[10, 12, 'Meeting'],
[12, 13, 'Lunch'],
[13, 15, 'Meeting'],
[15, 16, 'Coffee'],
[16, 17, 'Email'],
[17, 18, 'Commute,Reading,Music'],
[18, 19, 'Exercise'],
[19, 20, 'Dinner,Netflix'],
[20, 21, 'Walk Dog']
]
React.render(<Chronodex
title='Chronodex'
size={256}
center={128}
radius={64}
events={events}
/>, document.querySelector('#chronodex'))
| import React from 'react'
import Chronodex from './src/Chronodex.jsx'
let events = [
[9, 10, 'Email'],
[10, 12, 'Meeting'],
[12, 13, 'Lunch'],
[13, 15, 'Meeting'],
[15, 16, 'Coffee'],
[16, 17, 'Email'],
[17, 18, 'Commute,Reading,Music'],
[18, 19, 'Exercise'],
[19, 20, 'Dinner,Netflix']
]
React.render(<Chronodex
title='Chronodex'
size={256}
center={128}
radius={64}
events={events}
/>, document.querySelector('#chronodex'))
|
Fix for division by 0 warning in review rating validation. | <?php
namespace MetroPublisher\Api\Models;
use MetroPublisher\Exception\MetroPublisherException;
/**
* Class AbstractReview
* @package MetroPublisher\Api\Models
*/
abstract class AbstractReview extends Content
{
/** @var string */
protected $rating;
/**
* @inheritdoc
*/
public static function getMetaFields()
{
return array_merge(['rating'], parent::getMetaFields());
}
/**
* @return float
*/
public function getRating() {
return floatval($this->rating);
}
/**
* @param int $rating
*
* @return $this
* @throws MetroPublisherException
*/
public function setRating($rating)
{
if ($rating !== 0 && ($rating < 0 || $rating > 5 || ($rating / .5) % 1 !== 0)) {
throw new MetroPublisherException('Rating must be 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, or 5. ');
}
//API expects value to be string. Floats will trigger an error.
$this->rating = $rating . "";
return $this;
}
} | <?php
namespace MetroPublisher\Api\Models;
use MetroPublisher\Exception\MetroPublisherException;
/**
* Class AbstractReview
* @package MetroPublisher\Api\Models
*/
abstract class AbstractReview extends Content
{
/** @var string */
protected $rating;
/**
* @inheritdoc
*/
public static function getMetaFields()
{
return array_merge(['rating'], parent::getMetaFields());
}
/**
* @return float
*/
public function getRating() {
return floatval($this->rating);
}
/**
* @param int $rating
*
* @return $this
* @throws MetroPublisherException
*/
public function setRating($rating)
{
if ($rating !== 0 && ($rating < 0 || $rating > 5 || $rating % .5 > 0)) {
throw new MetroPublisherException('Rating must be 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, or 5. ');
}
//API expects value to be string. Floats will trigger an error.
$this->rating = $rating . "";
return $this;
}
} |
Print tracebacks that happened in tasks | from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
for template_engine in TEMPLATES:
template_engine['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
try:
import debug_toolbar
except ImportError:
pass
else:
INSTALLED_APPS += ('debug_toolbar',)
MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INTERNAL_IPS = ('127.0.0.1', 'localhost')
DEBUG_TOOLBAR_CONFIG = {
'JQUERY_URL': '',
}
try:
from .local import *
except ImportError:
pass
try:
from .polygons import *
except ImportError:
pass
LOGGING = {
'version': 1,
'handlers': {
'console': {
'class': 'logging.StreamHandler'},
},
'loggers': {'background_task': {'handlers': ['console'], 'level': 'INFO'}}}
try:
INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
pass
| from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
for template_engine in TEMPLATES:
template_engine['OPTIONS']['debug'] = True
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qid$h1o8&wh#p(j)lifis*5-rf@lbiy8%^3l4x%@b$z(tli@ab'
try:
import debug_toolbar
except ImportError:
pass
else:
INSTALLED_APPS += ('debug_toolbar',)
MIDDLEWARE += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INTERNAL_IPS = ('127.0.0.1', 'localhost')
DEBUG_TOOLBAR_CONFIG = {
'JQUERY_URL': '',
}
try:
from .local import *
except ImportError:
pass
try:
from .polygons import *
except ImportError:
pass
try:
INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
pass
|
Clear compiled projects when a project is created or switched to
If you create a new project, or start the process of switching to an
existing project, we want to clear the preview state. Otherwise:
* When you create a new project, the old project sticks around
* When switching projects, the preview is unpleasantly flashy between
old and new state | import {List} from 'immutable';
import {CompiledProject} from '../records';
const initialState = new List();
function trimRight(list, maxLength) {
if (list.size <= maxLength) {
return list;
}
return list.splice(0, list.size - maxLength);
}
export default function compiledProjects(stateIn, action) {
let state = stateIn;
if (state === undefined) {
state = initialState;
}
switch (action.type) {
case 'PROJECT_CREATED':
return initialState;
case 'CHANGE_CURRENT_PROJECT':
return initialState;
case 'PROJECT_COMPILED':
return trimRight(
state.push(new CompiledProject({
source: action.payload.source,
title: action.payload.title,
timestamp: action.meta.timestamp,
})),
2,
);
case 'USER_DONE_TYPING':
return trimRight(state, 1);
case 'VALIDATED_SOURCE':
if (action.payload.errors.length) {
return initialState;
}
return state;
}
return state;
}
| import {List} from 'immutable';
import {CompiledProject} from '../records';
const initialState = new List();
function trimRight(list, maxLength) {
if (list.size <= maxLength) {
return list;
}
return list.splice(0, list.size - maxLength);
}
export default function compiledProjects(stateIn, action) {
let state = stateIn;
if (state === undefined) {
state = initialState;
}
switch (action.type) {
case 'PROJECT_COMPILED':
return trimRight(
state.push(new CompiledProject({
source: action.payload.source,
title: action.payload.title,
timestamp: action.meta.timestamp,
})),
2,
);
case 'USER_DONE_TYPING':
return trimRight(state, 1);
case 'VALIDATED_SOURCE':
if (action.payload.errors.length) {
return initialState;
}
return state;
}
return state;
}
|
[CLEANUP] Convert dasherize test over to new style | import COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE from '../../lib/system/dasherize-component-name';
import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
moduleFor(
'dasherize-component-name',
class extends AbstractTestCase {
['@test names are correctly dasherized'](assert) {
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('Foo'), 'foo');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('foo-bar'), 'foo-bar');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('FooBar'), 'foo-bar');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('XBlah'), 'x-blah');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('X-Blah'), 'x-blah');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('Foo::BarBaz'), 'foo::bar-baz');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('Foo::Bar-Baz'), 'foo::bar-baz');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('Foo@BarBaz'), 'foo@bar-baz');
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get('Foo@Bar-Baz'), 'foo@bar-baz');
}
}
);
| import COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE from '../../lib/system/dasherize-component-name';
QUnit.module('dasherize-component-name', function() {
function equals(input, expected) {
QUnit.test(`${input} -> ${expected}`, function(assert) {
assert.equal(COMPONENT_NAME_SIMPLE_DASHERIZE_CACHE.get(input), expected);
});
}
equals('Foo', 'foo');
equals('foo-bar', 'foo-bar');
equals('FooBar', 'foo-bar');
equals('XBlah', 'x-blah');
equals('X-Blah', 'x-blah');
equals('Foo::BarBaz', 'foo::bar-baz');
equals('Foo::Bar-Baz', 'foo::bar-baz');
equals('Foo@BarBaz', 'foo@bar-baz');
equals('Foo@Bar-Baz', 'foo@bar-baz');
});
|
Use mdfind to find the name of Marked or Marked 2. | /* globals atom:false */
'use strict';
var spawnSync = require('child_process').spawnSync;
exports.provideBuilder = function () {
return {
niceName: 'Markdown',
isEligable: function () {
var textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || !textEditor.getPath()) {
return false;
}
var path = textEditor.getPath();
return path.endsWith('.md') || path.endsWith('.mkd');
},
settings: function () {
var app = spawnSync('mdfind', ['kMDItemCFBundleIdentifier == "com.brettterpstra.mark*"']);
app = app.stdout.toString().split('\n')[0];
return [ {
name: 'Markdown: view',
sh: false,
exec: 'open',
args: [ '-a', app || 'Marked 2', '{FILE_ACTIVE}' ]
}];
}
};
};
| /* globals atom:false */
'use strict';
exports.provideBuilder = function () {
return {
niceName: 'Markdown',
isEligable: function () {
var textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || !textEditor.getPath()) {
return false;
}
var path = textEditor.getPath();
return path.endsWith('.md') || path.endsWith('.mkd');
},
settings: function () {
return [ {
name: 'Markdown: view',
sh: false,
exec: 'open',
args: [ '-a', 'Marked.app', '{FILE_ACTIVE}' ]
}];
}
};
};
|
Update javadoc term to fix copy/paste error | package org.springframework.cloud.commons.util;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
/**
* @author Spencer Gibb
*/
@Data
@ConfigurationProperties(InetUtilsProperties.PREFIX)
public class InetUtilsProperties {
public static final String PREFIX = "spring.cloud.inetutils";
/**
* The default hostname. Used in case of errors.
*/
private String defaultHostname = "localhost";
/**
* The default ipaddress. Used in case of errors.
*/
private String defaultIpAddress = "127.0.0.1";
/**
* Timeout in seconds for calculating hostname.
*/
@Value("${spring.util.timeout.sec:${SPRING_UTIL_TIMEOUT_SEC:1}}")
private int timeoutSeconds = 1;
/**
* List of Java regex expressions for network interfaces that will be ignored.
*/
private List<String> ignoredInterfaces = new ArrayList<>();
/**
* Use only interfaces with site local addresses. See {@link InetAddress#isSiteLocalAddress()} for more details.
*/
private boolean useOnlySiteLocalInterfaces = false;
/**
* List of Java regex expressions for network addresses that will be preferred.
*/
private List<String> preferredNetworks = new ArrayList<>();
}
| package org.springframework.cloud.commons.util;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
/**
* @author Spencer Gibb
*/
@Data
@ConfigurationProperties(InetUtilsProperties.PREFIX)
public class InetUtilsProperties {
public static final String PREFIX = "spring.cloud.inetutils";
/**
* The default hostname. Used in case of errors.
*/
private String defaultHostname = "localhost";
/**
* The default ipaddress. Used in case of errors.
*/
private String defaultIpAddress = "127.0.0.1";
/**
* Timeout in seconds for calculating hostname.
*/
@Value("${spring.util.timeout.sec:${SPRING_UTIL_TIMEOUT_SEC:1}}")
private int timeoutSeconds = 1;
/**
* List of Java regex expressions for network interfaces that will be ignored.
*/
private List<String> ignoredInterfaces = new ArrayList<>();
/**
* Use only interfaces with site local addresses. See {@link InetAddress#isSiteLocalAddress()} for more details.
*/
private boolean useOnlySiteLocalInterfaces = false;
/**
* List of Java regex expressions for network addresses that will be ignored.
*/
private List<String> preferredNetworks = new ArrayList<>();
}
|
Fix config of fb messenger | <?php
return [
'debug' => env('MESSENGER_DEBUG', false),
'verify_token' => env('MESSENGER_VERIFY_TOKEN'),
'app_token' => env('MESSENGER_APP_TOKEN'),
'auto_typing' => false,
'handlers' => [
App\Chatbot\MessageHandlers\DefaultHandler::class,
],
'custom_url' => '/webhook',
'postbacks' => [
App\Chatbot\PostbackHandlers\DefaultPostbackHandler::class,
],
'home_url' => [
'url' => env('MESSENGER_HOME_URL'),
'webview_share_button' => 'show',
'in_test' => true,
],
];
| <?php
return [
'debug' => env('MESSENGER_DEBUG', false),
'verify_token' => env('MESSENGER_VERIFY_TOKEN'),
'app_token' => env('MESSENGER_APP_TOKEN'),
'app_secret' => env('MESSENGER_APP_SECRET'),
'auto_typing' => true,
'handlers' => [
Casperlaitw\LaravelFbMessenger\Contracts\DefaultHandler::class,
],
'custom_url' => '/webhook',
'postbacks' => [],
'home_url' => [
'url' => env('MESSENGER_HOME_URL'),
'webview_share_button' => 'show',
'in_test' => true,
],
];
|
Use let instead of var | import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["mapInfo"]
connect() {
const courseId = this.mapInfoTarget.dataset.courseId;
const splitId = this.mapInfoTarget.dataset.splitId;
Rails.ajax({
url: "/api/v1/courses/" + courseId,
type: "GET",
success: function (response) {
const attributes = response.data.attributes;
let locations = null;
if(splitId === undefined) {
locations = attributes.locations;
} else {
locations = attributes.locations.filter(function(e) {
return e.id === parseInt(splitId)
})
}
const trackPoints = attributes.trackPoints;
gmap_show(locations, trackPoints);
}
})
}
}
| import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["mapInfo"]
connect() {
const courseId = this.mapInfoTarget.dataset.courseId;
const splitId = this.mapInfoTarget.dataset.splitId;
Rails.ajax({
url: "/api/v1/courses/" + courseId,
type: "GET",
success: function (response) {
const attributes = response.data.attributes;
var locations = null;
if(splitId === undefined) {
locations = attributes.locations;
} else {
locations = attributes.locations.filter(function(e) {
return e.id === parseInt(splitId)
})
}
const trackPoints = attributes.trackPoints;
gmap_show(locations, trackPoints);
}
})
}
}
|
Delete load method, add start method | 'use strict';
var EventEmitter = require('events').EventEmitter
class Config {
constructor() {
this.requiredKeys = ['url','type']
this.messages = {
missingConfig: 'DataService missing config object',
missingKey: 'DataService config missing required key: '
}
}
error(msg) {
throw new Error(msg)
}
checkKeyValidity(config, key) {
if (!config.hasOwnProperty(key))
this.error(this.messages.missingKey + key)
}
validate(config) {
if (!config) this.error(this.messages.missingConfig)
this.requiredKeys.forEach((key) => this.checkKeyValidity(config, key))
return config
}
}
class DataService extends EventEmitter {
constructor(config) {
this.config = new Config().validate(config)
this.data = null
}
getData() {
return this.data
}
start() {
this.emit('data')
}
}
module.exports = function(config) {
return new DataService(config)
}
| 'use strict';
var EventEmitter = require('events').EventEmitter
class Config {
constructor() {
this.requiredKeys = ['url','type']
this.messages = {
missingConfig: 'DataService missing config object',
missingKey: 'DataService config missing required key: '
}
}
error(msg) {
throw new Error(msg)
}
checkKeyValidity(config, key) {
if (!config.hasOwnProperty(key))
this.error(this.messages.missingKey + key)
}
validate(config) {
if (!config) this.error(this.messages.missingConfig)
this.requiredKeys.forEach((key) => this.checkKeyValidity(config, key))
return config
}
}
class DataService extends EventEmitter {
constructor(config) {
this.config = new Config().validate(config)
this.data = null
}
getData() {
return this.data
}
load(cb) {
return cb(null, {})
}
}
module.exports = function(config) {
return new DataService(config)
}
|
Set projectile positions to the edge of the screen | "use strict";
function cast_to_edge(x, y, pos, data) {
var d = Math.sqrt((pos.x - x) * (pos.x - x) + (pos.y - y) * (pos.y - y));
var uv = {
"x": (x-pos.x)/d,
"y": (y-pos.y)/d
}
do {
x+=uv.x;
y+=uv.y;
} while( x >= 0 && x <= data.canvas.width && y >= 0 && y <= data.canvas.height );
return {"x": x, "y": y}
}
module.exports = function(entity, data) {
var constants = data.entities.get(entity, "constants");
var x = Math.floor(Math.random() * data.canvas.width)
var y = Math.floor(Math.random() * data.canvas.height)
var projectile = data.instantiatePrefab("projectile");
var new_pos = cast_to_edge(x, y, constants.center, data);
data.entities.set(projectile, "position", new_pos);
var timers = data.entities.get(entity, "timers");
timers.spawn_projectile.time = 0;
timers.spawn_projectile.running = true;
}
| "use strict";
function cast_to_edge(x, y, pos) {
var d = Math.sqrt((pos.x - x) * (pos.x - x) + (pos.y - y) * (pos.y - y));
var uv = {
"x": (x-pos.x)/d,
"y": (y-pos.y)/d
}
do {
x+=uv.x;
y+=uv.y;
} while( x >= 0 && x <= data.canvas.width && y >= 0 && y <= data.canvas.height );
}
module.exports = function(entity, data) {
var constants = data.entities.get(entity, "constants");
var x = Math.floor(Math.random() * data.canvas.width)
var y = Math.floor(Math.random() * data.canvas.height)
var projectile = data.instantiatePrefab("projectile");
cast_to_edge(x, y, constants.center);
var timers = data.entities.get(entity, "timers");
timers.spawn_projectile.time = 0;
timers.spawn_projectile.running = true;
}
|
Check for the entry kind | const fs = require('fs');
const process = require('process');
const assert = require('assert');
const buffer = fs.readFileSync(process.argv[2]);
let m = new WebAssembly.Module(buffer);
let list = WebAssembly.Module.exports(m);
console.log('exports', list);
const my_exports = {};
let nexports = 0;
for (const entry of list) {
if (entry.kind == 'function'){
nexports += 1;
}
my_exports[entry.name] = entry.kind;
}
if (my_exports.foo != "function")
throw new Error("`foo` wasn't defined");
if (my_exports.FOO != "global")
throw new Error("`FOO` wasn't defined");
if (my_exports.main === undefined) {
if (nexports != 1)
throw new Error("should only have one function export");
} else {
if (nexports != 2)
throw new Error("should only have two function exports");
}
| const fs = require('fs');
const process = require('process');
const assert = require('assert');
const buffer = fs.readFileSync(process.argv[2]);
let m = new WebAssembly.Module(buffer);
let list = WebAssembly.Module.exports(m);
console.log('exports', list);
const my_exports = {};
let nexports = 0;
for (const entry of list) {
if (entry.kind == 'function'){
nexports += 1;
}
my_exports[entry.name] = true;
}
if (my_exports.foo === undefined)
throw new Error("`foo` wasn't defined");
if (my_exports.FOO === undefined)
throw new Error("`FOO` wasn't defined");
if (my_exports.main === undefined) {
if (nexports != 1)
throw new Error("should only have one function export");
} else {
if (nexports != 2)
throw new Error("should only have two function exports");
}
|
Make sure that we reference the config file using an absolute path... just in case...
git-svn-id: 8a2b0a969c74f87a9c14cf35f460fb9b394f82c6@1775 a333f486-631f-4898-b8df-5754b55c2be0 | <?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';
/**
* Check that the configuration file exists and has the appropriate access rights
* If the file does not exist, launch the configuration wizard to create it
*/
if (file_exists(dirname(__FILE__).'/'.$sConfigFile))
{
if (!is_readable($sConfigFile))
{
echo "<p><b>Error</b>: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.</p>";
}
else if (is_writable($sConfigFile))
{
echo "<p><b>Security Warning</b>: the configuration file '$sConfigFile' should be read-only.</p>";
echo "<p>Please modify the access rights to this file.</p>";
echo "<p>Click <a href=\"$sStartPage\">here</a> to ignore this warning and continue to run iTop.</p>";
}
else
{
header("Location: $sStartPage");
}
}
else
{
// Config file does not exist, need to run the setup wizard to create it
header("Location: $sSetupPage");
}
?>
| <?php
$sConfigFile = 'conf/production/config-itop.php';
$sStartPage = './pages/UI.php';
$sSetupPage = './setup/index.php';
/**
* Check that the configuration file exists and has the appropriate access rights
* If the file does not exist, launch the configuration wizard to create it
*/
if (file_exists($sConfigFile))
{
if (!is_readable($sConfigFile))
{
echo "<p><b>Error</b>: Unable to read the configuration file: '$sConfigFile'. Please check the access rights on this file.</p>";
}
else if (is_writable($sConfigFile))
{
echo "<p><b>Security Warning</b>: the configuration file '$sConfigFile' should be read-only.</p>";
echo "<p>Please modify the access rights to this file.</p>";
echo "<p>Click <a href=\"$sStartPage\">here</a> to ignore this warning and continue to run iTop.</p>";
}
else
{
header("Location: $sStartPage");
}
}
else
{
// Config file does not exist, need to run the setup wizard to create it
header("Location: $sSetupPage");
}
?>
|
Use ResponseHeadersBag constants instead of strings for Content-Disposition validation | <?php
namespace Knp\Bundle\SnappyBundle\Snappy\Response;
use Symfony\Component\HttpFoundation\Response as Base;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
abstract class SnappyResponse extends Base
{
public function __construct($content, $fileName, $contentType, $contentDisposition = 'attachment', $status = 200, $headers = array())
{
$contentDispositionDirectives = array(ResponseHeaderBag::DISPOSITION_INLINE, ResponseHeaderBag::DISPOSITION_ATTACHMENT);
if (!in_array($contentDisposition, $contentDispositionDirectives)) {
throw new \InvalidArgumentException(sprintf('Expected one of the following directives: "%s", "%s" given.', implode('", "', $contentDispositionDirectives), $contentDisposition));
}
parent::__construct($content, $status, $headers);
$this->headers->add(array('Content-Type' => $contentType));
$this->headers->add(array('Content-Disposition' => $this->headers->makeDisposition($contentDisposition, $fileName)));
}
}
| <?php
namespace Knp\Bundle\SnappyBundle\Snappy\Response;
use Symfony\Component\HttpFoundation\Response as Base;
abstract class SnappyResponse extends Base
{
public function __construct($content, $fileName, $contentType, $contentDisposition = 'attachment', $status = 200, $headers = array())
{
$contentDispositionDirectives = array('inline', 'attachment');
if (!in_array($contentDisposition, $contentDispositionDirectives)) {
throw new \InvalidArgumentException(sprintf('Expected one of the following directives: "%s", "%s" given.', implode('", "', $contentDispositionDirectives), $contentDisposition));
}
parent::__construct($content, $status, $headers);
$this->headers->add(array('Content-Type' => $contentType));
$this->headers->add(array('Content-Disposition' => $this->headers->makeDisposition($contentDisposition, $fileName)));
}
}
|
Use an external service to deliver JS resource with ‘Content-Type: application/javascript;’ | /**
* Loads specific scripts, depending on the parameters.
* @class SDK Loader
* @param {Object} options
* @param {Integer} [options.kit] Represent the serveral bookmarklet types (default: tricket-print).
* @param {Integer} [options.env] Represent the environment aka branch name (default: master).
* @param {String} [options.path] Host url path of where the actual resource to be loaded.
*/
(function (options) {
'use strict';
options = options || {};
options.kit = options.kit || 0;
options.env = options.env || 0;
options.path = options.path || '//rawgit.com/cange/jira-bookmarklets/';
var doc = document,
scriptTag = doc.createElement('script'),
environments = ['master', 'develop'],
kits = [
'ticket-print',
'add-ticket',
'ticket-print-lay-scrum',
'add-ticket-lay-scrum'
],
environment = environments[options.env],
kit = kits[options.kit],
url = options.path + environment + '/build/' + kit + '-bookmarklet.js'
;
scriptTag.setAttribute('src', url);
doc.head.appendChild(scriptTag);
})(options);
| /**
* Loads specific scripts, depending on the parameters.
* @class SDK Loader
* @param {Object} options
* @param {Integer} [options.kit] Represent the serveral bookmarklet types (default: tricket-print).
* @param {Integer} [options.env] Represent the environment aka branch name (default: master).
* @param {String} [options.path] Host url path of where the actual resource to be loaded.
*/
(function (options) {
'use strict';
options = options || {};
options.kit = options.kit || 0;
options.env = options.env || 0;
options.path = options.path || '//source.xing.com/xws/jira-helpers/raw/';
var doc = document,
scriptTag = doc.createElement('script'),
environments = ['master', 'develop'],
kits = [
'ticket-print',
'add-ticket',
'ticket-print-lay-scrum',
'add-ticket-lay-scrum'
],
environment = environments[options.env],
kit = kits[options.kit],
url = options.path + environment + '/build/' + kit + '-bookmarklet.js'
;
scriptTag.setAttribute('src', url);
doc.head.appendChild(scriptTag);
})(options);
|
Change interval for populating index for ctags codecomplete | var _ = require("underscore");
var tags = require("./tags");
function setup(options, imports, register) {
var codecomplete = imports.codecomplete;
var workspace = imports.workspace;
// Normalize a tag
var normalizeTag = function(tag) {
return {
'name': tag.name,
'file': tag.file.replace(workspace.root, "")
}
};
// Populate the tags index
var populate = function(options) {
return tags.get(options.root).then(function(_tags) {
return _.map(_tags, normalizeTag);
})
};
// Create codecomplete index
codecomplete.addIndex("ctags", populate, {
interval: 10*60*1000
})
register(null, {});
}
// Exports
module.exports = setup;
| var _ = require("underscore");
var tags = require("./tags");
function setup(options, imports, register) {
var codecomplete = imports.codecomplete;
var workspace = imports.workspace;
// Normalize a tag
var normalizeTag = function(tag) {
return {
'name': tag.name,
'file': tag.file.replace(workspace.root, "")
}
};
// Populate the tags index
var populate = function(options) {
return tags.get(options.root).then(function(_tags) {
return _.map(_tags, normalizeTag);
})
};
// Create codecomplete index
codecomplete.addIndex("ctags", populate)
register(null, {});
}
// Exports
module.exports = setup;
|
Use __module__ to make @lock unique
Summary: Fixes T49428.
Test Plan:
Hard to test on changes_dev because it can't run both handlers (no
place to send notifications to), but this seems simple enough...
Reviewers: armooo, kylec
Reviewed By: kylec
Subscribers: changesbot, mkedia, jukka, vishal
Maniphest Tasks: T49428
Differential Revision: https://tails.corp.dropbox.com/D122408 | from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}:{2}'.format(
func.__module__,
func.__name__,
md5(
'&'.join('{0}={1}'.format(k, repr(v))
for k, v in sorted(kwargs.iteritems()))
).hexdigest()
)
try:
with redis.lock(key, timeout=1, expire=300, nowait=True):
return func(**kwargs)
except UnableToGetLock:
current_app.logger.warn('Unable to get lock for %s', key)
return wrapped
| from flask import current_app
from functools import wraps
from hashlib import md5
from changes.ext.redis import UnableToGetLock
from changes.config import redis
def lock(func):
@wraps(func)
def wrapped(**kwargs):
key = '{0}:{1}'.format(
func.__name__,
md5(
'&'.join('{0}={1}'.format(k, repr(v))
for k, v in sorted(kwargs.iteritems()))
).hexdigest()
)
try:
with redis.lock(key, timeout=1, expire=300, nowait=True):
return func(**kwargs)
except UnableToGetLock:
current_app.logger.warn('Unable to get lock for %s', key)
return wrapped
|
Fix mock test (remove "implicit" usage of previous Dice-setups) | <?php
namespace Friendica\Test\src\Core;
use Dice\Dice;
use Friendica\App\BaseURL;
use Friendica\Core\System;
use Friendica\DI;
use PHPUnit\Framework\TestCase;
class SystemTest extends TestCase
{
protected function setUp()
{
parent::setUp();
$baseUrl = \Mockery::mock(BaseURL::class);
$baseUrl->shouldReceive('getHostname')->andReturn('friendica.local')->once();
$dice = \Mockery::mock(Dice::class);
$dice->shouldReceive('create')->with(BaseURL::class, [])->andReturn($baseUrl);
DI::init($dice);
}
private function assertGuid($guid, $length, $prefix = '')
{
$length -= strlen($prefix);
$this->assertRegExp("/^" . $prefix . "[a-z0-9]{" . $length . "}?$/", $guid);
}
function testGuidWithoutParameter()
{
$guid = System::createGUID();
$this->assertGuid($guid, 16);
}
function testGuidWithSize32() {
$guid = System::createGUID(32);
$this->assertGuid($guid, 32);
}
function testGuidWithSize64() {
$guid = System::createGUID(64);
$this->assertGuid($guid, 64);
}
function testGuidWithPrefix() {
$guid = System::createGUID(23, 'test');
$this->assertGuid($guid, 23, 'test');
}
}
| <?php
namespace Friendica\Test\src\Core;
use Friendica\Core\System;
use PHPUnit\Framework\TestCase;
class SystemTest extends TestCase
{
private function assertGuid($guid, $length, $prefix = '')
{
$length -= strlen($prefix);
$this->assertRegExp("/^" . $prefix . "[a-z0-9]{" . $length . "}?$/", $guid);
}
function testGuidWithoutParameter()
{
$guid = System::createGUID();
$this->assertGuid($guid, 16);
}
function testGuidWithSize32() {
$guid = System::createGUID(32);
$this->assertGuid($guid, 32);
}
function testGuidWithSize64() {
$guid = System::createGUID(64);
$this->assertGuid($guid, 64);
}
function testGuidWithPrefix() {
$guid = System::createGUID(23, 'test');
$this->assertGuid($guid, 23, 'test');
}
}
|
Make the ratelimited error URL follow established conventions. | from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse_lazy
from MyInfo import views as my_info_views
from django_cas import views as cas_views
from oam_base import views as base_views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', my_info_views.index, name='index'),
url(r'^MyInfo/', include('MyInfo.urls', namespace='MyInfo')),
url(r'^AccountPickup/', include('AccountPickup.urls', namespace='AccountPickup')),
url(r'^PasswordReset/', include('PasswordReset.urls', namespace='PasswordReset')),
url(r'^accounts/login/$', cas_views.login, {'next_page': reverse_lazy('AccountPickup:next_step')}, name='CASLogin'),
url(r'^accounts/logout/$', cas_views.logout, name='CASLogout'),
url(r'^error/denied/$', base_views.rate_limited, name='rate_limited'),
url(r'^ajax/', include('ajax.urls')),
url(r'^admin/', include(admin.site.urls)),
)
handler500 = 'oam_base.views.custom_error' | from django.conf.urls import patterns, include, url
from django.core.urlresolvers import reverse_lazy
from MyInfo import views as my_info_views
from django_cas import views as cas_views
from oam_base import views as base_views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', my_info_views.index, name='index'),
url(r'^MyInfo/', include('MyInfo.urls', namespace='MyInfo')),
url(r'^AccountPickup/', include('AccountPickup.urls', namespace='AccountPickup')),
url(r'^PasswordReset/', include('PasswordReset.urls', namespace='PasswordReset')),
url(r'^accounts/login/$', cas_views.login, {'next_page': reverse_lazy('AccountPickup:next_step')}, name='CASLogin'),
url(r'^accounts/logout/$', cas_views.logout, name='CASLogout'),
url(r'^error/denied$', base_views.rate_limited, name='rate_limited'),
url(r'^ajax/', include('ajax.urls')),
url(r'^admin/', include(admin.site.urls)),
)
handler500 = 'oam_base.views.custom_error' |
Add absolute tolerance to allclose test | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_bands():
samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands')
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli,
[
'bands',
'-o', out_file.name,
'-k', os.path.join(samples_dir, 'kpoints.hdf5'),
'-i', os.path.join(samples_dir, 'silicon_model.hdf5')
],
catch_exceptions=False
)
print(run.output)
res = bs.io.load(out_file.name)
reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5'))
np.testing.assert_allclose(bs.compare.difference(res, reference), 0, atol=1e-10)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Dominik Gresch <greschd@gmx.ch>
import os
import pytest
import tempfile
import numpy as np
import bandstructure_utils as bs
from click.testing import CliRunner
import tbmodels
from tbmodels._cli import cli
from parameters import SAMPLES_DIR
def test_cli_bands():
samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands')
runner = CliRunner()
with tempfile.NamedTemporaryFile() as out_file:
run = runner.invoke(
cli,
[
'bands',
'-o', out_file.name,
'-k', os.path.join(samples_dir, 'kpoints.hdf5'),
'-i', os.path.join(samples_dir, 'silicon_model.hdf5')
],
catch_exceptions=False
)
print(run.output)
res = bs.io.load(out_file.name)
reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5'))
np.testing.assert_allclose(bs.compare.difference(res, reference), 0)
|
Extend templates dirs on settings.py | import os
from datetime import datetime
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bottery.conf import settings
@attr.s
class Message:
id = attr.ib()
platform = attr.ib()
user = attr.ib()
chat = attr.ib()
text = attr.ib()
timestamp = attr.ib()
raw = attr.ib()
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context=None):
context = context or {}
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user,
'platform': message.platform,
}
default_context.update(context)
return template.render(**default_context)
| import os
from datetime import datetime
import attr
from jinja2 import Environment, FileSystemLoader, select_autoescape
@attr.s
class Message:
id = attr.ib()
platform = attr.ib()
user = attr.ib()
chat = attr.ib()
text = attr.ib()
timestamp = attr.ib()
raw = attr.ib()
@property
def datetime(self):
return datetime.utcfromtimestamp(self.timestamp)
def render(message, template_name, context={}):
base_dir = os.path.join(os.getcwd(), 'templates')
paths = [base_dir]
# Include paths on settings
# paths.extend(settings.TEMPLATES)
env = Environment(
loader=FileSystemLoader(paths),
autoescape=select_autoescape(['html']))
template = env.get_template(template_name)
default_context = {
'user': message.user,
'platform': message.platform,
}
default_context.update(context)
return template.render(**default_context)
|
Set ISO date as the Sentry release tag | // @flow
import Raven from 'raven-js';
function addUserData(data) {
if (!window.champaign) return;
if (!window.champaign.personalization) return;
const { location, member } = window.champaign.personalization;
data.user = {
id: member ? member.id : undefined,
username: member ? member.name : undefined,
ip: location ? location.ip : undefined,
};
}
function addReduxState(data) {
if (window.champaign && window.champaign.store) {
data.extra = {
...data.extra,
reduxState: window.champaign.store.getState(),
};
}
}
Raven.config(process.env.SENTRY_DSN, {
release: new Date().toISOString(),
environment: process.env.SENTRY_ENVIRONMENT || 'development',
dataCallback: data => {
addUserData(data);
addReduxState(data);
return data;
},
}).install();
window.Raven = Raven;
| // @flow
import Raven from 'raven-js';
function addUserData(data) {
if (!window.champaign) return;
if (!window.champaign.personalization) return;
const { location, member } = window.champaign.personalization;
data.user = {
id: member ? member.id : undefined,
username: member ? member.name : undefined,
ip: location ? location.ip : undefined,
};
}
function addReduxState(data) {
if (window.champaign && window.champaign.store) {
data.extra = {
...data.extra,
reduxState: window.champaign.store.getState(),
};
}
}
Raven.config(process.env.SENTRY_DSN, {
release: process.env.CIRCLE_SHA1,
environment: process.env.SENTRY_ENVIRONMENT || 'development',
dataCallback: data => {
addUserData(data);
addReduxState(data);
return data;
},
}).install();
window.Raven = Raven;
|
Remove uuid in constructor, since strong loop server will see null as value provided, there won't be any defaultFn called. Otherwise you can give uuid "undefined", it's OK. | import CartBlogEditorCtrl from './base/cart-blog-editor.js';
class CartBlogCreateCtrl extends CartBlogEditorCtrl {
constructor(...args) {
super(...args);
this.logInit('CartBlogCreateCtrl');
this.init();
}
init() {
this.apiService.postDefaultCategory().then(
(category) => {
this.category = category;
this.post.category = category.uuid;
},
(error) => this.msgService.error(error)
);
this.tags = [];
this.attachments = [];
this.post = {
uuid: undefined, // have to be "undefined" to make stongloop server recognize this property shall apply defaultFn
driveId: null,
title: '',
created: new Date(),
updated: new Date(),
category: null,
tags: [],
attachments: [],
isPublic: this.apiService.postDefaultPrivacy()
}
}
//noinspection ES6Validation
async save() {
try {
//noinspection ES6Validation
let post = await this.apiService.postUpsert(this.post);
this.msgService.info('Post saved: ', post);
} catch (e) {
this.msgService.error('Error when creating post: ', e.data.error.message);
}
}
}
CartBlogCreateCtrl.$inject = [...CartBlogEditorCtrl.$inject];
export default CartBlogCreateCtrl;
| import CartBlogEditorCtrl from './base/cart-blog-editor.js';
class CartBlogCreateCtrl extends CartBlogEditorCtrl {
constructor(...args) {
super(...args);
this.logInit('CartBlogCreateCtrl');
this.init();
}
init() {
this.apiService.postDefaultCategory().then(
(category) => {
this.category = category;
this.post.category = category.uuid;
},
(error) => this.msgService.error(error)
);
this.tags = [];
this.attachments = [];
this.post = {
driveId: null,
title: '',
created: new Date(),
updated: new Date(),
category: null,
tags: [],
attachments: [],
isPublic: this.apiService.postDefaultPrivacy()
}
}
//noinspection ES6Validation
async save() {
try {
//noinspection ES6Validation
let post = await this.apiService.postUpsert(this.post);
this.msgService.info('Post saved: ', post);
} catch (e) {
this.msgService.error('Error when creating post: ', e.data.error.message);
}
}
}
CartBlogCreateCtrl.$inject = [...CartBlogEditorCtrl.$inject];
export default CartBlogCreateCtrl;
|
Use transform instead of embed | #!/usr/bin/env python
data = '../data/fm_train_real.dat'
parameter_list = [[data, 20]]
def converter_stochasticproximityembedding (data_fname, k):
try:
from shogun import RealFeatures,StochasticProximityEmbedding, SPE_GLOBAL, SPE_LOCAL, CSVFile
features = RealFeatures(CSVFile(data_fname))
converter = StochasticProximityEmbedding()
converter.set_target_dim(1)
converter.set_nupdates(40)
# Embed with local strategy
converter.set_k(k)
converter.set_strategy(SPE_LOCAL)
features = converter.transform(features)
# Embed with global strategy
converter.set_strategy(SPE_GLOBAL)
features = converter.transform(features)
return features
except ImportError:
print('No Eigen3 available')
if __name__=='__main__':
print('StochasticProximityEmbedding')
converter_stochasticproximityembedding(*parameter_list[0])
| #!/usr/bin/env python
data = '../data/fm_train_real.dat'
parameter_list = [[data, 20]]
def converter_stochasticproximityembedding (data_fname, k):
try:
from shogun import RealFeatures,StochasticProximityEmbedding, SPE_GLOBAL, SPE_LOCAL, CSVFile
features = RealFeatures(CSVFile(data_fname))
converter = StochasticProximityEmbedding()
converter.set_target_dim(1)
converter.set_nupdates(40)
# Embed with local strategy
converter.set_k(k)
converter.set_strategy(SPE_LOCAL)
converter.embed(features)
# Embed with global strategy
converter.set_strategy(SPE_GLOBAL)
converter.embed(features)
return features
except ImportError:
print('No Eigen3 available')
if __name__=='__main__':
print('StochasticProximityEmbedding')
converter_stochasticproximityembedding(*parameter_list[0])
|
Add more time to mqtt.test.client | import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTT1(MQTTTestCase):
def test(self):
import sys
from django.core.management.base import OutputWrapper
from django.core.management.color import color_style, no_style
# seed
from django.core import management
management.call_command('mqttseed',
verbosity=1)
print('>> Processing messages...')
self.assertEqual(True, True)
class TestMQTT2(MQTTTestCase):
def test(self):
self.assertEqual(True, True)
| import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTT1(MQTTTestCase):
def test(self):
self.assertEqual(True, True)
class TestMQTT2(MQTTTestCase):
def test(self):
self.assertEqual(True, True)
|
Fix composer helper and comment it
Former-commit-id: 0691b49f1e795659a2b37e7e1b34f9625bd1e952 | <?php
namespace Concrete\Core\Application\Service;
use Concrete\Core\Page\Type\Type;
use PageType;
use \Concrete\Core\Http\ResponseAssetGroup;
use \Concrete\Core\Page\Type\Composer\Control\Control as PageTypeComposerControl;
use Loader;
class Composer {
/**
* @param Type $pagetype
* @param bool|\Page $page
*/
public function display(Type $pagetype, $page = false) {
$pagetype->renderComposerOutputForm($page);
}
/**
* @param PageType $pagetype
* @param bool|\Page $page
*/
public function displayButtons(PageType $pagetype, $page = false) {
Loader::element('page_types/composer/form/output/buttons', array(
'pagetype' => $pagetype,
'page' => $page
));
}
/**
* @param PageType $pt
* @param \Controller $cnt
*/
public function addAssetsToRequest(PageType $pt, \Controller $cnt) {
$list = PageTypeComposerControl::getList($pt);
foreach($list as $l) {
$l->addAssetsToRequest($cnt);
}
}
}
| <?php
namespace Concrete\Core\Application\Service;
use Concrete\Core\Page\Type\Type;
use PageType;
use \Concrete\Core\Http\ResponseAssetGroup;
use \Concrete\Core\Page\Type\Composer\Control as PageTypeComposerControl;
use Loader;
class Composer {
public function display(Type $pagetype, $page = false) {
$pagetype->renderComposerOutputForm($page);
}
public function displayButtons(PageType $pagetype, $page = false) {
Loader::element('page_types/composer/form/output/buttons', array(
'pagetype' => $pagetype,
'page' => $page
));
}
public function addAssetsToRequest(PageType $pt, Controller $cnt) {
$list = PageTypeComposerControl::getList($pt);
foreach($list as $l) {
$l->addAssetsToRequest($cnt);
}
}
}
|
Move slice variable assignment out of loop | var isPatched = false;
var slice = Array.prototype.slice;
if (isPatched) return console.log('already patched');
function addColor(string, name) {
var colors = {
green: ['\x1B[32m', '\x1B[39m'],
red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
yellow: ['\x1B[33m', '\x1B[39m']
}
return colors[name][0] + string + colors[name][1];
}
function getColorName(methodName) {
switch (methodName) {
case 'error': return 'red';
case 'warn': return 'yellow';
default: return 'green';
}
}
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';
console[method] = function() {
var date = (new Date()).toISOString();
var args = slice.call(arguments);
if (process[output].isTTY)
messageType = addColor(messageType, color);
process[output].write('[' + date + '] ' + messageType + ' ');
return baseConsoleMethod.apply(console, args);
}
});
isPatched = true;
| var isPatched = false;
if (isPatched) return console.log('already patched');
function addColor(string, name) {
var colors = {
green: ['\x1B[32m', '\x1B[39m'],
red: ['\x1B[1m\x1B[31m', '\x1B[39m\x1B[22m'],
yellow: ['\x1B[33m', '\x1B[39m']
}
return colors[name][0] + string + colors[name][1];
}
function getColorName(methodName) {
switch (methodName) {
case 'error': return 'red';
case 'warn': return 'yellow';
default: return 'green';
}
}
['log', 'info', 'warn', 'error', 'dir', 'assert'].forEach(function(method) {
var baseConsoleMethod = console[method];
var slice = Array.prototype.slice;
var color = getColorName(method);
var messageType = method.toUpperCase();
var output = method === 'warn' || method === 'error' ? 'stderr' : 'stdout';
console[method] = function() {
var date = (new Date()).toISOString();
var args = slice.call(arguments);
if (process[output].isTTY)
messageType = addColor(messageType, color);
process[output].write('[' + date + '] ' + messageType + ' ');
return baseConsoleMethod.apply(console, args);
}
});
isPatched = true;
|
browse: Use correct Django HTML template for default view | # Copyright (C) 2017-2018 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from django.conf.urls import url
from django.shortcuts import render
import swh.web.browse.views.directory # noqa
import swh.web.browse.views.content # noqa
import swh.web.browse.views.identifiers # noqa
import swh.web.browse.views.origin # noqa
import swh.web.browse.views.person # noqa
import swh.web.browse.views.release # noqa
import swh.web.browse.views.revision # noqa
import swh.web.browse.views.snapshot # noqa
from swh.web.browse.browseurls import BrowseUrls
def default_browse_view(request):
"""Default django view used as an entry point
for the swh browse ui web application.
The url that point to it is /browse/.
Args:
request: input django http request
"""
return render(request, 'browse.html',
{'heading': 'Browse the Software Heritage archive',
'empty_browse': True})
urlpatterns = [
url(r'^$', default_browse_view, name='browse-homepage')
]
urlpatterns += BrowseUrls.get_url_patterns()
| # Copyright (C) 2017-2018 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU Affero General Public License version 3, or any later version
# See top-level LICENSE file for more information
from django.conf.urls import url
from django.shortcuts import render
import swh.web.browse.views.directory # noqa
import swh.web.browse.views.content # noqa
import swh.web.browse.views.identifiers # noqa
import swh.web.browse.views.origin # noqa
import swh.web.browse.views.person # noqa
import swh.web.browse.views.release # noqa
import swh.web.browse.views.revision # noqa
import swh.web.browse.views.snapshot # noqa
from swh.web.browse.browseurls import BrowseUrls
def default_browse_view(request):
"""Default django view used as an entry point
for the swh browse ui web application.
The url that point to it is /browse/.
Args:
request: input django http request
"""
return render(request, 'person.html',
{'heading': 'Browse the Software Heritage archive',
'empty_browse': True})
urlpatterns = [
url(r'^$', default_browse_view, name='browse-homepage')
]
urlpatterns += BrowseUrls.get_url_patterns()
|
Fix NPE upon exiting Eclipse coming from the Menus. | package org.strategoxt.imp.runtime.services.menus;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.swt.widgets.Display;
/**
* @author Oskar van Rest
*/
public class MenuEnabledTester extends PropertyTester {
private int menuIndex = -1;
@Override
public synchronized boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
menuIndex = (menuIndex + 1) % MenusServiceConstants.NO_OF_TOOLBAR_MENUS;
// Refresh toolbar menus after switching between two Spoofax editors.
if (menuIndex == MenusServiceConstants.NO_OF_TOOLBAR_MENUS - 1) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MenusServiceUtil.refreshToolbarMenuCommands();
}
});
}
MenuList menus = MenusServiceUtil.getMenus();
return menus != null && menus.getAll().size() > menuIndex;
}
}
| package org.strategoxt.imp.runtime.services.menus;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.swt.widgets.Display;
/**
* @author Oskar van Rest
*/
public class MenuEnabledTester extends PropertyTester {
private int menuIndex = -1;
@Override
public synchronized boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
menuIndex = (menuIndex + 1) % MenusServiceConstants.NO_OF_TOOLBAR_MENUS;
// Refresh toolbar menus after switching between two Spoofax editors.
if (menuIndex == MenusServiceConstants.NO_OF_TOOLBAR_MENUS - 1) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MenusServiceUtil.refreshToolbarMenuCommands();
}
});
}
return MenusServiceUtil.getMenus().getAll().size() > menuIndex;
}
}
|
CSPACE-210: Add new singleton for Intake resource | package org.collectionspace.services.jaxrs;
import org.collectionspace.services.CollectionObjectResource;
import org.collectionspace.services.IntakeResource;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class CollectionSpaceJaxRsApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public CollectionSpaceJaxRsApplication() {
singletons.add(new CollectionObjectResource());
singletons.add(new IntakeResource());
// singletons.add(new DomainIdentifierResource());
// singletons.add(new PingResource());
}
@Override
public Set<Class<?>> getClasses() {
return empty;
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
| package org.collectionspace.services.jaxrs;
import org.collectionspace.services.CollectionObjectResource;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
public class CollectionSpaceJaxRsApplication extends Application {
private Set<Object> singletons = new HashSet<Object>();
private Set<Class<?>> empty = new HashSet<Class<?>>();
public CollectionSpaceJaxRsApplication() {
singletons.add(new CollectionObjectResource());
// singletons.add(new DomainIdentifierResource());
// singletons.add(new PingResource());
}
@Override
public Set<Class<?>> getClasses() {
return empty;
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
|
Change to require_once so we dont have duplicate function errors. | <?php
# tocsv.php - OSDial
#
# Copyright (C) 2010 Lott Caskey <lottcaskey@gmail.com> LICENSE: AGPLv3
#
# This file is part of OSDial.
#
# OSDial 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.
#
# OSDial 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 OSDial. If not, see <http://www.gnu.org/licenses/>.
#
#
#
# Includes
require_once("include/dbconnect.php");
require_once("include/functions.php");
$mimetype = get_variable("mimetype");
$filename = get_variable("filename");
$download = get_variable('download');
if ($download=='') {
$download='inline';
} else {
$download='attachment';
}
if ($filename!='' and $mimetype!='') {
header("Content-type: $mimetype; charset=utf-8");
header("Content-Disposition: $download; filename=\"$filename\"");
echo media_get_filedata($link,$filename);
}
?>
| <?php
# tocsv.php - OSDial
#
# Copyright (C) 2010 Lott Caskey <lottcaskey@gmail.com> LICENSE: AGPLv3
#
# This file is part of OSDial.
#
# OSDial 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.
#
# OSDial 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 OSDial. If not, see <http://www.gnu.org/licenses/>.
#
#
#
# Includes
require("include/dbconnect.php");
require("include/functions.php");
$mimetype = get_variable("mimetype");
$filename = get_variable("filename");
$download = get_variable('download');
if ($download=='') {
$download='inline';
} else {
$download='attachment';
}
if ($filename!='' and $mimetype!='') {
header("Content-type: $mimetype; charset=utf-8");
header("Content-Disposition: $download; filename=\"$filename\"");
echo media_get_filedata($link,$filename);
}
?>
|
Fix the bug of initializing the active plugin array. | <?php
/**
* Class Google\Site_Kit\Modules\Analytics\Plugin_Detector
*
* @package Google\Site_Kit\Modules\Analytics
* @copyright 2019 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Modules\Analytics;
/**
* Detects the user's current active plugins that ShirshuClass supports
*
* Class Plugin_Detector
*/
class Plugin_Detector {
/**
* A list of Shirshu_Class supported plugins
*
* @var array
*/
private $supported_plugins = array();
/**
* Plugin_Detector constructor.
*
* @param array $supported_plugins list of supported plugins.
*/
public function __construct( $supported_plugins ) {
$this->supported_plugins = $supported_plugins;
}
/**
* Determines the user's current active plugins that Shirshu_Class supports
*
* @return array
*/
public function get_active_plugins() {
$active_plugins = array();
foreach ( $this->supported_plugins as $key => $function_name ) {
if ( defined( $function_name ) || function_exists( $function_name ) ) {
array_push( $active_plugins, $key);
}
}
return $active_plugins;
}
}
| <?php
/**
* Class Google\Site_Kit\Modules\Analytics\Plugin_Detector
*
* @package Google\Site_Kit\Modules\Analytics
* @copyright 2019 Google LLC
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
* @link https://sitekit.withgoogle.com
*/
namespace Google\Site_Kit\Modules\Analytics;
/**
* Detects the user's current active plugins that ShirshuClass supports
*
* Class Plugin_Detector
*/
class Plugin_Detector {
/**
* A list of Shirshu_Class supported plugins
*
* @var array
*/
private $supported_plugins = array();
/**
* Plugin_Detector constructor.
*
* @param array $supported_plugins list of supported plugins.
*/
public function __construct( $supported_plugins ) {
$this->supported_plugins = $supported_plugins;
}
/**
* Determines the user's current active plugins that Shirshu_Class supports
*
* @return array
*/
public function get_active_plugins() {
foreach ( $this->supported_plugins as $key => $function_name ) {
if ( defined( $function_name ) || function_exists( $function_name ) ) {
array_push( $active_plugins, $key );
}
}
return $active_plugins;
}
}
|
Use receive api to deliver event | #!/usr/bin/env node
// Usage: bin/simulate issues path/to/payload plugin.js
require('dotenv').config({silent: true});
const process = require('process');
const path = require('path');
const eventName = process.argv[2];
const payloadPath = process.argv[3];
const pluginPath = process.argv[4];
if (!eventName || !payloadPath) {
console.log('Usage: bin/probot-simulate event-name path/to/payload.json');
process.exit(1);
}
const payload = require(path.join(process.cwd(), payloadPath));
const createProbot = require('../');
const {findPrivateKey} = require('../lib/private-key');
const probot = createProbot({
id: process.env.INTEGRATION_ID,
secret: process.env.WEBHOOK_SECRET,
cert: findPrivateKey(),
port: process.env.PORT
});
const plugins = require('../lib/plugin')(probot);
plugins.load([pluginPath]);
probot.robot.log('Simulating event', eventName);
probot.receive({event: eventName, payload});
| #!/usr/bin/env node
// Usage: bin/simulate issues path/to/payload plugin.js
require('dotenv').config({silent: true});
const process = require('process');
const path = require('path');
const eventName = process.argv[2];
const payloadPath = process.argv[3];
const pluginPath = process.argv[4];
if (!eventName || !payloadPath) {
console.log('Usage: bin/probot-simulate event-name path/to/payload.json');
process.exit(1);
}
const payload = require(path.join(process.cwd(), payloadPath));
const createProbot = require('../');
const {findPrivateKey} = require('../lib/private-key');
const probot = createProbot({
id: process.env.INTEGRATION_ID,
secret: process.env.WEBHOOK_SECRET,
cert: findPrivateKey(),
port: process.env.PORT
});
const plugins = require('../lib/plugin')(probot);
plugins.load([pluginPath]);
probot.robot.log('Simulating event', eventName);
probot.robot.webhook.emit(eventName, {event: eventName, payload});
|
tests: Fix test that uses classList (which is IE >= 10). | 'use strict';
import registry from '../../src/registry';
import skate from '../../src/skate';
describe('Registry', function () {
afterEach(function () {
registry.clear();
});
it('should set definitions', function () {
registry.set('test', {});
try {
registry.set('test', {});
assert(false);
} catch (e) {}
});
it('should clear definitions', function () {
registry.set('test', {});
registry.clear();
registry.set('test', {});
});
it('should return definitions for a given element', function () {
var definition1 = { type: skate.type.ELEMENT };
var definition2 = { type: skate.type.ATTRIBUTE };
var definition3 = { type: skate.type.CLASSNAME };
var definitions;
var element = document.createElement('test1');
element.setAttribute('test2', '');
element.className += ' test3';
registry.set('test1', definition1);
registry.set('test2', definition2);
registry.set('test3', definition3);
definitions = registry.getForElement(element);
expect(definitions.length).to.equal(3);
expect(definitions[0]).to.equal(definition1);
expect(definitions[1]).to.equal(definition2);
expect(definitions[2]).to.equal(definition3);
});
});
| 'use strict';
import registry from '../../src/registry';
import skate from '../../src/skate';
describe('Registry', function () {
afterEach(function () {
registry.clear();
});
it('should set definitions', function () {
registry.set('test', {});
try {
registry.set('test', {});
assert(false);
} catch (e) {}
});
it('should clear definitions', function () {
registry.set('test', {});
registry.clear();
registry.set('test', {});
});
it('should return definitions for a given element', function () {
var definition1 = { type: skate.type.ELEMENT };
var definition2 = { type: skate.type.ATTRIBUTE };
var definition3 = { type: skate.type.CLASSNAME };
var definitions;
var element = document.createElement('test1');
element.setAttribute('test2', '');
element.classList.add('test3');
registry.set('test1', definition1);
registry.set('test2', definition2);
registry.set('test3', definition3);
definitions = registry.getForElement(element);
expect(definitions.length).to.equal(3);
expect(definitions[0]).to.equal(definition1);
expect(definitions[1]).to.equal(definition2);
expect(definitions[2]).to.equal(definition3);
});
});
|
Fix config if no list sort defined | <?php
namespace AlterPHP\EasyAdminExtensionBundle\Configuration;
use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigPassInterface;
/**
* Initializes the configuration for all the views of each entity, which is
* needed when some entity relies on the default configuration for some view.
*/
class EmbeddedListSortConfigPass implements ConfigPassInterface
{
public function process(array $backendConfig)
{
$backendConfig = $this->processSortingConfig($backendConfig);
return $backendConfig;
}
/**
* @param array $backendConfig
*
* @return array
*/
private function processSortingConfig(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
if (
!isset($entityConfig['embeddedList']['sort'])
&& isset($entityConfig['list']['sort'])
) {
$backendConfig['entities'][$entityName]['embeddedList']['sort'] = $entityConfig['list']['sort'];
}
}
return $backendConfig;
}
}
| <?php
namespace AlterPHP\EasyAdminExtensionBundle\Configuration;
use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigPassInterface;
/**
* Initializes the configuration for all the views of each entity, which is
* needed when some entity relies on the default configuration for some view.
*/
class EmbeddedListSortConfigPass implements ConfigPassInterface
{
public function process(array $backendConfig)
{
$backendConfig = $this->processSortingConfig($backendConfig);
return $backendConfig;
}
/**
* @param array $backendConfig
*
* @return array
*/
private function processSortingConfig(array $backendConfig)
{
foreach ($backendConfig['entities'] as $entityName => $entityConfig) {
if (!isset($entityConfig['embeddedList']['sort'])) {
$backendConfig['entities'][$entityName]['embeddedList']['sort'] = $entityConfig['list']['sort'];
}
}
return $backendConfig;
}
}
|
Remove auto include of numpy namespace.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@1522 d6536bca-fef9-0310-8506-e4c0a848fbcf | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is also available in the docstrings.
Available subpackages
---------------------
"""
import os, sys
SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0'))
try:
import pkg_resources # activate namespace packages (manipulates __path__)
except ImportError:
pass
import numpy._import_tools as _ni
pkgload = _ni.PackageLoader()
del _ni
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test')
from version import version as __version__
from numpy import __version__ as __numpy_version__
__all__.append('__version__')
__all__.append('__numpy_version__')
from __config__ import show as show_config
pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
| """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is also available in the docstrings.
Available subpackages
---------------------
"""
import os, sys
SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0'))
try:
import pkg_resources # activate namespace packages (manipulates __path__)
except ImportError:
pass
import numpy._import_tools as _ni
pkgload = _ni.PackageLoader()
del _ni
from numpy import *
del fft, ifft, info
import numpy
__all__.extend(filter(lambda x: x not in ['fft','ifft','info'], numpy.__all__))
del numpy
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test')
from version import version as __version__
from numpy import __version__ as __numpy_version__
__all__.append('__version__')
__all__.append('__numpy_version__')
from __config__ import show as show_config
pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
|
Add error parameter to forbidden interceptor | /**
* 403 Forbidden Network Error Interceptor
*
* This interceptor redirects to login page when
* any 403 session expired error is returned in any of the
* network requests
*/
var LOGIN_ROUTE = '/login?error=session_expired';
var SESSION_EXPIRED = 'session_expired';
var subdomainMatch = /https?:\/\/([^.]+)/;
module.exports = function (xhr, textStatus, errorThrown) {
if (xhr.status !== 403) return;
var error = xhr.responseJSON && xhr.responseJSON.error;
if (error === SESSION_EXPIRED) {
window.location.href = getRedirectURL();
}
};
function getRedirectURL () {
// We cannot get accountHost and username from configModel
// and userModel because of static pages. God save static pages.
var username = getUsernameFromURL(location.href);
if (!username) {
return '';
}
var newURL = location.origin.replace(subdomainMatch, function () {
return username;
});
return location.protocol + '//' + newURL + LOGIN_ROUTE;
}
function getUsernameFromURL (url) {
var usernameMatches = window.location.pathname.split('/');
if (usernameMatches.length > 2) {
return usernameMatches[2];
}
var subdomainMatches = url.match(subdomainMatch);
if (subdomainMatches) {
return subdomainMatches[1];
}
return '';
}
| /**
* 403 Forbidden Network Error Interceptor
*
* This interceptor redirects to login page when
* any 403 session expired error is returned in any of the
* network requests
*/
var LOGIN_ROUTE = '/login';
var SESSION_EXPIRED = 'session_expired';
var subdomainMatch = /https?:\/\/([^.]+)/;
module.exports = function (xhr, textStatus, errorThrown) {
if (xhr.status !== 403) return;
var error = xhr.responseJSON && xhr.responseJSON.error;
if (error === SESSION_EXPIRED) {
window.location.href = getRedirectURL();
}
};
function getRedirectURL () {
// We cannot get accountHost and username from configModel
// and userModel because of static pages. God save static pages.
var username = getUsernameFromURL(location.href);
if (!username) {
return '';
}
var newURL = location.origin.replace(subdomainMatch, function () {
return username;
});
return location.protocol + '//' + newURL + LOGIN_ROUTE;
}
function getUsernameFromURL (url) {
var usernameMatches = window.location.pathname.split('/');
if (usernameMatches.length > 2) {
return usernameMatches[2];
}
var subdomainMatches = url.match(subdomainMatch);
if (subdomainMatches) {
return subdomainMatches[1];
}
return '';
}
|
Throw an error on var declaration | module.exports = {
'extends': [
'eslint:recommended'
],
'rules': {
'indent': [2, 2, {
'SwitchCase': 1
}],
'arrow-spacing': [2, {
'before': true, 'after': true
}],
'quotes': [2, 'single'],
'semi': [2, 'always'],
'no-console': [0],
'no-var': 2,
'prefer-template': 2,
'no-useless-concat': 2,
'space-before-function-paren': [2, 'never'],
'object-curly-spacing': [2, 'always'],
'array-bracket-spacing': [2, 'never'],
'comma-spacing': [2, {
'before': false,
'after': true
}],
'space-infix-ops': 2,
'space-unary-ops': [2, {
'words': true,
'nonwords': false
}],
'space-in-parens': [2, 'never'],
'keyword-spacing': 2,
'no-unused-vars': [1, {
'args': 'none',
'vars': 'all',
'varsIgnorePattern': 'React'
}],
'default-case': 2
},
'ecmaFeatures': {
'modules': true
},
'env': {
'es6': true,
'node': true,
'browser': true
}
};
| module.exports = {
'extends': [
'eslint:recommended'
],
'rules': {
'indent': [2, 2, {
'SwitchCase': 1
}],
'arrow-spacing': [2, {
'before': true, 'after': true
}],
'quotes': [2, 'single'],
'semi': [2, 'always'],
'no-console': [0],
'no-var': 1,
'prefer-template': 2,
'no-useless-concat': 2,
'space-before-function-paren': [2, 'never'],
'object-curly-spacing': [2, 'always'],
'array-bracket-spacing': [2, 'never'],
'comma-spacing': [2, {
'before': false,
'after': true
}],
'space-infix-ops': 2,
'space-unary-ops': [2, {
'words': true,
'nonwords': false
}],
'space-in-parens': [2, 'never'],
'keyword-spacing': 2,
'no-unused-vars': [1, {
'args': 'none',
'vars': 'all',
'varsIgnorePattern': 'React'
}],
'default-case': 2
},
'ecmaFeatures': {
'modules': true
},
'env': {
'es6': true,
'node': true,
'browser': true
}
};
|
Add origin to option setting failure | 'use strict'
var jsYAML = require('js-yaml')
module.exports = yamlConfig
var origin = 'remark-yaml-config:invalid-options'
// Modify remark to read configuration from comments.
function yamlConfig() {
var Parser = this.Parser
var Compiler = this.Compiler
var parser = Parser && Parser.prototype.blockTokenizers
var compiler = Compiler && Compiler.prototype.visitors
if (parser && parser.yamlFrontMatter) {
parser.yamlFrontMatter = factory(parser.yamlFrontMatter)
}
if (compiler && compiler.yaml) {
compiler.yaml = factory(compiler.yaml)
}
}
// Wrapper factory.
function factory(original) {
replacement.locator = original.locator
return replacement
// Replacer for tokeniser or visitor.
function replacement(node) {
var self = this
var result = original.apply(self, arguments)
var marker = result && result.type ? result : node
var data
try {
data = jsYAML.safeLoad(marker.value)
data = data && data.remark
if (data) {
self.setOptions(data)
}
} catch (error) {
self.file.fail(error.message, marker, origin)
}
return result
}
}
| 'use strict'
var jsYAML = require('js-yaml')
module.exports = yamlConfig
// Modify remark to read configuration from comments.
function yamlConfig() {
var Parser = this.Parser
var Compiler = this.Compiler
var parser = Parser && Parser.prototype.blockTokenizers
var compiler = Compiler && Compiler.prototype.visitors
if (parser && parser.yamlFrontMatter) {
parser.yamlFrontMatter = factory(parser.yamlFrontMatter)
}
if (compiler && compiler.yaml) {
compiler.yaml = factory(compiler.yaml)
}
}
// Wrapper factory.
function factory(original) {
replacement.locator = original.locator
return replacement
// Replacer for tokeniser or visitor.
function replacement(node) {
var self = this
var result = original.apply(self, arguments)
var marker = result && result.type ? result : node
var data
try {
data = jsYAML.safeLoad(marker.value)
data = data && data.remark
if (data) {
self.setOptions(data)
}
} catch (error) {
self.file.fail(error.message, marker)
}
return result
}
}
|
Modify ffmpeg path heroku 2 | # Retrieve file from Facebook
import urllib, convert, re, os
# from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve(audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
| # Retrieve file from Facebook
import urllib, convert, re, os
# from speech_py import speech_to_text_offline as STT_o
# from speech_py import speech_to_text_google as STT
from speech_py import speech_to_text_ibm_rest as STT
def transcribe(audio_url):
if not os.path.isdir('./audio/retrieved_audio'):
os.makedirs('./audio/retrieved_audio')
reg_ex = '\w+.mp4'
file_name = re.search(reg_ex, audio_url).group(0)
urllib.urlretrieve (audio_url, './audio/retrieved_audio/{}'.format(file_name))
convert.convert('./audio/retrieved_audio/{}'.format(file_name))
# Converted in: ./converted/{name}.wav
return STT('./audio/converted/{}'.format(file_name[:-4]+".wav"))
|
Use body property of Notification
Instead of the non-existing content property. | // Main process
'use strict';
const path = require('path');
const app = require('app');
const ipcMain = require('electron').ipcMain;
const BrowserWindow = require('browser-window');
app.on('ready', () => {
const win = new BrowserWindow({
webPreferences: {
// Load `electron-notification-shim` in rendering view.
preload: path.join(__dirname, 'browser.js')
}
});
// Listen for notification events.
ipcMain.on('notification-shim', (e, msg) => {
console.log(`Title: ${msg.title}, Body: ${msg.options.body}`);
});
// Just to test. Don't do this at home, kids. :)
win.loadURL(`https://google.com`);
win.webContents.on('did-finish-load', () => {
win.webContents.executeJavaScript('new Notification("Hello!", {body: "Notification world!"})');
});
});
| // Main process
'use strict';
const path = require('path');
const app = require('app');
const ipcMain = require('electron').ipcMain;
const BrowserWindow = require('browser-window');
app.on('ready', () => {
const win = new BrowserWindow({
webPreferences: {
// Load `electron-notification-shim` in rendering view.
preload: path.join(__dirname, 'browser.js')
}
});
// Listen for notification events.
ipcMain.on('notification-shim', (e, msg) => {
console.log(`Title: ${msg.title}, Content: ${msg.options.content}`);
});
// Just to test. Don't do this at home, kids. :)
win.loadURL(`https://google.com`);
win.webContents.on('did-finish-load', () => {
win.webContents.executeJavaScript('new Notification("Hello!", {content: "Notification world!"})');
});
});
|
Rename class to sync with new file name. | import subprocess
import sys
import unittest
from django.conf import settings
#
# Must configure settings before importing base.
#
db = 'testdjangodb1'
schema = 'django1'
user = 'django1'
passwd = 'django1'
settings.configure(
DEBUG=True,
DATABASE_NAME=db,
DATABASE_USER=user,
DATABASE_PASSWORD=passwd
)
sys.path.append('../')
import base
class TestMonetDjango(unittest.TestCase):
def setUp(self):
cmd = './createdb.sh "%s" "%s" "%s" "%s"' % \
(db, user, passwd, schema)
try:
rc = subprocess.call(cmd, shell=True)
if rc == 0:
pass # normal
elif rc < 0:
self.fail("Child was terminated by signal %s" \
% (-rc,))
else:
self.fail("Child returned error code %s" \
% (rc,))
except OSError, e:
self.fail("Execution failed:", e)
def tearDown(self):
# XXX: delete database created in setup.
pass
def testcreate(self):
w = base.DatabaseWrapper({})
c = w.cursor()
self.failUnless(c)
if __name__ == '__main__':
unittest.main()
| import subprocess
import sys
import unittest
from django.conf import settings
#
# Must configure settings before importing base.
#
db = 'testdjangodb1'
schema = 'django1'
user = 'django1'
passwd = 'django1'
settings.configure(
DEBUG=True,
DATABASE_NAME=db,
DATABASE_USER=user,
DATABASE_PASSWORD=passwd
)
sys.path.append('../')
import base
class TestCursor(unittest.TestCase):
def setUp(self):
cmd = './createdb.sh "%s" "%s" "%s" "%s"' % \
(db, user, passwd, schema)
try:
rc = subprocess.call(cmd, shell=True)
if rc == 0:
pass # normal
elif rc < 0:
self.fail("Child was terminated by signal %s" \
% (-rc,))
else:
self.fail("Child returned error code %s" \
% (rc,))
except OSError, e:
self.fail("Execution failed:", e)
def tearDown(self):
# XXX: delete database created in setup.
pass
def testcreate(self):
w = base.DatabaseWrapper({})
c = w.cursor()
self.failUnless(c)
if __name__ == '__main__':
unittest.main()
|
Remove override of createJSModules (RN 0.47 compatibility)
The current release for React Native 0.47 has removed the createJSModules method in ReactPackage. Therefore any overrides of this method will need to be removed from the library, or this will cause a compilation error.
See: 75fd2ec54dffad8326e8bf9a8dcacfb223b624c2@ce6fb33
Commit ripped from https://github.com/oblador/react-native-vector-icons/pull/516 |
package io.rumors.reactnativesettings;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNSettingsPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNSettingsModule(reactContext));
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
package io.rumors.reactnativesettings;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNSettingsPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNSettingsModule(reactContext));
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
Support for startMock mode in getData | 'use strict'
/**
* Sample API controller. Can safely be removed.
*/
const Sample = require('../models').sample.Sample
const co = require('co')
module.exports = {
getData: co.wrap(getData),
postData: co.wrap(postData)
}
function * getData (req, res, next) {
try {
let doc = {}
if (process.env.NODE_MOCK) {
doc = yield {_id: 0, name: 'mockdata'}
} else {
doc = yield Sample.findById(req.params.id)
}
if (!doc) {
return next()
}
res.json({ id: doc._id, name: doc.name })
} catch (err) {
next(err)
}
}
function * postData (req, res, next) {
try {
let doc = yield Sample.findById(req.params.id)
if (!doc) {
doc = new Sample({
_id: req.params.id,
name: req.body.name
})
} else {
doc.name = req.body.name
}
yield doc.save()
res.json({ id: doc._id, name: doc.name })
} catch (err) {
next(err)
}
}
| 'use strict'
/**
* Sample API controller. Can safely be removed.
*/
const Sample = require('../models').sample.Sample
const co = require('co')
module.exports = {
getData: co.wrap(getData),
postData: co.wrap(postData)
}
function * getData (req, res, next) {
try {
const doc = yield Sample.findById(req.params.id)
if (!doc) {
return next()
}
res.json({ id: doc._id, name: doc.name })
} catch (err) {
next(err)
}
}
function * postData (req, res, next) {
try {
let doc = yield Sample.findById(req.params.id)
if (!doc) {
doc = new Sample({
_id: req.params.id,
name: req.body.name
})
} else {
doc.name = req.body.name
}
yield doc.save()
res.json({ id: doc._id, name: doc.name })
} catch (err) {
next(err)
}
}
|
Update meteor version to 1.4.1, bump version to 0.3.2 | Package.describe({
name: 'metemq:metemq',
version: '0.3.2',
// Brief, one-line summary of the package.
summary: 'MeteMQ',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Npm.depends({
'mqtt': '1.12.0',
'mqtt-emitter': '1.2.4',
'mosca': '2.0.2', // For testing
'portfinder': '1.0.3',
'metemq-broker': '0.0.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.4.1');
api.use('underscore@1.0.8');
api.use('accounts-password'); // For checking password
api.use('barbatus:typescript@0.4.0');
api.mainModule('client/index.ts', 'client');
api.mainModule('server/index.ts', 'server');
});
Package.onTest(function(api) {
api.use('metemq:metemq');
api.use('barbatus:typescript@0.4.0');
api.use(['practicalmeteor:mocha', 'practicalmeteor:chai']);
api.mainModule('test/index.ts');
});
| Package.describe({
name: 'metemq:metemq',
version: '0.3.1',
// Brief, one-line summary of the package.
summary: 'MeteMQ',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Npm.depends({
'mqtt': '1.12.0',
'mqtt-emitter': '1.2.4',
'mosca': '2.0.2', // For testing
'portfinder': '1.0.3',
'metemq-broker': '0.0.1'
});
Package.onUse(function(api) {
api.versionsFrom('1.4');
api.use('underscore@1.0.8');
api.use('accounts-password'); // For checking password
api.use('barbatus:typescript@0.4.0');
api.mainModule('client/index.ts', 'client');
api.mainModule('server/index.ts', 'server');
});
Package.onTest(function(api) {
api.use('metemq:metemq');
api.use('barbatus:typescript@0.4.0');
api.use(['practicalmeteor:mocha', 'practicalmeteor:chai']);
api.mainModule('test/index.ts');
});
|
Create post request for zipcode | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var alertMessage = 'Sorry! We cannot geolocate you. Please enter a zipcode';
function getGeolocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
}
else {
console.log('Browser does not support geolocation');
alert(alertMessage);
}
}
function displayLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var xhttp = new XMLHttpRequest();
xhttp.open('POST', '/data?lat=' + lat + '&lng=' + lng, true);
xhttp.send();
}
function displayError() {
console.log('Geolocation not enabled');
alert(alertMessage);
}
function getZip() {
var zip = document.getElementById('zipCode').value;
var xhttp = new XMLHttpRequest();
xhttp.open('POST', '/data?zipCode=' + zip, true);
xhttp.send();
} | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var alertMessage = 'Sorry! We cannot geolocate you. Please enter a zipcode';
function getGeolocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
}
else {
console.log('Browser does not support geolocation');
alert(alertMessage);
}
}
function displayLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var xhttp = new XMLHttpRequest();
xhttp.open('POST', '/data?lat=' + lat + '&lng=' + lng, true);
xhttp.send();
}
function displayError() {
// TODO: Write error to user interface
console.log('Geolocation not enabled');
alert(alertMessage);
} |
Fix proto lang handler to work minified and to use the type style for types like uint32. | // Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
'keywords': (
'bytes,default,double,enum,extend,extensions,false,'
+ 'group,import,max,message,option,'
+ 'optional,package,repeated,required,returns,rpc,service,'
+ 'syntax,to,true'),
'types': /^(bool|(double|s?fixed|[su]?int)(32|64)|float|string)\b/,
'cStyleComments': true
}), ['proto']);
| // Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* Registers a language handler for Protocol Buffers as described at
* http://code.google.com/p/protobuf/.
*
* Based on the lexical grammar at
* http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc202383715
*
* @author mikesamuel@gmail.com
*/
PR['registerLangHandler'](PR['sourceDecorator']({
keywords: (
'bool bytes default double enum extend extensions false fixed32 '
+ 'fixed64 float group import int32 int64 max message option '
+ 'optional package repeated required returns rpc service '
+ 'sfixed32 sfixed64 sint32 sint64 string syntax to true uint32 '
+ 'uint64'),
cStyleComments: true
}), ['proto']);
|
Add some defaults on the error handler to prevent undefined errors | import AbstractLambdaPlugin from './abstract-lambda-plugin'
import PluginHook from '../enums/hooks'
import LambdaType from '../enums/lambda-type'
export default class ErrorResponse extends AbstractLambdaPlugin {
constructor (defaultErrorResponse) {
super('errorResponse', LambdaType.API_GATEWAY)
this._defaultErrorResponse = defaultErrorResponse
this.addHook(PluginHook.ON_ERROR, this.mapErrorResponse.bind(this))
}
/**
* Map error to a custom body
*/
mapErrorResponse (errorResponseFn) {
const fn = errorResponseFn || this._defaultErrorResponse || null
return (req, res, error) => {
let errorBody
if (fn !== null) {
errorBody = fn(error)
} else {
const errorObj = error || {}
errorBody = {
error: {
message: error.message || 'Unknown error. No error specified',
...errorObj,
_stackTrace: (error.stack || '').split('\n').map(x => x.trim())
}
}
}
res.body = JSON.stringify(errorBody)
}
}
}
| import AbstractLambdaPlugin from './abstract-lambda-plugin'
import PluginHook from '../enums/hooks'
import LambdaType from '../enums/lambda-type'
export default class ErrorResponse extends AbstractLambdaPlugin {
constructor (defaultErrorResponse) {
super('errorResponse', LambdaType.API_GATEWAY)
this._defaultErrorResponse = defaultErrorResponse
this.addHook(PluginHook.ON_ERROR, this.mapErrorResponse.bind(this))
}
/**
* Map error to a custom body
*/
mapErrorResponse (errorResponseFn) {
const fn = errorResponseFn || this._defaultErrorResponse || null
return (req, res, error) => {
let errorBody
if (fn !== null) {
errorBody = fn(error)
} else {
const errorObj = error || {}
errorBody = {
error: {
message: error.message,
...errorObj,
_stackTrace: error.stack.split('\n').map(x => x.trim())
}
}
}
res.body = JSON.stringify(errorBody)
}
}
}
|
Fix descriptions color styling termination
Color styling terminates with |@ instead of @| | package examples.dustin.commandline.picocli;
import static java.lang.System.out;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
/**
* Demonstrate Java-based command-line processing with picocli.
*/
@Command(
name="Main",
description="@|bold Demonstrating picocli |@",
headerHeading="@|bold,underline Demonstration Usage|@:%n%n")
public class Main
{
@Option(names={"-v", "--verbose"}, description="Verbose output?")
private boolean verbose;
@Option(names={"-f", "--file"}, description="Path and name of file", required=true)
private String fileName;
@Option(names={"-h", "--help"}, description="Display help/usage.", help=true)
boolean help;
public static void main(final String[] arguments)
{
final Main main = CommandLine.populateCommand(new Main(), arguments);
if (main.help)
{
CommandLine.usage(main, out, CommandLine.Help.Ansi.AUTO);
}
else
{
out.println("The provided file path and name is " + main.fileName + " and verbosity is set to " + main.verbose);
}
}
}
| package examples.dustin.commandline.picocli;
import static java.lang.System.out;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
/**
* Demonstrate Java-based command-line processing with picocli.
*/
@Command(
name="Main",
description="@|bold Demonstrating picocli @|",
headerHeading="@|bold,underline Demonstration Usage|@:%n%n")
public class Main
{
@Option(names={"-v", "--verbose"}, description="Verbose output?")
private boolean verbose;
@Option(names={"-f", "--file"}, description="Path and name of file", required=true)
private String fileName;
@Option(names={"-h", "--help"}, description="Display help/usage.", help=true)
boolean help;
public static void main(final String[] arguments)
{
final Main main = CommandLine.populateCommand(new Main(), arguments);
if (main.help)
{
CommandLine.usage(main, out, CommandLine.Help.Ansi.AUTO);
}
else
{
out.println("The provided file path and name is " + main.fileName + " and verbosity is set to " + main.verbose);
}
}
}
|
Update metric name label to "__name__". | /*
* Copyright 2013 Prometheus Team 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 io.prometheus.client.utility.labels;
/**
* <p>
* A collection of various reserved label names.
* </p>
*
* @author matt.proud@gmail.com (Matt T. Proud)
*/
public enum Reserved {
/**
* <p>
* {@code name} is a reserved label name key in Prometheus used to indicate
* the name of the {@link io.prometheus.client.metrics.Metric}.
* </p>
*/
NAME("__name__");
private final String name;
private Reserved(final String name) {
this.name = name;
}
public String label() {
return name;
}
}
| /*
* Copyright 2013 Prometheus Team 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 io.prometheus.client.utility.labels;
/**
* <p>
* A collection of various reserved label names.
* </p>
*
* @author matt.proud@gmail.com (Matt T. Proud)
*/
public enum Reserved {
/**
* <p>
* {@code name} is a reserved label name key in Prometheus used to indicate
* the name of the {@link io.prometheus.client.metrics.Metric}.
* </p>
*/
NAME("name");
private final String name;
private Reserved(final String name) {
this.name = name;
}
public String label() {
return name;
}
}
|
Fix for Symfony 2.8, with an explicit (correct-case) template file | <?php
namespace KPhoen\ContactBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
class ContactController extends BaseContactController
{
/**
* @Template("@KPhoenContact/Contact/contact.html.twig")
*/
public function contactAction(Request $request)
{
list($message, $form) = $this->getContactForm();
if ($request->isMethod('POST') && ($res = $this->handleContactForm($request, $form, $message)) !== null) {
return $res;
}
return [
'form' => $form->createView(),
'route' => 'contact_send',
'route_args' => [],
];
}
}
| <?php
namespace KPhoen\ContactBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
class ContactController extends BaseContactController
{
/**
* @Template()
*/
public function contactAction(Request $request)
{
list($message, $form) = $this->getContactForm();
if ($request->isMethod('POST') && ($res = $this->handleContactForm($request, $form, $message)) !== null) {
return $res;
}
return [
'form' => $form->createView(),
'route' => 'contact_send',
'route_args' => [],
];
}
}
|
Work on the custom date and time picker | (function() {
'use strict';
angular.module('triplanner.common.dateTimePicker', [])
.directive('dateTimePicker', [
function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
// $('#datetimepicker1').datetimepicker({
// pick12HourFormat: scope.pick12HourFormat,
// language: scope.language,
// useCurrent: scope.useCurrent
// }); // Change '#datetimepicker1' to '[date-time-picker]'.
console.log($('#datetimepicker1'));
console.log($('#datetimepicker1').datetimepicker);
element.on('blur', function() {
// scope.departureDateTime = new Date(element.data('DateTimePicker').getDate().format());
console.log(element.data('DateTimePicker'));
// scope.$apply();
});
}
}
}]);
})(); | (function() {
'use strict';
angular.module('triplanner.common.dateTimePicker', [])
.directive('dateTimePicker', [
function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$('#datetimepicker1').datetimepicker({
pick12HourFormat: scope.pick12HourFormat,
language: scope.language,
useCurrent: scope.useCurrent
}); // Change '#datetimepicker1' to '[date-time-picker]'.
element.on('blur', function() {
// scope.departureDateTime = new Date(element.data('DateTimePicker').getDate().format());
console.log(element.data('DateTimePicker'));
// scope.$apply();
});
}
}
}]);
})(); |
Remove importlib from install_requires because of issues with py3k.
This breaks compatibility with Python 2.6, but these users just need to 'pip install importlib' to fix this. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='django-sirtrevor',
version= '0.2.1',
packages=['sirtrevor'],
include_package_data=True,
license='MIT License',
description='A simple Django app that provides a model field and corresponding widget based on the fantastic Sir Trevor project',
long_description=open('README.rst', 'r').read(),
url='https://github.com/philippbosch/django-sirtrevor/',
author='Philipp Bosch',
author_email='hello@pb.io',
install_requires=['markdown2', 'django-appconf', 'django', 'six'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
setup(
name='django-sirtrevor',
version= '0.2.0',
packages=['sirtrevor'],
include_package_data=True,
license='MIT License',
description='A simple Django app that provides a model field and corresponding widget based on the fantastic Sir Trevor project',
long_description=open('README.rst', 'r').read(),
url='https://github.com/philippbosch/django-sirtrevor/',
author='Philipp Bosch',
author_email='hello@pb.io',
install_requires=['markdown2', 'django-appconf', 'django', 'six', 'importlib'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
Update string arg to url() to callable | from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from analyticsdataserver import views
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/docs')), # pylint: disable=no-value-for-parameter
url(r'^api-auth/', include('rest_framework.urls', 'rest_framework')),
url(r'^api-token-auth/', obtain_auth_token),
url(r'^api/', include('analytics_data_api.urls', 'api')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^status/$', views.StatusView.as_view(), name='status'),
url(r'^authenticated/$', views.AuthenticationTestView.as_view(), name='authenticated'),
url(r'^health/$', views.HealthView.as_view(), name='health'),
]
if settings.ENABLE_ADMIN_SITE: # pragma: no cover
admin.autodiscover()
urlpatterns.append(url(r'^site/admin/', include(admin.site.urls)))
handler500 = 'analyticsdataserver.views.handle_internal_server_error' # pylint: disable=invalid-name
handler404 = 'analyticsdataserver.views.handle_missing_resource_error' # pylint: disable=invalid-name
| from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from analyticsdataserver import views
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/docs')), # pylint: disable=no-value-for-parameter
url(r'^api-auth/', include('rest_framework.urls', 'rest_framework')),
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^api/', include('analytics_data_api.urls', 'api')),
url(r'^docs/', include('rest_framework_swagger.urls')),
url(r'^status/$', views.StatusView.as_view(), name='status'),
url(r'^authenticated/$', views.AuthenticationTestView.as_view(), name='authenticated'),
url(r'^health/$', views.HealthView.as_view(), name='health'),
]
if settings.ENABLE_ADMIN_SITE: # pragma: no cover
admin.autodiscover()
urlpatterns.append(url(r'^site/admin/', include(admin.site.urls)))
handler500 = 'analyticsdataserver.views.handle_internal_server_error' # pylint: disable=invalid-name
handler404 = 'analyticsdataserver.views.handle_missing_resource_error' # pylint: disable=invalid-name
|
Modify regex group for username to allow periods
Fix for #1076 | from app.plugins import PluginBase, Menu, MountPoint
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext as _
from .api import GetShortLink, EditShortLink, DeleteShortLink, HandleShortLink
class Plugin(PluginBase):
def build_jsx_components(self):
return ['SLControls.jsx']
def include_js_files(self):
return ['main.js']
def root_mount_points(self):
return [
MountPoint(r'^s(?P<view_type>[m3])/(?P<username>[^/]+)/(?P<short_id>[A-Za-z0-9_-]+)/?$', HandleShortLink)
]
def api_mount_points(self):
return [
MountPoint('task/(?P<pk>[^/.]+)/shortlink', GetShortLink.as_view()),
MountPoint('task/(?P<pk>[^/.]+)/edit', EditShortLink.as_view()),
MountPoint('task/(?P<pk>[^/.]+)/delete', DeleteShortLink.as_view())
]
| from app.plugins import PluginBase, Menu, MountPoint
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext as _
from .api import GetShortLink, EditShortLink, DeleteShortLink, HandleShortLink
class Plugin(PluginBase):
def build_jsx_components(self):
return ['SLControls.jsx']
def include_js_files(self):
return ['main.js']
def root_mount_points(self):
return [
MountPoint(r'^s(?P<view_type>[m3])/(?P<username>[^/.]+)/(?P<short_id>[A-Za-z0-9_-]+)/?$', HandleShortLink)
]
def api_mount_points(self):
return [
MountPoint('task/(?P<pk>[^/.]+)/shortlink', GetShortLink.as_view()),
MountPoint('task/(?P<pk>[^/.]+)/edit', EditShortLink.as_view()),
MountPoint('task/(?P<pk>[^/.]+)/delete', DeleteShortLink.as_view())
]
|
Switch around fixtures.js and dummy.js in path config | var src = exports.src = {};
src.app = [
'src/index.js',
'src/api.js',
'src/app.js'
];
src.dummy = [
'src/fixtures.js',
'src/dummy.js'
];
src.lib = [].concat(
src.app,
src.dummy);
src.demo = [].concat(src.lib, [
'src/demo.js'
]);
src.prd = [].concat(src.app, [
'src/init.js'
]);
src.all = [
'src/**/*.js'
];
module.exports = {
src: src,
dest: {
prd: 'lib/vumi-ureport.js',
demo: 'lib/vumi-ureport.demo.js'
},
test: {
spec: [
'test/**/*.test.js'
],
requires: [
'test/setup.js'
]
}
};
| var src = exports.src = {};
src.app = [
'src/index.js',
'src/api.js',
'src/app.js'
];
src.dummy = [
'src/dummy.js',
'src/fixtures.js'
];
src.lib = [].concat(
src.app,
src.dummy);
src.demo = [].concat(src.lib, [
'src/demo.js'
]);
src.prd = [].concat(src.app, [
'src/init.js'
]);
src.all = [
'src/**/*.js'
];
module.exports = {
src: src,
dest: {
prd: 'lib/vumi-ureport.js',
demo: 'lib/vumi-ureport.demo.js'
},
test: {
spec: [
'test/**/*.test.js'
],
requires: [
'test/setup.js'
]
}
};
|
Revert an accidental requirement bump to python 3.7 | #!/usr/bin/env python
from __future__ import print_function
from codecs import open
from setuptools import setup
setup(name="abzer",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url="https://github.com/mineo/abzer/tarball/master",
url="https://github.com/mineo/abzer",
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5"],
description="AcousticBrainz submission tool",
long_description=open("README.txt", encoding="utf-8").read(),
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "abzer/version.py"},
install_requires=["aiohttp"],
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']},
python_requires='>=3.5',
entry_points={
'console_scripts': ['abzer=abzer.__main__:main']
}
)
| #!/usr/bin/env python
from __future__ import print_function
from codecs import open
from setuptools import setup
setup(name="abzer",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url="https://github.com/mineo/abzer/tarball/master",
url="https://github.com/mineo/abzer",
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5"],
description="AcousticBrainz submission tool",
long_description=open("README.txt", encoding="utf-8").read(),
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "abzer/version.py"},
install_requires=["aiohttp"],
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']},
python_requires='>=3.7',
entry_points={
'console_scripts': ['abzer=abzer.__main__:main']
}
)
|
Fix double slash in link relation | package octokit
import (
"net/url"
)
var GitTreesURL = Hyperlink("repos/{owner}/{repo}/git/trees/{sha}{?recursive}")
func (c *Client) GitTrees(url *url.URL) (trees *GitTreesService) {
trees = &GitTreesService{client: c, URL: url}
return
}
type GitTreesService struct {
client *Client
URL *url.URL
}
// Get a Git Tree
func (c *GitTreesService) One() (tree *GitTree, result *Result) {
result = c.client.get(c.URL, &tree)
return
}
type GitTree struct {
Sha string `json:"sha,omitempty"`
Tree []GitTreeEntry `json:"tree,omitempty"`
Truncated bool `json:"truncated,omitempty"`
URL string `json:"url,omitempty"`
}
type GitTreeEntry struct {
Mode string `json:"mode,omitempty"`
Path string `json:"path,omitempty"`
Sha string `json:"sha,omitempty"`
Size int `json:"size,omitempty"`
Type string `json:"type,omitempty"`
URL string `json:"url,omitempty"`
}
| package octokit
import (
"net/url"
)
var GitTreesURL = Hyperlink("repos/{owner}/{repo}/git/trees/{/sha}{?recursive}")
func (c *Client) GitTrees(url *url.URL) (trees *GitTreesService) {
trees = &GitTreesService{client: c, URL: url}
return
}
type GitTreesService struct {
client *Client
URL *url.URL
}
// Get a Git Tree
func (c *GitTreesService) One() (tree *GitTree, result *Result) {
result = c.client.get(c.URL, &tree)
return
}
type GitTree struct {
Sha string `json:"sha,omitempty"`
Tree []GitTreeEntry `json:"tree,omitempty"`
Truncated bool `json:"truncated,omitempty"`
URL string `json:"url,omitempty"`
}
type GitTreeEntry struct {
Mode string `json:"mode,omitempty"`
Path string `json:"path,omitempty"`
Sha string `json:"sha,omitempty"`
Size int `json:"size,omitempty"`
Type string `json:"type,omitempty"`
URL string `json:"url,omitempty"`
}
|
Improve test. skip access block test when not exists mmdb file. | <?php
declare(strict_types=1);
namespace Fc2blog\Tests\App\Service;
use Fc2blog\Service\AccessBlock;
use Fc2blog\Web\Request;
use PHPUnit\Framework\TestCase;
class AccessBlockTest extends TestCase
{
public function testAccessBlock(): void
{
if (!file_exists(AccessBlock::MMDB_FILE_PATH)) {
$this->markTestSkipped();
return;
}
$jp_ip_address = "133.0.0.1"; // Some JP address https://www.nic.ad.jp/ja/dns/jp-addr-block.html
$r = new Request(null, null, null, null, null, null, [
'REMOTE_ADDR' => $jp_ip_address
]);
$ab = new AccessBlock("JP");
$this->assertTrue($ab->isUserBlockIp($r));
$ab = new AccessBlock("JP,US");
$this->assertTrue($ab->isUserBlockIp($r));
$ab = new AccessBlock("US,JP");
$this->assertTrue($ab->isUserBlockIp($r));
$ab = new AccessBlock("US");
$this->assertFalse($ab->isUserBlockIp($r));
$ab = new AccessBlock();
$this->assertFalse($ab->isUserBlockIp($r));
}
}
| <?php
declare(strict_types=1);
namespace Fc2blog\Tests\App\Service;
use Fc2blog\Service\AccessBlock;
use Fc2blog\Web\Request;
use PHPUnit\Framework\TestCase;
class AccessBlockTest extends TestCase
{
public function testAccessBlock(): void
{
$jp_ip_address = "133.0.0.1"; // Some JP address https://www.nic.ad.jp/ja/dns/jp-addr-block.html
$r = new Request(null, null, null, null, null, null, [
'REMOTE_ADDR' => $jp_ip_address
]);
$ab = new AccessBlock("JP");
$this->assertTrue($ab->isUserBlockIp($r));
$ab = new AccessBlock("JP,US");
$this->assertTrue($ab->isUserBlockIp($r));
$ab = new AccessBlock("US,JP");
$this->assertTrue($ab->isUserBlockIp($r));
$ab = new AccessBlock("US");
$this->assertFalse($ab->isUserBlockIp($r));
$ab = new AccessBlock();
$this->assertFalse($ab->isUserBlockIp($r));
}
}
|
Remove some print lines from the fake server. | import os
import SimpleHTTPServer
class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Overrides the default request handler to handle GitHub custom 404 pages.
(Pretty much a 404.html page in your root.)
See https://help.github.com/articles/custom-404-pages
This currently only works for erroneous pages in the root directory, but
that's enough to test what the 404 page looks like.
"""
def do_GET(self):
path = self.translate_path(self.path)
# If the path doesn't exist, fake it to be the 404 page.
if not os.path.exists(path):
self.path = '404.html'
# Call the superclass methods to actually serve the page.
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
SimpleHTTPServer.test(GitHubHandler)
| import os
import SimpleHTTPServer
class GitHubHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Overrides the default request handler to handle GitHub custom 404 pages.
(Pretty much a 404.html page in your root.)
See https://help.github.com/articles/custom-404-pages
This currently only works for erroneous pages in the root directory, but
that's enough to test what the 404 page looks like.
"""
def do_GET(self):
path = self.translate_path(self.path)
print(self.path)
print(path)
# If the path doesn't exist, fake it to be the 404 page.
if not os.path.exists(path):
self.path = '404.html'
# Call the superclass methods to actually serve the page.
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
print(self.path)
print(self.translate_path(self.path))
SimpleHTTPServer.test(GitHubHandler)
|
UI: Fix for duplicate items in navs.
We now clear out the nav list before appending new items to it. | function setupNav(nav) {
$('.nav.current').empty();
nav.forEach(function(i) {
$('.nav.current').append('<li><a href="#">' + i + '</a></li>');
});
$('.nav.current li').first().addClass('active');
}
function navUp() {
var el = $('.nav.current li.active').prev();
if (!el.length)
el = $('.nav.current li').last();
$('.nav.current li').removeClass('active');
el.addClass('active');
}
function navDown() {
var el = $('.nav.current li.active').next();
if (!el.length)
el = $('.nav.current li').first();
$('.nav.current li').removeClass('active');
el.addClass('active');
}
function navEnter() {
do_nav($('.tab-pane.active').attr('id'), $(".nav.current li.active a").html());
}
function switchToTab(id) {
$('#tabs a[href=#' + id + ']').tab('show');
$('.nav').removeClass('current');
$('#' + id + ' .nav').addClass('current');
$('.nav.current li').removeClass('active');
$('.nav.current li').first().addClass('active');
} | function setupNav(nav) {
nav.forEach(function(i) {
$('.nav.current').append('<li><a href="#">' + i + '</a></li>');
});
$('.nav.current li').first().addClass('active');
}
function navUp() {
var el = $('.nav.current li.active').prev();
if (!el.length)
el = $('.nav.current li').last();
$('.nav.current li').removeClass('active');
el.addClass('active');
}
function navDown() {
var el = $('.nav.current li.active').next();
if (!el.length)
el = $('.nav.current li').first();
$('.nav.current li').removeClass('active');
el.addClass('active');
}
function navEnter() {
do_nav($('.tab-pane.active').attr('id'), $(".nav.current li.active a").html());
}
function switchToTab(id) {
$('#tabs a[href=#' + id + ']').tab('show');
$('.nav').removeClass('current');
$('#' + id + ' .nav').addClass('current');
$('.nav.current li').removeClass('active');
$('.nav.current li').first().addClass('active');
} |
Add (helpful) comments to docBlocks | <?php
/***************************************************************************
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @category PH7 Template Engine
* @package PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license CC-BY License - http://creativecommons.org/licenses/by/3.0/
***************************************************************************/
namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;
defined('PH7') or exit('Restricted access');
abstract class Syntax
{
/** @var string */
protected $sCode;
/**
* Parse pH7Tpl's language syntax.
*
* @return void
*/
abstract public function parse();
/**
* Get the converted PHP code from template engine's syntax.
*
* @return string
*/
public function get()
{
return $this->sCode;
}
/**
* Set the template contents.
*
* @param string $sCode
*/
public function set($sCode)
{
$this->sCode = $sCode;
}
}
| <?php
/***************************************************************************
* @author Pierre-Henry Soria <ph7software@gmail.com>
* @category PH7 Template Engine
* @package PH7 / Framework / Layout / Tpl / Engine / PH7Tpl / Syntax
* @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved.
* @license CC-BY License - http://creativecommons.org/licenses/by/3.0/
***************************************************************************/
namespace PH7\Framework\Layout\Tpl\Engine\PH7Tpl\Syntax;
defined('PH7') or exit('Restricted access');
abstract class Syntax
{
/** @var string */
protected $sCode;
/**
* Parse pH7Tpl's language syntax.
*
* @return void
*/
abstract public function parse();
/**
* @return string
*/
public function get()
{
return $this->sCode;
}
/**
* @param string $sCode
*/
public function set($sCode)
{
$this->sCode = $sCode;
}
}
|
Update to use new bmi model. | #!/usr/bin/env python
from __future__ import print_function
import sys
import numpy as np
from poisson import BmiPoisson
def main():
model = BmiPoisson()
model.initialize()
print('%s' % model.get_component_name ())
for i in xrange(10):
print('Time %d' % i)
np.savetxt(sys.stdout, model.get_value('land_surface__elevation'),
fmt='%.3f')
model.update()
print('Time %d' % i)
np.savetxt(sys.stdout, model.get_value('land_surface__elevation'),
fmt='%.3f')
model.finalize()
if __name__ == '__main__':
main()
| #!/usr/bin/env python
from __future__ import print_function
import sys
import numpy as np
from bmi import MyBMI
def print_var_values (bmi, var_name):
s = ', '.join ([str (x) for x in bmi.get_value (var_name)])
print ('%s' % s)
def run ():
bmi = MyBMI ()
bmi.initialize (None)
print ('%s' % bmi.get_component_name ())
for i in range (10):
print ('Time %d: ' % i, end='')
print_var_values (bmi, 'height_above_sea_floor')
bmi.update ()
print ('Time %d: ' % i, end='')
print_var_values (bmi, 'height_above_sea_floor')
bmi.finalize ()
if __name__ == '__main__':
run ()
|
Include approved/rejected/etc. in LabelInfo from /detail
Change-Id: I7b630fa66cc2224fcdc3df3a2b881e4dd1cc3700 | // Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.server.change;
import com.google.gerrit.common.changes.ListChangesOption;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
public class GetDetail implements RestReadView<ChangeResource> {
private final ChangeJson json;
@Inject
GetDetail(ChangeJson json) {
this.json = json
.addOption(ListChangesOption.LABELS)
.addOption(ListChangesOption.DETAILED_LABELS)
.addOption(ListChangesOption.DETAILED_ACCOUNTS);
}
@Override
public Object apply(ChangeResource rsrc) throws OrmException {
return json.format(rsrc);
}
}
| // Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.server.change;
import com.google.gerrit.common.changes.ListChangesOption;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
public class GetDetail implements RestReadView<ChangeResource> {
private final ChangeJson json;
@Inject
GetDetail(ChangeJson json) {
this.json = json.addOption(ListChangesOption.DETAILED_LABELS)
.addOption(ListChangesOption.DETAILED_ACCOUNTS);
}
@Override
public Object apply(ChangeResource rsrc) throws OrmException {
return json.format(rsrc);
}
}
|
Complete happy path for About You form | describe('Mini test', function() {
it('should work', function () {
cy.visit("https://lga-1543-install-and-integra.staging.checklegalaid.service.gov.uk/start")
cy.contains('Choose the area you most need help with')
cy.contains('Debt').click()
cy.contains('Choose the option that best describes your debt problem')
cy.get(':nth-child(1) > .cla-scope-options-list-item-link').click()
cy.contains('Legal aid is available for this type of problem')
cy.contains('Check if you qualify financially').click()
// About you form
cy.setRadioInput('have_partner', 'No')
cy.setRadioInput('on_benefits', 'Yes')
cy.setRadioInput('have_children', 'Yes')
cy.setTextInput('num_children', '4')
cy.setRadioInput('have_dependants', 'No')
cy.setRadioInput('own_property', 'Yes')
cy.setRadioInput('is_employed', 'No')
cy.setRadioInput('is_self_employed', 'No')
cy.setRadioInput('aged_60_or_over', 'No')
cy.setRadioInput('have_savings', 'Yes')
cy.setRadioInput('have_valuables', 'No')
cy.get("#submit-button").click();
});
})
| describe('Mini test', function() {
it('should work', function () {
cy.visit("https://lga-1543-install-and-integra.staging.checklegalaid.service.gov.uk/start")
cy.contains('Choose the area you most need help with')
cy.contains('Debt').click()
cy.contains('Choose the option that best describes your debt problem')
cy.get(':nth-child(1) > .cla-scope-options-list-item-link').click()
cy.contains('Legal aid is available for this type of problem')
cy.contains('Check if you qualify financially').click()
// About you page form
cy.setRadioInput('have_partner', 'Yes')
cy.setRadioInput('in_dispute', 'No') // Depends on have_partner being set to 'Yes'
cy.setRadioInput('on_benefits', 'Yes')
cy.setRadioInput('have_children')
cy.setRadioInput('have_dependants')
cy.setRadioInput('own_property')
cy.setRadioInput('is_employed')
cy.setRadioInput('is_self_employed')
cy.setRadioInput('aged_60_or_over')
cy.setRadioInput('have_savings')
cy.setRadioInput('have_valuables')
// cy.get("#submit-button").click();
});
})
|
Revert "make MkDirP a bit faster"
This reverts commit ebf15f9de4418ec0ca477c6aa9a43b90d5c08f77. | package etcdutil
import (
"path"
"github.com/coreos/go-etcd/etcd"
)
// Creates the given dir (and all of its parent directories if they don't
// already exist). Will not return an error if the given directory already
// exists
func MkDirP(ec *etcd.Client, dir string) error {
parts := make([]string, 0, 4)
for {
parts = append(parts, dir)
dir = path.Dir(dir)
if dir == "/" {
break
}
}
for i := range parts {
ai := len(parts) - i - 1
_, err := ec.CreateDir(parts[ai], 0)
if err != nil && err.(*etcd.EtcdError).ErrorCode != 105 {
return err
}
}
return nil
}
// Returns the contents of a directory as a list of absolute paths
func Ls(ec *etcd.Client, dir string) ([]string, error) {
r, err := ec.Get(dir, false, false)
if err != nil {
return nil, err
}
dirNode := r.Node
ret := make([]string, len(dirNode.Nodes))
for i, node := range dirNode.Nodes {
ret[i] = node.Key
}
return ret, nil
}
| package etcdutil
import (
"path"
"github.com/coreos/go-etcd/etcd"
)
// Creates the given dir (and all of its parent directories if they don't
// already exist). Will not return an error if the given directory already
// exists
func MkDirP(ec *etcd.Client, dir string) error {
parts := make([]string, 0, 4)
for {
parts = append(parts, dir)
dir = path.Dir(dir)
if dir == "/" {
break
}
}
for i := range parts {
ai := len(parts) - i - 1
_, err := ec.CreateDir(parts[ai], 0)
if err != nil {
if err.(*etcd.EtcdError).ErrorCode == 105 {
return nil
}
return err
}
}
return nil
}
// Returns the contents of a directory as a list of absolute paths
func Ls(ec *etcd.Client, dir string) ([]string, error) {
r, err := ec.Get(dir, false, false)
if err != nil {
return nil, err
}
dirNode := r.Node
ret := make([]string, len(dirNode.Nodes))
for i, node := range dirNode.Nodes {
ret[i] = node.Key
}
return ret, nil
}
|
Add duplicated package pattern test. | package dragon
import (
"bytes"
"strings"
"testing"
)
func TestOut(t *testing.T) {
libChan := make(chan lib)
go func() {
libChan <- lib{
object: "Imports",
path: "github.com/monochromegane/dragon-imports",
}
libChan <- lib{
object: "Imports",
path: "github.com/someone/dragon-imports",
}
close(libChan)
}()
expect := `// AUTO-GENERATED BY dragon-imports
package imports
var stdlib = map[string]map[string]bool{`
buf := &bytes.Buffer{}
out(libChan, buf)
actual := buf.String()
if !strings.HasPrefix(actual, expect) {
t.Errorf("out should have prefix\n%s\n but\n%s", expect, actual)
}
contains := []string{
`"github.com/monochromegane/dragon-imports":map[string]bool{"Imports":true}`,
`"github.com/someone/dragon-imports":map[string]bool{"Imports":true}`,
`"unsafe":map[string]bool{`,
}
for _, s := range contains {
if !strings.Contains(actual, s) {
t.Errorf("out should contain \n%s\n but\n%s", s, actual)
}
}
}
| package dragon
import (
"bytes"
"strings"
"testing"
)
func TestOut(t *testing.T) {
libChan := make(chan lib)
go func() {
libChan <- lib{
pkg: "dragon",
object: "Imports",
path: "github.com/monochromegane/dragon-imports",
}
close(libChan)
}()
expect := `// AUTO-GENERATED BY dragon-imports
package imports
var stdlib = map[string]map[string]bool{`
buf := &bytes.Buffer{}
out(libChan, buf)
actual := buf.String()
if !strings.HasPrefix(actual, expect) {
t.Errorf("out should have prefix\n%s\n but\n%s", expect, actual)
}
contains := []string{
`"github.com/monochromegane/dragon-imports":map[string]bool{"Imports":true}`,
`"unsafe":map[string]bool{`,
}
for _, s := range contains {
if !strings.Contains(actual, s) {
t.Errorf("out should contain \n%s\n but\n%s", s, actual)
}
}
}
|
Rename some stuff and add locations | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var Location = require("./location_model");
var SpecialofferSchema = new Schema({
name: { type: String, unique: true, index: true },
img: String,
description: String, // Short description
body: String, // Page body
link: String,
partner: String,
partner_code: String,
locations: [ { type: ObjectId, ref: "Location" } ],
date: { type: Date, default: Date.now, required: true, index: true },
start_date: { type: Date, default: Date.now, index: true },
end_date: { type: Date, default: Date.now, index: true },
});
SpecialofferSchema.set("_perms", {
admin: "crud",
user: "cr",
all: "cr"
});
function toLower (v) {
return v.toLowerCase();
}
module.exports = mongoose.model('Specialoffer', SpecialofferSchema); | var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var Mixed = mongoose.Schema.Types.Mixed;
var SpecialofferSchema = new Schema({
name: { type: String, unique: true, index: true, set: toLower },
img: String,
description: String, // Short description
body: String, // Page body
partner: String,
partner_product_id: String,
urlid: { type: String, unique: true, index: true },
date: { type: Date, default: Date.now, required: true, index: true },
start_date: { type: Date, default: Date.now, index: true },
end_date: { type: Date, default: Date.now, index: true },
});
SpecialofferSchema.set("_perms", {
admin: "crud",
user: "cr",
all: "cr"
});
function toLower (v) {
return v.toLowerCase();
}
module.exports = mongoose.model('Specialoffer', SpecialofferSchema); |
Implement build method of ReadInstructionBuilder | package scheduler;
import os.OperatingSystem;
import readinstruction.ReadInstruction;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by Karol on 2017-04-20.
*/
public class FcfsScheduler implements Scheduler {
private Queue<ReadInstruction> waitingQueue;
private OperatingSystem parentOs;
public FcfsScheduler(){
this.waitingQueue = new LinkedList<>();
}
@Override
public void setOs(OperatingSystem parentOs) {
this.parentOs = parentOs;
}
@Override
public void push(ReadInstruction instruction) {
this.waitingQueue.add(instruction);
}
@Override
public String getName() {
return null;
}
@Override
public void update(int time) {
}
}
| package scheduler;
import os.OperatingSystem;
import readinstruction.ReadInstruction;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by Karol on 2017-04-20.
*/
public class FcfsScheduler implements Scheduler {
private Queue<ReadInstruction> waitingQueue;
private OperatingSystem parentOs;
public FcfsScheduler(){
this.waitingQueue = new LinkedList<>();
}
@Override
public void setOs(OperatingSystem parentOs) {
this.parentOs = parentOs;
}
@Override
public void push(ReadInstruction instruction) {
}
@Override
public String getName() {
return null;
}
@Override
public void update(int time) {
}
}
|
Fix bug added added because of cleanup of rabbitMQ examples | package main
import (
"log"
"github.com/streadway/amqp"
)
func rabbitStart() (ch *amqp.Channel, close func(), err error) {
conn, err := amqp.Dial("amqp://guest:guest@amqp.stardew.rocks:5672/")
if err != nil {
log.Fatalf("Failed to connect to AMQP server: %v", err)
}
if ch, err = conn.Channel(); err != nil {
return nil, nil, err
}
return ch, func() {
conn.Close()
ch.Close()
}, nil
}
func publishSavedGame(ch *amqp.Channel, save []byte) error {
return ch.Publish(
"logs", // exchange
"", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: save,
})
}
| package main
import (
"log"
"github.com/streadway/amqp"
)
func rabbitStart() (ch *amqp.Channel, close func(), err error) {
conn, err := amqp.Dial("amqp://guest:guest@amqp.stardew.rocks:5672/")
log.Fatalf("Failed to connect to AMQP server: %v", err)
if ch, err = conn.Channel(); err != nil {
return nil, nil, err
}
return ch, func() {
conn.Close()
ch.Close()
}, nil
}
func publishSavedGame(ch *amqp.Channel, save []byte) error {
return ch.Publish(
"logs", // exchange
"", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: save,
})
}
|
Adjust field for platform to platform_type as in json | const m = require('mithril');
const User = module.exports = function (data) {
this.id = m.prop(data.userId);
this.username = m.prop(data.username);
this.platform = m.prop(data.platform_type);
this.alias = m.prop(data.alias);
this.description = m.prop(data.description);
this.email = m.prop(data.email);
};
User.get = () =>
m.request({
method: 'GET',
url: 'js/modules/mockdata/user.json',
type: User
});
User.list = () =>
m.request({
method: 'GET',
url: 'js/modules/mockdata/users.json',
type: User
});
User.update = (user) =>
m.request({
method: 'PUT',
url: '/users/' + user.id(),
data: {
alias: user.alias(),
description: user.description(),
email: user.email()
}
});
| const m = require('mithril');
const User = module.exports = function (data) {
this.id = m.prop(data.userId);
this.username = m.prop(data.username);
this.platform = m.prop(data.platformType);
this.alias = m.prop(data.alias);
this.description = m.prop(data.description);
this.email = m.prop(data.email);
};
User.get = () =>
m.request({
method: 'GET',
url: 'js/modules/mockdata/user.json',
type: User
});
User.list = () =>
m.request({
method: 'GET',
url: 'js/modules/mockdata/users.json',
type: User
});
User.update = (user) =>
m.request({
method: 'PUT',
url: '/users/' + user.id(),
data: {
alias: user.alias(),
description: user.description(),
email: user.email()
}
});
|
Handle case where bundler exists, but there is no Gemfile
```
adrian@kamek:~$ bundle list
Could not locate Gemfile
adrian@kamek:~$ echo $?
10
``` | import os
import subprocess
def in_path(name):
"""
Check whether or not a command line tool
exists in the system path.
@return boolean
"""
for dirname in os.environ['PATH'].split(os.pathsep):
if os.path.exists(os.path.join(dirname, name)):
return True
return False
def npm_exists(name):
"""
Check whether or not a cli tool exists in a node_modules/.bin
dir in os.cwd
@return boolean
"""
cwd = os.getcwd()
path = os.path.join(cwd, 'node_modules', '.bin', name)
return os.path.exists(path)
def composer_exists(name):
"""
Check whether or not a cli tool exists in vendor/bin/{name}
relative to os.cwd
@return boolean
"""
cwd = os.getcwd()
path = os.path.join(cwd, 'vendor', 'bin', name)
return os.path.exists(path)
def bundle_exists(name):
"""
Check whether or not a ruby tool exists in
the os.cwd using bundler.
This assumes that you installed bundler packages
into ./bundle as documented in the README.
@return boolean
"""
try:
installed = subprocess.check_output(['bundle', 'list'])
except subprocess.CalledProcessError or OSError:
return False
return name in installed
| import os
import subprocess
def in_path(name):
"""
Check whether or not a command line tool
exists in the system path.
@return boolean
"""
for dirname in os.environ['PATH'].split(os.pathsep):
if os.path.exists(os.path.join(dirname, name)):
return True
return False
def npm_exists(name):
"""
Check whether or not a cli tool exists in a node_modules/.bin
dir in os.cwd
@return boolean
"""
cwd = os.getcwd()
path = os.path.join(cwd, 'node_modules', '.bin', name)
return os.path.exists(path)
def composer_exists(name):
"""
Check whether or not a cli tool exists in vendor/bin/{name}
relative to os.cwd
@return boolean
"""
cwd = os.getcwd()
path = os.path.join(cwd, 'vendor', 'bin', name)
return os.path.exists(path)
def bundle_exists(name):
"""
Check whether or not a ruby tool exists in
the os.cwd using bundler.
This assumes that you installed bundler packages
into ./bundle as documented in the README.
@return boolean
"""
try:
installed = subprocess.check_output(['bundle', 'list'])
except OSError:
return False
return name in installed
|
Add `build` and `default` tasks. | "use strict";
var gulp = require("gulp")
, $ = require("gulp-load-plugins")()
, del = require("del")
gulp.task("img", function () {
return gulp.src("img/*.sketch")
.pipe($.sketch({
export: "slices"
, formats: [
"png"
, "svg"
]
, scales: [
"1.0"
, "2.0"
]
}))
.pipe($.ignore.exclude(/@2x.svg$/))
.pipe($.cache($.imagemin({
svgoPlugins: [
{ removeTitle: true }
, { removeDesc: true }
]
})))
.pipe(gulp.dest("dist"))
.pipe($.size({
showFiles: true
}))
})
gulp.task("build", ["img"])
gulp.task("default", ["build"])
gulp.task("watch", function () {
gulp.watch("img/*.sketch", ["img"])
})
| "use strict";
var gulp = require("gulp")
, $ = require("gulp-load-plugins")()
, del = require("del")
gulp.task("img", function () {
return gulp.src("img/*.sketch")
.pipe($.sketch({
export: "slices"
, formats: [
"png"
, "svg"
]
, scales: [
"1.0"
, "2.0"
]
}))
.pipe($.ignore.exclude(/@2x.svg$/))
.pipe($.cache($.imagemin({
svgoPlugins: [
{ removeTitle: true }
, { removeDesc: true }
]
})))
.pipe(gulp.dest("dist"))
.pipe($.size({
showFiles: true
}))
})
gulp.task("watch", function () {
gulp.watch("img/*.sketch", ["img"])
})
|
Exit if unable to create ninja. | var
fs = require('fs')
, path = require('path')
, util = require('util')
, events = require('events')
, argv = require(path.resolve(__dirname, 'app', 'argv'))
, client = require(path.resolve(__dirname, 'app', 'client'))
, config = require(path.resolve(__dirname, 'app', 'config'))
, logger = require(path.resolve(__dirname, 'lib', 'logger'))
, app = new events.EventEmitter()
, log = new logger(argv)
, creds = {}
;
logger.default = log;
app.log = log;
app.on('error', function(err) {
log.error(err);
/**
* Do more stuff with errors.
* err should include .stack,
* which we could pipe to the cloud
* at some point, it would be useful!
*/
});
var ninja = new client(argv, creds, app);
if((!ninja) || !ninja.credentials.id) {
log.error("Unable to create ninja client.");
process.exit(1);
}
config(ninja, app);
/**
* Note about apps (event emitters):
*
* We can instantiate multiple apps to
* allow our modules to be namespaced/sandboxed
* if we so desire. This allows us to provide
* isolation without any additional infrastructure
*/
| var
fs = require('fs')
, path = require('path')
, util = require('util')
, events = require('events')
, argv = require(path.resolve(__dirname, 'app', 'argv'))
, client = require(path.resolve(__dirname, 'app', 'client'))
, config = require(path.resolve(__dirname, 'app', 'config'))
, logger = require(path.resolve(__dirname, 'lib', 'logger'))
, app = new events.EventEmitter()
, log = new logger(argv)
, creds = {}
;
logger.default = log;
app.log = log;
app.on('error', function(err) {
log.error(err);
/**
* Do more stuff with errors.
* err should include .stack,
* which we could pipe to the cloud
* at some point, it would be useful!
*/
});
var ninja = new client(argv, creds, app);
config(ninja, app);
/**
* Note about apps (event emitters):
*
* We can instantiate multiple apps to
* allow our modules to be namespaced/sandboxed
* if we so desire. This allows us to provide
* isolation without any additional infrastructure
*/
|
Add license mapping to config | 'use strict';
var path = require('path');
var rootPath = path.normalize(__dirname + '/../..');
const REVIEW_STATE_FIELD = ''; // TODO: Adjust this to a new field GUID.
module.exports = {
root: rootPath,
ip: process.env.IP || '0.0.0.0',
port: process.env.PORT || 9000,
cip: {
baseURL: 'http://www.neaonline.dk/CIP',
username: process.env.CIP_USERNAME,
password: process.env.CIP_PASSWORD,
proxyMaxSockets: 10,
// rotationCategoryName: 'Rotationsbilleder', // TODO: Disable in indexing.
indexingRestriction: REVIEW_STATE_FIELD + ' is 3'
},
googleAnalyticsPropertyID: null,
// googleMapsAPIKey: '',
googleAPIKey: process.env.GOOGLE_API_KEY,
projectOxfordAPIKey: process.env.PROJECT_OXFORD_API_KEY,
esHost: process.env.ES_HOST || 'localhost:9200',
esAssetsIndex: process.env.ES_ASSETS_INDEX || 'assets',
categoryBlacklist: require('../category-blacklist.js'),
enableGeotagging: false,
filterOptions: require('../filter-options.json'),
sortOptions: require('../sort-options.json'),
assetFields: require('../asset-fields.json'),
assetLayout: require('../asset-layout.json'),
licenseMapping: require('../license-mapping.json'),
themeColor: '#262626',
appName: 'KBH Billeder',
};
| 'use strict';
var path = require('path');
var rootPath = path.normalize(__dirname + '/../../..');
const REVIEW_STATE_FIELD = ''; // TODO: Adjust this to a new field GUID.
module.exports = {
root: rootPath,
ip: process.env.IP || '0.0.0.0',
port: process.env.PORT || 9000,
cip: {
baseURL: 'http://www.neaonline.dk/CIP',
username: process.env.CIP_USERNAME,
password: process.env.CIP_PASSWORD,
proxyMaxSockets: 10,
// rotationCategoryName: 'Rotationsbilleder', // TODO: Disable in indexing.
indexingRestriction: REVIEW_STATE_FIELD + ' is 3'
},
googleAnalyticsPropertyID: null,
// googleMapsAPIKey: '',
googleAPIKey: process.env.GOOGLE_API_KEY,
projectOxfordAPIKey: process.env.PROJECT_OXFORD_API_KEY,
esHost: process.env.ES_HOST || 'localhost:9200',
esAssetsIndex: process.env.ES_ASSETS_INDEX || 'assets',
categoryBlacklist: require('../category-blacklist.js'),
enableGeotagging: false,
filterOptions: require('../filter-options.json'),
sortOptions: require('../sort-options.json'),
assetFields: require('../asset-fields.json'),
assetLayout: require('../asset-layout.json'),
themeColor: '#262626',
appName: 'KBH Billeder',
};
|
Fix invisibility potions and cloaking device | package techreborn.events;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import tconstruct.armor.ArmorTickHandler;
import techreborn.api.TechRebornItems;
import techreborn.init.ModItems;
import techreborn.items.tools.ItemCloakingDevice;
public class TRTickHandler extends TickEvent {
public TRTickHandler(Type type, Side side, Phase phase) {
super(type, side, phase);
}
public Item previouslyWearing;
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=true)
public void onPlayerTick(TickEvent.PlayerTickEvent e) {
EntityPlayer player = e.player;
Item chestslot = player.getEquipmentInSlot(3) != null ? player.getEquipmentInSlot(3).getItem() : null;
if(previouslyWearing != chestslot && previouslyWearing == ModItems.cloakingDevice && player.isInvisible())
player.setInvisible(false);
previouslyWearing = chestslot;
}
}
| package techreborn.events;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.entity.player.EntityPlayer;
import techreborn.api.TechRebornItems;
import techreborn.init.ModItems;
import techreborn.items.tools.ItemCloakingDevice;
public class TRTickHandler extends TickEvent {
public TRTickHandler(Type type, Side side, Phase phase) {
super(type, side, phase);
}
@SubscribeEvent(priority=EventPriority.NORMAL, receiveCanceled=true)
public void onPlayerTick(TickEvent.PlayerTickEvent e) {
EntityPlayer player = e.player;
if(player.getEquipmentInSlot(3)== null) {
player.setInvisible(false);
}
else if(player.getEquipmentInSlot(3).getItem() != ModItems.cloakingDevice) {
player.setInvisible(false);
}
}
}
|
Add providers application form woo | <div class="page-header">
<h1>Apply to be a listed Provider</h1>
</div>
<div class="row providers">
<div class="span12">
<p>To apply to be listed on the <a href="/providers">ownCloud.org/providers</a> webpage as an open source
provider, please complete the following form.</p>
<script charset="utf-8" src="//js.hsforms.net/forms/current.js"></script>
<script>
hbspt.forms.create({
portalId: '328096',
formId: 'ecc0f964-1dd7-4159-913a-89172fbadfb6'
});
</script>
<p>If you are interested in becoming an enterprise provider with a support contract from
<a target="_blank" href="https://owncloud.com">ownCloud Inc</a> you can find more information
<a target="_blank" href="https://owncloud.com/products/service-provider">here</a>.</p>
</div>
</div> | <div class="page-header">
<h1>Apply to be a listed Provider</h1>
</div>
<div class="row providers">
<div class="span12">
<p>To apply to be listed on the <a href="/providers">ownCloud.org/providers</a> webpage as an open source provider, please send an email to <strong>providers (at) owncloud (dot) org</strong> with the following details:</p>
<ul>
<li>Your company name</li>
<li>The website link to your ownCloud offering</li>
<li>A 290 x 70 pixel logo banner as an attachment (.gif, .jpg or .png)</li>
<li>Your target clients (businesses, consumers, a mix etc)</li>
<li>Headquarter location</li>
<li>Whether you offer free ownCloud accounts</li>
</ul>
<p>If you are interested in becoming an enterprise provider with a support contract from <a target="_blank" href="https://owncloud.com">ownCloud Inc</a> you can find more information <a target="_blank" href="https://owncloud.com/products/service-provider">here</a>.</p>
</div>
</div> |
Add missing Node view import | from django.conf.urls import url, include
from rest_framework import routers
import service.authors.views
import service.friendrequest.views
import service.users.views
import service.nodes.views
import service.posts.views
router = routers.DefaultRouter()
router.register(r'users', service.users.views.UserViewSet)
router.register(r'nodes', service.nodes.views.NodeViewSet)
router.register(r'author', service.authors.views.AuthorViewSet, base_name="author")
router.register(r'posts', service.posts.views.PublicPostsViewSet, base_name="post")
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browseable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^friendrequest/', service.friendrequest.views.friendrequest, name='friend-request'),
]
| from django.conf.urls import url, include
from rest_framework import routers
import service.authors.views
import service.friendrequest.views
import service.users.views
import service.posts.views
router = routers.DefaultRouter()
router.register(r'users', service.users.views.UserViewSet)
router.register(r'nodes', service.nodes.views.NodeViewSet)
router.register(r'author', service.authors.views.AuthorViewSet, base_name="author")
router.register(r'posts', service.posts.views.PublicPostsViewSet, base_name="post")
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browseable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^friendrequest/', service.friendrequest.views.friendrequest, name='friend-request'),
]
|
Fix for the noah thing | from plugin import Plugin
from utils import create_logger
from config import OwnerID
class Jacob_Noah(Plugin):
is_global = True
log = create_logger('noah_stuff')
async def on_message(self, message, pfx):
if message.content.startswith('<@' + self.client.user.id + '> kish meh'):
await self.client.send_typing(message.channel)
cmd_name = 'Jacob Noah Meme'
self.log.info('User %s [%s] on server %s [%s], used the ' + cmd_name + ' command on #%s channel',
message.author,
message.author.id, message.server.name, message.server.id, message.channel)
if message.author.id == OwnerID:
await self.client.send_message(message.channel, 'Of course <@' + OwnerID + '>, my love, anything for you! Chu~')
else:
await self.client.send_message(message.channel, 'Ew <@' + OwnerID + '>... Would kindly piss off...') | from plugin import Plugin
from utils import create_logger
from config import OwnerID
class Jacob_Noah(Plugin):
is_global = True
log = create_logger('noah_stuff')
async def on_message(self, message, pfx):
if message.content.startswith('<@' + self.client.id + '> kish meh'):
await self.client.send_typing(message.channel)
cmd_name = 'Jacob Noah Meme'
self.log.info('User %s [%s] on server %s [%s], used the ' + cmd_name + ' command on #%s channel',
message.author,
message.author.id, message.server.name, message.server.id, message.channel)
if message.author.id == OwnerID:
await self.client.send_message(message.channel, 'Of course <@' + OwnerID + '>, my love, anything for you! Chu~')
else:
await self.client.send_message(message.channel, 'Ew <@' + OwnerID + '>... Would kindly piss off...') |
Change default health to 1. | function Actor(other) {
other = other || {};
this.name = other.name || "";
this.init = other.init || 0;
this.hp = other.hp || 1;
};
var sort = function(left, right) {
return left.init==right.init ? 0 : (left.init > right.init ? -1 : 1);
};
function Encounter() {
this.actors = [];
};
var ViewModel = function() {
self = this;
self.formActor = ko.observable(new Actor());
self.actors = ko.observableArray([]);
self.addActor = function() {
self.actors.push(new Actor(self.formActor()));
self.formActor(new Actor());
};
self.sortActors = function() {
self.actors.sort(sort);
};
self.endTurn = function() {
self.actors.remove(this);
self.actors.push(this);
};
};
ko.applyBindings(new ViewModel());
| function Actor(other) {
other = other || {};
this.name = other.name || "";
this.init = other.init || 0;
this.hp = other.hp || 0;
};
var sort = function(left, right) {
return left.init==right.init ? 0 : (left.init > right.init ? -1 : 1);
};
function Encounter() {
this.actors = [];
};
var ViewModel = function() {
self = this;
self.formActor = ko.observable(new Actor());
self.actors = ko.observableArray([]);
self.addActor = function() {
self.actors.push(new Actor(self.formActor()));
self.formActor(new Actor());
};
self.sortActors = function() {
self.actors.sort(sort);
};
self.endTurn = function() {
self.actors.remove(this);
self.actors.push(this);
};
};
ko.applyBindings(new ViewModel());
|
ZON-2838: Fix xml path to topcpagelink | import zope.interface
import zeit.cms.content.reference
import zeit.campus.interfaces
class TopicpageLink(zeit.cms.related.related.RelatedBase):
zope.interface.implements(zeit.campus.interfaces.ITopicpageLink)
topicpagelink = zeit.cms.content.reference.SingleResource(
'.head.topicpagelink', 'related')
topicpagelink_label = zeit.cms.content.dav.mapProperties(
zeit.campus.interfaces.ITopicpageLink,
zeit.cms.interfaces.DOCUMENT_SCHEMA_NS,
('topicpagelink_label',))
topicpagelink_label = zeit.cms.content.property.ObjectPathProperty(
'.head.topicpagelink.label',
zeit.campus.interfaces.ITopicpageLink['topicpagelink_label'])
| import zope.interface
import zeit.cms.content.reference
import zeit.campus.interfaces
class TopicpageLink(zeit.cms.related.related.RelatedBase):
zope.interface.implements(zeit.campus.interfaces.ITopicpageLink)
topicpagelink = zeit.cms.content.reference.SingleResource(
'.head.topicpagelink.url', 'related')
topicpagelink_label = zeit.cms.content.dav.mapProperties(
zeit.campus.interfaces.ITopicpageLink,
zeit.cms.interfaces.DOCUMENT_SCHEMA_NS,
('topicpagelink_label',))
topicpagelink_label = zeit.cms.content.property.ObjectPathProperty(
'.head.topicpagelink.label',
zeit.campus.interfaces.ITopicpageLink['topicpagelink_label'])
|
Fix order on opps menu | # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects.filter(site=site,
date_available__lte=timezone.now(),
published=True,
show_in_menu=True).order_by('order')
return {'opps_menu': opps_menu,
'opps_channel_conf_all': settings.OPPS_CHANNEL_CONF}
| # -*- coding: utf-8 -*-
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import get_current_site
from .models import Channel
def channel_context(request):
""" Channel context processors
"""
site = get_current_site(request)
opps_menu = Channel.objects.filter(site=site,
date_available__lte=timezone.now(),
published=True,
show_in_menu=True)
return {'opps_menu': opps_menu,
'opps_channel_conf_all': settings.OPPS_CHANNEL_CONF}
|
Fix automated deployments by actually changing directory | <?php
use Illuminate\Console\Command;
class SiteDeployCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'site:deploy';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Deploy the site on live';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
SSH::run([
"cd " . @$_ENV["SSH_ROOT"],
"php artisan down",
"git pull origin develop",
"composer update",
"php artisan up",
]);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [];
}
}
| <?php
use Illuminate\Console\Command;
class SiteDeployCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'site:deploy';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Deploy the site on live';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
SSH::run([
"php artisan down",
"git pull origin develop",
"composer update",
"php artisan up",
]);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [];
}
}
|
Make sure extended pages can be added in structure add page feature | <ul class="toolbar toolbar-right">
<?= $this->partial('tools-top') ?>
<?php if (false && !$content->isNewMaster()) { ?>
<li><a href="#" class="btn icon-history">
View <?= $info->singular ?> History
</a></li>
<?php } ?>
<?php if (!$content->isNewMaster() && $info->class != 'Chalk\Core\File') { ?>
<?php if (isset($node)) { ?>
<? if (is_a($info->name, 'Chalk\Core\Page', true)) { ?>
<li><a href="<?= $this->url([
'action' => 'edit',
'node' => null,
]) ?><?= $this->url->query([
'parent' => $node->id,
'type' => $info->name,
]) ?>" class="btn btn-focus btn-out icon-add">
New Child <?= $info->singular ?>
</a></li>
<? } ?>
<? } else { ?>
<li><a href="<?= $this->url([
'entity' => $info->name,
'action' => 'edit',
], 'core_content', true) ?>" class="btn btn-focus btn-out icon-add">
New <?= $info->singular ?>
</a></li>
<? } ?>
<?php } ?>
<?= $this->partial('tools-bottom') ?>
</ul> | <ul class="toolbar toolbar-right">
<?= $this->partial('tools-top') ?>
<?php if (false && !$content->isNewMaster()) { ?>
<li><a href="#" class="btn icon-history">
View <?= $info->singular ?> History
</a></li>
<?php } ?>
<?php if (!$content->isNewMaster() && $info->class != 'Chalk\Core\File') { ?>
<?php if (isset($node)) { ?>
<? if ($info->class == 'Chalk\Core\Page') { ?>
<li><a href="<?= $this->url([
'action' => 'edit',
'node' => null,
]) ?><?= $this->url->query([
'parent' => $node->id,
'type' => $info->name,
]) ?>" class="btn btn-focus btn-out icon-add">
New Child <?= $info->singular ?>
</a></li>
<? } ?>
<? } else { ?>
<li><a href="<?= $this->url([
'entity' => $info->name,
'action' => 'edit',
], 'core_content', true) ?>" class="btn btn-focus btn-out icon-add">
New <?= $info->singular ?>
</a></li>
<? } ?>
<?php } ?>
<?= $this->partial('tools-bottom') ?>
</ul> |
Use all available cores in the router program | package main
import (
"flag"
"log"
"net/http"
"runtime"
)
var pubAddr = flag.String("pubAddr", ":8080", "Address on which to serve public requests")
var apiAddr = flag.String("apiAddr", ":8081", "Address on which to receive reload requests")
var mongoUrl = flag.String("mongoUrl", "localhost", "Address of mongo cluster (e.g. 'mongo1,mongo2,mongo3')")
var mongoDbName = flag.String("mongoDbName", "router", "Name of mongo database to use")
var quit = make(chan int)
func main() {
// Use all available cores
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
rout := NewRouter(*mongoUrl, *mongoDbName)
rout.ReloadRoutes()
log.Println("router: listening for requests on " + *pubAddr)
log.Println("router: listening for refresh on " + *apiAddr)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
rout.ReloadRoutes()
})
go http.ListenAndServe(*pubAddr, rout)
go http.ListenAndServe(*apiAddr, nil)
<-quit
}
| package main
import (
"flag"
"log"
"net/http"
)
var pubAddr = flag.String("pubAddr", ":8080", "Address on which to serve public requests")
var apiAddr = flag.String("apiAddr", ":8081", "Address on which to receive reload requests")
var mongoUrl = flag.String("mongoUrl", "localhost", "Address of mongo cluster (e.g. 'mongo1,mongo2,mongo3')")
var mongoDbName = flag.String("mongoDbName", "router", "Name of mongo database to use")
var quit = make(chan int)
func main() {
flag.Parse()
rout := NewRouter(*mongoUrl, *mongoDbName)
rout.ReloadRoutes()
log.Println("router: listening for requests on " + *pubAddr)
log.Println("router: listening for refresh on " + *apiAddr)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
rout.ReloadRoutes()
})
go http.ListenAndServe(*pubAddr, rout)
go http.ListenAndServe(*apiAddr, nil)
<-quit
}
|
Fix test to work with python 2.6 | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
class TestNode(TestCase):
def test_is_installed(self):
proc = subprocess.Popen(['node', '--version'], stdout=subprocess.PIPE)
output = proc.stdout.read()
self.assertEquals(output.strip(), 'v0.8.11')
| import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
class TestNode(TestCase):
def test_is_installed(self):
output = subprocess.check_output(['node', '--version'])
self.assertEquals(output.strip(), 'v0.8.11')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.