text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Enable drf_yasg in test settings | #
# Django Tests
# ..........................
TEST = True
CELERY_ALWAYS_EAGER = True
TEST_EXCLUDE = ('django',)
INSTALLED_APPS += (
'geotrek.diving',
'geotrek.sensitivity',
'geotrek.outdoor',
'drf_yasg',
)
LOGGING['handlers']['console']['level'] = 'CRITICAL'
LANGUAGE_CODE = 'en'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
MODELTRANSLATION_LANGUAGES = ('en', 'es', 'fr', 'it')
LAND_BBOX_AREAS_ENABLED = True
class DisableMigrations():
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
ADMINS = (
('test', 'test@test.com'),
)
MANAGERS = ADMINS
TEST_RUNNER = 'geotrek.test_runner.TestRunner'
| #
# Django Tests
# ..........................
TEST = True
CELERY_ALWAYS_EAGER = True
TEST_EXCLUDE = ('django',)
INSTALLED_APPS += (
'geotrek.diving',
'geotrek.sensitivity',
'geotrek.outdoor',
)
LOGGING['handlers']['console']['level'] = 'CRITICAL'
LANGUAGE_CODE = 'en'
MODELTRANSLATION_DEFAULT_LANGUAGE = 'en'
MODELTRANSLATION_LANGUAGES = ('en', 'es', 'fr', 'it')
LAND_BBOX_AREAS_ENABLED = True
class DisableMigrations():
def __contains__(self, item):
return True
def __getitem__(self, item):
return None
MIGRATION_MODULES = DisableMigrations()
ADMINS = (
('test', 'test@test.com'),
)
MANAGERS = ADMINS
TEST_RUNNER = 'geotrek.test_runner.TestRunner'
|
Add hardware interface in sockets constructor | /**
* Main application file
*/
'use strict';
var path = require('path');
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
var hardware = require('./config/config.json').hardware;
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
// Populate DB with sample data
if(config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
var hardwareInterface;
if (hardware) {
hardwareInterface = require('./hardware')(sockets);
}
var sockets = require('./sockets')(server, hardwareInterface);
require('./routes')(app, sockets);
// Start server
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
// Expose app
exports = module.exports = app; | /**
* Main application file
*/
'use strict';
var path = require('path');
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
var hardware = require('./config/config.json').hardware;
// Connect to database
mongoose.connect(config.mongo.uri, config.mongo.options);
// Populate DB with sample data
if(config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
var sockets = require('./sockets')(server);
if (hardware) {
require('./hardware')(sockets);
}
require('./routes')(app, sockets);
// Start server
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
// Expose app
exports = module.exports = app; |
Change to get test to pass. | """Tests the menu features."""
##==============================================================#
## SECTION: Imports #
##==============================================================#
from testlib import *
from qprompt import enum_menu
##==============================================================#
## SECTION: Class Definitions #
##==============================================================#
class TestCase(unittest.TestCase):
def test_menu_1(test):
"""Check for main() call from console functionality."""
test.assertFalse(op.exists("generated_file.txt"))
subprocess.call("python ./menu_helper_1.py g q", shell=True)
test.assertTrue(op.exists("generated_file.txt"))
subprocess.call("python ./menu_helper_1.py d q", shell=True)
test.assertFalse(op.exists("generated_file.txt"))
##==============================================================#
## SECTION: Main Body #
##==============================================================#
if __name__ == '__main__':
unittest.main()
| """Tests the menu features."""
##==============================================================#
## SECTION: Imports #
##==============================================================#
from testlib import *
from qprompt import enum_menu
##==============================================================#
## SECTION: Class Definitions #
##==============================================================#
class TestCase(unittest.TestCase):
def test_menu_1(test):
"""Check for main() call from console functionality."""
test.assertFalse(op.exists("generated_file.txt"))
subprocess.call("menu_helper_1.py g q", shell=True)
test.assertTrue(op.exists("generated_file.txt"))
subprocess.call("menu_helper_1.py d q", shell=True)
test.assertFalse(op.exists("generated_file.txt"))
##==============================================================#
## SECTION: Main Body #
##==============================================================#
if __name__ == '__main__':
unittest.main()
|
Fix arguments order of reqon.deprecated.build_terms(). | import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
return build_terms(query['$query'], reql)
def build_terms(reql, query):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
| import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
return build_terms(query['$query'], reql)
def build_terms(query, reql):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
|
[BUG] Fix duplicate method from merge | package org.openkilda.messaging.ctrl;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DumpStateResponseData extends ResponseData {
@JsonProperty("state")
private AbstractDumpState state;
@JsonCreator
public DumpStateResponseData(
@JsonProperty("component") String component,
@JsonProperty("task_id") Integer taskId,
@JsonProperty("topology") String topology,
@JsonProperty("state") AbstractDumpState state) {
super(component, taskId, topology);
this.state = state;
}
public AbstractDumpState getState() {
return state;
}
}
| package org.openkilda.messaging.ctrl;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DumpStateResponseData extends ResponseData {
@JsonProperty("state")
private AbstractDumpState state;
@JsonCreator
public DumpStateResponseData(
@JsonProperty("component") String component,
@JsonProperty("task_id") Integer taskId,
@JsonProperty("topology") String topology,
@JsonProperty("state") AbstractDumpState state) {
super(component, taskId, topology);
this.state = state;
}
public AbstractDumpState getState() {
return state;
}
public AbstractDumpState getState() {
return state;
}
}
|
Update TestGenerateApexDocs regex to fix windows test
This commit updates the test regex to match either windows or unix file
separators.
The command generated on Windows:
java -jar c:\users\ieuser\appdata\local\temp\tmp9splyd\apexdoc.jar -s \Users\IEUser\Documents\GitHub\CumulusCI-Test\src\classes -t \Users\IEUser\Documents\GitHub\CumulusCI-Test -p "global;public;private;testmethod;webService" | import mock
import re
import unittest
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.config import OrgConfig
from cumulusci.tasks.apexdoc import GenerateApexDocs
class TestGenerateApexDocs(unittest.TestCase):
def setUp(self):
self.global_config = BaseGlobalConfig()
self.project_config = BaseProjectConfig(self.global_config)
self.task_config = TaskConfig({"options": {"version": "1.0"}})
self.org_config = OrgConfig({}, "test")
def test_task(self):
task = GenerateApexDocs(self.project_config, self.task_config, self.org_config)
task._run_command = mock.Mock()
task()
self.assertTrue(
re.match(
r"java -jar .*.apexdoc.jar -s .*.src.classes -t .*",
task.options["command"],
)
)
| import mock
import re
import unittest
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.config import OrgConfig
from cumulusci.tasks.apexdoc import GenerateApexDocs
class TestGenerateApexDocs(unittest.TestCase):
def setUp(self):
self.global_config = BaseGlobalConfig()
self.project_config = BaseProjectConfig(self.global_config)
self.task_config = TaskConfig({"options": {"version": "1.0"}})
self.org_config = OrgConfig({}, "test")
def test_task(self):
task = GenerateApexDocs(self.project_config, self.task_config, self.org_config)
task._run_command = mock.Mock()
task()
self.assertTrue(
re.match(
r"java -jar .*/apexdoc.jar -s .*/src/classes -t .*",
task.options["command"],
)
)
|
Add new predefined generic message for announcement query failure | /*
* Copyright 2015 Ryan Gilera.
*
* 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.github.daytron.revworks.data;
/**
* Collection of error messages.
*
* @author Ryan Gilera
*/
public enum ErrorMsg {
CONSULT_YOUR_ADMIN("Please consult your administrator for help."),
INVALID_INPUT_CAPTION("Invalid input!"),
SIGNIN_FAILED_CAPTION("Sign-In failed!"),
NO_USER_SIGNIN("No login user found. The session has been reset. "),
DATA_FETCH_ERROR("Could not retrieve user data.");
private final String text;
private ErrorMsg(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
| /*
* Copyright 2015 Ryan Gilera.
*
* 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.github.daytron.revworks.data;
/**
* Collection of error messages.
*
* @author Ryan Gilera
*/
public enum ErrorMsg {
INVALID_INPUT_CAPTION("Invalid input!"),
SIGNIN_FAILED_CAPTION("Sign-In failed!"),
NO_USER_SIGNIN("No login user found. The session has been reset. ");
private final String text;
private ErrorMsg(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
|
Change in the typ output. |
"""
municipios_parser
-----------------
Module which contains the process of parsing data of municipios.
TODO
----
"""
import pandas as pd
from pythonUtils.ProcessTools import Processer
class Municipios_Parser(Processer):
"""This class is the one which controls the parsing process of municipios
information.
"""
indices = None
files = ''
def __init__(self, logfile, bool_inform=False):
"Instantiation of the class remembering it is a subclass of Processer."
self.proc_name = "Municipios parser"
self.proc_desc = "Parser the standarize data from file"
self.subproc_desc = []
self.t_expended_subproc = []
self.logfile = logfile
def parse(self, filepath):
"Parse the data from the file given."
data = pd.read_csv(filepath, sep=';', index_col=0)
typevars = {}
typevars['feat_vars'] = ['Poblacion', "Superficie", "Densidad"]
typevars['loc_vars'] = ["longitud", "latitud"]
return data, typevars
|
"""
municipios_parser
-----------------
Module which contains the process of parsing data of municipios.
TODO
----
"""
import pandas as pd
from pythonUtils.ProcessTools import Processer
class Municipios_Parser(Processer):
"""This class is the one which controls the parsing process of municipios
information.
"""
indices = None
files = ''
def __init__(self, logfile, bool_inform=False):
"Instantiation of the class remembering it is a subclass of Processer."
self.proc_name = "Municipios parser"
self.proc_desc = "Parser the standarize data from file"
self.subproc_desc = []
self.t_expended_subproc = []
self.logfile = logfile
def parse(self, filepath):
"Parse the data from the file given."
data = pd.read_csv(filepath, sep=';', index_col=0)
typevars = {}
typevars['pop_vars'] = ['Poblacion', "Superficie", "Densidad"]
typevars['loc_vars'] = ["longitud", "latitud"]
return data, typevars
|
Add hold_reason to the Order Entity | <?php
/*
* This file is part of the PayBreak/basket package.
*
* (c) PayBreak <dev@paybreak.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PayBreak\Sdk\Entities\Application;
use WNowicki\Generic\AbstractEntity;
/**
* Order Entity
*
* @author WN
* @method $this setReference(string $reference)
* @method string|null getReference()
* @method $this setAmount(int $amount)
* @method int|null getAmount()
* @method $this setDescription(string $description)
* @method string|null getDescription()
* @method $this setValidity(string $validity)
* @method string|null getValidity()
* @method $this setDepositAmount(int $depositAmount)
* @method int|null getDepositAmount()
* @method $this setHold(string $hold)
* @method string|null getHold()
* @package PayBreak\Sdk\Entities
*/
class OrderEntity extends AbstractEntity
{
protected $properties = [
'reference',
'amount',
'description',
'validity',
'deposit_amount',
'hold',
'hold_reason',
];
}
| <?php
/*
* This file is part of the PayBreak/basket package.
*
* (c) PayBreak <dev@paybreak.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PayBreak\Sdk\Entities\Application;
use WNowicki\Generic\AbstractEntity;
/**
* Order Entity
*
* @author WN
* @method $this setReference(string $reference)
* @method string|null getReference()
* @method $this setAmount(int $amount)
* @method int|null getAmount()
* @method $this setDescription(string $description)
* @method string|null getDescription()
* @method $this setValidity(string $validity)
* @method string|null getValidity()
* @method $this setDepositAmount(int $depositAmount)
* @method int|null getDepositAmount()
* @method $this setHold(string $hold)
* @method string|null getHold()
* @package PayBreak\Sdk\Entities
*/
class OrderEntity extends AbstractEntity
{
protected $properties = [
'reference',
'amount',
'description',
'validity',
'deposit_amount',
'hold'
];
}
|
Make `async-to-gen` work on Now | #!/usr/bin/env node
// Native
const path = require('path')
// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')
// Ours
const pkg = require('../package')
// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
const pathSep = process.platform === 'win32' ? '\\\\' : '/'
const directoryName = path.parse(path.join(__dirname, '..')).base
asyncToGen({
includes: new RegExp(`.*${directoryName}?${pathSep}(lib|bin).*`),
excludes: null,
sourceMaps: false
})
}
// Throw an error if node version is too low
if (nodeVersion.major < 6) {
console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
process.exit(1)
}
// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW && pkg.dist) {
updateNotifier({pkg}).notify()
}
// Load package core with async/await support
require('../lib')
| #!/usr/bin/env node
// Packages
const asyncToGen = require('async-to-gen/register')
const updateNotifier = require('update-notifier')
const {red} = require('chalk')
const nodeVersion = require('node-version')
const isAsyncSupported = require('is-async-supported')
// Ours
const pkg = require('../package')
// Support for keywords "async" and "await"
if (!isAsyncSupported()) {
const pathSep = process.platform === 'win32' ? '\\\\' : '/'
asyncToGen({
includes: new RegExp(`.*serve?${pathSep}(lib|bin).*`),
excludes: null,
sourceMaps: false
})
}
// Throw an error if node version is too low
if (nodeVersion.major < 6) {
console.error(`${red('Error!')} Serve requires at least version 6 of Node. Please upgrade!`)
process.exit(1)
}
// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW && pkg.dist) {
updateNotifier({pkg}).notify()
}
// Load package core with async/await support
require('../lib')
|
Update AddStateServerMachine testing helper for completeness | // Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package testing
import (
gc "launchpad.net/gocheck"
"launchpad.net/juju-core/instance"
"launchpad.net/juju-core/state"
)
// AddStateServerMachine adds a "state server" machine to the state so
// that State.Addresses and State.APIAddresses will work. It returns the
// added machine. The addresses that those methods will return bear no
// relation to the addresses actually used by the state and API servers.
// It returns the addresses that will be returned by the State.Addresses
// and State.APIAddresses methods, which will not bear any relation to
// the be the addresses used by the state servers.
func AddStateServerMachine(c *gc.C, st *state.State) *state.Machine {
machine, err := st.AddMachine("quantal", state.JobManageEnviron)
c.Assert(err, gc.IsNil)
err = machine.SetAddresses(instance.NewAddress("0.1.2.3", instance.NetworkUnknown))
c.Assert(err, gc.IsNil)
hostPorts := [][]instance.HostPort{{{
Address: instance.NewAddress("0.1.2.3", instance.NetworkUnknown),
Port: 1234,
}}}
err = st.SetAPIHostPorts(hostPorts)
c.Assert(err, gc.IsNil)
return machine
}
| // Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package testing
import (
gc "launchpad.net/gocheck"
"launchpad.net/juju-core/instance"
"launchpad.net/juju-core/state"
)
// AddStateServerMachine adds a "state server" machine to the state so
// that State.Addresses and State.APIAddresses will work. It returns the
// added machine. The addresses that those methods will return bear no
// relation to the addresses actually used by the state and API servers.
// It returns the addresses that will be returned by the State.Addresses
// and State.APIAddresses methods, which will not bear any relation to
// the be the addresses used by the state servers.
func AddStateServerMachine(c *gc.C, st *state.State) *state.Machine {
machine, err := st.AddMachine("quantal", state.JobManageEnviron)
c.Assert(err, gc.IsNil)
err = machine.SetAddresses(instance.NewAddress("0.1.2.3", instance.NetworkUnknown))
c.Assert(err, gc.IsNil)
return machine
}
|
Change user's port value style | /*
* Copyright (C) 2016 Lynn
*
* 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.lynn9388.rmichatroom.rmi;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 8116975872176331171L;
private String username;
private String ip;
private int port;
private String remoteName;
public User(String username, String ip, int port, String remoteName) {
this.username = username;
this.ip = ip;
this.port = port;
this.remoteName = remoteName;
}
public String getUsername() {
return username;
}
public String getIp() {
return ip;
}
public int getPort() {
return port;
}
public String getRemoteName() {
return remoteName;
}
}
| /*
* Copyright (C) 2016 Lynn
*
* 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.lynn9388.rmichatroom.rmi;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 148606460530002054L;
private String username;
private String ip;
private String port;
private String remoteName;
public User(String username, String ip, String port, String remoteName) {
this.username = username;
this.ip = ip;
this.port = port;
this.remoteName = remoteName;
}
public String getUsername() {
return username;
}
public String getIp() {
return ip;
}
public String getPort() {
return port;
}
public String getRemoteName() {
return remoteName;
}
}
|
Fix strictness error when using node 4 | // report.js -- Report of the results of a batch and its sub-batches
//
// Copyright 2017 fuzzy.ai <evan@fuzzy.ai>
//
// 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.
/* jshint esversion: 6 */
'use strict';
class Report {
constructor(title) {
this.title = title
this.broken = 0
this.successes = 0
this.failures = 0
this.tests = {}
this.subs = {}
}
}
module.exports = Report
| // report.js -- Report of the results of a batch and its sub-batches
//
// Copyright 2017 fuzzy.ai <evan@fuzzy.ai>
//
// 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.
/* jshint esversion: 6 */
class Report {
constructor(title) {
this.title = title
this.broken = 0
this.successes = 0
this.failures = 0
this.tests = {}
this.subs = {}
}
}
module.exports = Report
|
Use all 8 decimal places currency details | <?php
namespace Emailme\Currency;
use Exception;
use Emailme\Debug\Debug;
/*
* CurrencyUtil
*/
class CurrencyUtil
{
const SATOSHI = 100000000;
////////////////////////////////////////////////////////////////////////
public static function numberToSatoshis($number) {
return intval(round($number * self::SATOSHI));
}
public static function satoshisToNumber($satoshis, $places=null) {
if (!strlen($satoshis)) { return $satoshis; }
if ($places === null) { $places = 8; }
$out = number_format($satoshis / self::SATOSHI, $places);
if (strpos($out, '.') !== false) {
$out = rtrim($out, '0');
$out = rtrim($out, '.');
}
return $out;
}
public static function addTwigFilters($twig) {
$filter = new \Twig_SimpleFilter('to_currency', function ($satoshis) {
return CurrencyUtil::satoshisToNumber($satoshis);
});
$twig->addFilter($filter);
return $twig;
}
////////////////////////////////////////////////////////////////////////
}
| <?php
namespace Emailme\Currency;
use Exception;
use Emailme\Debug\Debug;
/*
* CurrencyUtil
*/
class CurrencyUtil
{
const SATOSHI = 100000000;
////////////////////////////////////////////////////////////////////////
public static function numberToSatoshis($number) {
return intval(round($number * self::SATOSHI));
}
public static function satoshisToNumber($satoshis, $places=null) {
if (!strlen($satoshis)) { return $satoshis; }
if ($places === null) { $places = 7; }
$out = number_format($satoshis / self::SATOSHI, $places);
if (strpos($out, '.') !== false) {
$out = rtrim($out, '0');
$out = rtrim($out, '.');
}
return $out;
}
public static function addTwigFilters($twig) {
$filter = new \Twig_SimpleFilter('to_currency', function ($satoshis) {
return CurrencyUtil::satoshisToNumber($satoshis);
});
$twig->addFilter($filter);
return $twig;
}
////////////////////////////////////////////////////////////////////////
}
|
Copy static dirs as well | import os.path
from shutil import copyfile
from shutil import copytree
from shutil import rmtree
try:
from jinja2 import Template
except:
print "Could not import Jinja2, run 'easy_install Jinja2'"
exit()
output_dir = os.path.join('./', 'chrome_webstore')
if os.path.exists(output_dir):
rmtree(output_dir)
os.makedirs(output_dir)
def add_background_script():
copyfile('chrome_webstore_background.js', os.path.join(output_dir, 'background.js'))
def copy_static_dirs():
copytree('images', os.path.join(output_dir, 'images'))
copytree('styles', os.path.join(output_dir, 'styles'))
copytree('scripts', os.path.join(output_dir, 'scripts'))
def add_manifest():
copyfile('chrome_webstore_manifest.json', os.path.join(output_dir, 'manifest.json'))
def render_main_template():
f = open('./html/index.html')
template = Template(f.read().decode('utf-8'))
f.close()
html = template.render(og_tag='', url='', ON_PRODUCTION=True, ON_DEV=False, USE_PRODUCTION_JAVASCRIPT=True)
f = open(os.path.join(output_dir, 'index.html'), 'w')
f.write(html.encode('utf-8'))
f.close()
print "Template rendered"
add_manifest()
add_background_script()
render_main_template()
copy_static_dirs()
| import os.path
from shutil import copyfile
try:
from jinja2 import Template
except:
print "Could not import Jinja2, run 'easy_install Jinja2'"
exit()
output_dir = os.path.join('./', 'chrome_webstore')
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def add_background_script():
copyfile('chrome_webstore_background.js', os.path.join(output_dir, 'background.js'))
def add_manifest():
copyfile('chrome_webstore_manifest.json', os.path.join(output_dir, 'manifest.json'))
def render_main_template():
f = open('./html/index.html')
template = Template(f.read().decode('utf-8'))
f.close()
html = template.render(og_tag='', url='', ON_PRODUCTION=True, ON_DEV=False, USE_PRODUCTION_JAVASCRIPT=True)
f = open(os.path.join(output_dir, 'index.html'), 'w')
f.write(html.encode('utf-8'))
f.close()
print "Template rendered"
add_manifest()
add_background_script()
render_main_template()
|
Add target blank for anchors in paragraph block. | export const sizing = (textSize, align) => ({
a: {
props: {
target: '_blank',
},
},
p: {
props: {
size: textSize,
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h1: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h2: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h3: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h4: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h5: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
}); | export const sizing = (textSize, align) => ({
p: {
props: {
size: textSize,
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h1: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h2: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h3: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h4: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
h5: {
props: {
margin: 'small',
align,
style: {
marginTop: 0,
},
},
},
}); |
Make bgl the default OpenGL implementation snice it is currently faster than PyOpenGL. | # This file handles differences between BGL and PyOpenGL, and provides various
# utility functions for OpenGL
try:
from bgl import *
USING_BGL = True
except ImportError:
from OpenGL.GL import *
from OpenGL.GLU import *
from bgl import Buffer
if USING_BGL:
_glGenTextures = glGenTextures
def glGenTextures(n, textures=None):
id_buf = Buffer(GL_INT, n)
_glGenTextures(n, id_buf)
if textures:
textures.extend(id_buf.to_list())
return id_buf.to_list()[0] if n == 1 else id_buf.to_list()
_glDeleteTextures = glDeleteTextures
def glDeleteTextures(textures):
n = len(textures)
id_buf = Buffer(GL_INT, n, textures)
_glDeleteTextures(n, id_buf)
_glGetIntegerv = glGetIntegerv
def glGetIntegerv(pname):
# Only used for GL_VIEWPORT right now, so assume we want a size 4 Buffer
buf = Buffer(GL_INT, 4)
_glGetIntegerv(pname, buf)
return buf.to_list()
else:
_glTexImage2D = glTexImage2D
def glTexImage2D(target, level, internalFormat, width, height, border, format, type, data):
_glTexImage2D(target, level, internalFormat, width, height,
border, format, type, data.to_list())
| # This file handles differences between BGL and PyOpenGL, and provides various
# utility functions for OpenGL
try:
from OpenGL.GL import *
from OpenGL.GLU import *
from bgl import Buffer
USING_BGL = False
except ImportError:
from bgl import *
USING_BGL = True
if USING_BGL:
_glGenTextures = glGenTextures
def glGenTextures(n, textures=None):
id_buf = Buffer(GL_INT, n)
_glGenTextures(n, id_buf)
if textures:
textures.extend(id_buf.to_list())
return id_buf.to_list()[0] if n == 1 else id_buf.to_list()
_glDeleteTextures = glDeleteTextures
def glDeleteTextures(textures):
n = len(textures)
id_buf = Buffer(GL_INT, n, textures)
_glDeleteTextures(n, id_buf)
_glGetIntegerv = glGetIntegerv
def glGetIntegerv(pname):
# Only used for GL_VIEWPORT right now, so assume we want a size 4 Buffer
buf = Buffer(GL_INT, 4)
_glGetIntegerv(pname, buf)
return buf.to_list()
else:
_glTexImage2D = glTexImage2D
def glTexImage2D(target, level, internalFormat, width, height, border, format, type, data):
_glTexImage2D(target, level, internalFormat, width, height,
border, format, type, data.to_list())
|
feat: Change background of spinner to match login | import React from 'react';
import '../../aframeComponents/scene-load';
import '../../aframeComponents/aframe-minecraft';
import AssetLoader from './AssetLoader';
import InitialLoading from './InitialLoading';
export default function App (props) {
console.log('props ', props);
return (
// AssetLoader is a stateless component containing the a-assets for all of the React components
// rendered via props.children. It must reside here because A-Frame requires a-assets to a
// direct child of a-scene.
<div style={{ width: '100%', height: '100%' }}>
{!props.isLoaded ? (
<div id="loadScreen" style={{ width: '100%', height: '100%', backgroundImage: 'url(/images/background.png)', display: 'flex', alignItems: 'center', flexDirection: 'row', justifyContent: 'center' }}>
<InitialLoading/>
</div>
)
: null
}
<a-scene id="scene" scene-load>
<AssetLoader />
{props.children}
</a-scene>
</div>
);
}
| import React from 'react';
import '../../aframeComponents/scene-load';
import '../../aframeComponents/aframe-minecraft';
import AssetLoader from './AssetLoader';
import InitialLoading from './InitialLoading';
export default function App (props) {
console.log('props ', props);
return (
// AssetLoader is a stateless component containing the a-assets for all of the React components
// rendered via props.children. It must reside here because A-Frame requires a-assets to a
// direct child of a-scene.
<div style={{ width: '100%', height: '100%' }}>
{!props.isLoaded ? (
<div id="loadScreen" style={{ width: '100%', height: '100%', background: '#72C8F1', display: 'flex', alignItems: 'center', flexDirection: 'row', justifyContent: 'center' }}>
<InitialLoading/>
</div>
)
: null
}
<a-scene id="scene" scene-load>
<AssetLoader />
{props.children}
</a-scene>
</div>
);
}
|
Fix database infra save method | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
from django import forms
from .. import models
log = logging.getLogger(__name__)
class DatabaseInfraForm(forms.ModelForm):
class Meta:
model = models.DatabaseInfra
def __init__(self, *args, **kwargs):
if args and 'disk_offering' in args[0]:
disk_offering = args[0]['disk_offering']
plan_id = args[0]['plan']
if not disk_offering and plan_id:
plan = models.Plan.objects.get(id=plan_id)
if plan.disk_offering:
args[0]['disk_offering'] = plan.disk_offering.id
super(DatabaseInfraForm, self).__init__(*args, **kwargs)
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
from django import forms
from .. import models
log = logging.getLogger(__name__)
class DatabaseInfraForm(forms.ModelForm):
class Meta:
model = models.DatabaseInfra
def __init__(self, *args, **kwargs):
if args:
disk_offering = args[0]['disk_offering']
plan_id = args[0]['plan']
if not disk_offering and plan_id:
plan = models.Plan.objects.get(id=plan_id)
if plan.disk_offering:
args[0]['disk_offering'] = plan.disk_offering.id
super(DatabaseInfraForm, self).__init__(*args, **kwargs)
|
Add defaults for cache control start and end times. | package uk.ac.ebi.quickgo.ontology;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalTime;
/**
* Holds values related to the operation of the Ontology REST service.
* <p>
* Created by Tony on 04-Apr-17.
*/
@Component
@ConfigurationProperties(prefix = "ontology.cache.control.time")
public class OntologyRestProperties {
private static final int MINUTES = 0;
private static final int DEFAULT_START_HOURS = 18;
private static final int DEFAULT_END_HOURS = 17;
private LocalTime startTime = LocalTime.of(DEFAULT_START_HOURS, MINUTES);
private LocalTime endTime = LocalTime.of(DEFAULT_END_HOURS, MINUTES);
private long midnightToEndCacheTime;
public void setStart(int hours) {
startTime = LocalTime.of(hours, MINUTES);
}
public void setEnd(int hours) {
endTime = LocalTime.of(hours, MINUTES);
this.midnightToEndCacheTime = Duration.between(LocalTime.MIDNIGHT, endTime).getSeconds();
}
public LocalTime getStartTime() {
return startTime;
}
public LocalTime getEndTime() {
return endTime;
}
public long midnightToEndCacheTime() {
return midnightToEndCacheTime;
}
}
| package uk.ac.ebi.quickgo.ontology;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalTime;
/**
* Holds values related to the operation of the Ontology REST service.
* <p>
* Created by Tony on 04-Apr-17.
*/
@Component
@ConfigurationProperties(prefix = "ontology.cache.control.time")
public class OntologyRestProperties {
private static final int MINUTES = 0;
private LocalTime startTime;
private LocalTime endTime;
private long midnightToEndCacheTime;
public void setStart(int hours) {
startTime = LocalTime.of(hours, MINUTES);
}
public void setEnd(int hours) {
endTime = LocalTime.of(hours, MINUTES);
this.midnightToEndCacheTime = Duration.between(LocalTime.MIDNIGHT, endTime).getSeconds();
}
public LocalTime getStartTime() {
return startTime;
}
public LocalTime getEndTime() {
return endTime;
}
public long midnightToEndCacheTime() {
return midnightToEndCacheTime;
}
}
|
Add correct documentation for variantForOptions from product helpers | /**
* @namespace ProductHelpers
*/
export default {
/**
* Returns the variant of a product corresponding to the options given.
*
* @example
* const selectedVariant = client.product.helpers.variantForOptions(product, {
* size: "Small",
* color: "Red"
* });
*
* @memberof ProductHelpers
* @method variantForOptions
* @param {GraphModel} product The product to find the variant on. Must include `variants`.
* @param {Object} options An object containing the options for the variant.
* @return {GraphModel} The variant corresponding to the options given.
*/
variantForOptions(product, options) {
return product.variants.find((variant) => {
return variant.selectedOptions.every((selectedOption) => {
return options[selectedOption.name] === selectedOption.value.valueOf();
});
});
}
};
| /**
* @namespace ProductHelpers
*/
export default {
/**
* Returns the variant of a product corresponding to the options given.
*
* @example
* const selectedVariant = client.product.variantForOptions(product, {
* size: "Small",
* color: "Red"
* });
*
* @memberof ProductHelpers
* @method variantForOptions
* @param {GraphModel} product The product to find the variant on. Must include `variants`.
* @param {Object} options An object containing the options for the variant.
* @return {GraphModel} The variant corresponding to the options given.
*/
variantForOptions(product, options) {
return product.variants.find((variant) => {
return variant.selectedOptions.every((selectedOption) => {
return options[selectedOption.name] === selectedOption.value.valueOf();
});
});
}
};
|
Fix thread color parameter as optional | "use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function changeThreadColor(color, threadID, callback) {
if(!callback) {
callback = function() {};
}
var form = {
'color_choice' : color,
'thread_or_other_fbid' : threadID
};
defaultFuncs
.post("https://www.messenger.com/messaging/save_thread_color/?source=thread_settings&dpr=1", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.error === 1357031) {
throw {error: "Trying to change colors of a chat that doesn't exist. Have at least one message in the thread before trying to change the colors."};
}
if (resData.error) {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("Error in changeThreadColor", err);
return callback(err);
});
};
};
| "use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function(defaultFuncs, api, ctx) {
return function changeThreadColor(color, threadID, callback) {
var form = {
'color_choice' : color,
'thread_or_other_fbid' : threadID
};
defaultFuncs
.post("https://www.messenger.com/messaging/save_thread_color/?source=thread_settings&dpr=1", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx.jar, defaultFuncs))
.then(function(resData) {
if (resData.error === 1357031) {
throw {error: "Trying to change colors of a chat that doesn't exist. Have at least one message in the thread before trying to change the colors."};
}
if (resData.error) {
throw resData;
}
return callback();
})
.catch(function(err) {
log.error("Error in changeThreadColor", err);
return callback(err);
});
};
};
|
Fix event type in handler manager | import React from 'react';
import PropTypes from 'prop-types';
import { withModules } from '../Modules';
import { stripesShape } from '../../Stripes';
import { getHandlerComponents } from '../../handlerService';
class HandlerManager extends React.Component {
static propTypes = {
stripes: stripesShape.isRequired,
event: PropTypes.string,
data: PropTypes.object,
modules: PropTypes.shape({
handler: PropTypes.array,
}),
props: PropTypes.object,
};
constructor(props) {
super(props);
const { event, stripes, modules, data } = props;
this.components = getHandlerComponents(event, stripes, modules.handler, data);
}
render() {
const { stripes, data, props } = this.props;
return (this.components.map(Component =>
(<Component key={Component.name} stripes={stripes} data={data} {...props} />)));
}
}
export default withModules(HandlerManager);
| import React from 'react';
import PropTypes from 'prop-types';
import { withModules } from '../Modules';
import { stripesShape } from '../../Stripes';
import { getHandlerComponents } from '../../handlerService';
class HandlerManager extends React.Component {
static propTypes = {
stripes: stripesShape.isRequired,
event: PropTypes.number,
data: PropTypes.object,
modules: PropTypes.shape({
handler: PropTypes.array,
}),
props: PropTypes.object,
};
constructor(props) {
super(props);
const { event, stripes, modules, data } = props;
this.components = getHandlerComponents(event, stripes, modules.handler, data);
}
render() {
const { stripes, data, props } = this.props;
return (this.components.map(Component =>
(<Component key={Component.name} stripes={stripes} data={data} {...props} />)));
}
}
export default withModules(HandlerManager);
|
Fix a couple trivial bugs. | class UnitId:
def __init__(self, playerId, unitSubId):
self.playerId = playerId
self.subId = unitSubId
def __eq__(self, other):
return self.playerId == other.playerId and self.subId == other.subId
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash((self.playerId, self.subId))
def __repr__(self):
return repr((self.playerId, self.subId))
def unitToPlayer(unitId):
return unitId.playerId
# FIXME [#15]: This function shouldn't exist.
def playerToUnit(playerId):
return UnitId(playerId, 0)
# For using UnitIds in messages
def encodeUnitId(unitId):
return (str(unitId.playerId), str(unitId.subId))
def parseUnitId(words):
# TODO: Somewhere higher up, handle all exceptions in parsing functions and
# turn them into InvalidMessageErrors. Do we do this already?
playerId, subId = map(int, words)
return UnitId(playerId, subId)
| class UnitId:
def __init__(self, playerId, unitSubId):
self.playerId = playerId
self.subId = unitSubId
def __eq__(self, rhs):
return self.playerId == rhs.playerId and self.subId == other.subId
def __ne__(self, rhs):
return not (self == rhs)
def __hash__(self):
return hash((self.playerId, self.unitSubId))
def __repr__(self):
return repr((self.playerId, self.unitSubId))
def unitToPlayer(unitId):
return unitId.playerId
# FIXME [#15]: This function shouldn't exist.
def playerToUnit(playerId):
return UnitId(playerId, 0)
# For using UnitIds in messages
def encodeUnitId(unitId):
return (str(unitId.playerId), str(unitId.subId))
def parseUnitId(words):
# TODO: Somewhere higher up, handle all exceptions in parsing functions and
# turn them into InvalidMessageErrors. Do we do this already?
playerId, subId = map(int, words)
return UnitId(playerId, subId)
|
Change default terminal size arguments - Add server debug log message | # -*- coding: iso-8859-15 -*-
"""Main HTTP routes request handlers."""
import tornado.web
import tornado.escape
from os import getcwd
class MainHandler(tornado.web.RequestHandler):
"""Handles creation of new terminals."""
@tornado.gen.coroutine
def post(self):
"""POST verb: Create a new terminal."""
rows = int(self.get_argument('rows', default=23))
cols = int(self.get_argument('cols', default=73))
cwd = self.get_cookie('cwd', default=getcwd())
self.application.logger.info('CWD: {0}'.format(cwd))
self.application.logger.info('Size: ({0}, {1})'.format(cols, rows))
pid = yield self.application.term_manager.create_term(rows, cols, cwd)
self.write(pid)
class ResizeHandler(tornado.web.RequestHandler):
"""Handles resizing of terminals."""
@tornado.gen.coroutine
def post(self, pid):
"""POST verb: Resize a terminal."""
rows = int(self.get_argument('rows', None, 23))
cols = int(self.get_argument('cols', None, 73))
self.application.term_manager.resize_term(pid, rows, cols)
| # -*- coding: iso-8859-15 -*-
"""Main HTTP routes request handlers."""
import tornado.web
import tornado.escape
from os import getcwd
class MainHandler(tornado.web.RequestHandler):
"""Handles creation of new terminals."""
@tornado.gen.coroutine
def post(self):
"""POST verb: Create a new terminal."""
rows = int(self.get_argument('rows', None, 23))
cols = int(self.get_argument('cols', None, 73))
cwd = self.get_cookie('cwd', default=getcwd())
self.application.logger.info('CWD: {0}'.format(cwd))
pid = yield self.application.term_manager.create_term(rows, cols, cwd)
self.write(pid)
class ResizeHandler(tornado.web.RequestHandler):
"""Handles resizing of terminals."""
@tornado.gen.coroutine
def post(self, pid):
"""POST verb: Resize a terminal."""
rows = int(self.get_argument('rows', None, 23))
cols = int(self.get_argument('cols', None, 73))
self.application.term_manager.resize_term(pid, rows, cols)
|
Add todo for signed phars | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
/**
* Downloader for phar files
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class PharDownloader extends FileDownloader
{
/**
* {@inheritDoc}
*/
protected function extract($file, $path)
{
// Can throw an UnexpectedValueException
$archive = new \Phar($file);
$archive->extractTo($path);
/* TODO: handle openssl signed phars
* https://github.com/composer/composer/pull/33#issuecomment-2250768
* https://github.com/koto/phar-util
* http://blog.kotowicz.net/2010/08/hardening-php-how-to-securely-include.html
*/
}
}
| <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Downloader;
use Composer\Package\PackageInterface;
/**
* Downloader for phar files
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class PharDownloader extends FileDownloader
{
/**
* {@inheritDoc}
*/
protected function extract($file, $path)
{
// Can throw an UnexpectedValueException
$archive = new \Phar($file);
$archive->extractTo($path);
}
}
|
Add gnu99 build flag for linuxy builds | #!/usr/bin/env python
"""
setup.py file for helium-client-python
"""
from distutils.core import setup, Extension
sourcefiles = ['src/helium_client.c',
'src/helium-serial.c',
'src/helium-client/helium-client.c',
'src/helium-client/cauterize/atom_api.c',
'src/helium-client/cauterize/atom_api_message.c',
'src/helium-client/cauterize/cauterize.c']
extensions = [Extension('helium_client',
include_dirs=['src/helium-client'],
extra_compile_args=['-std=gnu99'],
sources=sourcefiles)]
setup(name='helium-client',
version='0.1',
author="Helium Client",
description="""Python interface to the Helium Atom""",
ext_modules=extensions)
| #!/usr/bin/env python
"""
setup.py file for helium-client-python
"""
from distutils.core import setup, Extension
sourcefiles = ['src/helium_client.c',
'src/helium-serial.c',
'src/helium-client/helium-client.c',
'src/helium-client/cauterize/atom_api.c',
'src/helium-client/cauterize/atom_api_message.c',
'src/helium-client/cauterize/cauterize.c']
extensions = [Extension('helium_client',
include_dirs=['src/helium-client'],
sources=sourcefiles)]
setup(name='helium-client',
version='0.1',
author="Helium Client",
description="""Python interface to the Helium Atom""",
ext_modules=extensions)
|
Remove page title from frontpage
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php
/*
|--------------------------------------------------------------------------
| HTML::title() macro
|--------------------------------------------------------------------------
|
| Page title macro helper.
|
*/
HTML::macro('title', function ($page_title)
{
$memory = Orchestra::memory();
$site_title = $memory->get('site.name');
$page_title = trim($page_title);
$format = $memory->get('site.format.title', ':page-title — :site-title');
if (empty($page_title) or URI::is('/')) return $site_title;
return strtr($format, array(
":site-title" => $site_title,
":page-title" => $page_title,
));
});
/*
|--------------------------------------------------------------------------
| Blade extend for @placeholder
|--------------------------------------------------------------------------
|
| Placeholder is Orchestra version of widget for theme.
|
*/
Blade::extend(function ($view)
{
$pattern = '/(\s*)@placeholder\s?\(\s*(.*)\)/';
$replacement = '$1<?php foreach (Orchestra\Widget::make("placeholder.".$2)->get() as $_placeholder_): echo value($_placeholder_->value ?:""); endforeach; ?>';
return preg_replace($pattern, $replacement, $view);
});
| <?php
/*
|--------------------------------------------------------------------------
| HTML::title() macro
|--------------------------------------------------------------------------
|
| Page title macro helper.
|
*/
HTML::macro('title', function ($page_title)
{
$memory = Orchestra::memory();
$site_title = $memory->get('site.name');
$page_title = trim($page_title);
$format = $memory->get('site.format.title', ':page-title — :site-title');
if (empty($page_title)) return $site_title;
return strtr($format, array(
":site-title" => $site_title,
":page-title" => $page_title,
));
});
/*
|--------------------------------------------------------------------------
| Blade extend for @placeholder
|--------------------------------------------------------------------------
|
| Placeholder is Orchestra version of widget for theme.
|
*/
Blade::extend(function ($view)
{
$pattern = '/(\s*)@placeholder\s?\(\s*(.*)\)/';
$replacement = '$1<?php foreach (Orchestra\Widget::make("placeholder.".$2)->get() as $_placeholder_): echo value($_placeholder_->value ?:""); endforeach; ?>';
return preg_replace($pattern, $replacement, $view);
});
|
Remove trailing comma not compatible with Python 3.5 | from enum import Enum
from .base import Item
class KeepDirectories(Enum):
NONE = 'none'
SUFFIX = 'suffix'
FULL = 'full'
@classmethod
def cast(cls, value):
if not value:
return KeepDirectories.NONE
if value is True:
return KeepDirectories.FULL
return KeepDirectories(str(value).lower())
class Input(Item):
def __init__(
self,
*,
name,
default=None,
optional=False,
description=None,
keep_directories=False,
filename=None
) -> None:
self.name = name
self.default = default # may be None, a string or a list of strings
self.optional = bool(optional)
self.description = description
self.keep_directories = KeepDirectories.cast(keep_directories)
self.filename = filename
def get_data(self) -> dict:
data = super().get_data()
if self.keep_directories is not KeepDirectories.NONE:
data['keep_directories'] = data['keep_directories'].value
else:
data.pop('keep_directories', None)
return data
| from enum import Enum
from .base import Item
class KeepDirectories(Enum):
NONE = 'none'
SUFFIX = 'suffix'
FULL = 'full'
@classmethod
def cast(cls, value):
if not value:
return KeepDirectories.NONE
if value is True:
return KeepDirectories.FULL
return KeepDirectories(str(value).lower())
class Input(Item):
def __init__(
self,
*,
name,
default=None,
optional=False,
description=None,
keep_directories=False,
filename=None,
) -> None:
self.name = name
self.default = default # may be None, a string or a list of strings
self.optional = bool(optional)
self.description = description
self.keep_directories = KeepDirectories.cast(keep_directories)
self.filename = filename
def get_data(self) -> dict:
data = super().get_data()
if self.keep_directories is not KeepDirectories.NONE:
data['keep_directories'] = data['keep_directories'].value
else:
data.pop('keep_directories', None)
return data
|
Terminate gracefully on nearing memory limit
If the process is approaching the configured memory limit then terminate gracefully instead of allowing the process to hit the limit and crash losing data. | 'use strict';
const v8 = require('v8');
const Promise = require('bluebird');
const times = require('./times');
const page = require('./page');
const zip = require('./zip');
function runner (opts) {
const iterator = (url) => page(Object.assign({}, opts, { url: url }));
const concurrency = opts.parallel ? opts.url.length : 1;
let interrupted = false;
process.on('SIGINT', () => {
if (interrupted) {
process.exit();
} else {
interrupted = true;
console.log('\nShutting down gracefully - CTRL^C again to terminate immediately');
}
});
return Promise.reduce(times(opts.count), (results, i) => {
if (interrupted) {
// if count is set very high then we can hit maximum call stack size
// introduce some async every 1000 iterations to break call stack
return i % 1000 ? results : Promise.delay(0).then(() => results);
}
const memory = v8.getHeapStatistics();
if (memory.total_available_size / memory.heap_size_limit < 0.1) {
console.log('Less than 10% of process memory limit remaining. Terminating...');
console.log('To increase available memory start with `--max_old_space_size=<size>`');
interrupted = true;
return results;
} else {
return Promise.map(opts.url, iterator, { concurrency: concurrency })
.then((logs) => results.concat([logs]));
}
}, [])
.then(zip);
}
module.exports = runner;
| 'use strict';
const Promise = require('bluebird');
const times = require('./times');
const page = require('./page');
const zip = require('./zip');
function runner (opts) {
const iterator = (url) => page(Object.assign({}, opts, { url: url }));
const concurrency = opts.parallel ? opts.url.length : 1;
let interrupted = false;
process.on('SIGINT', () => {
if (interrupted) {
process.exit();
} else {
interrupted = true;
console.log('Shutting down - press CTRL^C again to terminate immediately');
}
});
return Promise.reduce(times(opts.count), (results) => {
if (interrupted) {
return results;
} else {
return Promise.map(opts.url, iterator, { concurrency: concurrency })
.then((logs) => results.concat([logs]));
}
}, [])
.then(zip);
}
module.exports = runner;
|
Allow passing more params to trackPageView | import Ember from 'ember';
export default Ember.Mixin.create({
init: function() {
this._super();
if(!this.hasAnalytics()) {
Ember.Logger.warn('Segment.io is not loaded yet (window.analytics)');
}
},
hasAnalytics: function() {
return !!(window.analytics && typeof window.analytics === "object");
},
log: function() {
if(this.config && this.config.segment && this.config.segment.LOG_EVENT_TRACKING) {
Ember.Logger.info('[Segment.io] ', arguments);
}
},
trackPageView: function() {
if(this.hasAnalytics()) {
window.analytics.page.apply(this, arguments);
this.log('trackPageView', arguments);
}
},
trackEvent: function(event, properties, options, callback) {
if(this.hasAnalytics()) {
window.analytics.track(event, properties, options, callback);
this.log(event, properties, options);
}
},
identifyUser: function(userId, traits, options, callback) {
if(this.hasAnalytics()) {
window.analytics.identify(userId, traits, options, callback);
this.log('identifyUser', traits, options);
}
},
aliasUser: function(userId, previousId, options, callback) {
if(this.hasAnalytics()) {
window.analytics.alias(userId, previousId, options, callback);
this.log('aliasUser', previousId, options);
}
}
});
| import Ember from 'ember';
export default Ember.Mixin.create({
init: function() {
this._super();
if(!this.hasAnalytics()) {
Ember.Logger.warn('Segment.io is not loaded yet (window.analytics)');
}
},
hasAnalytics: function() {
return !!(window.analytics && typeof window.analytics === "object");
},
log: function() {
if(this.config && this.config.segment && this.config.segment.LOG_EVENT_TRACKING) {
Ember.Logger.info('[Segment.io] ', arguments);
}
},
trackPageView: function(page) {
if(this.hasAnalytics()) {
window.analytics.page(page);
this.log('trackPageView', page);
}
},
trackEvent: function(event, properties, options, callback) {
if(this.hasAnalytics()) {
window.analytics.track(event, properties, options, callback);
this.log(event, properties, options);
}
},
identifyUser: function(userId, traits, options, callback) {
if(this.hasAnalytics()) {
window.analytics.identify(userId, traits, options, callback);
this.log('identifyUser', traits, options);
}
},
aliasUser: function(userId, previousId, options, callback) {
if(this.hasAnalytics()) {
window.analytics.alias(userId, previousId, options, callback);
this.log('aliasUser', previousId, options);
}
}
});
|
Reduce string duplication in autodisovery code | /**
* Utility methods used when querying a site in order to discover its available
* API endpoints
*
* @module autodiscovery
*/
'use strict';
const parseLinkHeader = require( 'parse-link-header' );
/**
* Attempt to locate a `rel="https://api.w.org"` link relation header
*
* @method locateAPIRootHeader
* @param {Object} response A response object with a link or headers property
* @returns {String} The URL of the located API root
*/
function locateAPIRootHeader( response ) {
// See https://developer.wordpress.org/rest-api/using-the-rest-api/discovery/
const rel = 'https://api.w.org/';
// Extract & parse the response link headers
const link = response.link || ( response.headers && response.headers.link );
const headers = parseLinkHeader( link );
const apiHeader = headers && headers[ rel ];
if ( apiHeader && apiHeader.url ) {
return apiHeader.url;
}
throw new Error( `No header link found with rel="${ rel }"` );
}
module.exports = {
locateAPIRootHeader: locateAPIRootHeader,
};
| /**
* Utility methods used when querying a site in order to discover its available
* API endpoints
*
* @module autodiscovery
*/
'use strict';
const parseLinkHeader = require( 'parse-link-header' );
/**
* Attempt to locate a `rel="https://api.w.org"` link relation header
*
* @method locateAPIRootHeader
* @param {Object} response A response object with a link or headers property
* @returns {String} The URL of the located API root
*/
function locateAPIRootHeader( response ) {
// Extract & parse the response link headers
const link = response.link || ( response.headers && response.headers.link );
const headers = parseLinkHeader( link );
// See https://developer.wordpress.org/rest-api/using-the-rest-api/discovery/
const apiHeader = headers && headers[ 'https://api.w.org/' ];
if ( apiHeader && apiHeader.url ) {
return apiHeader.url;
}
throw new Error( 'No header link found with rel="https://api.w.org/"' );
}
module.exports = {
locateAPIRootHeader: locateAPIRootHeader,
};
|
Move import that depends on devserver | import os
from django.core import checks
from djangae.environment import get_application_root
def check_deferred_builtin(app_configs=None, **kwargs):
"""
Check that the deferred builtin is switched off, as it'll override Djangae's deferred handler
"""
from google.appengine.tools.devappserver2.application_configuration import ModuleConfiguration
app_yaml_path = os.path.join(get_application_root(), "app.yaml")
config = ModuleConfiguration(app_yaml_path)
errors = []
for handler in config.handlers:
if handler.url == '/_ah/queue/deferred':
if handler.script == 'google.appengine.ext.deferred.application':
errors.append(
checks.Warning(
"Deferred builtin is switched on. This overrides Djangae's deferred handler",
hint='Remove deferred builtin from app.yaml',
id='djangae.W001'
)
)
break
return errors
| import os
from django.core import checks
from google.appengine.tools.devappserver2.application_configuration import ModuleConfiguration
from djangae.environment import get_application_root
def check_deferred_builtin(app_configs=None, **kwargs):
"""
Check that the deferred builtin is switched off, as it'll override Djangae's deferred handler
"""
app_yaml_path = os.path.join(get_application_root(), "app.yaml")
config = ModuleConfiguration(app_yaml_path)
errors = []
for handler in config.handlers:
if handler.url == '/_ah/queue/deferred':
if handler.script == 'google.appengine.ext.deferred.application':
errors.append(
checks.Warning(
"Deferred builtin is switched on. This overrides Djangae's deferred handler",
hint='Remove deferred builtin from app.yaml',
id='djangae.W001'
)
)
break
return errors
|
Fix in defining keys for x,y | var util = require('util');
GeometryBounds = function(bounds) {
this.xKey = "x";
this.yKey = "y";
this.bounds = [];
if(!bounds || !bounds[0] || !bounds[0][0]) return;
this.xKey = Object.keys(bounds[0][0])[0];
this.yKey = Object.keys(bounds[0][0])[1];
for(var b1 in bounds) {
var constructedBound = [];
var bound = bounds[b1];
for(var b2 in bound) {
var constructedPoint = [];
var point = bound[b2];
constructedPoint.push(parseFloat(point[this.xKey]));
constructedPoint.push(parseFloat(point[this.yKey]));
}
}
}
GeometryBounds.prototype.contains = function contains(dot) {
if(dot == null || !(this.xKey in dot) || !(this.yKey in dot)) {
return false;
}
var x = parseFloat(dot[this.xKey]);
var y = parseFloat(dot[this.yKey]);
console.log(this.bounds);
for(var index in this.bounds) {
if(testInPolygon(this.bounds[index], x, y)) return true;
}
return false;
}
function testInPolygon(bound, x, y) {
var c = false;
console.log(bound);
for(i = 0, j = bound.length - 1; i < bound.length; j = i++) {
console.log(util.format("i = %d, j = %d", i, j));
}
}
exports.GeometryBounds = GeometryBounds;
| var util = require('util');
GeometryBounds = function(bounds) {
this.xKey = "x";
this.yKey = "y";
this.bounds = [];
if(!bounds || !bounds[0]) return;
this.xKey = Object.keys(bounds[0])[0];
this.yKey = Object.keys(bounds[0])[1];
for(var b1 in bounds) {
var constructedBound = [];
var bound = bounds[b1];
for(var b2 in bound) {
var constructedPoint = [];
var point = bound[b2];
constructedPoint.push(parseFloat(point[this.xKey]));
constructedPoint.push(parseFloat(point[this.yKey]));
}
}
}
GeometryBounds.prototype.contains = function contains(dot) {
if(dot == null || !(this.xKey in dot) || !(this.yKey in dot)) {
return false;
}
var x = parseFloat(dot[this.xKey]);
var y = parseFloat(dot[this.yKey]);
for(var index in this.bounds) {
if(testInPolygon(this.bounds[index], x, y)) return true;
}
return false;
}
function testInPolygon(bound, x, y) {
var c = false;
for(i = 0, j = 1; i < bound.length; i++) {
}
}
exports.GeometryBounds = GeometryBounds;
|
[native] Fix bug where Lifecycle listener subscription wasn't being torn down properly | // @flow
import * as React from 'react';
import { useDispatch } from 'react-redux';
import {
backgroundActionType,
foregroundActionType,
} from 'lib/reducers/foreground-reducer';
import { appBecameInactive } from '../redux/redux-setup';
import { addLifecycleListener } from './lifecycle';
const LifecycleHandler = React.memo<{||}>(() => {
const dispatch = useDispatch();
const lastStateRef = React.useRef();
const onLifecycleChange = React.useCallback(
(nextState: ?string) => {
if (!nextState || nextState === 'unknown') {
return;
}
const lastState = lastStateRef.current;
lastStateRef.current = nextState;
if (lastState === 'background' && nextState === 'active') {
dispatch({ type: foregroundActionType, payload: null });
} else if (lastState !== 'background' && nextState === 'background') {
dispatch({ type: backgroundActionType, payload: null });
appBecameInactive();
}
},
[lastStateRef, dispatch],
);
React.useEffect(() => {
const subscription = addLifecycleListener(onLifecycleChange);
return () => subscription.remove();
}, [onLifecycleChange]);
return null;
});
LifecycleHandler.displayName = 'LifecycleHandler';
export default LifecycleHandler;
| // @flow
import * as React from 'react';
import { useDispatch } from 'react-redux';
import {
backgroundActionType,
foregroundActionType,
} from 'lib/reducers/foreground-reducer';
import { appBecameInactive } from '../redux/redux-setup';
import { addLifecycleListener } from './lifecycle';
const LifecycleHandler = React.memo<{||}>(() => {
const dispatch = useDispatch();
const lastStateRef = React.useRef();
const onLifecycleChange = React.useCallback(
(nextState: ?string) => {
if (!nextState || nextState === 'unknown') {
return;
}
const lastState = lastStateRef.current;
lastStateRef.current = nextState;
if (lastState === 'background' && nextState === 'active') {
dispatch({ type: foregroundActionType, payload: null });
} else if (lastState !== 'background' && nextState === 'background') {
dispatch({ type: backgroundActionType, payload: null });
appBecameInactive();
}
},
[lastStateRef, dispatch],
);
React.useEffect(() => {
const { remove } = addLifecycleListener(onLifecycleChange);
return remove;
}, [onLifecycleChange]);
return null;
});
LifecycleHandler.displayName = 'LifecycleHandler';
export default LifecycleHandler;
|
Add new-action button to toggle default_block for messages | $(document).on('page:load', init_default_data_block);
$(document).ready(init_default_data_block);
function init_default_data_block() {
$('.default_data_block .title').click(function () {
toggle_default_data_bloc(this, 400);
});
$('.new-action').click(function () {
var messages_block = $(this).parents().closest(".default_data_block").find(".title")
toggle_default_data_bloc(messages_block, 400);
});
$('.default_data_block.default_visible').each(function() {
toggle_default_data_bloc($(this).find('.title'), 0);
});
function toggle_default_data_bloc(element, duration){
var block = $(element).parents('.show-block');
if (block.attr("id") == "messages") {
block.children(".last-message").toggle();
}
block.children(".body").slideToggle(duration);
block.find(".carret-right").toggle();
block.find(".carret-down").toggle();
}
}
| $(document).on('page:load', init_default_data_block);
$(document).ready(init_default_data_block);
function init_default_data_block() {
$('.default_data_block .title').click(function () {
toggle_default_data_bloc(this, 400);
});
$('.default_data_block.default_visible').each(function() {
toggle_default_data_bloc($(this).find('.title'), 0);
});
function toggle_default_data_bloc(element, duration){
var block = $(element).parents('.show-block');
if (block.attr("id") == "messages") {
block.children(".last-message").toggle();
}
block.children(".body").slideToggle(duration);
block.find(".carret-right").toggle();
block.find(".carret-down").toggle();
}
}
|
Remove TID= from string representation of thread | // Package thread is designed for manage OS thread parameters. Usually you
// need to call runtime.LockOSThread before use it.
//
// Only String methods allocates memory (mainly because using of fmt package)
// so don't use them when GC is disabled.
package thread
import (
"fmt"
"github.com/ziutek/sched"
"syscall"
)
type Thread struct {
tid int
}
func Current() Thread {
tid, _, e := syscall.RawSyscall(syscall.SYS_GETTID, 0, 0, 0)
if e != 0 {
panic(e)
}
return Thread{int(tid)}
}
func (t Thread) String() string {
return fmt.Sprint(t.tid)
}
func (t Thread) SetSchedPolicy(policy sched.Policy, param *sched.Param) error {
return sched.SetPolicy(t.tid, policy, param)
}
func (t Thread) SchedPolicy() (sched.Policy, error) {
return sched.GetPolicy(t.tid)
}
func (t Thread) SetSchedParam(param *sched.Param) error {
return sched.SetParam(t.tid, param)
}
func (t Thread) SchedParam(param *sched.Param) error {
return sched.GetParam(t.tid, param)
}
| // Package thread is designed for manage OS thread parameters. Usually you
// need to call runtime.LockOSThread before use it.
//
// Only String methods allocates memory (mainly because using of fmt package)
// so don't use them when GC is disabled.
package thread
import (
"fmt"
"github.com/ziutek/sched"
"syscall"
)
type Thread struct {
tid int
}
func Current() Thread {
tid, _, e := syscall.RawSyscall(syscall.SYS_GETTID, 0, 0, 0)
if e != 0 {
panic(e)
}
return Thread{int(tid)}
}
func (t Thread) String() string {
return fmt.Sprint("TID=", t.tid)
}
func (t Thread) SetSchedPolicy(policy sched.Policy, param *sched.Param) error {
return sched.SetPolicy(t.tid, policy, param)
}
func (t Thread) SchedPolicy() (sched.Policy, error) {
return sched.GetPolicy(t.tid)
}
func (t Thread) SetSchedParam(param *sched.Param) error {
return sched.SetParam(t.tid, param)
}
func (t Thread) SchedParam(param *sched.Param) error {
return sched.GetParam(t.tid, param)
}
|
Throw error if app isn't authenticated | //= require ./core
//= require ./static_config
//= require_self
(function () {
if (!Drop.config.JSON_CONFIG_URL) {
throw Error("json_config_url is required!");
}
Drop.fetchConfig = function () {
new Marbles.HTTP({
method: 'GET',
url: Drop.config.JSON_CONFIG_URL,
middleware: [
Marbles.HTTP.Middleware.WithCredentials,
Marbles.HTTP.Middleware.SerializeJSON
],
callback: function (res, xhr) {
if (xhr.status !== 200) {
throw Error("failed to fetch json config: " + xhr.status + " - " + JSON.stringify(res));
}
if (!Drop.config) {
Drop.config = {};
}
for (var key in res) {
Drop.config[key] = res[key];
}
if (!Drop.config.meta) {
throw Error("invalid config! missing meta post: " + JSON.stringify(res));
}
Drop.config_ready = true;
Drop.trigger('config:ready');
}
});
};
Drop.fetchConfig();
})();
| //= require ./core
//= require ./static_config
//= require_self
(function () {
if (!Drop.config.JSON_CONFIG_URL) {
throw Error("json_config_url is required!");
}
Drop.fetchConfig = function () {
new Marbles.HTTP({
method: 'GET',
url: Drop.config.JSON_CONFIG_URL,
middleware: [
Marbles.HTTP.Middleware.WithCredentials,
Marbles.HTTP.Middleware.SerializeJSON
],
callback: function (res, xhr) {
if (xhr.status !== 200) {
throw Error("failed to fetch json config: " + xhr.status + " - " + JSON.stringify(res));
}
if (!Drop.config) {
Drop.config = {};
}
for (var key in res) {
Drop.config[key] = res[key];
}
Drop.config_ready = true;
Drop.trigger('config:ready');
}
});
};
Drop.fetchConfig();
})();
|
Revert "Updating version now that docs are up-to-date"
This reverts commit 3f2ed8f7bfbed7162f4047cea534d83e52e714af. | from setuptools import setup
config = {
'include_package_data': True,
'description': 'Simulated datasets of DNA',
'download_url': 'https://github.com/kundajelab/simdna',
'version': '0.4.3.2',
'packages': ['simdna', 'simdna.resources', 'simdna.synthetic'],
'package_data': {'simdna.resources': ['encode_motifs.txt.gz', 'HOCOMOCOv10_HUMAN_mono_homer_format_0.001.motif.gz']},
'setup_requires': [],
'install_requires': ['numpy>=1.9', 'matplotlib', 'scipy'],
'dependency_links': [],
'scripts': ['scripts/densityMotifSimulation.py',
'scripts/emptyBackground.py',
'scripts/motifGrammarSimulation.py',
'scripts/variableSpacingGrammarSimulation.py'],
'name': 'simdna'
}
if __name__== '__main__':
setup(**config)
| from setuptools import setup
config = {
'include_package_data': True,
'description': 'Simulated datasets of DNA',
'download_url': 'https://github.com/kundajelab/simdna',
'version': '0.4.3.3',
'packages': ['simdna', 'simdna.resources', 'simdna.synthetic'],
'package_data': {'simdna.resources': ['encode_motifs.txt.gz', 'HOCOMOCOv10_HUMAN_mono_homer_format_0.001.motif.gz']},
'setup_requires': [],
'install_requires': ['numpy>=1.9', 'matplotlib', 'scipy'],
'dependency_links': [],
'scripts': ['scripts/densityMotifSimulation.py',
'scripts/emptyBackground.py',
'scripts/motifGrammarSimulation.py',
'scripts/variableSpacingGrammarSimulation.py'],
'name': 'simdna'
}
if __name__== '__main__':
setup(**config)
|
:bug: Fix empty file at boot of backend | package commons
import (
"encoding/json"
"log"
"os"
)
type Manager interface {
Commit() error
GetSaveFilePath() (fullPath string, dirPath string, fileName string)
GetConfig() interface{}
}
func LoadFromDB(manager Manager) {
f, err := OpenSaveFile(manager, os.O_RDONLY)
defer f.Close()
Check(err)
err = json.NewDecoder(f).Decode(manager.GetConfig())
log.Println(err)
Check(err)
}
func Commit(manager Manager) error {
configFullPath, _, configFileName := manager.GetSaveFilePath()
f, err := OpenSaveFile(manager, os.O_WRONLY)
defer f.Close()
if err != nil {
log.Printf("Unable to open configuration file %s (%s) : %s", configFileName, configFullPath, err)
return err
}
if err = json.NewEncoder(f).Encode(manager.GetConfig()); err != nil {
log.Printf("Unable to write in configuration file %s (%s) : %s", configFileName, configFullPath, err)
}
return err
}
func OpenSaveFile(manager Manager, osFlag int) (*os.File, error) {
configFullPath, _, _ := manager.GetSaveFilePath()
return os.OpenFile(configFullPath, osFlag|os.O_CREATE, 0644)
}
| package commons
import (
"encoding/json"
"log"
"os"
)
type Manager interface {
Commit() error
GetSaveFilePath() (fullPath string, dirPath string, fileName string)
GetConfig() interface{}
}
func LoadFromDB(manager Manager) {
f, err := OpenSaveFile(manager, os.O_RDONLY)
defer f.Close()
Check(err)
err = json.NewDecoder(f).Decode(manager.GetConfig())
log.Println(err)
Check(err)
}
func Commit(manager Manager) error {
configFullPath, _, configFileName := manager.GetSaveFilePath()
f, err := OpenSaveFile(manager, os.O_WRONLY)
defer f.Close()
if err != nil {
log.Printf("Unable to open configuration file %s (%s) : %s", configFileName, configFullPath, err)
return err
}
if err = json.NewEncoder(f).Encode(manager.GetConfig()); err != nil {
log.Printf("Unable to write in configuration file %s (%s) : %s", configFileName, configFullPath, err)
}
return err
}
func OpenSaveFile(manager Manager, osFlag int) (*os.File, error) {
configFullPath, _, _ := manager.GetSaveFilePath()
return os.OpenFile(configFullPath, osFlag|os.O_CREATE|os.O_TRUNC, 0644)
}
|
Return CAS for get operation
Change-Id: I50d3851dd1954e96c3046e69e507caa6622b6412
Reviewed-on: http://review.couchbase.org/11954
Tested-by: Sergey Avseyev <87f6d5e4fd3644c3c20800cde7fd3ad1569370b3@gmail.com>
Reviewed-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com> | /*
* Copyright 2011 Couchbase, 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.
* under the License.
*/
package org.couchbase.mock.memcached.protocol;
import java.nio.ByteBuffer;
import org.couchbase.mock.memcached.Item;
/**
*
* @author Trond Norbye <trond.norbye@gmail.com>
*/
public class BinaryGetResponse extends BinaryResponse {
public BinaryGetResponse(BinaryCommand command, ErrorCode error) {
super(command, error);
}
public BinaryGetResponse(BinaryCommand command, Item item) {
super(create(command, item));
}
private static ByteBuffer create(BinaryCommand command, Item item) {
final ByteBuffer message = BinaryResponse.create(command, ErrorCode.SUCCESS,
4 /* flags */, 0, item.getValue().length, item.getCas());
message.putInt(item.getFlags());
message.put(item.getValue());
message.rewind();
return message;
}
}
| /*
* Copyright 2011 Couchbase, 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.
* under the License.
*/
package org.couchbase.mock.memcached.protocol;
import java.nio.ByteBuffer;
import org.couchbase.mock.memcached.Item;
/**
*
* @author Trond Norbye <trond.norbye@gmail.com>
*/
public class BinaryGetResponse extends BinaryResponse {
public BinaryGetResponse(BinaryCommand command, ErrorCode error) {
super(command, error);
}
public BinaryGetResponse(BinaryCommand command, Item item) {
super(create(command, item));
}
private static ByteBuffer create(BinaryCommand command, Item item) {
final ByteBuffer message = BinaryResponse.create(command, ErrorCode.SUCCESS,
4 /* flags */, 0, item.getValue().length, 0);
message.putInt(item.getFlags());
message.put(item.getValue());
message.rewind();
return message;
}
}
|
Add super call to db Base class
Without this call, multiple inheritance involving the db Base
class does not work correctly.
Change-Id: Iac6b99d34f00babb8b66fede4977bf75f0ed61d4 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Base class for classes that need modular database access."""
from oslo.config import cfg
from nova.openstack.common import importutils
db_driver_opt = cfg.StrOpt('db_driver',
default='nova.db',
help='The driver to use for database access')
CONF = cfg.CONF
CONF.register_opt(db_driver_opt)
class Base(object):
"""DB driver is injected in the init method."""
def __init__(self, db_driver=None):
super(Base, self).__init__()
if not db_driver:
db_driver = CONF.db_driver
self.db = importutils.import_module(db_driver) # pylint: disable=C0103
| # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Base class for classes that need modular database access."""
from oslo.config import cfg
from nova.openstack.common import importutils
db_driver_opt = cfg.StrOpt('db_driver',
default='nova.db',
help='The driver to use for database access')
CONF = cfg.CONF
CONF.register_opt(db_driver_opt)
class Base(object):
"""DB driver is injected in the init method."""
def __init__(self, db_driver=None):
if not db_driver:
db_driver = CONF.db_driver
self.db = importutils.import_module(db_driver) # pylint: disable=C0103
|
Fix target entity not found | <?php
namespace Tienvx\Bundle\MbtBundle\Entity\Petrinet;
use Doctrine\ORM\Mapping as ORM;
use Tienvx\Bundle\MbtBundle\Model\Petrinet\PlaceMarking as BasePlaceMarking;
/**
* @ORM\Entity
* @ORM\Table(name="place_marking")
*/
class PlaceMarking extends BasePlaceMarking
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Tienvx\Bundle\MbtBundle\Entity\Petrinet\Place")
*/
protected $place;
/**
* @ORM\ManyToMany(targetEntity="Tienvx\Bundle\MbtBundle\Entity\Petrinet\Token", cascade={"persist"})
* @ORM\JoinTable(
* name="place_marking_token_xref",
* joinColumns={@ORM\JoinColumn(name="place_marking_id")},
* inverseJoinColumns={@ORM\JoinColumn(name="token_id", unique=true)}
* )
*/
protected $tokens;
}
| <?php
namespace Tienvx\Bundle\MbtBundle\Entity\Petrinet;
use Doctrine\ORM\Mapping as ORM;
use Tienvx\Bundle\MbtBundle\Model\Petrinet\PlaceMarking as BasePlaceMarking;
/**
* @ORM\Entity
* @ORM\Table(name="place_marking")
*/
class PlaceMarking extends BasePlaceMarking
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Tienvx\Bundle\MbtBundle\Entity\Petrinet\Place")
*/
protected $place;
/**
* @ORM\ManyToMany(targetEntity="Tienvx\Bundle\MbtBundle\Entity\Petrinet\ColorfulToken", cascade={"persist"})
* @ORM\JoinTable(
* name="place_marking_token_xref",
* joinColumns={@ORM\JoinColumn(name="place_marking_id")},
* inverseJoinColumns={@ORM\JoinColumn(name="token_id", unique=true)}
* )
*/
protected $tokens;
}
|
Add recv_keys and add_repo to apt | import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
#TODO: Split me out to key
RECV_KEY = ['sudo', '-E', 'apt-key', 'adv', '--keyserver', 'hkp://pgp.mit.edu:80', '--recv-keys']
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
def recv_keys(*keys):
if keys:
Config.ENV_CALL(Config.RECV_KEY + list(keys))
else:
#FIXME: need to output failure
pass
def add_repo(filename, *line_items):
if filename and line_items:
#FIXME, open file and write lines to the end.
pass
else:
#FIXME: need to output failure
pass
| import os
from subprocess import call
from functools import partial
#TODO: stop using sudo or ensure it exists
#TODOE: specify user to run as
#TODO: utilize functools partial to handle some of the above functionality
class Config:
APT_GET = ['sudo', '-E', 'apt-get']
ENV = os.environ.copy()
ENV['DEBIAN_FRONTEND'] = "noninteractive"
ENV_CALL = partial(call, env=ENV)
def install(*packages):
if packages:
Config.ENV_CALL(Config.APT_GET + ['install'] + list(packages))
else:
#FIXME: need to output failure
pass
update = partial(Config.ENV_CALL, Config.APT_GET + ['update'])
upgrade = partial(Config.ENV_CALL, Config.APT_GET + ['upgrade'])
|
Handle an error where data chunks from camera could be undefined | var os = require('os');
var io = require('socket.io-client');
// The Castle address is loaded dynamically and passed to this script as an argument
var socket = io.connect('http://'+process.argv[2]+':8888');
if(!process.stdin.isTTY) {
var image = Buffer.alloc(0);
// Data is read in chunks of up to 64K (65356 bytes)
// These need to be assembled into JPEG before being sent to castle
process.stdin.on('data', function(chunk) {
if(chunk != undefined) {
try {
image = Buffer.concat([image, chunk]);
if(chunk[chunk.length-2].toString(16) == 'ff' && chunk[chunk.length-1].toString(16) == 'd9') {
console.log('Sending image to Castle '+image.length);
socket.emit('watchman', {id: os.hostname(), image: image});
image = Buffer.alloc(0);
}
}
catch(error) {
console.log(error);
}
}
});
}
| var os = require('os');
var io = require('socket.io-client');
// The Castle address is loaded dynamically and passed to this script as an argument
var socket = io.connect('http://'+process.argv[2]+':8888');
if(!process.stdin.isTTY) {
var image = Buffer.alloc(0);
// Data is read in chunks of up to 64K (65356 bytes)
// These need to be assembled into JPEG before being sent to castle
process.stdin.on('data', function(chunk) {
image = Buffer.concat([image, chunk]);
if(chunk[chunk.length-2].toString(16) == 'ff' && chunk[chunk.length-1].toString(16) == 'd9') {
console.log('Sending image to Castle '+image.length);
socket.emit('watchman', {id: os.hostname(), image: image});
image = Buffer.alloc(0);
}
});
}
|
packer: Test to make sure DispatchHook implements Hook | package packer
import (
"cgl.tideland.biz/asserts"
"testing"
)
type TestHook struct {
runCalled bool
runData interface{}
runName string
runUi Ui
}
func (t *TestHook) Run(name string, data interface{}, ui Ui) {
t.runCalled = true
t.runData = data
t.runName = name
t.runUi = ui
}
func TestDispatchHook_Implements(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
var r Hook
c := &DispatchHook{nil}
assert.Implementor(c, &r, "should be a Hook")
}
func TestDispatchHook_Run_NoHooks(t *testing.T) {
// Just make sure nothing blows up
dh := &DispatchHook{make(map[string][]Hook)}
dh.Run("foo", nil, nil)
}
func TestDispatchHook_Run(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
hook := &TestHook{}
mapping := make(map[string][]Hook)
mapping["foo"] = []Hook{hook}
dh := &DispatchHook{mapping}
dh.Run("foo", 42, nil)
assert.True(hook.runCalled, "run should be called")
assert.Equal(hook.runName, "foo", "should be proper event")
assert.Equal(hook.runData, 42, "should be correct data")
}
| package packer
import (
"cgl.tideland.biz/asserts"
"testing"
)
type TestHook struct {
runCalled bool
runData interface{}
runName string
runUi Ui
}
func (t *TestHook) Run(name string, data interface{}, ui Ui) {
t.runCalled = true
t.runData = data
t.runName = name
t.runUi = ui
}
func TestDispatchHook_Run_NoHooks(t *testing.T) {
// Just make sure nothing blows up
dh := &DispatchHook{make(map[string][]Hook)}
dh.Run("foo", nil, nil)
}
func TestDispatchHook_Run(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
hook := &TestHook{}
mapping := make(map[string][]Hook)
mapping["foo"] = []Hook{hook}
dh := &DispatchHook{mapping}
dh.Run("foo", 42, nil)
assert.True(hook.runCalled, "run should be called")
assert.Equal(hook.runName, "foo", "should be proper event")
assert.Equal(hook.runData, 42, "should be correct data")
}
|
Add missing semicolons in js
Change-Id: I1cb8d044766924e554411ce45c3c056139f19078 | angular.module('horizonApp').directive('hrNumberPicker', function() {
return {
restrict: 'A',
replace: true,
scope: { initial_value: '=value' },
templateUrl: '../../static/infrastructure/angular_templates/numberpicker.html',
link: function(scope, element, attrs) {
input = element.find('input').first();
angular.forEach(element[0].attributes, function(attribute) {
input_attr = input.attr(attribute.nodeName);
if (typeof input_attr === 'undefined' || input_attr === false) {
input.attr(attribute.nodeName, attribute.nodeValue);
}
});
scope.value = scope.initial_value;
scope.disabledInput = (angular.isDefined(attrs.readonly)) ? true : false;
scope.disableArrow = function() {
return (scope.value === 0) ? true : false;
};
scope.incrementValue = function() {
if(!scope.disabledInput) {
scope.value++;
}
};
scope.decrementValue = function() {
if(!scope.disabledInput && scope.value !== 0) {
scope.value--;
}
};
}
};
});
| angular.module('horizonApp').directive('hrNumberPicker', function() {
return {
restrict: 'A',
replace: true,
scope: { initial_value: '=value' },
templateUrl: '../../static/infrastructure/angular_templates/numberpicker.html',
link: function(scope, element, attrs) {
input = element.find('input').first();
angular.forEach(element[0].attributes, function(attribute) {
input_attr = input.attr(attribute.nodeName);
if (typeof input_attr === 'undefined' || input_attr === false) {
input.attr(attribute.nodeName, attribute.nodeValue);
}
});
scope.value = scope.initial_value;
scope.disabledInput = (angular.isDefined(attrs.readonly)) ? true : false;
scope.disableArrow = function() {
return (scope.value === 0) ? true : false;
}
scope.incrementValue = function() {
if(!scope.disabledInput) {
scope.value++;
}
}
scope.decrementValue = function() {
if(!scope.disabledInput && scope.value !== 0) {
scope.value--;
}
}
}
};
})
|
Throw exception when url could not be created from result set. | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jdbi.v3.sqlite3;
import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
public class URLColumnMapper implements ColumnMapper<URL> {
@Override
public URL map(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException {
URL url = null;
try {
url = URI.create(r.getString(columnNumber)).toURL();
} catch (MalformedURLException e) {
throw new SQLException(e);
}
return url;
}
}
| /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jdbi.v3.sqlite3;
import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.statement.StatementContext;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
public class URLColumnMapper implements ColumnMapper<URL> {
@Override
public URL map(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException {
URL url = null;
try {
url = URI.create(r.getString(columnNumber)).toURL();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
}
|
Add some docs to PMT time slewing | # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Time slewing corrects the hit time due to different rise times of the
PMT signals depending on the number of photo electrons.
The reference point is at 26.4ns and hits with a different ToT values
are corrected to refer to comparable arrival times.
The time slewing is subtracted from the measured hit time, in contrast
to the time calibration (t0), which is added.
Variant 3 is currently (as of 2020-10-16) also used in Jpp.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import km3pipe as kp
import numpy as np
import matplotlib.pyplot as plt
kp.style.use()
tots = np.arange(256)
slews = {variant: kp.calib.slew(tots, variant=variant) for variant in (1, 2, 3)}
fig, ax = plt.subplots()
for variant, slew in slews.items():
ax.plot(tots, slew, label=f"Variant {variant}")
ax.set_xlabel("ToT / ns")
ax.set_ylabel("time slewing / ns")
ax.legend()
fig.tight_layout()
plt.show()
| # -*- coding: utf-8 -*-
"""
==================
PMT Time Slewing
==================
Show different variants of PMT time slewing calculations.
Variant 3 is currently (as of 2020-10-16) what's also used in Jpp.
"""
# Author: Tamas Gal <tgal@km3net.de>
# License: BSD-3
import km3pipe as kp
import numpy as np
import matplotlib.pyplot as plt
kp.style.use()
tots = np.arange(256)
slews = {variant: kp.calib.slew(tots, variant=variant) for variant in (1, 2, 3)}
fig, ax = plt.subplots()
for variant, slew in slews.items():
ax.plot(tots, slew, label=f"Variant {variant}")
ax.set_xlabel("ToT / ns")
ax.set_ylabel("time slewing / ns")
ax.legend()
fig.tight_layout()
plt.show()
|
feature: Add dangling underscore exceptions for elasticsearch results | module.exports = {
extends: 'airbnb-base',
plugins: [
'mocha',
],
env: {
node: true,
mocha: true,
},
rules: {
strict: [0, 'global'],
indent: [1, 'tab', { SwitchCase: 1, VariableDeclarator: 1 }],
'no-tabs': 0,
'no-plusplus': 0,
'arrow-body-style': [2, 'as-needed', { requireReturnForObjectLiteral: true }],
'arrow-parens': [2, 'as-needed', { requireForBlockBody: true }],
'no-console': [1, { allow: ['warn'] }],
'max-len': [2, 160, 2, {
ignoreUrls: true,
ignoreComments: false,
}],
'no-underscore-dangle': ['error', { allow: [
'_id',
'_index',
'_score',
'_shards',
'_source',
'_type',
], allowAfterThis: true, allowAfterSuper: true }],
'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
'import/named': 2,
'mocha/no-exclusive-tests': 'error',
'no-restricted-syntax': [
'error',
'ForInStatement',
'LabeledStatement',
'WithStatement',
],
'no-await-in-loop': 0,
},
};
| module.exports = {
extends: 'airbnb-base',
plugins: [
'mocha',
],
env: {
node: true,
mocha: true,
},
rules: {
strict: [0, 'global'],
indent: [1, 'tab', { SwitchCase: 1, VariableDeclarator: 1 }],
'no-tabs': 0,
'no-plusplus': 0,
'arrow-body-style': [2, 'as-needed', { requireReturnForObjectLiteral: true }],
'arrow-parens': [2, 'as-needed', { requireForBlockBody: true }],
'no-console': [1, { allow: ['warn'] }],
'max-len': [2, 160, 2, {
ignoreUrls: true,
ignoreComments: false,
}],
'no-underscore-dangle': ['error', { allow: ['_id'], allowAfterThis: true, allowAfterSuper: true }],
'import/no-extraneous-dependencies': ['error', { devDependencies: true }],
'import/named': 2,
'mocha/no-exclusive-tests': 'error',
'no-restricted-syntax': [
'error',
'ForInStatement',
'LabeledStatement',
'WithStatement',
],
'no-await-in-loop': 0,
},
};
|
Add new case insensitive string contains | package tools
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strings"
"unicode"
"unicode/utf8"
)
func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func Capitalize(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
func JsonToGolang(in *string) (out string) {
res := strings.Split(*in, "_")
out = ""
for _, s := range res {
out += Capitalize(s)
}
return out
}
func CaseInsensitiveContains(s, substr string) bool {
s, substr = strings.ToUpper(s), strings.ToUpper(substr)
return strings.Contains(s, substr)
}
| package tools
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"strings"
"unicode"
"unicode/utf8"
)
func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func Capitalize(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
func JsonToGolang(in *string) (out string) {
res := strings.Split(*in, "_")
out = ""
for _, s := range res {
out += Capitalize(s)
}
return out
}
|
Add a Logging Event to demonstrate the Forensics\Console use | <?php
/**
* Events - all standard Events are defined here.
*
* @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
* @version 3.0
*/
use Support\Facades\Event;
use Core\View;
use Helpers\Hooks;
use Forensics\Console;
/** Define Events. */
// Add a Listener Class to the Event 'test'.
Event::listen('test', 'App\Events\Test@handle');
// Add a Listener Closure to the Event 'test'.
Event::listen('test', function($data) {
return '<pre>Closure : ' .var_export($data, true) .'</pre>';
});
// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
// Run the Hooks associated to the Views.
$hooks = Hooks::get();
foreach (array('afterBody', 'css', 'js') as $hook) {
$result = $hooks->run($hook);
// Share the result into Views.
View::share($hook, $result);
}
});
// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
$className = get_class($instance);
Console::log("Executing '$className@$method'");
});
| <?php
/**
* Events - all standard Events are defined here.
*
* @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com
* @version 3.0
*/
use Support\Facades\Event;
use Core\View;
use Helpers\Hooks;
/** Define Events. */
// Add a Listener Class to the Event 'test'.
Event::listen('test', 'App\Events\Test@handle');
// Add a Listener Closure to the Event 'test'.
Event::listen('test', function($data) {
return '<pre>Closure : ' .var_export($data, true) .'</pre>';
});
// Add a Listener Closure to the Event 'framework.controller.executing'.
Event::listen('framework.controller.executing', function($instance, $method, $params) {
// Run the Hooks associated to the Views.
$hooks = Hooks::get();
foreach (array('afterBody', 'css', 'js') as $hook) {
$result = $hooks->run($hook);
// Share the result into Views.
View::share($hook, $result);
}
});
|
Fix incorrect argument to notify function | #!/usr/bin/env node
'use strict';
var program = require('commander')
, gulp = require('gulp')
, chalk = require('chalk')
, exec = require('exec')
, pjson = require('./package.json')
var strings = {
create: 'Creating new project',
install: 'Installing dependencies',
complete: 'Done!'
}
var paths = {
basefiles: __dirname + '/assets/**/*',
dotfiles: __dirname + '/assets/.*'
}
function notify(message) {
if (!program.quiet)
console.log(chalk.green(message))
}
function installDependencies(name) {
notify(strings.install)
exec('cd ' + name + ' && npm install', function () {
notify(strings.complete)
})
}
function newProject(name) {
notify(strings.create)
gulp.src([paths.basefiles, paths.dotfiles])
.pipe(gulp.dest(process.cwd() + '/' + name))
.on('end', installDependencies.bind(this, name))
}
program
.version(pjson.version)
.option('-q, --quiet', 'Hide logging information')
program
.command('new <name>')
.description('Scaffold out a new app with given name')
.action(newProject)
program.parse(process.argv);
| #!/usr/bin/env node
'use strict';
var program = require('commander')
, gulp = require('gulp')
, chalk = require('chalk')
, exec = require('exec')
, pjson = require('./package.json')
var strings = {
create: 'Creating new project',
install: 'Installing dependencies',
complete: 'Done!'
}
var paths = {
basefiles: __dirname + '/assets/**/*',
dotfiles: __dirname + '/assets/.*'
}
function notify(message) {
if (!program.quiet)
console.log(chalk.green(message))
}
function installDependencies(name) {
notify(strings.install)
exec('cd ' + name + ' && npm install', function () {
notify(strings.complete)
})
}
function newProject(name) {
notify(strings.create, name)
gulp.src([paths.basefiles, paths.dotfiles])
.pipe(gulp.dest(process.cwd() + '/' + name))
.on('end', installDependencies.bind(this, name))
}
program
.version(pjson.version)
.option('-q, --quiet', 'Hide logging information')
program
.command('new <name>')
.description('Scaffold out a new app with given name')
.action(newProject)
program.parse(process.argv);
|
Add missing test listener method | <?php
namespace Pinq\Tests;
use Exception;
use PHPUnit_Framework_Test;
class Timer implements \PHPUnit_Framework_TestListener
{
private static $log = [];
public static function getLongRunningTests($amount)
{
arsort(Timer::$log);
return array_slice(Timer::$log, 0, $amount);
}
public function endTest(\PHPUnit_Framework_Test $test, $length)
{
self::$log[get_class($test) . '::' . $test->getName()] = $length;
}
public function startTest(\PHPUnit_Framework_Test $test) {}
public function addWarning(PHPUnit_Framework_Test $test, \PHPUnit_Framework_Warning $e, $time) {}
public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time) {}
public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time) {}
public function addIncompleteTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) {}
public function addSkippedTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) {}
public function startTestSuite(\PHPUnit_Framework_TestSuite $suite) { }
public function endTestSuite(\PHPUnit_Framework_TestSuite $suite) {}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time) {}
}
| <?php
namespace Pinq\Tests;
use Exception;
use PHPUnit_Framework_Test;
class Timer implements \PHPUnit_Framework_TestListener
{
private static $log = [];
public static function getLongRunningTests($amount)
{
arsort(Timer::$log);
return array_slice(Timer::$log, 0, $amount);
}
public function endTest(\PHPUnit_Framework_Test $test, $length)
{
self::$log[get_class($test) . '::' . $test->getName()] = $length;
}
public function startTest(\PHPUnit_Framework_Test $test) {}
public function addError(\PHPUnit_Framework_Test $test, \Exception $e, $time) {}
public function addFailure(\PHPUnit_Framework_Test $test, \PHPUnit_Framework_AssertionFailedError $e, $time) {}
public function addIncompleteTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) {}
public function addSkippedTest(\PHPUnit_Framework_Test $test, \Exception $e, $time) {}
public function startTestSuite(\PHPUnit_Framework_TestSuite $suite) { }
public function endTestSuite(\PHPUnit_Framework_TestSuite $suite) {}
public function addRiskyTest(PHPUnit_Framework_Test $test, Exception $e, $time) {}
}
|
Expire mobile guide cookie after 24 hours
See https://github.com/vector-im/riot-web/issues/9360
This is to prevent it from always working. Cookies without an expiration are supposed to expire at the end of the session, however the nature of mobile browsers means that the session is unlikely to ever end. | import {getVectorConfig} from '../getconfig';
function onBackToRiotClick() {
// Cookie should expire in 24 hours
document.cookie = 'mobile_redirect_to_guide=false;path=/;max-age=86400';
window.location.href = '../';
}
async function initPage() {
document.getElementById('back_to_riot_button').onclick = onBackToRiotClick;
const config = await getVectorConfig('..');
let hsUrl;
if (config && config['default_hs_url']) {
hsUrl = config['default_hs_url'];
}
if (hsUrl && !hsUrl.endsWith('/')) hsUrl += '/';
if (hsUrl && hsUrl !== 'https://matrix.org/') {
document.getElementById('step2_container').style.display = 'block';
document.getElementById('hs_url').innerHTML = hsUrl;
document.getElementById('step_login_header').innerHTML= 'Step 3: Register or Log in';
}
}
initPage();
| import {getVectorConfig} from '../getconfig';
function onBackToRiotClick() {
document.cookie = 'mobile_redirect_to_guide=false;path=/';
window.location.href = '../';
}
async function initPage() {
document.getElementById('back_to_riot_button').onclick = onBackToRiotClick;
const config = await getVectorConfig('..');
let hsUrl;
if (config && config['default_hs_url']) {
hsUrl = config['default_hs_url'];
}
if (hsUrl && !hsUrl.endsWith('/')) hsUrl += '/';
if (hsUrl && hsUrl !== 'https://matrix.org/') {
document.getElementById('step2_container').style.display = 'block';
document.getElementById('hs_url').innerHTML = hsUrl;
document.getElementById('step_login_header').innerHTML= 'Step 3: Register or Log in';
}
}
initPage();
|
Fix deprecated call to constructor
Fixes #56 | <?php
/**
* This file is part of the Cron package.
*
* (c) Dries De Peuter <dries@nousefreak.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cron\Job;
use Symfony\Component\Process\Process;
/**
* ShellJob is a job for running shell commands.
*
* @author Dries De Peuter <dries@nousefreak.be>
*/
class ShellJob extends AbstractProcessJob
{
/**
* Set the command to execute as if you would run it in the shell.
*
* @param string $command
*/
public function setCommand($command, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
{
if (method_exists(Process::class, 'fromShellCommandline')) {
$this->process = Process::fromShellCommandline($command, $cwd, $env, $input, $timeout, $options);
} else {
$this->process = new Process($command, $cwd, $env, $input, $timeout, $options);
}
}
}
| <?php
/**
* This file is part of the Cron package.
*
* (c) Dries De Peuter <dries@nousefreak.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cron\Job;
use Symfony\Component\Process\Process;
/**
* ShellJob is a job for running shell commands.
*
* @author Dries De Peuter <dries@nousefreak.be>
*/
class ShellJob extends AbstractProcessJob
{
/**
* Set the command to execute as if you would run it in the shell.
*
* @param string $command
*/
public function setCommand($command, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
{
$this->process = new Process($command, $cwd, $env, $input, $timeout, $options);
}
}
|
Use parent 'post' function to actually send message | from __future__ import absolute_import
import logging
from .telegram import TelegramBot
logger = logging.getLogger(__name__)
class TelegramBotSplit(TelegramBot):
def __init__(self, chat_id=None, split_on="\n"):
self.split_on = split_on
super(TelegramBotSplit, self).__init__(chat_id=chat_id)
def post(self, report, **kwargs):
"""Overwrite post to split message on token"""
for m in report.split(self.split_on):
super(TelegramBotSplit, self).post(m)
def notify_factory(conf, value):
try:
chat_id = value['chat-id']
except (TypeError, KeyError):
chat_id = value
try:
split_on = value['split-on']
except (TypeError, KeyError):
split_on = "\n"
return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post
def chat_id():
bot = TelegramBotSplit()
print(bot.chat_id)
| from __future__ import absolute_import
import logging
from .telegram import TelegramBot
logger = logging.getLogger(__name__)
class TelegramBotSplit(TelegramBot):
def __init__(self, chat_id=None, split_on="\n"):
self.split_on = split_on
super(TelegramBotSplit, self).__init__(chat_id=chat_id)
def post(self, report, **kwargs):
"""Overwrite post to split message on token"""
for m in report.split(self.split_on):
self.bot.send_message(
self.chat_id,
m,
parse_mode='Markdown',
)
def notify_factory(conf, value):
try:
chat_id = value['chat-id']
except (TypeError, KeyError):
chat_id = value
try:
split_on = value['split-on']
except (TypeError, KeyError):
split_on = "\n"
print(split_on)
return TelegramBotSplit(chat_id=chat_id, split_on=split_on).post
def chat_id():
bot = TelegramBotSplit()
print(bot.chat_id)
|
Update property-types test case with more realistic types. | public class Widget {
private boolean primitive;
private Widget recursiveType;
private Final finalType;
private Pair<? extends Widget, ? super Widget> generics;
private int[][] multiDimensionalArray;
public Widget() {
}
public boolean isPrimitive() {
return primitive;
}
public Widget getRecursiveType() {
return recursiveType;
}
public Widget getFinalType() {
return recursiveType;
}
public Pair<? extends Widget, ? super Widget> getGenerics() {
return generics;
}
public int[][] getMultiDimensionalArray() {
return multiDimensionalArray;
}
public class Pair<U, V> {
}
public final class Final {
}
}
| public class Widget {
private boolean primitive;
private Widget simpleObject;
private Pair<? extends Pair<? extends Widget, ? super Widget>, ?> nestedGenerics;
private Pair<Widget, ?>[] arrayOfGeneric;
private int[][] multiDimensionalArray;
public Widget() {
}
public boolean isPrimitive() {
return primitive;
}
public Widget getSimpleObject() {
return simpleObject;
}
public Pair<? extends Pair<? extends Widget, ? super Widget>, ?> getNestedGenerics() {
return nestedGenerics;
}
public Pair<Widget, ?>[] getArrayOfGeneric() {
return arrayOfGeneric;
}
public int[][] getMultiDimensionalArray() {
return multiDimensionalArray;
}
public class Pair<U, V> {
}
}
|
Remove unused dom node generator. | // Example of running gg in node
var d3 = require('d3');
var _ = require('underscore');
var gg = require('./gg.js');
var linechart = gg.gg({
layers: [
{ geometry: 'line', mapping: { x: 'd', y: 'r', group: 'subject', color: 'subject'} },
{ geometry: 'text', mapping: { x: 'd', y: 'r', text: '{d}, {r}' }, show: "hover" }
]
});
gg.sampleData = {};
gg.sampleData.upwardSubjects = (function () {
var subjects = ['a', 'b', 'c', 'd'];
var x = 0;
var y = 0;
return _.flatten(_.map(_.range(20), function (i) {
x += Math.round(Math.random() * 30);
y += Math.round(Math.abs(20 - Math.random() * 30));
return _.map(subjects, function(subject, i) {
var skew = i + 1;
return { d: x, r: y * (Math.random() * skew), subject: subject };
})
}));
}());
var div = d3.select(document.createElement('div'));
var data = gg.sampleData;
var w = 300;
var h = 200;
linechart.render(w, h, div, data.upwardSubjects);
console.log(div.html());
| // Example of running gg in node
var d3 = require('d3');
var _ = require('underscore');
var gg = require('./gg.js');
var linechart = gg.gg({
layers: [
{ geometry: 'line', mapping: { x: 'd', y: 'r', group: 'subject', color: 'subject'} },
{ geometry: 'text', mapping: { x: 'd', y: 'r', text: '{d}, {r}' }, show: "hover" }
]
});
gg.sampleData = {};
gg.sampleData.upwardSubjects = (function () {
var subjects = ['a', 'b', 'c', 'd'];
var x = 0;
var y = 0;
return _.flatten(_.map(_.range(20), function (i) {
x += Math.round(Math.random() * 30);
y += Math.round(Math.abs(20 - Math.random() * 30));
return _.map(subjects, function(subject, i) {
var skew = i + 1;
return { d: x, r: y * (Math.random() * skew), subject: subject };
})
}));
}());
var div = d3.select(document.createElement('div'));
var data = gg.sampleData;
var w = 300;
var h = 200;
var ex = function () { return d3.select('#examples').append('span'); };
linechart.render(w, h, div, data.upwardSubjects);
console.log(div.html());
|
Exclude folio/react-big-calendar from being transpiled during a platform build | const path = require('path');
// These modules are already transpiled and should be excluded
const folioScopeBlacklist = [
'react-githubish-mentions',
'react-big-calendar',
].map(segment => path.join('@folio', segment));
// We want to transpile files inside node_modules/@folio or outside
// any node_modules directory. And definitely not files in
// node_modules outside the @folio namespace even if some parent
// directory happens to be in @folio.
//
// fn is the path after all symlinks are resolved so we need to be
// wary of all the edge cases yarn link will find for us.
function babelLoaderTest(fileName) {
const nodeModIdx = fileName.lastIndexOf('node_modules');
if (fileName.endsWith('.js')
&& (nodeModIdx === -1 || fileName.lastIndexOf('@folio') > nodeModIdx)
&& (folioScopeBlacklist.findIndex(ignore => fileName.includes(ignore)) === -1)) {
return true;
}
return false;
}
module.exports = {
test: babelLoaderTest,
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
[require.resolve('babel-preset-env'), { modules: false }],
[require.resolve('babel-preset-stage-2')],
[require.resolve('babel-preset-react')],
],
plugins: [
[require.resolve('babel-plugin-transform-decorators-legacy')],
[require.resolve('react-hot-loader/babel')]
]
},
};
| const path = require('path');
// These modules are already transpiled and should be excluded
const folioScopeBlacklist = [
'react-githubish-mentions',
].map(segment => path.join('@folio', segment));
// We want to transpile files inside node_modules/@folio or outside
// any node_modules directory. And definitely not files in
// node_modules outside the @folio namespace even if some parent
// directory happens to be in @folio.
//
// fn is the path after all symlinks are resolved so we need to be
// wary of all the edge cases yarn link will find for us.
function babelLoaderTest(fileName) {
const nodeModIdx = fileName.lastIndexOf('node_modules');
if (fileName.endsWith('.js')
&& (nodeModIdx === -1 || fileName.lastIndexOf('@folio') > nodeModIdx)
&& (folioScopeBlacklist.findIndex(ignore => fileName.includes(ignore)) === -1)) {
return true;
}
return false;
}
module.exports = {
test: babelLoaderTest,
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
[require.resolve('babel-preset-env'), { modules: false }],
[require.resolve('babel-preset-stage-2')],
[require.resolve('babel-preset-react')],
],
plugins: [
[require.resolve('babel-plugin-transform-decorators-legacy')],
[require.resolve('react-hot-loader/babel')]
]
},
};
|
Use the existing util.cli module | """Displays currently active gpu by optimus-manager
Requires the following packages:
* optimus-manager
"""
import core.module
import core.widget
import util.cli
class Module(core.module.Module):
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.output))
self.__gpumode = ""
def output(self, _):
return "GPU: {}".format(self.__gpumode)
def update(self):
cmd = "optimus-manager --print-mode"
output = util.cli.execute(cmd).strip()
if "intel" in output:
self.__gpumode = "Intel"
elif "nvidia" in output:
self.__gpumode = "Nvidia"
elif "amd" in output:
self.__gpumode = "AMD"
| """Displays currently active gpu by optimus-manager
Requires the following packages:
* optimus-manager
"""
import subprocess
import core.module
import core.widget
class Module(core.module.Module):
def __init__(self, config, theme):
super().__init__(config, theme, core.widget.Widget(self.output))
self.__gpumode = ""
def output(self, _):
return "GPU: {}".format(self.__gpumode)
def update(self):
cmd = ["optimus-manager", "--print-mode"]
output = (
subprocess.Popen(cmd, stdout=subprocess.PIPE)
.communicate()[0]
.decode("utf-8")
.lower()
)
if "intel" in output:
self.__gpumode = "Intel"
elif "nvidia" in output:
self.__gpumode = "Nvidia"
elif "amd" in output:
self.__gpumode = "AMD"
|
Fix naming to folliwng naming conventions for mclab | #!/usr/bin/env python
""" Set of helper function and variables for plotting.
This module provides a set of functions and variables that will be useful for
plotting.
"""
class ColorMarker:
def __init__(self):
# A list of colors
self._colors = ['k', 'b', 'g', 'c', 'm', 'y']
# A list of markers
self._markers = ['o', 's', '^', 'D', 'd', 'h', 'x', '*', '+', 'v', '<', '>', '1', '2', '3', '4', '8', 'p', 'H']
def get_colors(self):
""" Get a set of color/marker combinations.
:rtype: list of tuple
:returns: A list of tuples containing color|marker pairs. There are a total
of 114 combinations. Red and white are not used in this color scheme.
Red is reserved for coloring points beyond a threshold, and white does not
show up on white backgrounds.
"""
comb = list()
for marker in self._markers:
for color in self._colors:
comb.append((color, marker))
return comb
| #!/usr/bin/env python
""" Set of helper function and variables for plotting.
This module provides a set of functions and variables that will be useful for
plotting.
"""
class ColorMarker:
def __init__(self):
# A list of colors
self._colors = ['k', 'b', 'g', 'c', 'm', 'y']
# A list of markers
self._markers = ['o', 's', '^', 'D', 'd', 'h', 'x', '*', '+', 'v', '<', '>', '1', '2', '3', '4', '8', 'p', 'H']
def get_colors(self):
""" Get a set of color/marker combinations.
:rtype: list of tuple
:returns: A list of tuples containing color|marker pairs. There are a total
of 114 combinations. Red and white are not used in this color scheme.
Red is reserved for coloring points beyond a threshold, and white does not
show up on white backgrounds.
"""
comb = list()
for i in self._markers:
for j in self._colors:
comb.append((j, i))
return comb
|
Change variable name & int comparison. | from flask import jsonify, current_app
from . import status
from . import utils
from ..main.helpers.service import ServiceLoader
from ..main import main
@status.route('/_status')
def status():
# ServiceLoader is the only thing that actually connects to the API
service_loader = ServiceLoader(
main.config['API_URL'],
main.config['API_AUTH_TOKEN']
)
api_response = utils.return_response_from_api_status_call(
service_loader.status
)
apis_with_errors = []
if api_response is None or api_response.status_code != 200:
apis_with_errors.append("(Data) API")
# if no errors found, return everything
if not apis_with_errors:
return jsonify(
status="ok",
version=utils.get_version_label(),
api_status=api_response.json(),
)
message = "Error connecting to the " \
+ (" and the ".join(apis_with_errors)) \
+ "."
current_app.logger.error(message)
return jsonify(
status="error",
version=utils.get_version_label(),
api_status=utils.return_json_or_none(api_response),
message=message,
), 500
| from flask import jsonify, current_app
from . import status
from . import utils
from ..main.helpers.service import ServiceLoader
from ..main import main
@status.route('/_status')
def status():
# ServiceLoader is the only thing that actually connects to the API
service_loader = ServiceLoader(
main.config['API_URL'],
main.config['API_AUTH_TOKEN']
)
api_response = utils.return_response_from_api_status_call(
service_loader.status
)
apis_wot_got_errors = []
if api_response is None or api_response.status_code is not 200:
apis_wot_got_errors.append("(Data) API")
# if no errors found, return everything
if not apis_wot_got_errors:
return jsonify(
status="ok",
version=utils.get_version_label(),
api_status=api_response.json(),
)
message = "Error connecting to the " \
+ (" and the ".join(apis_wot_got_errors)) \
+ "."
current_app.logger.error(message)
return jsonify(
status="error",
version=utils.get_version_label(),
api_status=utils.return_json_or_none(api_response),
message=message,
), 500
|
Update osm way used due to data change | # http://www.openstreetmap.org/way/444491374
assert_has_feature(
16, 10475, 25332, 'roads',
{ 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
| # http://www.openstreetmap.org/way/367477828
assert_has_feature(
16, 10471, 25331, 'roads',
{ 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' })
# Way: The Embarcadero (397140734)
# http://www.openstreetmap.org/way/397140734
assert_has_feature(
16, 10486, 25326, 'roads',
{ 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' })
# Way: Carrie Furnace Boulevard (438362919)
# http://www.openstreetmap.org/way/438362919
assert_has_feature(
16, 18225, 24712, 'roads',
{ 'id': 438362919, 'kind': 'major_road',
'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
|
Upgrade SQLAlchemy 0.9.7 => 1.1.6 | from setuptools import setup
setup(
name='tangled.website',
version='0.1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'tangled.auth>=0.1a3',
'tangled.session>=0.1a2',
'tangled.site>=0.1a2',
'SQLAlchemy>=1.1.6',
],
extras_require={
'dev': ['coverage'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| from setuptools import setup
setup(
name='tangled.website',
version='0.1.dev0',
description='tangledframework.org',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
download_url='https://github.com/TangledWeb/tangled.website/tags',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tangled',
'tangled.website',
],
include_package_data=True,
install_requires=[
'tangled.auth>=0.1a3',
'tangled.session>=0.1a2',
'tangled.site>=0.1a2',
'SQLAlchemy>=0.9.7',
],
extras_require={
'dev': ['coverage'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Hide `createdAt` and `updatedAt` for verified users | 'use strict';
const _ = require('lodash');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
lowercase: true,
minlength: [3, 'Text less than 3 char'],
required: [true, '{PATH} is required'],
trim: true,
unique: true
},
firebaseToken: {
type: String,
default: ' ',
required: [true, '{PATH} is required'],
trim: true
},
name: {
type: String,
minlength: [3, 'Text less than 3 char'],
required: [true, '{PATH} is required'],
trim: true
},
ethAccount: {
type: String,
trim: true
},
publicKey: {
type: String,
trim: true
}
}, {
timestamps: true
});
userSchema.methods.toJSON = function() {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', 'email', 'firebaseToken', 'name', 'ethAccount', 'publicKey']);
};
const User = mongoose.model('User', userSchema);
module.exports = User;
| 'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
lowercase: true,
minlength: [3, 'Text less than 3 char'],
required: [true, '{PATH} is required'],
trim: true,
unique: true
},
firebaseToken: {
type: String,
default: ' ',
required: [true, '{PATH} is required'],
trim: true
},
name: {
type: String,
minlength: [3, 'Text less than 3 char'],
required: [true, '{PATH} is required'],
trim: true
},
ethAccount: {
type: String,
trim: true
},
publicKey: {
type: String,
trim: true
}
}, {
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
|
Revert "Properly handle non-hex characters in MAC"
This reverts commit 2734a3f0212c722fb9fe3698dfea0dbd8a14faa7. | import re
from django import forms
mac_pattern = re.compile("^[0-9a-f]{12}$")
class MacAddrFormField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
super(MacAddrFormField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(MacAddrFormField, self).clean(value)
value = value.lower().replace(':', '').replace('-', '')
if mac_pattern.match(value) is None:
raise forms.ValidationError('Invalid MAC address')
value = reduce(lambda x,y: x + ':' + y,
(value[i:i+2] for i in xrange(0, 12, 2)))
return value
| import re
from django import forms
mac_pattern = re.compile("^[0-9a-f]{12}$")
class MacAddrFormField(forms.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 17
super(MacAddrFormField, self).__init__(*args, **kwargs)
def clean(self, value):
value = super(MacAddrFormField, self).clean(value)
value = filter(lambda x: x in "0123456789abcdef", value)
if mac_pattern.match(value) is None:
raise forms.ValidationError('Invalid MAC address')
value = reduce(lambda x,y: x + ':' + y,
(value[i:i+2] for i in xrange(0, 12, 2)))
return value
|
Remove beautifulsoup4 and lxml as dependencies. | from setuptools import setup
setup(
name='gethazel',
version='0.1.0',
description='A balanced life is a good life.',
author='Reilly Tucker Siemens',
author_email='reilly.siemens@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.4'
],
keywords='Corgi Hazel Balance',
py_modules=['gethazel'],
install_requires=[
'requests',
],
entry_points={
'console_scripts': [
'gethazel=gethazel:main',
]
},
)
| from setuptools import setup
setup(
name='gethazel',
version='0.1.0',
description='A balanced life is a good life.',
author='Reilly Tucker Siemens',
author_email='reilly.siemens@gmail.com',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.4'
],
keywords='Corgi Hazel Balance',
py_modules=['gethazel'],
install_requires=[
'beautifulsoup4',
'lxml',
'requests',
],
entry_points={
'console_scripts': [
'gethazel=gethazel:main',
]
},
)
|
Fix FileSystemFinder's find return value if not all | import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches if all else None
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
| import os
from .exceptions import ImproperlyConfigured
from .utils import safe_join
class BaseFinder(object):
def find(self, path, all=False):
raise NotImplementedError()
class FileSystemFinder(BaseFinder):
def __init__(self, directories):
self.locations = []
if not isinstance(directories, (list, tuple)):
raise ImproperlyConfigured(
"FileSystemFinder's 'directories' parameter is not a "
"tuple or list; perhaps you forgot a trailing comma?")
for directory in directories:
if directory not in self.locations:
self.locations.append(directory)
def find(self, path, all=False):
matches = []
for root in self.locations:
matched_path = self.find_location(root, path)
if matched_path:
if not all:
return matched_path
matches.append(matched_path)
return matches
def find_location(self, root, path):
path = safe_join(root, path)
if os.path.exists(path):
return path
|
Remove unused item deferred register in block deferred register | package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;
public class BlockDeferredRegister {
public final DeferredRegister<Block> blocks;
public BlockDeferredRegister(String modid) {
blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
}
public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
final RegistryObject<B> block = blocks.register(name, supplier);
final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);
return new BlockRegistryObject<B, I>(block, item);
}
public void register(IEventBus bus) {
blocks.register(bus);
}
}
| package info.u_team.u_team_core.util.registry;
import java.util.function.Supplier;
import info.u_team.u_team_core.api.registry.IUBlockRegistryType;
import net.minecraft.block.Block;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;
public class BlockDeferredRegister {
public final DeferredRegister<Block> blocks;
public final DeferredRegister<Item> items;
public BlockDeferredRegister(String modid) {
blocks = DeferredRegister.create(ForgeRegistries.BLOCKS, modid);
items = DeferredRegister.create(ForgeRegistries.ITEMS, modid);
}
public <B extends Block & IUBlockRegistryType, I extends BlockItem> BlockRegistryObject<B, I> register(String name, Supplier<? extends B> supplier) {
final RegistryObject<B> block = blocks.register(name, supplier);
final RegistryObject<I> item = RegistryObject.of(new ResourceLocation(name), ForgeRegistries.ITEMS);
return new BlockRegistryObject<B, I>(block, item);
}
public void register(IEventBus bus) {
blocks.register(bus);
items.register(bus);
}
}
|
Change iteritems() to items() for future compatibility | # pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring
from __future__ import absolute_import
from unittest import TestCase
from nose.tools import *
from mock import *
from dear_astrid.rtm.importer import Importer as rtmimp
class TestRTMImport(TestCase):
def setUp(self):
self.patches = dict(
time = patch('time.sleep'),
rtm = patch('rtm.createRTM'),
)
self.mocks = dict()
for (k, v) in self.patches.items():
self.mocks[k] = v.start()
def test_sleep_before_rtm(self):
imp = rtmimp(['task'])
imp._rtm = Mock()
assert not self.mocks['time'].called
# assert that it is our mock object
assert_equal(imp.rtm, imp._rtm)
self.mocks['time'].assert_called_once_with(1)
# test calling other methods
imp.rtm.foo.bar
self.mocks['time'].assert_has_calls([ call(1), call(1) ])
# not used this time
assert not self.mocks['rtm'].called
| # pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring
from __future__ import absolute_import
from unittest import TestCase
from nose.tools import *
from mock import *
from dear_astrid.rtm.importer import Importer as rtmimp
class TestRTMImport(TestCase):
def setUp(self):
self.patches = dict(
time = patch('time.sleep'),
rtm = patch('rtm.createRTM'),
)
self.mocks = dict()
for (k, v) in self.patches.iteritems():
self.mocks[k] = v.start()
def test_sleep_before_rtm(self):
imp = rtmimp(['task'])
imp._rtm = Mock()
assert not self.mocks['time'].called
# assert that it is our mock object
assert_equal(imp.rtm, imp._rtm)
self.mocks['time'].assert_called_once_with(1)
# test calling other methods
imp.rtm.foo.bar
self.mocks['time'].assert_has_calls([ call(1), call(1) ])
# not used this time
assert not self.mocks['rtm'].called
|
Move location of OncallMember to be consistent | package somaproto
type Oncall struct {
Id string `json:"id, omitempty"`
Name string `json:"name, omitempty"`
Number string `json:"number, omitempty"`
Members *[]OncallMember `json:"members, omitempty"`
Details *OncallDetails `json:"details, omitempty"`
}
type OncallDetails struct {
DetailsCreation
}
type OncallMember struct {
UserName string `json:"userName, omitempty"`
UserId string `json"userId, omitempty"`
}
type OncallFilter struct {
Name string `json:"name, omitempty"`
Number string `json:"number, omitempty"`
}
//
func (p *Oncall) DeepCompare(a *Oncall) bool {
if p.Id != a.Id || p.Name != a.Name || p.Number != a.Number {
return false
}
return true
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
| package somaproto
type Oncall struct {
Id string `json:"id, omitempty"`
Name string `json:"name, omitempty"`
Number string `json:"number, omitempty"`
Details *OncallDetails `json:"details, omitempty"`
}
type OncallDetails struct {
DetailsCreation
Members *[]OncallMember `json:"members, omitempty"`
}
type OncallMember struct {
UserName string `json:"userName, omitempty"`
UserId string `json"userId, omitempty"`
}
type OncallFilter struct {
Name string `json:"name, omitempty"`
Number string `json:"number, omitempty"`
}
//
func (p *Oncall) DeepCompare(a *Oncall) bool {
if p.Id != a.Id || p.Name != a.Name || p.Number != a.Number {
return false
}
return true
}
// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
|
Add missing ocs resource for user workflows
Signed-off-by: Julius Härtl <bf353fa4999f2f148afcc6d8ee6cb1ee74cc07c3@bitgrid.net> | <?php
/**
* @copyright Copyright (c) 2016 Morris Jobke <hey@morrisjobke.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
return [
'routes' => [
['name' => 'requestTime#getTimezones', 'url' => '/timezones', 'verb' => 'GET'],
],
'ocs-resources' => [
'global_workflows' => ['url' => '/api/v1/workflows/global'],
'user_workflows' => ['url' => '/api/v1/workflows/user'],
],
];
| <?php
/**
* @copyright Copyright (c) 2016 Morris Jobke <hey@morrisjobke.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
return [
'routes' => [
['name' => 'requestTime#getTimezones', 'url' => '/timezones', 'verb' => 'GET'],
],
'ocs-resources' => [
'global_workflows' => ['url' => '/api/v1/workflows/global'],
],
];
|
Revert "Revert "list: print message with there's no task with description""
This reverts commit e065dcb81659e5b3c38255ece1702d6c408ffebe.
Reintroducing this. Reverted unintentionally. | package task
import (
"fmt"
"sort"
"text/tabwriter"
)
// PrintTasksHelp prints help os tasks that have a description
func (e *Executor) PrintTasksHelp() {
tasks := e.tasksWithDesc()
if len(tasks) == 0 {
e.outf("task: No tasks with description available")
return
}
e.outf("task: Available tasks for this project:")
// Format in tab-separated columns with a tab stop of 8.
w := tabwriter.NewWriter(e.Stdout, 0, 8, 0, '\t', 0)
for _, task := range tasks {
fmt.Fprintln(w, fmt.Sprintf("* %s: \t%s", task, e.Tasks[task].Desc))
}
w.Flush()
}
func (e *Executor) tasksWithDesc() (tasks []string) {
for name, task := range e.Tasks {
if task.Desc != "" {
tasks = append(tasks, name)
}
}
sort.Strings(tasks)
return
}
| package task
import (
"fmt"
"sort"
"text/tabwriter"
)
// PrintTasksHelp prints help os tasks that have a description
func (e *Executor) PrintTasksHelp() {
tasks := e.tasksWithDesc()
if len(tasks) == 0 {
return
}
e.outf("Available tasks for this project:")
// Format in tab-separated columns with a tab stop of 8.
w := tabwriter.NewWriter(e.Stdout, 0, 8, 0, '\t', 0)
for _, task := range tasks {
fmt.Fprintln(w, fmt.Sprintf("* %s: \t%s", task, e.Tasks[task].Desc))
}
w.Flush()
}
func (e *Executor) tasksWithDesc() (tasks []string) {
for name, task := range e.Tasks {
if task.Desc != "" {
tasks = append(tasks, name)
}
}
sort.Strings(tasks)
return
}
|
Remove from inventory on select | var play = require('../engine/play');
var Player = function(game, name) {
this.name = name;
this.inventory = null;
this.chosen = false;
}
Player.prototype.populateInventory = function (constructSprite) {
this.inventory = _.map(play.chooseIngredients(4), function(name) {
return {
name : name,
sprite : constructSprite(name)
}
});
}
Player.prototype.addIngredient = function (food, plate) {
this.removeFromInventory(food);
plate.foods.push(food.name);
plate.update();
}
Player.prototype.removeFromInventory = function (food) {
food.sprite.alpha = 0;
var index = _(this.inventory).findIndex({name : food.name});
this.inventory.splice(index, 1);
}
Player.prototype.choose = function (index) {
var food = this.inventory[index];
this.addIngredient(food, plates[0]);
console.log('%s selected %s', this.name, food.name);
this.chosen = true;
/*var tween = this.game.add.tween(newFood, this.game, this.game.tweens);
// tween.to({
// x: 200,
// y: 0
// });
// tween.start();*/
// /*tween.onComplete = function(target, tween) {
// target.kill();
// }*/
// }
}
module.exports = Player;
| var play = require('../engine/play');
var Player = function(game, name) {
this.name = name;
this.inventory = null;
this.chosen = false;
}
Player.prototype.populateInventory = function (constructSprite) {
this.inventory = _.map(play.chooseIngredients(4), function(name) {
return {
name : name,
sprite : constructSprite(name)
}
});
}
Player.prototype.addIngredient = function (food, plate) {
this.removeFromInventory(this.inventory, food);
plate.foods.push(food.name);
plate.update();
}
Player.prototype.removeFromInventory = function (inventory, food) {
food.sprite.alpha = .1;
}
Player.prototype.choose = function (index) {
// var foodIndex = getIndex(sprite.xDif, sprite.yDif);
var food = this.inventory[index];
this.addIngredient(food, plates[0]);
console.log('%s selected %s', this.name, food.name);
this.chosen = true;
/*var tween = this.game.add.tween(newFood, this.game, this.game.tweens);
// tween.to({
// x: 200,
// y: 0
// });
// tween.start();*/
// /*tween.onComplete = function(target, tween) {
// target.kill();
// }*/
// }
}
module.exports = Player;
|
Update formatting to Salt guidelines | # -*- coding: utf-8 -*-
'''
SCSI administration module
'''
import os.path
import logging
log = logging.getLogger(__name__)
def lsscsi():
'''
List SCSI devices
CLI Example:
.. code-block:: bash
salt '*' scsi.lsscsi
'''
cmd = 'lsscsi'
return __salt__['cmd.run'](cmd).splitlines()
def rescan_all(host):
'''
List scsi devices
CLI Example:
.. code-block:: bash
salt '*' scsi.rescan_all(0)
'''
if os.path.isdir('/sys/class/scsi_host/host{0}').format(host):
cmd = 'echo "- - -" > /sys/class/scsi_host/host{0}/scan'.format(host)
else:
return 'Host {0} does not exist'.format(host)
return __salt__['cmd.run'](cmd).splitlines()
| # -*- coding: utf-8 -*-
"""
SCSI administration module
"""
import logging
log = logging.getLogger(__name__)
def lsscsi():
'''
List scsi devices
CLI Example:
.. code-block:: bash
salt '*' scsi.lsscsi
'''
cmd = 'lsscsi'
return __salt__['cmd.run'](cmd).splitlines()
def rescan_all(host):
'''
List scsi devices
CLI Example:
.. code-block:: bash
salt '*' scsi.rescan_all(0)
'''
if os.path.isdir("/sys/class/scsi_host/host{0}").format(host):
cmd = 'echo "- - -" > /sys/class/scsi_host/host{0}/scan'.format(host)
else:
return 'Host {0} does not exist'.format(host)
return __salt__['cmd.run'](cmd).splitlines()
|
Add some missing return types to internal/final classes | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http\Authentication;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* This class is used when the authenticator system is activated.
*
* This is used to not break AuthenticationChecker and ContextListener when
* using the authenticator system. Once the authenticator system is no longer
* experimental, this class can be used to trigger deprecation notices.
*
* @author Wouter de Jong <wouter@wouterj.nl>
*
* @internal
*/
class NoopAuthenticationManager implements AuthenticationManagerInterface
{
public function authenticate(TokenInterface $token): TokenInterface
{
return $token;
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Http\Authentication;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* This class is used when the authenticator system is activated.
*
* This is used to not break AuthenticationChecker and ContextListener when
* using the authenticator system. Once the authenticator system is no longer
* experimental, this class can be used to trigger deprecation notices.
*
* @internal
*
* @author Wouter de Jong <wouter@wouterj.nl>
*/
class NoopAuthenticationManager implements AuthenticationManagerInterface
{
public function authenticate(TokenInterface $token)
{
return $token;
}
}
|
Use enum for the type | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWatches extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('watches', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->enum('notifiable_type', ['beatmapset', 'build', 'news_post']);
$table->bigInteger('notifiable_id')->unsigned();
$table->string('subtype');
$table->timestampsTz();
$table->unique(['user_id', 'notifiable_type', 'notifiable_id', 'subtype']);
$table->index(['notifiable_type', 'notifiable_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('watches');
}
}
| <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWatches extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('watches', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->string('notifiable_type');
$table->bigInteger('notifiable_id')->unsigned();
$table->string('subtype');
$table->timestampsTz();
$table->unique(['user_id', 'notifiable_type', 'notifiable_id', 'subtype']);
$table->index(['notifiable_type', 'notifiable_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('watches');
}
}
|
Update to use <span> instead of <input> for non-modifiable text. |
<!-- Sleep so users see the activity indicator -->
<?php sleep(2); ?>
<ul id="stats" title="Stats">
<li><a href="#usage">Usage</a></li>
<li><a href="#battery">Battery</a></li>
</ul>
<div id="usage" title="Usage" class="panel">
<h2>Play Time</h2>
<fieldset>
<div class="row">
<label>Years</label>
<span>2</span>
</div>
<div class="row">
<label>Months</label>
<span>8</span>
</div>
<div class="row">
<label>Days</label>
<span>27</span>
</div>
</fieldset>
</div>
<div id="battery" title="Battery" class="panel">
<h2>Better recharge soon!</h2>
</div>
|
<!-- Sleep so users see the activity indicator -->
<?php sleep(2); ?>
<ul id="stats" title="Stats">
<li><a href="#usage">Usage</a></li>
<li><a href="#battery">Battery</a></li>
</ul>
<div id="usage" title="Usage" class="panel">
<h2>Play Time</h2>
<fieldset>
<div class="row">
<label>Years</label>
<input type="text" value="2"/>
</div>
<div class="row">
<label>Months</label>
<input type="text" value="8"/>
</div>
<div class="row">
<label>Days</label>
<input type="text" value="27"/>
</div>
</fieldset>
</div>
<div id="battery" title="Battery" class="panel">
<h2>Better recharge soon!</h2>
</div>
|
Add logging message to sessionless op processor. | package com.tinkerpop.gremlin.server.op.standard;
import com.tinkerpop.gremlin.driver.Tokens;
import com.tinkerpop.gremlin.driver.message.RequestMessage;
import com.tinkerpop.gremlin.server.Context;
import com.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor;
import com.tinkerpop.gremlin.server.op.OpProcessorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import java.util.Map;
import java.util.Optional;
/**
* Operations to be used by the {@link StandardOpProcessor}.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
final class StandardOps {
private static final Logger logger = LoggerFactory.getLogger(StandardOps.class);
public static void evalOp(final Context context) throws OpProcessorException {
final RequestMessage msg = context.getRequestMessage();
logger.debug("Sessionless request {} for eval in thread {}", msg.getRequestId(), Thread.currentThread().getName());
AbstractEvalOpProcessor.evalOp(context, context::getGremlinExecutor, () -> {
final Bindings bindings = new SimpleBindings();
Optional.ofNullable((Map<String, Object>) msg.getArgs().get(Tokens.ARGS_BINDINGS)).ifPresent(bindings::putAll);
return bindings;
});
}
}
| package com.tinkerpop.gremlin.server.op.standard;
import com.tinkerpop.gremlin.driver.Tokens;
import com.tinkerpop.gremlin.driver.message.RequestMessage;
import com.tinkerpop.gremlin.server.Context;
import com.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor;
import com.tinkerpop.gremlin.server.op.OpProcessorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import java.util.Map;
import java.util.Optional;
/**
* Operations to be used by the {@link StandardOpProcessor}.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
final class StandardOps {
private static final Logger logger = LoggerFactory.getLogger(StandardOps.class);
public static void evalOp(final Context context) throws OpProcessorException {
final RequestMessage msg = context.getRequestMessage();
AbstractEvalOpProcessor.evalOp(context, context::getGremlinExecutor, () -> {
final Bindings bindings = new SimpleBindings();
Optional.ofNullable((Map<String, Object>) msg.getArgs().get(Tokens.ARGS_BINDINGS)).ifPresent(bindings::putAll);
return bindings;
});
}
}
|
Make all end-points accepting post | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.post( '/healthy' )
def healthy():
return _Json({})
@app.post( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
| import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.get( '/healthy' )
def healthy():
return _Json({})
@app.get( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
|
Use partially synchronized map in Event hasAnnotation cache.
Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com> | package nallar.patched.forge;
import nallar.collections.PartiallySynchronizedMap;
import net.minecraftforge.event.Cancelable;
import net.minecraftforge.event.Event;
public abstract class PatchEvent extends Event {
private static final PartiallySynchronizedMap<Class, Boolean> annotationMap = new PartiallySynchronizedMap<Class, Boolean>();
@Override
protected boolean hasAnnotation(Class annotation) {
Class cls = this.getClass();
Boolean cachedResult = annotationMap.get(cls);
if (cachedResult != null) {
return cachedResult;
}
Class searchClass = cls;
while (searchClass != Event.class) {
if (searchClass.isAnnotationPresent(Cancelable.class)) // TODO: Forge bug, not fixed. Buggy behaviour may be required for some mods.
{
annotationMap.put(cls, true);
return true;
}
searchClass = searchClass.getSuperclass();
}
annotationMap.put(cls, false);
return false;
}
}
| package nallar.patched.forge;
import java.util.concurrent.ConcurrentHashMap;
import net.minecraftforge.event.Cancelable;
import net.minecraftforge.event.Event;
public abstract class PatchEvent extends Event {
private static final ConcurrentHashMap<Class, Boolean> annotationMap = new ConcurrentHashMap<Class, Boolean>();
@Override
protected boolean hasAnnotation(Class annotation) {
Class cls = this.getClass();
Boolean cachedResult = annotationMap.get(cls);
if (cachedResult != null) {
return cachedResult;
}
Class searchClass = cls;
while (searchClass != Event.class) {
if (searchClass.isAnnotationPresent(Cancelable.class)) // Forge bug, not fixed. Buggy behaviour may be required for some mods.
{
annotationMap.put(cls, true);
return true;
}
searchClass = searchClass.getSuperclass();
}
annotationMap.put(cls, false);
return false;
}
}
|
Make code follow the Python style guidelines
+ Use a doc string for the whole file.
+ Lower case function names.
+ Consistently use single-quotes for quoted strings.
+ align wrapped elements with opening delimiter.
+ use a main() function
Review URL: https://chromiumcodereview.appspot.com//10837127
git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@10307 260f80e4-7a28-3924-810f-c04153c831b5 | #!/usr/bin/env python
# Copyright (c) 2012 The Dart Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Invoke gyp to generate build files for building the Dart VM.
"""
import os
import subprocess
import sys
def execute(args):
process = subprocess.Popen(args)
process.wait()
return process.returncode
def main():
args = ['python', 'dart/third_party/gyp/gyp', '--depth=dart',
'-Idart/tools/gyp/all.gypi', 'dart/dart.gyp']
if sys.platform == 'win32':
# Generate Visual Studio 2008 compatible files by default.
if not os.environ.get('GYP_MSVS_VERSION'):
args.extend(['-G', 'msvs_version=2008'])
sys.exit(execute(args))
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# Copyright (c) 2012 The Dart Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script is wrapper for Dart that adds some support for how GYP
# is invoked by Dart beyond what can be done in the gclient hooks.
import os
import subprocess
import sys
def Execute(args):
process = subprocess.Popen(args)
process.wait()
return process.returncode
if __name__ == '__main__':
args = ['python', "dart/third_party/gyp/gyp", "--depth=dart",
"-Idart/tools/gyp/all.gypi", "dart/dart.gyp"]
if sys.platform == 'win32':
# Generate Visual Studio 2008 compatible files by default.
if not os.environ.get('GYP_MSVS_VERSION'):
args.extend(['-G', 'msvs_version=2008'])
sys.exit(Execute(args))
|
Add methods to change the beat and volume of tone | from flask import Flask, url_for , request
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
@app.route('/beat/<tone_id>' , methods=['POST'])
def api_change_beat(tone_id):
return 'Changed beat of ' + tone_id + ' to ' + request.form['value']
@app.route('/volume/<tone_id>' , methods=['POST'])
def api_change_volume(tone_id):
return 'Changed Volume of ' + tone_id + ' to ' + request.form['value']
if __name__ == '__main__':
app.run(debug=True) | from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def api_root():
return 'Welcome'
# Deprecated
# @app.route('/toggle')
# def api_toggle():
# # Toggle the state of the player
# return 'state changed'
# @app.route('/volume/<volume_value>')
# def api_volume(volume_value):
# # Adjusts volume of the player
# return 'Volume is now ' + volume_value
@app.route('/start/<tone_id>')
def api_start_tone(tone_id):
# Start the tone
return 'Started Playing ' + tone_id
@app.route('/stop/<tone_id>')
def api_stop_tone(tone_id):
# Stop the tone
return 'Stopped Playing ' + tone_id
if __name__ == '__main__':
app.run(debug=True) |
Add deleteAll() as its own method | 'use strict';
/**
* DRY out REST requests to the data API
*/
module.exports = function(app) {
app.factory('httpService', function($http, $location) {
// Generic helper function
var http = function(method, params) {
params.id = params.id || '';
var promise = $http[method]('/api/0_0_1/data/' + params.id, params.data)
.error(function(error, status) {
console.log('Error in http ' + method + ': ' + error + ' | status ' + status);
if (status === 401) {
$location.path('/signin');
}
});
return promise;
};
// Specific verbs
var httpVerbs = {
get: function() {
return http('get', {});
},
post: function(data) {
return http('post', {
data: data
});
},
put: function(data) {
return http('put', {
data: data,
id: data._id
});
},
delete: function(data) {
return http('delete', {
id: 'delete/' + data._id
});
},
// Dev only
deleteAll: function() {
return http('delete', {
id: 'deleteAll'
});
}
};
return httpVerbs;
});
}; | 'use strict';
module.exports = function(app) {
app.factory('httpService', function($http, $location) {
// Generic helper function
var http = function(method, params) {
params.id = params.id || '';
var promise = $http[method]('/api/0_0_1/data/' + params.id, params.data)
.error(function(error, status) {
console.log('Error in http ' + method + ': ' + error + ' | status ' + status);
if (status === 401) {
$location.path('/signin');
}
});
return promise;
};
// Specific verbs
var httpVerbs = {
get: function() {
return http('get', {});
},
post: function(data) {
return http('post', {
data: data
});
},
put: function(data) {
return http('put', {
data: data,
id: data._id
});
},
delete: function(data) {
return http('delete', {
id: data._id
});
}
};
return httpVerbs;
});
}; |
Check more data about riemann | from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_config():
return Config({})
class TestBase(object):
def test_base_config_interval(self, base_config):
assert base_config.interval == 5
class TestRiemann(object):
def test_base_config_get_riemann(self, base_config):
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
obj = incomplete_config.riemann
assert isinstance(obj, RiemannConfig)
assert isinstance(obj._data, dict)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
def test_riemann_default_port(self, incomplete_config):
assert incomplete_config.riemann.port == 5555
| from pytest import fixture
from oshino.config import Config, RiemannConfig
@fixture
def base_config():
return Config({"riemann": {"host": "localhost",
"port": 5555
},
"interval": 5
})
@fixture
def incomplete_config():
return Config({})
class TestBase(object):
def test_base_config_interval(self, base_config):
assert base_config.interval == 5
class TestRiemann(object):
def test_base_config_get_riemann(self, base_config):
assert isinstance(base_config.riemann, RiemannConfig)
def test_incomplete_config_get_riemann(self, incomplete_config):
assert isinstance(incomplete_config.riemann, RiemannConfig)
def test_riemann_default_host(self, incomplete_config):
assert incomplete_config.riemann.host == "localhost"
def test_riemann_default_port(self, incomplete_config):
assert incomplete_config.riemann.port == 5555
|
Add methods for convert responses | <?php
namespace Artesaos\Zenvia\Contracts;
use Artesaos\Zenvia\Exceptions\ZenviaResponseException;
use Psr\Http\Message\ResponseInterface;
interface ResponseHandlerInterface
{
/**
* Convert a PSR-7 response to a data type you want to work with.
*
* @param ResponseInterface $response
* @param string $format
*
* @return ResponseInterface|\Psr\Http\Message\StreamInterface|\SimpleXMLElement|string
*
* @throws \InvalidArgumentException
*/
public static function convert(ResponseInterface $response, $format);
/**
* @param ResponseInterface $response
*
* @return string
*/
public static function convertToArray(ResponseInterface $response);
/**
* @param ResponseInterface $response
*
* @return \SimpleXMLElement
*
* @throws ZenviaResponseException
*/
public static function convertToSimpleXml(ResponseInterface $response);
} | <?php
namespace Artesaos\Zenvia\Contracts;
use Artesaos\Zenvia\Exceptions\ZenviaResponseException;
use Psr\Http\Message\ResponseInterface;
interface ResponseHandlerInterface
{
/**
* Convert a PSR-7 response to a data type you want to work with.
*
* @param ResponseInterface $response
* @param string $format
*
* @return ResponseInterface|\Psr\Http\Message\StreamInterface|\SimpleXMLElement|string
*
* @throws \InvalidArgumentException
*/
public function convert(ResponseInterface $response, $format);
/**
* @param ResponseInterface $response
*
* @return string
*/
public function convertToArray(ResponseInterface $response);
/**
* @param ResponseInterface $response
*
* @return \SimpleXMLElement
*
* @throws ZenviaResponseException
*/
public function convertToSimpleXml(ResponseInterface $response);
} |
WIP: Move to JS and Refactoring | (function() {
"use strict";
var _;
var host = process.argv[2];
var port = process.argv[3];
if (!host || !port) {
logger.log("Usage: app.js host port");
process.exit();
}
var server = require('fora-app-server');
var config = {
baseConfiguration: require('../conf'),
/* Extensions needed by this app */
extensionsService: {
extensionTypes: {
containers: ['api'],
apps: ['api'],
records: ['model']
}
},
/*
App server will start applicationContainer:containerModuleName
For example: containers/fora/1.0.0:api
*/
containerModuleName: "api",
host: host,
port: port
};
co(function*() {
_ = yield* loader.init();
_ = yield* server(config);
logger.log("Fora API started at " + new Date() + " on " + host + ":" + port);
})();
})();
| (function() {
"use strict";
var _;
var host = process.argv[2];
var port = process.argv[3];
if (!host || !port) {
logger.log("Usage: app.js host port");
process.exit();
}
var server = require('fora-app-server');
var config = {
baseConfiguration: require('../conf'),
/* Extensions needed by this app */
extensionsService: {
extensionTypes: {
containers: ['api'],
apps: ['api'],
records: ['model']
}
},
/*
App server will start baseConfigurationapplicationContainer:containerModuleName
For example: containers/fora/1.0.0:api
*/
containerModuleName: "api",
host: host,
port: port
};
co(function*() {
_ = yield* loader.init();
_ = yield* server(config);
logger.log("Fora API started at " + new Date() + " on " + host + ":" + port);
})();
})();
|
Add matplotlib as dev dependency | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.2.1dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oemof developer group',
author_email='windpowerlib@rl-institut.de',
license='MIT',
packages=['windpowerlib'],
package_data={
'windpowerlib': [os.path.join('data', '*.csv'),
os.path.join('oedb', '*.csv')]},
long_description=read('README.rst'),
long_description_content_type='text/x-rst',
zip_safe=False,
install_requires=['pandas >= 0.20.0, < 0.26',
'requests < 3.0'],
extras_require={
'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat',
'numpy', 'matplotlib']})
| import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='windpowerlib',
version='0.2.1dev',
description='Creating time series of wind power plants.',
url='http://github.com/wind-python/windpowerlib',
author='oemof developer group',
author_email='windpowerlib@rl-institut.de',
license='MIT',
packages=['windpowerlib'],
package_data={
'windpowerlib': [os.path.join('data', '*.csv'),
os.path.join('oedb', '*.csv')]},
long_description=read('README.rst'),
long_description_content_type='text/x-rst',
zip_safe=False,
install_requires=['pandas >= 0.20.0, < 0.26',
'requests < 3.0'],
extras_require={
'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat',
'numpy']})
|
Fix dash in author email | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as v_file:
version = v_file.read().strip()
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
name='canvas_python_sdk',
version=version,
description='A python SDK for Instructure\'s Canvas LMS API',
author='Harvard University',
author_email='tlt-opensource@g.harvard.edu',
url='https://github.com/penzance/canvas_python_sdk',
packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
long_description=README,
classifiers=[
"License :: OSI Approved :: MIT License",
'Operating System :: OS Independent',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development",
],
keywords='canvas api sdk LMS',
license='MIT',
zip_safe=False,
install_requires=[
'requests',
],
test_suite='tests',
tests_require=[
'mock>=1.0.1',
],
)
| import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as v_file:
version = v_file.read().strip()
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
name='canvas_python_sdk',
version=version,
description='A python SDK for Instructure\'s Canvas LMS API',
author='Harvard University',
author_email='tlt_opensource@g.harvard.edu',
url='https://github.com/penzance/canvas_python_sdk',
packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
long_description=README,
classifiers=[
"License :: OSI Approved :: MIT License",
'Operating System :: OS Independent',
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Topic :: Software Development",
],
keywords='canvas api sdk LMS',
license='MIT',
zip_safe=False,
install_requires=[
'requests',
],
test_suite='tests',
tests_require=[
'mock>=1.0.1',
],
)
|
Make a utf-8 string in getLine for Node | var i$putStr = (function() {
var fs = require('fs');
return function(s) {
fs.write(1,s);
};
})();
var i$getLine = (function() {
var fs = require( "fs" )
return function() {
var ret = "";
var b = new Buffer(1024);
var i = 0;
while(true) {
fs.readSync(0, b, i, 1 )
if (b[i] == 10) {
ret = b.toString('utf8', 0, i);
break;
}
i++;
if (i == b.length) {
nb = new Buffer (b.length*2);
b.copy(nb)
b = nb;
}
}
return ret;
};
})();
var i$systemInfo = function(index) {
var os = require('os')
switch(index) {
case 0:
return "node";
case 1:
return os.platform();
}
return "";
}
| var i$putStr = (function() {
var fs = require('fs');
return function(s) {
fs.write(1,s);
};
})();
var i$getLine = (function() {
var fs = require( "fs" )
return function() {
var ret = "";
while(true) {
var b = new Buffer(1);
fs.readSync(0, b, 0, 1 )
if (b[0] == 10)
break;
else
ret += String.fromCharCode(b[0]);
}
return ret;
};
})();
var i$systemInfo = function(index) {
var os = require('os')
switch(index) {
case 0:
return "node";
case 1:
return os.platform();
}
return "";
}
|
Remove unload objects as this leads to errors | (function() {
var app;
var getApplication = function() {
return app;
};
var shutDown = function() {
lowland.ObjectManager.dispose();
};
var startUp = function() {
var Application = core.Class.getByName(core.Env.getValue("application") + ".Application");
var init = new Application();
app = init;
init.main();
init.finalize();
//lowland.bom.Events.listen(window, "shutdown", shutDown);
//lowland.bom.Events.listen(window, "beforeunload", shutDown);
};
core.Class("unify.core.Init", {
include : [unify.core.Object],
construct : function() {
unify.core.Object.call(this);
},
members : {
main : function() {
throw new Error("main is not implemented");
},
finalize : function() {}
}
});
unify.core.Statics.annotate(unify.core.Init, {
getApplication : getApplication,
startUp : startUp,
shutDown : shutDown
});
})();
| (function() {
var app;
var getApplication = function() {
return app;
};
var shutDown = function() {
lowland.ObjectManager.dispose();
};
var startUp = function() {
var Application = core.Class.getByName(core.Env.getValue("application") + ".Application");
var init = new Application();
app = init;
init.main();
init.finalize();
//lowland.bom.Events.listen(window, "shutdown", shutDown);
lowland.bom.Events.listen(window, "beforeunload", shutDown);
};
core.Class("unify.core.Init", {
include : [unify.core.Object],
construct : function() {
unify.core.Object.call(this);
},
members : {
main : function() {
throw new Error("main is not implemented");
},
finalize : function() {}
}
});
unify.core.Statics.annotate(unify.core.Init, {
getApplication : getApplication,
startUp : startUp,
shutDown : shutDown
});
})(); |
Make missing assets 404 correctly | /**
* Module dependencies.
*/
var Promise = require('bluebird');
var path = require('path');
var _ = require('lodash');
var highlighter = require('../../../highlighter');
var utils = require('../../../utils');
/*
* Export the pages route handlers.
*/
var handlers = exports = module.exports = {};
handlers.params = {};
/*
* Resolve a page from a path parameter
*/
handlers.params.page = function(req, res, next, pagePath) {
try {
var page = req._pages.resolve(pagePath);
page.renderContent().then(function(){
res.locals.page = page.toJSON();
next();
});
} catch(err) {
return res.status(404).render('pages/404', {
message: err.message
});
}
};
/*
* Render a generic page.
*/
handlers.page = function(req, res){
var section = res.locals.section || {
handle: 'pages',
baseUrl: '/',
};
res.render('pages/page', {
section: section
});
};
| /**
* Module dependencies.
*/
var Promise = require('bluebird');
var path = require('path');
var _ = require('lodash');
var utils = require('../../../utils');
/*
* Export the pages route handlers.
*/
var handlers = exports = module.exports = {};
handlers.params = {};
/*
* Resolve a page from a path parameter
*/
handlers.params.page = function(req, res, next, pagePath) {
var page = req._pages.resolve(pagePath);
page.renderContent().then(function(){
res.locals.page = page.toJSON();
next();
});
};
/*
* Render a generic page.
*/
handlers.page = function(req, res){
var section = res.locals.section || {
handle: 'pages',
baseUrl: '/',
};
res.render('pages/page', {
section: section
});
};
|
Revert "Update usage of less-middleware"
This reverts commit d6bbc054f68fc7382ab1b14cb8afaff521548019. | var express = require('express');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.configure(function(){
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, express.favicon());
application.use(prefix, express.bodyParser());
application.use(prefix, express.methodOverride());
application.use(prefix, less(path.join(topDirectory, 'public')));
application.use(prefix, express.static(path.join(topDirectory, 'public')));
});
application.configure('development', function() {
application.use(prefix, express.errorHandler());
});
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
| var express = require('express');
var less = require('less-middleware');
var path = require('path');
exports.register = function(application, params) {
params = params || {};
var prefix = params.prefix || '';
prefix = prefix.replace(/\/$/, '');
var topDirectory = path.join(__dirname, '..', '..', '..');
application.configure(function(){
application.set('views', path.join(topDirectory, 'views'));
application.set('view engine', 'jade');
application.use(prefix, express.favicon());
application.use(prefix, express.bodyParser());
application.use(prefix, express.methodOverride());
application.use(prefix, less({ src: path.join(topDirectory, 'public') }));
application.use(prefix, express.static(path.join(topDirectory, 'public')));
});
application.configure('development', function() {
application.use(prefix, express.errorHandler());
});
application.get(prefix + '/dashboard', function(request, response) {
response.render('index', { title: '', prefix: prefix });
});
}
|
Fix process params to only accept StateMachine
It must accept all class that implement StateMachineInterface | <?php
namespace Finite\Transition;
use Finite\StateMachine\StateMachineInterface;
/**
* The base Transition interface
*
* @author Yohan Giarelli <yohan@frequence-web.fr>
*/
interface TransitionInterface
{
/**
* Returns the array of states that supports this transition
*
* @return array
*/
public function getInitialStates();
/**
* Returns the state resulting of this transition
*
* @return string
*/
public function getState();
/**
* Process the transition
*
* @param StateMachineInterface $stateMachine
*
* @return mixed
*/
public function process(StateMachineInterface $stateMachine);
/**
* Returns the name of the transition
*
* @return string
*/
public function getName();
/**
* Returns the closure. If closure execution returns false, transition cannot be applied.
*
* @return callable
*/
public function getGuard();
}
| <?php
namespace Finite\Transition;
use Finite\StateMachine\StateMachine;
/**
* The base Transition interface
*
* @author Yohan Giarelli <yohan@frequence-web.fr>
*/
interface TransitionInterface
{
/**
* Returns the array of states that supports this transition
*
* @return array
*/
public function getInitialStates();
/**
* Returns the state resulting of this transition
*
* @return string
*/
public function getState();
/**
* Process the transition
*
* @param StateMachine $stateMachine
*
* @return mixed
*/
public function process(StateMachine $stateMachine);
/**
* Returns the name of the transition
*
* @return string
*/
public function getName();
/**
* Returns the closure. If closure execution returns false, transition cannot be applied.
*
* @return callable
*/
public function getGuard();
}
|
Fix 'Datacash' to 'Sagepay' in Dashboard
Copy-paste did it again | from django.conf.urls import patterns, url
from django.contrib.admin.views.decorators import staff_member_required
from oscar.core.application import Application
from . import views
try:
from oscar.apps.dashboard.nav import register, Node
except ImportError:
pass
else:
# Old way of registering Dashboard nodes
node = Node('Sagepay', 'sagepay-transaction-list')
register(node, 100)
class SagepayDashboard(Application):
name = None
list_view = views.Transactions
detail_view = views.Transaction
def get_urls(self):
urlpatterns = patterns('',
url(r'^transactions/$', self.list_view.as_view(),
name='sagepay-transaction-list'),
url(r'^transactions/(?P<pk>\d+)/$', self.detail_view.as_view(),
name='sagepay-transaction-detail'),
)
return self.post_process_urls(urlpatterns)
def get_url_decorator(self, url_name):
return staff_member_required
application = SagepayDashboard()
| from django.conf.urls import patterns, url
from django.contrib.admin.views.decorators import staff_member_required
from oscar.core.application import Application
from . import views
try:
from oscar.apps.dashboard.nav import register, Node
except ImportError:
pass
else:
# Old way of registering Dashboard nodes
node = Node('Datacash', 'sagepay-transaction-list')
register(node, 100)
class SagepayDashboard(Application):
name = None
list_view = views.Transactions
detail_view = views.Transaction
def get_urls(self):
urlpatterns = patterns('',
url(r'^transactions/$', self.list_view.as_view(),
name='sagepay-transaction-list'),
url(r'^transactions/(?P<pk>\d+)/$', self.detail_view.as_view(),
name='sagepay-transaction-detail'),
)
return self.post_process_urls(urlpatterns)
def get_url_decorator(self, url_name):
return staff_member_required
application = SagepayDashboard()
|
Update docblocks for begin & end methods | <?php
namespace Benrowe\Laravel\Widgets\Traits;
/**
* Provides the begin & end functionality for the Widget factory
*
* @package Benrowe\Laravel\Widgets
*/
trait BeginEndFactory
{
private $stack = [];
/**
* Being the widget
*
* @return Expression
*/
public function begin()
{
$args = func_get_args();
$this->stack[] = $args;
$this->instantiateWidget($args);
return $this->asExpression($this->widget->begin());
}
/**
* End the widget
*
* @param array $config suplementry config
* @return Expression
*/
public function end($config = [])
{
$args = array_pop($this->stack);
$args[1] = $args[1] ? array_merge($args[1], $config) : [];
$this->instantiateWidget($args);
return $this->asExpression($this->widget->end());
}
}
| <?php
namespace Benrowe\Laravel\Widgets\Traits;
/**
* Provides the begin & end functionality for the Widget factory
*
* @package Benrowe\Laravel\Widgets
*/
trait BeginEndFactory
{
private $stack = [];
/**
* [begin description]
* @return [type] [description]
*/
public function begin()
{
$args = func_get_args();
$this->stack[] = $args;
$this->instantiateWidget($args);
return $this->asExpression($this->widget->begin());
}
/**
* [end description]
* @return [type] [description]
*/
public function end()
{
$args = array_pop($this->stack);
$args[1] = $args[1] ? array_merge($args[1], $config) : [];
$this->instantiateWidget($args);
return $this->asExpression($this->widget->end());
}
}
|
Fix timeout error in UserContainer test. | var _ = require('underscore');
var UserContainer = require('../lib/authentication/user-container');
var assert = require('chai').assert;
describe('tests of garbage collecting of outdated cookies', function() {
var responseMock = {
cookies: {
set: function() {
}
}
};
it('', function(done) {
//for the sake of the test
UserContainer._collectorIntervalMs = 100;
UserContainer._oudatedTimeMs = UserContainer._collectorIntervalMs + 10;
var userContainer = new UserContainer();
userContainer.saveUser(responseMock, 'token');
assert(_.size(userContainer._userList) == 1);
var user = userContainer._userList[0];
setTimeout(function() {
assert(userContainer.hasUserByCookie(user.cookie), 'Cookie should be presented');
assert(userContainer.hasUserByToken(user.token), 'Token should be presented');
setTimeout(function() {
assert(!userContainer.hasUserByCookie(user), 'User should be deleted');
assert(!userContainer.hasUserByToken(user), 'User should be deleted');
done();
}, (UserContainer._oudatedTimeMs + 2 * UserContainer._collectorIntervalMs));
}, UserContainer._collectorIntervalMs);
});
});
| var _ = require('underscore');
var UserContainer = require('../lib/authentication/user-container');
var assert = require('chai').assert;
describe('tests of garbage collecting of outdated cookies', function() {
var responseMock = {
cookies: {
set: function() {
}
}
};
it('', function(done) {
//for the sake of the test
UserContainer._collectorIntervalMs = 100;
UserContainer._oudatedTimeMs = UserContainer._collectorIntervalMs + 1;
var userContainer = new UserContainer();
userContainer.saveUser(responseMock, 'token');
assert(_.size(userContainer._userList) == 1);
var user = userContainer._userList[0];
setTimeout(function() {
assert(userContainer.hasUserByCookie(user.cookie), 'Cookie should be presented');
assert(userContainer.hasUserByToken(user.token), 'Token should be presented');
setTimeout(function() {
assert(!userContainer.hasUserByCookie(user), 'User should be deleted');
assert(!userContainer.hasUserByToken(user), 'User should be deleted');
done();
}, (UserContainer._oudatedTimeMs + 2 * UserContainer._collectorIntervalMs));
}, UserContainer._collectorIntervalMs);
});
});
|
Fix a typo in blorg test | package blorg
import (
"fmt"
"io/ioutil"
"os/exec"
"strings"
"testing"
)
func TestBlorg(t *testing.T) {
config, err := ReadConfig("testdata/blorg.org")
if err != nil {
t.Errorf("Could not read config: %s", err)
return
}
committedHashBs, err := ioutil.ReadFile("testdata/public.md5")
if err != nil {
t.Errorf("Could not read hash bytes: %s", err)
return
}
if err := config.Render(); err != nil {
t.Errorf("Could not render: %s", err)
return
}
renderedHashBs, err := exec.Command("bash", "-c", fmt.Sprintf("find %s -type f | sort -u | xargs cat | md5sum", config.PublicDir)).Output()
if err != nil {
t.Errorf("Could not hash PublicDir: %s", err)
return
}
rendered, committed := strings.TrimSpace(string(renderedHashBs)), strings.TrimSpace(string(committedHashBs))
if rendered != committed {
t.Errorf("PublicDir hashes do not match: '%s' -> '%s'", committed, rendered)
return
}
}
| package blorg
import (
"fmt"
"io/ioutil"
"os/exec"
"strings"
"testing"
)
func TestBlorg(t *testing.T) {
config, err := ReadConfig("testdata/blorg.org")
if err != nil {
t.Errorf("Could not read config: %s", err)
return
}
commitedHashBs, err := ioutil.ReadFile("testdata/public.md5")
if err != nil {
t.Errorf("Could not read hash bytes: %s", err)
return
}
if err := config.Render(); err != nil {
t.Errorf("Could not render: %s", err)
return
}
renderedHashBs, err := exec.Command("bash", "-c", fmt.Sprintf("find %s -type f | sort -u | xargs cat | md5sum", config.PublicDir)).Output()
if err != nil {
t.Errorf("Could not hash PublicDir: %s", err)
return
}
rendered, committed := strings.TrimSpace(string(renderedHashBs)), strings.TrimSpace(string(commitedHashBs))
if rendered != committed {
t.Errorf("PublicDir hashes do not match: '%s' -> '%s'", committed, rendered)
return
}
}
|
Add provider client method to get provider version history |
from app.notify_client import _attach_current_user, NotifyAdminAPIClient
class ProviderClient(NotifyAdminAPIClient):
def __init__(self):
super().__init__("a", "b", "c")
def init_app(self, app):
self.base_url = app.config['API_HOST_NAME']
self.service_id = app.config['ADMIN_CLIENT_USER_NAME']
self.api_key = app.config['ADMIN_CLIENT_SECRET']
def get_all_providers(self):
return self.get(
url='/provider-details'
)
def get_provider_by_id(self, provider_id):
return self.get(
url='/provider-details/{}'.format(provider_id)
)
def get_provider_versions(self, provider_id):
return self.get(
url='/provider-details/{}/versions'.format(provider_id)
)
def update_provider(self, provider_id, priority):
data = {
"priority": priority
}
data = _attach_current_user(data)
return self.post(url='/provider-details/{}'.format(provider_id), data=data)
|
from app.notify_client import _attach_current_user, NotifyAdminAPIClient
class ProviderClient(NotifyAdminAPIClient):
def __init__(self):
super().__init__("a", "b", "c")
def init_app(self, app):
self.base_url = app.config['API_HOST_NAME']
self.service_id = app.config['ADMIN_CLIENT_USER_NAME']
self.api_key = app.config['ADMIN_CLIENT_SECRET']
def get_all_providers(self):
return self.get(
url='/provider-details'
)
def get_provider_by_id(self, provider_id):
return self.get(
url='/provider-details/{}'.format(provider_id)
)
def update_provider(self, provider_id, priority):
data = {
"priority": priority
}
data = _attach_current_user(data)
return self.post(url='/provider-details/{}'.format(provider_id), data=data)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.