text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Make axios automatically send the `X-CSRF-TOKEN`
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require('axios'); window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.Laravel.csrfToken, 'X-Requested-With': 'XMLHttpRequest' }; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from "laravel-echo" // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); require('bootstrap-sass'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require('axios'); window.axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest' }; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from "laravel-echo" // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
Extend example to also send messages from STDIN
<?php require_once __DIR__.'/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $factory = new React\Dns\Resolver\Factory(); $resolver = $factory->createCached('8.8.8.8', $loop); $factory = new Datagram\Factory($loop, $resolver); $factory->createClient('localhost', 1234)->then(function (Datagram\Client $client) use ($loop) { $client->send('first'); $client->on('message', function($message, $server) { //$remote->send() is same as $client->send() echo 'received "' . $message . '" from ' . $server->getAddress() . PHP_EOL; }); $client->on('error', function($error, $server) { echo 'error from ' . $server . PHP_EOL; }); $n = 0; $loop->addPeriodicTimer(2.0, function() use ($client, &$n) { $client->send('tick' . ++$n); }); // read input from STDIN and forward everything to server $loop->addReadStream(STDIN, function () use ($client) { $client->send(trim(fgets(STDIN, 2000))); }); }, function($error) { echo 'ERROR: ' . $error->getMessage() . PHP_EOL; }); $loop->run();
<?php require_once __DIR__.'/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $factory = new React\Dns\Resolver\Factory(); $resolver = $factory->createCached('8.8.8.8', $loop); $factory = new Datagram\Factory($loop, $resolver); $factory->createClient('localhost', 1234)->then(function (Datagram\Client $client) use ($loop) { $client->send('first'); $client->on('message', function($message, $server) { //$remote->send() is same as $client->send() echo 'received "' . $message . '" from ' . $server->getAddress() . PHP_EOL; }); $client->on('error', function($error, $server) { echo 'error from ' . $server . PHP_EOL; }); $n = 0; $loop->addPeriodicTimer(2.0, function() use ($client, &$n) { $client->send('tick' . ++$n); }); }, function($error) { echo 'ERROR: ' . $error->getMessage() . PHP_EOL; }); $loop->run();
Use full row width for image field
<div class="form-group {{ $errors->has('image') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="image">{{ trans('general.image_upload') }}</label> <div class="col-md-9"> <label class="btn btn-default"> {{ trans('button.select_file') }} <input type="file" name="image" id="uploadFile" data-maxsize="{{ \App\Helpers\Helper::file_upload_max_size() }}" accept="image/gif,image/jpeg,image/png,image/svg" style="display:none"> </label> <span class='label label-default' id="upload-file-info"></span> <p class="help-block" id="upload-file-status">{{ trans('general.image_filetypes_help', ['size' => \App\Helpers\Helper::file_upload_max_size_readable()]) }}</p> {!! $errors->first('image', '<span class="alert-msg">:message</span>') !!} </div> <div class="col-md-4"> <img id="imagePreview" style="max-width: 200px;"> </div> </div>
<div class="form-group {{ $errors->has('image') ? 'has-error' : '' }}"> <label class="col-md-3 control-label" for="image">{{ trans('general.image_upload') }}</label> <div class="col-md-5"> <label class="btn btn-default"> {{ trans('button.select_file') }} <input type="file" name="image" id="uploadFile" data-maxsize="{{ \App\Helpers\Helper::file_upload_max_size() }}" accept="image/gif,image/jpeg,image/png,image/svg" style="display:none"> </label> <span class='label label-default' id="upload-file-info"></span> <p class="help-block" id="upload-file-status">{{ trans('general.image_filetypes_help', ['size' => \App\Helpers\Helper::file_upload_max_size_readable()]) }}</p> {!! $errors->first('image', '<span class="alert-msg">:message</span>') !!} </div> <div class="col-md-4"> <img id="imagePreview" style="max-width: 200px;"> </div> </div>
Revert "add 'start' parameter to getusertransactions api page"
<?php $defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1; // Check if the API is activated $api->isActive(); // Check user token $user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']); // Fetch transactions if (isset($_REQUEST['limit']) && $_REQUEST['limit'] <= 100) { $limit = $_REQUEST['limit']; } else { // Force limit $limit = 100; } $data['transactions'] = $transaction->getTransactions(0, NULL, $limit, $user_id); // Fetch summary if enabled if (!$setting->getValue('disable_transactionsummary')) { $aTransactionSummary = $transaction->getTransactionSummary($user_id); $data['transactionsummary'] = $aTransactionSummary; } // Output JSON format echo $api->get_json($data); // Supress master template $supress_master = 1;
<?php $defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1; // Check if the API is activated $api->isActive(); // Check user token $user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']); // Fetch transactions if (isset($_REQUEST['start'])) { $start = $_REQUEST['start']; } else { // start at the beginning $start = 0; } if (isset($_REQUEST['limit']) && $_REQUEST['limit'] <= 100) { $limit = $_REQUEST['limit']; } else { // Force limit $limit = 100; } $data['transactions'] = $transaction->getTransactions($start, NULL, $limit, $user_id); // Fetch summary if enabled if (!$setting->getValue('disable_transactionsummary')) { $aTransactionSummary = $transaction->getTransactionSummary($user_id); $data['transactionsummary'] = $aTransactionSummary; } // Output JSON format echo $api->get_json($data); // Supress master template $supress_master = 1;
Fix minor function call naming bug
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(output_dir=output_dir) print(trainer.bert_model_hub) data = pd.DataFrame({ 'abstract': ['test one', 'test two', 'test three'] * 5, 'section': ['U.S.', 'Arts', 'U.S.'] * 5, }) data_column = 'abstract' label_column = 'section' train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length) trainer.train(train_features, label_list) results = trainer.test(test_features) print('Evaluation results:', results) results2 = trainer.test(test_features) print('Evaluation results:', results2) eval_acc1, eval_acc2 = results['eval_accuracy'], results2['eval_accuracy'] self.assertEqual(eval_acc1, eval_acc2) if __name__ == '__main__': unittest.main()
import unittest import time import pandas as pd from bert_trainer import BERTTrainer from utils import * class TestBERT(unittest.TestCase): def test_init(self): trainer = BERTTrainer() def test_train(self): output_dir = 'test_{}'.format(str(int(time.time()))) trainer = BERTTrainer(output_dir=output_dir) print(trainer.bert_model_hub) data = pd.DataFrame({ 'abstract': ['test one', 'test two', 'test three'] * 5, 'section': ['U.S.', 'Arts', 'U.S.'] * 5, }) data_column = 'abstract' label_column = 'section' train_features, test_features, _, label_list = train_and_test_features_from_df(data, data_column, label_column, trainer.bert_model_hub, trainer.max_seq_length) trainer.train(train_features, label_list) results = trainer.test(test_features) print('Evaluation results:', results) results2 = trainer.test(test_features) print('Evaluation results:', results2) eval_acc1, eval_acc2 = results['eval_accuracy'], results2['eval_accuracy'] assertEqual(eval_acc1, eval_acc2) if __name__ == '__main__': unittest.main()
Update i18n domain to correct project name The current oslo_i18n domain name is listed as oslo.versionedobjects Change-Id: I493b66efbd83fb7704fe927866a24b765feb1576
# 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. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html """ import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo.cache') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
# 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. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html """ import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='oslo.versionedobjects') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
Tweak indentation to pass jshint
var http = require('http'); var httpProxy = require('http-proxy'); /** * Creates a proxy server to handle nodejitsu requests based on subdomain */ module.exports = function (config, callback) { // skip this server if not on nodejitsu if (!config.run_nodejitsu_server) { return callback(); } var proxy = httpProxy.createProxyServer({}); return http.createServer(function (req, res) { var host = req.headers.host; var subdomain = host.split('.')[0]; var options = { target: 'http://' + config.host + ':' }; switch (subdomain) { case 'admin': options.target += config.admin_port; break; case 'couch': options.target = config.couch.url; break; default: options.target += config.www_port; break; } proxy.web(req, res, options); }).listen(80, config.host, callback); };
var http = require('http'); var httpProxy = require('http-proxy'); /** * Creates a proxy server to handle nodejitsu requests based on subdomain */ module.exports = function (config, callback) { // skip this server if not on nodejitsu if (!config.run_nodejitsu_server) { return callback(); } var proxy = httpProxy.createProxyServer({}); return http.createServer(function (req, res) { var host = req.headers.host; var subdomain = host.split('.')[0]; var options = { target: 'http://' + config.host + ':' }; switch (subdomain) { case 'admin': options.target += config.admin_port; break; case 'couch': options.target = config.couch.url; break; default: options.target += config.www_port; break; } proxy.web(req, res, options); }).listen(80, config.host, callback); };
Clean up test, add missing expected files
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('bespoke generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('bespoke:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ '.bowerrc', '.editorconfig', '.gitignore', '.jshintrc', 'bower.json', 'Gruntfile.js', 'package.json', 'README.md', 'src/index.jade', 'src/scripts/main.js', 'src/styles/main.styl' ]; helpers.mockPrompt(this.app, { 'title': 'Foo Bar', 'bullets': 'Y', 'hash': 'Y', 'state': 'Y', 'prism': 'Y' }); this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('bespoke generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('bespoke:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. 'package.json', 'bower.json', 'Gruntfile.js', 'README.md', '.gitignore', '.jshintrc', '.bowerrc', 'src/index.jade', 'src/scripts/main.js', 'src/styles/main.styl' ]; helpers.mockPrompt(this.app, { 'title': 'Foo Bar', 'bullets': 'Y', 'hash': 'Y' }); this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
Add version contraints to dependencies to satisfy meteor 0.9.0
Package.describe({ summary: "A package that provides easy, editable, static pages", version: "0.2.0", name: "hellogerard:voltage", git: "https://github.com/Differential/meteor-voltage.git" }); Package.onUse(function(api) { api.versionsFrom("METEOR@0.9.0"); var both = ['client', 'server']; /** * Packages for client */ api.use([ 'templating', 'ui', 'less', 'deps', 'session', 'mrt:ace-embed@0.0.4' ], 'client'); /** * Files for client */ api.addFiles([ 'client/boot.coffee', 'client/compatibility/voltage.editor.js', 'client/views/voltagePage.less', 'client/views/voltagePage.html', 'client/views/voltagePage.coffee' ], 'client'); /** * Files for server */ api.addFiles([ 'server/boot.coffee', 'server/publications.coffee' ], 'server'); /** * Packages for server and client */ api.use([ 'coffeescript', 'accounts-base', 'mrt:minimongoid@0.8.8', 'alanning:roles@1.2.12', 'chuangbo:marked@0.3.4' ], both); /** * Files for server and client */ api.addFiles([ 'collections/page.coffee' ], both); });
Package.describe({ summary: "A package that provides easy, editable, static pages", version: "0.2.0", name: "hellogerard:voltage", git: "https://github.com/Differential/meteor-voltage.git" }); Package.onUse(function(api) { api.versionsFrom("METEOR@0.9.0"); var both = ['client', 'server']; /** * Packages for client */ api.use([ 'templating', 'ui', 'less', 'deps', 'session', 'mrt:ace-embed' ], 'client'); /** * Files for client */ api.addFiles([ 'client/boot.coffee', 'client/compatibility/voltage.editor.js', 'client/views/voltagePage.less', 'client/views/voltagePage.html', 'client/views/voltagePage.coffee' ], 'client'); /** * Files for server */ api.addFiles([ 'server/boot.coffee', 'server/publications.coffee' ], 'server'); /** * Packages for server and client */ api.use([ 'coffeescript', 'accounts-base', 'mrt:minimongoid', 'alanning:roles', 'chuangbo:marked' ], both); /** * Files for server and client */ api.addFiles([ 'collections/page.coffee' ], both); });
Fix NPE when trying to reference delta port statistics via REST API Change-Id: Ic195d06e55bd4d8379ac28938e93105d6d181bf6
/* * Copyright 2014-present Open Networking Foundation * * 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.onosproject.net; import static com.google.common.base.Preconditions.checkArgument; import static org.onosproject.net.DefaultAnnotations.EMPTY; /** * Base abstraction of an annotated entity. */ public abstract class AbstractAnnotated implements Annotated { private final Annotations annotations; // For serialization protected AbstractAnnotated() { this.annotations = null; } /** * Creates a new entity, annotated with the specified annotations. * * @param annotations optional key/value annotations map */ protected AbstractAnnotated(Annotations... annotations) { checkArgument(annotations.length <= 1, "Only one set of annotations is expected"); this.annotations = annotations.length == 0 || annotations[0] == null ? EMPTY : annotations[0]; } @Override public Annotations annotations() { return annotations; } }
/* * Copyright 2014-present Open Networking Foundation * * 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.onosproject.net; import static com.google.common.base.Preconditions.checkArgument; import static org.onosproject.net.DefaultAnnotations.EMPTY; /** * Base abstraction of an annotated entity. */ public abstract class AbstractAnnotated implements Annotated { private final Annotations annotations; // For serialization protected AbstractAnnotated() { this.annotations = null; } /** * Creates a new entity, annotated with the specified annotations. * * @param annotations optional key/value annotations map */ protected AbstractAnnotated(Annotations... annotations) { checkArgument(annotations.length <= 1, "Only one set of annotations is expected"); this.annotations = annotations.length == 1 ? annotations[0] : EMPTY; } @Override public Annotations annotations() { return annotations; } }
Send response while database is still updating
const slaveService = require('../services/slave'); const versionService = require('../services/version'); const version = { currentVersion(req, res) { const {slaveUID, slaveVersion} = req.params, remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress, tag = versionService.getCurrent(); const respondWithTag = () => { res.json(200, {tag}); }; slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress) .catch(error => { console.error(`An error occurred when updating ${slaveUID}: ${error}`); }); // send back current version regardless of success or failure of db entry respondWithTag(); } } module.exports = version;
const slaveService = require('../services/slave'); const versionService = require('../services/version'); const version = { currentVersion(req, res) { const {slaveUID, slaveVersion} = req.params, remoteAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress, tag = versionService.getCurrent(); const respondWithTag = () => { res.json(200, {tag}); }; slaveService.updateSlave(slaveUID, slaveVersion, remoteAddress) .then(respondWithTag) .catch(error => { console.error(`An error occurred when updating ${slaveUID}: ${error}`); // send back current version regardless respondWithTag(); }); } } module.exports = version;
TRUNK-4408: Change Logging Advice so that it doesn't log all exceptions
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Controller to display the uncaughtException page and ensure that it always displays * via the spring dispatcherServlet. */ @Controller public class UncaughtExceptionController { private static final long serialVersionUID = 1L; @RequestMapping(value = "/uncaughtException", method = {RequestMethod.POST,RequestMethod.GET}) public void displayUncaughtException() { } }
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Controller to display the uncaughtException page and ensure that it always displays * via the spring dispatcherServlet. */ @Controller public class UncaughtExceptionController { private static final long serialVersionUID = 1L; @RequestMapping(value = "/uncaughtException", method = RequestMethod.POST) public void displayUncaughtException() { } }
Fix typo in Map error handling
package flagx import ( "fmt" "reflect" "strings" ) func Map(m interface{}, parseValue func(string) (interface{}, error)) Value { v := reflect.ValueOf(m) if v.IsNil() || v.Kind() != reflect.Map { panic("non-nil pointer to a map expected") } // check that keys are strings if v.Type().Key().Kind() != reflect.String { panic("keys must be of type string") } return &stringMap{v, parseValue} } type stringMap struct { Map reflect.Value Parse func(string) (interface{}, error) } func (m *stringMap) String() string { return "" } func (m *stringMap) Set(s string) error { i := strings.IndexByte(s, '=') if i < 0 { return fmt.Errorf("%q: '=' expected", s) } key := s[:i] var value interface{} if m.Parse == nil { value = s[i+1:] } else { var err error value, err = m.Parse(s[i+1:]) if err != nil { return err } } m.Map.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value)) return nil } func (m *stringMap) Get() interface{} { return m.Map.Interface() }
package flagx import ( "fmt" "reflect" "strings" ) func Map(m interface{}, parseValue func(string) (interface{}, error)) Value { v := reflect.ValueOf(m) if v.IsNil() || v.Kind() != reflect.Map { panic("non-nil pointer to a map expected") } // check that keys are strings if v.Type().Key().Kind() != reflect.String { panic("keys must be of type string") } return &stringMap{v, parseValue} } type stringMap struct { Map reflect.Value Parse func(string) (interface{}, error) } func (m *stringMap) String() string { return "" } func (m *stringMap) Set(s string) error { i := strings.IndexByte(s, '=') if i < 0 { return fmt.Errorf("%q: '=' expected") } key := s[:i] var value interface{} if m.Parse == nil { value = s[i+1:] } else { var err error value, err = m.Parse(s[i+1:]) if err != nil { return err } } m.Map.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value)) return nil } func (m *stringMap) Get() interface{} { return m.Map.Interface() }
Fix slug to be lowercase
<?php namespace Grav\Common\GPM\Local; use Grav\Common\Data\Data; use Grav\Common\GPM\Common\Package as BasePackage; class Package extends BasePackage { protected $settings; public function __construct(Data $package, $package_type = null) { $data = new Data($package->blueprints()->toArray()); parent::__construct($data, $package_type); $this->settings = $package->toArray(); $html_description = \Parsedown::instance()->line($this->description); $this->data->set('slug', strtolower($this->name)); $this->data->set('description_html', $html_description); $this->data->set('description_plain', strip_tags($html_description)); $this->data->set('symlink', is_link(USER_DIR . $package_type . DS . $this->name)); } /** * @return mixed */ public function isEnabled() { return $this->settings['enabled']; } }
<?php namespace Grav\Common\GPM\Local; use Grav\Common\Data\Data; use Grav\Common\GPM\Common\Package as BasePackage; class Package extends BasePackage { protected $settings; public function __construct(Data $package, $package_type = null) { $data = new Data($package->blueprints()->toArray()); parent::__construct($data, $package_type); $this->settings = $package->toArray(); $html_description = \Parsedown::instance()->line($this->description); $this->data->set('slug', $this->name); $this->data->set('description_html', $html_description); $this->data->set('description_plain', strip_tags($html_description)); $this->data->set('symlink', is_link(USER_DIR . $package_type . DS . $this->name)); } /** * @return mixed */ public function isEnabled() { return $this->settings['enabled']; } }
Load input directly to simplexml
<?php include("/home/c0smic/secure/data_db_settings.php"); //$body = file_get_contents('php://input'); $xml = simplexml_load_file('php://input'); # Read GET variables $stime = $xml->data->stime; $etime = $xml->data->etime; $moves = $xml->data->moves; $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
<?php include("/home/c0smic/secure/data_db_settings.php"); $body = file_get_contents('php://input'); $xml = simplexml_load_file($body); # Read GET variables $stime = $xml->data->stime; $etime = $xml->data->etime; $moves = $xml->data->moves; $conn = mysql_connect('localhost:3036', $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } unset($dbuser, $dbpass); mysql_select_db('c0smic_maze-game'); $sql= "INSERT INTO data (stime, etime, moves) VALUES ('$stime','$etime','$moves')"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } mysql_close($conn); echo $str; ?>
Set base path for refinement model
framework.addJavaScriptHelp("setCircuitComponentRefinement", "circuitWork, componentRef, refinementPath", "set 'refinementPath' file as refinement for component 'componentRef' in Circuit 'circuitWork'"); function setCircuitComponentRefinement(circuitWork, componentRef, refinementPath) { circuitMathModel = circuitWork.getModelEntry().getMathModel(); component = circuitMathModel.getNodeByReference(componentRef); if (!(component instanceof org.workcraft.plugins.circuit.CircuitComponent)) { throw "Circuit component '" + componentRef + "' not found"; } refinement = org.workcraft.dom.references.FileReference(); file = framework.getWorkspace().getFile(circuitWork); refinementBase = org.workcraft.utils.FileUtils.getBasePath(file); refinement.setBase(refinementBase) refinement.setPath(refinementPath); component.setRefinement(refinement); } framework.addJavaScriptHelp("getCircuitComponentRefinement", "circuitWork, componentRef", "get path to refinement file for component 'componentRef' in Circuit 'circuitWork'"); function getCircuitComponentRefinement(circuitWork, componentRef) { circuitMathModel=circuitWork.getModelEntry().getMathModel(); component = circuitMathModel.getNodeByReference(componentRef); if (!(component instanceof org.workcraft.plugins.circuit.CircuitComponent)) { throw "Circuit component '" + componentRef + "' not found"; } refinement = component.getRefinement(); if (!(refinement instanceof org.workcraft.dom.references.FileReference)) { return null; } return refinement.getPath(); }
framework.addJavaScriptHelp("setCircuitComponentRefinement", "circuitWork, componentRef, refinementPath", "set 'refinementPath' file as refinement for component 'componentRef' in Circuit 'circuitWork'"); function setCircuitComponentRefinement(circuitWork, componentRef, refinementPath) { circuitMathModel = circuitWork.getModelEntry().getMathModel(); component = circuitMathModel.getNodeByReference(componentRef); if (!(component instanceof org.workcraft.plugins.circuit.CircuitComponent)) { throw "Circuit component '" + componentRef + "' not found"; } refinement = org.workcraft.dom.references.FileReference(); refinement.setPath(refinementPath); component.setRefinement(refinement); } framework.addJavaScriptHelp("getCircuitComponentRefinement", "circuitWork, componentRef", "get path to refinement file for component 'componentRef' in Circuit 'circuitWork'"); function getCircuitComponentRefinement(circuitWork, componentRef) { circuitMathModel=circuitWork.getModelEntry().getMathModel(); component = circuitMathModel.getNodeByReference(componentRef); if (!(component instanceof org.workcraft.plugins.circuit.CircuitComponent)) { throw "Circuit component '" + componentRef + "' not found"; } refinement = component.getRefinement(); if (!(refinement instanceof org.workcraft.dom.references.FileReference)) { return null; } return refinement.getPath(); }
Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing.
"""Django DDP utils for DDP messaging.""" from copy import deepcopy from dddp import THREAD_LOCAL as this from django.db.models.expressions import ExpressionNode def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" # check for F expressions exps = [ name for name, val in vars(obj).items() if isinstance(val, ExpressionNode) ] if exps: # clone and update obj with values but only for the expression fields obj = deepcopy(obj) # Django 1.8 makes obj._meta public --> pylint: disable=W0212 for name, val in obj._meta.model.objects.values(*exps).get(pk=obj.pk): setattr(obj, name, val) # run serialization now that all fields are "concrete" (not F expressions) serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] # cast ID as string if not isinstance(data['pk'], basestring): data['pk'] = '%d' % data['pk'] payload = { 'msg': msg, 'collection': name, 'id': data['pk'], } if msg != 'removed': payload['fields'] = data['fields'] return (name, payload)
"""Django DDP utils for DDP messaging.""" from dddp import THREAD_LOCAL as this def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] # cast ID as string if not isinstance(data['pk'], basestring): data['pk'] = '%d' % data['pk'] payload = { 'msg': msg, 'collection': name, 'id': data['pk'], } if msg != 'removed': payload['fields'] = data['fields'] return (name, payload)
Add exception to tempest plugin Exception 'SnapshotBuildErrorException' was used, but was not defined. Change-Id: Ida7554d65eb6657fa05b7d53cbfa452cc0239f74
# Copyright 2014 Mirantis Inc. # 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. from tempest.exceptions import base class ShareBuildErrorException(base.TempestException): message = "Share %(share_id)s failed to build and is in ERROR status" class AccessRuleBuildErrorException(base.TempestException): message = "Share's rule with id %(rule_id) is in ERROR status" class SnapshotBuildErrorException(base.TempestException): message = "Snapshot %(snapshot_id)s failed to build and is in ERROR status" class ShareProtocolNotSpecified(base.TempestException): message = "Share can not be created, share protocol is not specified" class ShareNetworkNotSpecified(base.TempestException): message = "Share can not be created, share network not specified" class NoAvailableNetwork(base.TempestException): message = "No available network for service VM"
# Copyright 2014 Mirantis Inc. # 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. from tempest.exceptions import base class ShareBuildErrorException(base.TempestException): message = "Share %(share_id)s failed to build and is in ERROR status" class AccessRuleBuildErrorException(base.TempestException): message = "Share's rule with id %(rule_id) is in ERROR status" class ShareProtocolNotSpecified(base.TempestException): message = "Share can not be created, share protocol is not specified" class ShareNetworkNotSpecified(base.TempestException): message = "Share can not be created, share network not specified" class NoAvailableNetwork(base.TempestException): message = "No available network for service VM"
Update Admin page scenario test - check for different fields depending on COM or ORG - Updated UI text check
<?php /* @var $scenario Codeception\Scenario */ $I = new AcceptanceTester($scenario); $I->amGoingTo('admin login page'); $I->amOnPage('/admin'); $I->canSee('Admin Login'); $I->canSee('Username'); $I->canSee('Password'); $I->amGoingTo('enter admin credentials'); $I->fillField('LoginForm[username]', 'admin'); $I->fillField('LoginForm[password]', 'ChangeMePlease'); $I->click('button[type=submit]'); $I->wait(3); $I->wantTo('see API configuration parameters'); $I->see('Admin'); $I->see('Current config'); switch($I->getConfig()->type){ case 'com': $adminParams = ['clientId', 'clientSecret', 'redirectUrl', 'blogId', 'blogUrl', 'adminToken']; break; case 'org': $adminParams = ['consumerKey', 'consumerSecret', 'blogUrl']; break; default: throw new \Exception('config file not found.'); } foreach ($adminParams as $k){ $I->see("[$k]"); } $I->see('WP Com Setup'); $I->see('WP Org Setup'); $I->click('Logout'); $I->wait(3); $I->see('Shared Links:');
<?php /* @var $scenario Codeception\Scenario */ $I = new AcceptanceTester($scenario); $I->amGoingTo('admin login page'); $I->amOnPage('/admin'); $I->canSee('Admin Login'); $I->canSee('Username'); $I->canSee('Password'); $I->amGoingTo('enter admin credentials'); $I->fillField('LoginForm[username]', 'admin'); $I->fillField('LoginForm[password]', 'ChangeMePlease'); $I->click('button[type=submit]'); $I->wait(3); $I->wantTo('see API configuration parameters'); $I->see('Admin'); $I->see('Current config'); $cfg = json_decode(file_get_contents(Yii::$app->runtimePath . '/api.cfg'), true); unset($cfg['type']); foreach ($cfg as $k => $v){ $I->see("[$k] => $v"); } $I->see('WP Com Setup'); $I->see('WP Org Setup'); $I->click('Logout'); $I->wait(3); $I->see('Links Index');
Fix is_site_root when no page
import jinja2 from django.conf import settings from django_jinja import library from jinja2.ext import Extension from wagtail.wagtailcore.models import Page from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import ( routablepageurl as dj_routablepageurl ) from wapps.utils import get_image_url @library.global_function def menu(): return Page.objects.live().in_menu().filter(depth__lte=3) @library.global_function @jinja2.contextfunction def is_site_root(context, page): if 'request' not in context or not context['request'].site or not page: return False site = context['request'].site return site.root_page.pk == page.pk @library.global_function def image_url(image, specs): return get_image_url(image, specs) @library.global_function @jinja2.contextfunction def routablepageurl(context, page, name, *args, **kwargs): return dj_routablepageurl(context, page, name, *args, **kwargs) @library.extension class WagtailSettings(Extension): def __init__(self, environment): super(WagtailSettings, self).__init__(environment) environment.globals['WAGTAIL_SITE_NAME'] = getattr(settings, 'WAGTAIL_SITE_NAME', None)
import jinja2 from django.conf import settings from django_jinja import library from jinja2.ext import Extension from wagtail.wagtailcore.models import Page from wagtail.contrib.wagtailroutablepage.templatetags.wagtailroutablepage_tags import ( routablepageurl as dj_routablepageurl ) from wapps.utils import get_image_url @library.global_function def menu(): return Page.objects.live().in_menu().filter(depth__lte=3) @library.global_function @jinja2.contextfunction def is_site_root(context, page): if 'request' not in context or not context['request'].site: return False site = context['request'].site return site.root_page.pk == page.pk @library.global_function def image_url(image, specs): return get_image_url(image, specs) @library.global_function @jinja2.contextfunction def routablepageurl(context, page, name, *args, **kwargs): return dj_routablepageurl(context, page, name, *args, **kwargs) @library.extension class WagtailSettings(Extension): def __init__(self, environment): super(WagtailSettings, self).__init__(environment) environment.globals['WAGTAIL_SITE_NAME'] = getattr(settings, 'WAGTAIL_SITE_NAME', None)
fix(resolve): Fix resolving to assumed but presently not available node module relatively
import resolve from "resolve"; import path from "path"; const cache = {}; export default function (basedir, filename, extensions) { const cached = cache[basedir]; if(cached) { const withFilename = cached[filename]; if(withFilename) { let resolved = withFilename.get(extensions); if(resolved !== undefined) return resolved; resolved = getResolved(); withFilename.set(extensions, resolved); return resolved; } const resolved = getResolved(); cached[filename] = new Map().set(extensions, resolved); return resolved; } const resolved = getResolved(); cache[basedir] = { [filename]: new Map().set(extensions, resolved) }; return resolved; function getResolved(){ try { return resolve.sync(filename, { basedir, extensions }); } catch (err) { let errMessage = err.message + "\nMake sure it is available later", resolved; if(filename.startsWith("/") || filename.startsWith(".")) { resolved = path.resolve(basedir, filename); } else { errMessage += " in node_modules"; resolved = "/node_modules/" + filename; } console.error(errMessage); return resolved; } } }
import resolve from "resolve"; const cache = {}; export default function (basedir, filename, extensions) { const cached = cache[basedir]; if(cached) { const withFilename = cached[filename]; if(withFilename) { let resolved = withFilename.get(extensions); if(resolved !== undefined) return resolved; resolved = getResolved(); withFilename.set(extensions, resolved); return resolved; } const resolved = getResolved(); cached[filename] = new Map().set(extensions, resolved); return resolved; } const resolved = getResolved(); cache[basedir] = { [filename]: new Map().set(extensions, resolved) }; return resolved; function getResolved(){ return resolve.sync(filename, { basedir, extensions }); } }
Expand regex for location of site-packages. Provide more info to user about possible failure to find site-packages
from setuptools import setup from distutils import sysconfig import re #from setuptools.dist import Distribution site_packages_path = sysconfig.get_python_lib() try: sprem = re.match( r'.*(lib[\\/](python\d(\.\d)*[\\/])?site-packages)', site_packages_path, re.I) if sprem is None: sprem = re.match( r'.*(lib[\\/](python\d(\.\d)*[\\/])?dist-packages)', site_packages_path, re.I) rel_site_packages = sprem.group(1) except Exception as exc: print("I'm having trouble finding your site-packages directory. Is it where you expect?") print("sysconfig.get_python_lib() returns '{}'".format(site_packages_path)) print("Exception was: {}".format(exc)) sys.exit(-1) #class PureDistribution(Distribution): # def is_pure(self): # return True setup( name = 'coverage_pth', version = '0.0.1', description = 'Coverage PTH file to enable coverage at the virtualenv level', #packages = '..', #include_pacakage_date=True, data_files=[ (rel_site_packages, ['coverage_pth.pth',]), ], install_requires=[ 'coverage', ], #distclass=PureDistribution, zip_safe=False, )
from setuptools import setup from distutils import sysconfig import re #from setuptools.dist import Distribution site_packages_path = sysconfig.get_python_lib() sprem = re.match( r'.*(lib[\\/](python\d\.\d[\\/])?site-packages)', site_packages_path, re.I) rel_site_packages = sprem.group(1) #class PureDistribution(Distribution): # def is_pure(self): # return True setup( name = 'coverage_pth', version = '0.0.1', description = 'Coverage PTH file to enable coverage at the virtualenv level', #packages = '..', #include_pacakage_date=True, data_files=[ (rel_site_packages, ['coverage_pth.pth',]), ], install_requires=[ 'coverage', ], #distclass=PureDistribution, zip_safe=False, )
Fix Dutch translation of beatmap_discussion.php
<?php /** * Copyright 2016 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed in the hopes of * attracting more community contributions to the core ecosystem of osu! * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'authorizations' => [ 'update' => [ 'null_user' => 'Moet ingelogd zijn om te bewerken.', 'system_generated' => 'Systeemgegenereerde posts kunnen niet worden bewerkt.', 'wrong_user' => 'Je moet de eigenaar zijn om te kunnen bewerken.', ], ], 'system' => [ 'resolved' => [ 'true' => 'Gemarkeerd als opgelost door :user', 'false' => 'Heropend door :user', ], ], ];
<?php /** * Copyright 2016 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed in the hopes of * attracting more community contributions to the core ecosystem of osu! * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'authorizations' => [ 'update' => [ 'null_user' => 'Moet ingelogd zijn om te bewerken.', 'system_generated' => 'Systeemgegenereerde posts kunnen niet bewerkt worden.', 'wrong_user' => 'Moet de eigenaar zijn om te bewerken.', ], ], 'system' => [ 'resolved' => [ 'true' => 'Gemarkeerd als opgelost door :user', 'false' => 'Heropend door :user', ], ], ];
Save to store skip failed files
package edu.isi.karma.rdf; import java.io.File; import com.uwyn.jhighlight.tools.FileUtils; import edu.isi.karma.er.helper.TripleStoreUtil; import edu.isi.karma.webserver.KarmaException; public class LoadRDFToTripleStore { public static void main(String args[]) { TripleStoreUtil util = new TripleStoreUtil(); if (args.length < 3) return; File file = new File(args[0]); String context = args[1]; String tripleStoreUrl = args[2]; if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { System.out.println(FileUtils.getExtension(f.getName())); if (FileUtils.getExtension(f.getName()) != null && FileUtils.getExtension(f.getName()).compareTo("ttl") == 0) try { util.saveToStore(f.getAbsolutePath(), tripleStoreUrl, context, false, null); } catch (KarmaException e) { System.err.println(e.getMessage()); } } } else { if (FileUtils.getExtension(file.getName()) != null && FileUtils.getExtension(file.getName()).compareTo("ttl") == 0) try { util.saveToStore(file.getAbsolutePath(), tripleStoreUrl, context, false, null); } catch (KarmaException e) { System.err.println(e.getMessage()); } } } }
package edu.isi.karma.rdf; import java.io.File; import com.uwyn.jhighlight.tools.FileUtils; import edu.isi.karma.er.helper.TripleStoreUtil; import edu.isi.karma.webserver.KarmaException; public class LoadRDFToTripleStore { public static void main(String args[]) throws KarmaException { TripleStoreUtil util = new TripleStoreUtil(); if (args.length < 3) return; File file = new File(args[0]); String context = args[1]; String tripleStoreUrl = args[2]; if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { System.out.println(FileUtils.getExtension(f.getName())); if (FileUtils.getExtension(f.getName()) != null && FileUtils.getExtension(f.getName()).compareTo("ttl") == 0) util.saveToStore(f.getAbsolutePath(), tripleStoreUrl, context, false, null); } } else { if (FileUtils.getExtension(file.getName()) != null && FileUtils.getExtension(file.getName()).compareTo("ttl") == 0) util.saveToStore(file.getAbsolutePath(), tripleStoreUrl, context, false, null); } } }
Add the missing require for path module
var fs = require('fs'); var mkdirp = require('mkdirp'); var existsSync = fs.existsSync || require('path').existsSync; // to support older nodes than 0.8 var CONFIG_FILE_NAME = 'config.json'; var Config = function(home) { this.home = home; this.load(); }; Config.prototype = { home: null, data: {}, configFilePath: function() { return this.home + '/' + CONFIG_FILE_NAME; }, load: function() { if (existsSync(this.configFilePath())) { this.data = JSON.parse(fs.readFileSync(this.configFilePath())); } }, save: function() { var json = JSON.stringify(this.data); mkdirp.sync(this.home); fs.writeFileSync(this.configFilePath(), json); } }; module.exports.Config = Config;
var fs = require('fs'); var mkdirp = require('mkdirp'); var existsSync = fs.existsSync || path.existsSync; // to support older nodes than 0.8 var CONFIG_FILE_NAME = 'config.json'; var Config = function(home) { this.home = home; this.load(); }; Config.prototype = { home: null, data: {}, configFilePath: function() { return this.home + '/' + CONFIG_FILE_NAME; }, load: function() { if (existsSync(this.configFilePath())) { this.data = JSON.parse(fs.readFileSync(this.configFilePath())); } }, save: function() { var json = JSON.stringify(this.data); mkdirp.sync(this.home); fs.writeFileSync(this.configFilePath(), json); } }; module.exports.Config = Config;
Add foundation script so mobile menu works
<?php /** * Remove parent theme scripts so we can handle all the scripts that are included * @see de_grona_15_add_scripts() */ function dequeue_parent_theme_scripts() { wp_dequeue_script( 'modernizr' ); } add_action( 'wp_enqueue_scripts', 'dequeue_parent_theme_scripts', 9999 ); /** * Remove parent theme widgets (because it's easier to handle all the sidebars in this theme) */ function remove_parent_theme_widgets(){ unregister_sidebar( 'sidebar-widgets' ); unregister_sidebar( 'footer-widgets' ); } add_action( 'widgets_init', 'remove_parent_theme_widgets', 11 ); /** * Unset parent theme page templates that we don't want to show */ function remove_parent_theme_page_templates( $templates ) { unset( $templates['kitchen-sink.php'] ); unset( $templates['hero.php'] ); return $templates; } add_filter( 'theme_page_templates', 'remove_parent_theme_page_templates' ); /** * Remove some theme support */ function remove_parent_theme_support() { // This will remove support for custom header remove_theme_support( 'custom-header' ); } add_action( 'after_setup_theme', 'remove_parent_theme_support', 11 );
<?php /** * Remove parent theme scripts so we can handle all the scripts that are included * @see de_grona_15_add_scripts() */ function dequeue_parent_theme_scripts() { wp_dequeue_script( 'modernizr' ); wp_dequeue_script( 'foundation' ); } add_action( 'wp_enqueue_scripts', 'dequeue_parent_theme_scripts', 9999 ); /** * Remove parent theme widgets (because it's easier to handle all the sidebars in this theme) */ function remove_parent_theme_widgets(){ unregister_sidebar( 'sidebar-widgets' ); unregister_sidebar( 'footer-widgets' ); } add_action( 'widgets_init', 'remove_parent_theme_widgets', 11 ); /** * Unset parent theme page templates that we don't want to show */ function remove_parent_theme_page_templates( $templates ) { unset( $templates['kitchen-sink.php'] ); unset( $templates['hero.php'] ); return $templates; } add_filter( 'theme_page_templates', 'remove_parent_theme_page_templates' ); /** * Remove some theme support */ function remove_parent_theme_support() { // This will remove support for custom header remove_theme_support( 'custom-header' ); } add_action( 'after_setup_theme', 'remove_parent_theme_support', 11 );
Add test case for svg() (like h() is)
'use strict'; /* global describe, it */ let assert = require('assert'); let Cycle = require('../../src/cycle'); describe('Cycle', function () { describe('API', function () { it('should have `applyToDOM`', function () { assert.strictEqual(typeof Cycle.applyToDOM, 'function'); }); it('should have `renderAsHTML`', function () { assert.strictEqual(typeof Cycle.renderAsHTML, 'function'); }); it('should have `registerCustomElement`', function () { assert.strictEqual(typeof Cycle.registerCustomElement, 'function'); }); it('should have a shortcut to Rx', function () { assert.strictEqual(typeof Cycle.Rx, 'object'); }); it('should have a shortcut to virtual-hyperscript', function () { assert.strictEqual(typeof Cycle.h, 'function'); }); it('should have a shortcut to virtual-dom\'s svg', function () { assert.strictEqual(typeof Cycle.svg, 'function'); }); }); });
'use strict'; /* global describe, it */ let assert = require('assert'); let Cycle = require('../../src/cycle'); describe('Cycle', function () { describe('API', function () { it('should have `applyToDOM`', function () { assert.strictEqual(typeof Cycle.applyToDOM, 'function'); }); it('should have `renderAsHTML`', function () { assert.strictEqual(typeof Cycle.renderAsHTML, 'function'); }); it('should have `registerCustomElement`', function () { assert.strictEqual(typeof Cycle.registerCustomElement, 'function'); }); it('should have a shortcut to Rx', function () { assert.strictEqual(typeof Cycle.Rx, 'object'); }); it('should have a shortcut to virtual-hyperscript', function () { assert.strictEqual(typeof Cycle.h, 'function'); }); }); });
Make sure we require at least python 2.7
import os try: from setuptools import setup except ImportError: from distutils.core import setup from pypvwatts.__version__ import VERSION setup( name='pypvwatts', version=VERSION, author='Miguel Paolino', author_email='mpaolino@gmail.com', url='https://github.com/mpaolino/pypvwatts', download_url='https://github.com/mpaolino/pypvwatts/archive/master.zip', description='Python wrapper for NREL PVWatts\'s API.', long_description=open('README.md').read(), packages=['pypvwatts'], provides=['pypvwatts'], requires=['requests'], install_requires=['requests >= 2.1.0'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'License :: OSI Approved :: MIT License', 'Topic :: Internet', 'Topic :: Internet :: WWW/HTTP', ], keywords='nrel pvwatts pypvwatts', license='MIT', python_requires=">=2.7", )
import os try: from setuptools import setup except ImportError: from distutils.core import setup from pypvwatts.__version__ import VERSION setup( name='pypvwatts', version=VERSION, author='Miguel Paolino', author_email='mpaolino@gmail.com', url='https://github.com/mpaolino/pypvwatts', download_url='https://github.com/mpaolino/pypvwatts/archive/master.zip', description='Python wrapper for NREL PVWatts\'s API.', long_description=open('README.md').read(), packages=['pypvwatts'], provides=['pypvwatts'], requires=['requests'], install_requires=['requests >= 2.1.0'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'License :: OSI Approved :: MIT License', 'Topic :: Internet', 'Topic :: Internet :: WWW/HTTP', ], keywords='nrel pvwatts pypvwatts', license='MIT', )
Add optional spans for list blocks
package ru.noties.markwon.core; import android.support.annotation.NonNull; import org.commonmark.node.Node; import ru.noties.markwon.MarkwonVisitor; /** * A {@link ru.noties.markwon.MarkwonVisitor.NodeVisitor} that ensures that a markdown * block starts with a new line, all children are visited and if further content available * ensures a new line after self. Does not render any spans * * @since 3.0.0 */ public class SimpleBlockNodeVisitor implements MarkwonVisitor.NodeVisitor<Node> { @Override public void visit(@NonNull MarkwonVisitor visitor, @NonNull Node node) { // @since 3.0.1-SNAPSHOT we keep track of start in order to apply spans (optionally) final int length = visitor.length(); visitor.ensureNewLine(); visitor.visitChildren(node); // @since 3.0.1-SNAPSHOT we apply optional spans visitor.setSpansForNodeOptional(node, length); if (visitor.hasNext(node)) { visitor.ensureNewLine(); visitor.forceNewLine(); } } }
package ru.noties.markwon.core; import android.support.annotation.NonNull; import org.commonmark.node.Node; import ru.noties.markwon.MarkwonVisitor; /** * A {@link ru.noties.markwon.MarkwonVisitor.NodeVisitor} that ensures that a markdown * block starts with a new line, all children are visited and if further content available * ensures a new line after self. Does not render any spans * * @since 3.0.0 */ public class SimpleBlockNodeVisitor implements MarkwonVisitor.NodeVisitor<Node> { @Override public void visit(@NonNull MarkwonVisitor visitor, @NonNull Node node) { visitor.ensureNewLine(); visitor.visitChildren(node); if (visitor.hasNext(node)) { visitor.ensureNewLine(); visitor.forceNewLine(); } } }
Fix parsing bug for white colors
package editor.util; import java.awt.Color; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class ColorAdapter implements JsonSerializer<Color>, JsonDeserializer<Color> { @Override public JsonElement serialize(Color src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(Integer.toHexString(src.getRGB())); } @Override public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // Need to parse as a long and cast to int in case the color is white, // which has value 0xFFFFFFFF and is outside the range of an int return new Color((int)Long.parseLong(json.getAsString(), 16), true); } }
package editor.util; import java.awt.Color; import java.lang.reflect.Type; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class ColorAdapter implements JsonSerializer<Color>, JsonDeserializer<Color> { @Override public JsonElement serialize(Color src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(Integer.toHexString(src.getRGB())); } @Override public Color deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Color(Integer.valueOf(json.getAsString(), 16), true); } }
Apply code formatter and code style
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial APInd implementation *******************************************************************************/ package org.eclipse.kapua.commons.model.id; import java.math.BigInteger; import java.security.SecureRandom; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.setting.system.SystemSettingKey; /** * Generates random identifier * * @since 1.0 * */ public class IdGenerator { private final static SecureRandom secureRandom = new SecureRandom(); private final static int ID_SIZE = SystemSetting.getInstance().getInt(SystemSettingKey.KAPUA_KEY_SIZE); /** * Generate a {@link BigInteger} random value.<br> * For more detail refer to: {@link SystemSettingKey#KAPUA_KEY_SIZE} * * @return */ public static BigInteger generate() { byte[] bytes = new byte[ID_SIZE]; secureRandom.nextBytes(bytes); return new BigInteger(bytes); } }
/******************************************************************************* * Copyright (c) 2011, 2016 Eurotech and/or its affiliates * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eurotech - initial APInd implementation *******************************************************************************/ package org.eclipse.kapua.commons.model.id; import java.math.BigInteger; import java.security.SecureRandom; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.setting.system.SystemSettingKey; /** * Generates random identifier * * @since 1.0 * */ public class IdGenerator { private final static SecureRandom secureRandom = new SecureRandom(); private static int ID_SIZE = SystemSetting.getInstance().getInt(SystemSettingKey.KAPUA_KEY_SIZE); /** * Generate a {@link BigInteger} random value.<br> * For more detail refer to: {@link SystemSettingKey#KAPUA_KEY_SIZE} * * @return */ public static BigInteger generate() { byte[] bytes = new byte[ID_SIZE]; secureRandom.nextBytes(bytes); return new BigInteger(bytes); } }
Support multiple tags in embed code. Closes #21
export default function createEagerSchema({embedCode, properties}) { embedCode = JSON.stringify(embedCode) const initializeApp = function initializeApp(embedCodeInjection) { if (!window.addEventListener) return // Check for IE9+ const TRACKED_ENTITY_PATTERN = /TRACKED_ENTITY\[(\S+)\]/g const options = INSTALL_OPTIONS const insertOption = (match, key) => options[key] function insertEmbedCode() { const serializer = document.createElement("div") serializer.innerHTML = embedCodeInjection.replace(TRACKED_ENTITY_PATTERN, insertOption) Array.prototype.forEach.call(serializer.children, element => { document.body.appendChild(element) if (element.nodeName === "SCRIPT") { eval(element.textContent) // eslint-disable-line no-eval } }) } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", insertEmbedCode) } else { insertEmbedCode() } }.toString() const installJSON = { resources: { body: [ { type: "script", contents: `(${initializeApp}(${embedCode}))` } ] }, options: {properties} } return installJSON }
export default function createEagerSchema({embedCode, properties}) { embedCode = JSON.stringify(embedCode) const initializeApp = function initializeApp(embedCodeInjection) { if (!window.addEventListener) return // Check for IE9+ const TRACKED_ENTITY_PATTERN = /TRACKED_ENTITY\[(\S+)\]/g const options = INSTALL_OPTIONS const insertOption = (match, key) => options[key] function insertEmbedCode() { document.head.innerHTML += embedCodeInjection.replace(TRACKED_ENTITY_PATTERN, insertOption) eval(document.head.lastChild.textContent) // eslint-disable-line no-eval } if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", insertEmbedCode) } else { insertEmbedCode() } }.toString() const installJSON = { resources: { body: [ { type: "script", contents: `(${initializeApp}(${embedCode}))` } ] }, options: {properties} } return installJSON }
Add comment for user idle
// SERVER: Listen for events if(Meteor.isServer) { // listen for user logout events, call the clearAssignments server method UserStatus.events.on("connectionLogout", function(fields){ //console.log("Logout Event"); //console.log(fields.userId); Meteor.call('clearAssignments', Meteor.users.findOne({_id: fields.userId})); }); // listen for user idle events, for now do nothing but in the future maybe logout UserStatus.events.on("connectionIdle", function(fields){ //console.log("Idle Event"); //console.log(fields.userId); //Meteor.call('logoutUser', Meteor.users.findOne({_id: fields.userId})); }); } // CLIENT: Start idle monitor if(Meteor.isClient) { try { UserStatus.startMonitor({ // idle after five minutes, do not count blurring the window as idle threshold: 300000, idleOnBlur: false }); } // not ideal but sometimes startMonitor throws a sync error catch (e) {} }
// SERVER: Listen for events if(Meteor.isServer) { // listen for user logout events, call the clearAssignments server method UserStatus.events.on("connectionLogout", function(fields){ //console.log("Logout Event"); //console.log(fields.userId); Meteor.call('clearAssignments', Meteor.users.findOne({_id: fields.userId})); }); // listen for user idle events, for now do nothing but in the future maybe logout UserStatus.events.on("connectionIdle", function(fields){ //console.log("Idle Event"); //console.log(fields.userId); //Meteor.call('logoutUser', Meteor.users.findOne({_id: fields.userId})); }); } // CLIENT: Start idle monitor if(Meteor.isClient) { try { UserStatus.startMonitor({ threshold: 300000, idleOnBlur: false }); } // not ideal but sometimes startMonitor throws a sync error catch (e) {} }
Fix error when no loading analytics
(function() { if (document.location.hostname === "josephduffy.co.uk") { // Don't load analytics for noanalytics.josephduffy.co.uk or onion service return; } var _paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(["disableCookies"]); _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://analytics.josephduffy.co.uk/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '1']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); })();
if (document.location.hostname === "josephduffy.co.uk") { // Don't load analytics for noanalytics.josephduffy.co.uk or onion service return; } var _paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(["disableCookies"]); _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://analytics.josephduffy.co.uk/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '1']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })();
Fix typo/bug in validate_params function
from django import template class InvalidParamsError(template.TemplateSyntaxError): ''' Custom exception class to distinguish usual TemplateSyntaxErrors and validation errors for templatetags introduced by ``validate_params`` function''' pass def validate_params(bits, arguments_count, keyword_positions): ''' Raises exception if passed params (`bits`) do not match signature. Signature is defined by `arguments_count` (acceptible number of params) and keyword_positions (dictionary with positions in keys and keywords in values, for ex. {2:'by', 4:'of', 5:'type', 7:'as'}). ''' if len(bits) != arguments_count+1: raise InvalidParamsError("'%s' tag takes %d arguments" % (bits[0], arguments_count,)) for pos in keyword_positions: value = keyword_positions[pos] if bits[pos] != value: raise InvalidParamsError("argument #%d to '%s' tag must be '%s'" % (pos, bits[0], value))
from django import template class InvalidParamsError(template.TemplateSyntaxError): ''' Custom exception class to distinguish usual TemplateSyntaxErrors and validation errors for templatetags introduced by ``validate_params`` function''' pass def validate_params(bits, arguments_count, keyword_positions): ''' Raises exception if passed params (`bits`) do not match signature. Signature is defined by `arguments_count` (acceptible number of params) and keyword_positions (dictionary with positions in keys and keywords in values, for ex. {2:'by', 4:'of', 5:'type', 7:'as'}). ''' if len(bits) != arguments_count+1: raise InvalidTagParamsError("'%s' tag takes %d arguments" % (bits[0], arguments_count,)) for pos in keyword_positions: value = keyword_positions[pos] if bits[pos] != value: raise InvalidTagParamsError("argument #%d to '%s' tag must be '%s'" % (pos, bits[0], value))
Settings: Read database configuration from base directory
#! /usr/bin/env python # -*- coding: utf-8 -*- from defaults import * # noqa import json DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['.searchlogger.tutorons.com'] # Read in the Postgres database configuration from a file DATABASE_CONFIG_FILENAME = os.path.join(BASE_DIR, 'database_config.json') with open(DATABASE_CONFIG_FILENAME) as database_config_file: database_config = json.load(databse_config_file) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': database_config['name'], 'USER': database_config['user'], 'PASSWORD': database_config['password'], 'HOST': database_config['host'], 'PORT': database_config['port'], } }
#! /usr/bin/env python # -*- coding: utf-8 -*- from defaults import * # noqa import json DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['.searchlogger.tutorons.com'] # Read in the Postgres database configuration from a file DATABASE_CONFIG_FILENAME = os.path.join( os.path.abspath(os.sep), # root directory 'etc', 'django', 'searchlogger', 'database_config.json' ) with open(DATABASE_CONFIG_FILENAME) as database_config_file: database_config = json.load(databse_config_file) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': database_config['name'], 'USER': database_config['user'], 'PASSWORD': database_config['password'], 'HOST': database_config['host'], 'PORT': database_config['port'], } }
Fix incorrect description of returned dict entries
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with key 'S1' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
import sys sys.path.append('../..') from SALib.analyze import rbd_fast from SALib.sample import latin from SALib.test_functions import Ishigami from SALib.util import read_param_file # Read the parameter range file and generate samples problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt') # Generate samples param_values = latin.sample(problem, 1000) # Run the "model" and save the output in a text file # This will happen offline for external models Y = Ishigami.evaluate(param_values) # Perform the sensitivity analysis using the model output # Specify which column of the output file to analyze (zero-indexed) Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True) # Returns a dictionary with keys 'S1' and 'ST' # e.g. Si['S1'] contains the first-order index for each parameter, in the # same order as the parameter file
Update dummy app config to use `rootURL`
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.rootURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.locationType = 'hash'; ENV.rootURL = '/ivy-tabs/'; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, rootURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.rootURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.locationType = 'hash'; ENV.baseURL = '/ivy-tabs/'; } return ENV; };
Add REST call for files.
module.exports = function(model) { 'use strict'; let validateProjectAccess = require('./project-access')(model.access); let schema = require('.././schema')(model); let router = require('koa-router')(); let projects = require('./projects')(model.projects); let samples = require('./samples')(model.samples, schema); let files = require('./files')(model.files); let processes = require('./processes')(model.processes, schema); router.get('/projects2', projects.all); router.get('/projects2/:project_id/dir/:directory_id', validateProjectAccess, projects.dirTree); router.post('/projects2/:project_id/processes', validateProjectAccess, processes.create); router.post('/projects2/:project_id/samples', validateProjectAccess, samples.create); router.put('/projects2/:project_id/samples/:sample_id', validateProjectAccess, samples.update); router.get('/projects2/:project_id/files/:file_id', validateProjectAccess, files.get); return router; };
module.exports = function(model) { 'use strict'; let validateProjectAccess = require('./project-access')(model.access); let schema = require('.././schema')(model); let router = require('koa-router')(); let projects = require('./projects')(model.projects); let samples = require('./samples')(model.samples, schema); let processes = require('./processes')(model.processes, schema); router.get('/projects2', projects.all); router.post('/projects2/:project_id/processes', validateProjectAccess, processes.create); router.post('/projects2/:project_id/samples', validateProjectAccess, samples.create); router.put('/projects2/:project_id/samples/:sample_id', validateProjectAccess, samples.update); router.get('/projects2/:project_id/dir/:directory_id', validateProjectAccess, projects.dirTree); return router; };
Move comment to rational location
from projects_controller import ProjectsController from redirects_controller import RedirectsController from flask import Flask, render_template, redirect, abort DATA_DIR = 'data' app = Flask(__name__) app.url_map.strict_slashes = False projects_controller = ProjectsController(DATA_DIR) redirects_controller = RedirectsController(DATA_DIR) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): projects = projects_controller.get_current_projects() return render_template('index.html', projects=projects) @app.route('/start') def start_project(): return render_template('start_project.html') @app.route('/<dynamic>') def project(dynamic): projects = projects_controller.get_all_projects() redirects = redirects_controller.get_redirects() # First, test if if it's a project if dynamic in projects: project_data = projects[dynamic] if 'conclusion_post' in project_data: # The project is over, we should redirect to the post return redirect(project_data['conclusion_post']) else: return render_template('project.html', project_data=project_data) # Next, check if it's a redirect elif dynamic in redirects: return redirect(redirects[dynamic]) else: abort(404) if __name__ == '__main__': app.run(debug=True)
from projects_controller import ProjectsController from redirects_controller import RedirectsController from flask import Flask, render_template, redirect, abort DATA_DIR = 'data' app = Flask(__name__) app.url_map.strict_slashes = False projects_controller = ProjectsController(DATA_DIR) redirects_controller = RedirectsController(DATA_DIR) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.route('/') def index(): projects = projects_controller.get_current_projects() return render_template('index.html', projects=projects) @app.route('/start') def start_project(): return render_template('start_project.html') @app.route('/<dynamic>') def project(dynamic): # First, test if if it's a project projects = projects_controller.get_all_projects() redirects = redirects_controller.get_redirects() if dynamic in projects: project_data = projects[dynamic] if 'conclusion_post' in project_data: # The project is over, we should redirect to the post return redirect(project_data['conclusion_post']) else: return render_template('project.html', project_data=project_data) # Next, check if it's a redirect elif dynamic in redirects: return redirect(redirects[dynamic]) else: abort(404) if __name__ == '__main__': app.run(debug=True)
Set default Innomatic legacy directory
<?php namespace Innomatic\Composer; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Installer\LibraryInstaller; use Composer\Package\PackageInterface; abstract class LegacyInstaller extends LibraryInstaller { protected $innomaticLegacyDir; public function __construct(IOInterface $io, Composer $composer, $type = '') { parent::__construct($io, $composer, $type); $options = $composer->getPackage()->getExtra(); $this->innomaticLegacyDir = isset($options['innomatic-legacy-dir']) ? rtrim($options['innomatic-legacy-dir'], '/') : 'innomatic_legacy'; } public function getInstallPath(PackageInterface $package) { if ($this->io->isVerbose()) { $this->io->write("Innomatic legacy directory is '$this->innomaticLegacyDir/'"); } return $this->innomaticLegacyDir; } }
<?php namespace Innomatic\Composer; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Installer\LibraryInstaller; use Composer\Package\PackageInterface; abstract class LegacyInstaller extends LibraryInstaller { protected $innomaticLegacyDir; public function __construct(IOInterface $io, Composer $composer, $type = '') { parent::__construct($io, $composer, $type); $options = $composer->getPackage()->getExtra(); $this->innomaticLegacyDir = isset($options['innomatic-legacy-dir']) ? rtrim($options['innomatic-legacy-dir'], '/') : '.'; } public function getInstallPath(PackageInterface $package) { if ($this->io->isVerbose()) { $this->io->write("Innomatic legacy directory is '$this->innomaticLegacyDir/'"); } return $this->innomaticLegacyDir; } }
Add no_timber_caching method to the Mara_Development class
<?php class Maera_Development { function __construct() { if ( self::dev_mode() ) { $this->jetpack_dev_mode(); $this->no_timber_caching(); } } /** * Detect if dev mode is active OR if we're on the customizer * @return bool */ public static function dev_mode() { global $wp_customize; $theme_options = get_option( 'maera_admin_options', array() ); if ( isset( $theme_options['dev_mode'] ) && 0 == $theme_options['dev_mode'] && ! isset( $wp_customize ) ) { return false; } else { return true; } } /** * set JETPACK_DEV_DEBUG to true if not already defined */ function jetpack_dev_mode() { if ( ! defined( 'JETPACK_DEV_DEBUG' ) ) { define( 'JETPACK_DEV_DEBUG', true); } } function no_timber_caching() { TimberLoader::CACHE_NONE; } }
<?php class Maera_Development { function __construct() { if ( self::dev_mode() ) { $this->jetpack_dev_mode(); } } /** * Detect if dev mode is active OR if we're on the customizer * @return bool */ public static function dev_mode() { global $wp_customize; $theme_options = get_option( 'maera_admin_options', array() ); if ( isset( $theme_options['dev_mode'] ) && 0 == $theme_options['dev_mode'] && ! isset( $wp_customize ) ) { return false; } else { return true; } } /** * set JETPACK_DEV_DEBUG to true if not already defined */ function jetpack_dev_mode() { if ( ! defined( 'JETPACK_DEV_DEBUG' ) ) { define( 'JETPACK_DEV_DEBUG', true); } } }
Fix first upper case problem.
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.netbeans.modules.web.primefaces.crudgenerator.util; /** * * @author kuw */ public class StringHelper { public static String firstLower(String string) { boolean makeFirstLower = string.length() < 2 || (!Character.isUpperCase(string.charAt(1))); return makeFirstLower ? string.substring(0, 1).toLowerCase() + string.substring(1) : string; } public static String firstUpper(String string) { return string.length() > 1 ? string.substring(0, 1).toUpperCase() + string.substring(1) : string.toUpperCase(); } public static String removeBeanMethodPrefix(String methodName) { if (methodName.startsWith("get")) { //NOI18N methodName = methodName.replaceFirst("get", ""); } if (methodName.startsWith("set")) { //NOI18N methodName = methodName.replaceFirst("set", ""); } if (methodName.startsWith("is")) { //NOI18N methodName = methodName.replaceFirst("is", ""); } return methodName; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.netbeans.modules.web.primefaces.crudgenerator.util; /** * * @author kuw */ public class StringHelper { public static String firstLower(String string) { boolean makeFirstLower = string.length() < 2 || (!Character.isUpperCase(string.charAt(1))); return makeFirstLower ? string.substring(0, 1).toLowerCase() + string.substring(1) : string; } public static String firstUpper(String string) { boolean makeFirstUpper = string.length() < 2 || (!Character.isLowerCase(string.charAt(1))); return makeFirstUpper ? string.substring(0, 1).toUpperCase() + string.substring(1) : string; } public static String removeBeanMethodPrefix(String methodName) { if (methodName.startsWith("get")) { //NOI18N methodName = methodName.replaceFirst("get", ""); } if (methodName.startsWith("set")) { //NOI18N methodName = methodName.replaceFirst("set", ""); } if (methodName.startsWith("is")) { //NOI18N methodName = methodName.replaceFirst("is", ""); } return methodName; } }
Add transition on PostItem component
import styled from 'styled-components' import { Link } from 'gatsby' export const PostItemTitle = styled.h1` ${props => props.theme.Home_PostTitle} margin-bottom: 0.8rem; color: var(--text); transition: color 0.3s; ` export const PostItemLink = styled(Link)` display: block; width: 100%; color: var(--text); text-decoration: none; transition: color 0.3s; @media (hover: hover) { &:hover ${PostItemTitle} { color: var(--accent); } } ` export const PostItemWrapper = styled.article` display: flex; flex-direction: column; align-items: flex-start; ` export const PostItemDateAndReadTime = styled.small` ${props => props.theme.Home_PostDateAndReadTime} display: block; margin-bottom: 1.2rem; ` export const PostItemDescription = styled.p` ${props => props.theme.Home_PostDescription} margin-bottom: 0.8rem; ` export const PostItemTags = styled.small` ${props => props.theme.General_Tag} ` export const PostItemTag = styled(Link)` color: var(--text); transition: color 0.3s; text-decoration: underline; @media (hover: hover) { &:hover { color: var(--accent); } } `
import styled from 'styled-components' import { Link } from 'gatsby' export const PostItemTitle = styled.h1` ${props => props.theme.Home_PostTitle} margin-bottom: 0.8rem; color: var(--text); transition: color 0.3s; ` export const PostItemLink = styled(Link)` display: block; width: 100%; color: var(--text); text-decoration: none; @media (hover: hover) { &:hover ${PostItemTitle} { color: var(--accent); } } ` export const PostItemWrapper = styled.article` display: flex; flex-direction: column; align-items: flex-start; ` export const PostItemDateAndReadTime = styled.small` ${props => props.theme.Home_PostDateAndReadTime} display: block; margin-bottom: 1.2rem; ` export const PostItemDescription = styled.p` ${props => props.theme.Home_PostDescription} margin-bottom: 0.8rem; ` export const PostItemTags = styled.small` ${props => props.theme.General_Tag} ` export const PostItemTag = styled(Link)` color: var(--text); transition: color 0.3s; text-decoration: underline; @media (hover: hover) { &:hover { color: var(--accent); } } `
Use constants instead of magic numbers
'use strict'; /* global Connector */ var INFO_TRACK = 3; var INFO_ARTIST = 4; var INFO_DURATION = 5; var trackInfo = null; function updateTrackInfo() { trackInfo = JSON.parse(localStorage.getItem('audio_v10_track')); } /** * Decodes HTML entities in given text string * @param {String} str String with HTML entities * @return {String} Decoded string */ var decodeHtmlEntity = function(str) { if (str === null) { return null; } return str.replace(/&#(\d+);/g, function(match, dec) { return String.fromCharCode(dec); }); }; Connector.artistTrackSelector = '.top_audio_player_title'; Connector.playerSelector = '#top_audio_player'; Connector.getArtist = function () { updateTrackInfo(); return decodeHtmlEntity(trackInfo[INFO_ARTIST]); }; Connector.getTrack = function () { updateTrackInfo(); return decodeHtmlEntity(trackInfo[INFO_TRACK]); }; Connector.getCurrentTime = function () { updateTrackInfo(); var progress = parseFloat(localStorage.getItem('audio_v10_progress')); return Math.round(parseInt(trackInfo[INFO_DURATION]) * progress); }; Connector.getDuration = function () { updateTrackInfo(); return parseInt(trackInfo[INFO_DURATION]); }; Connector.isPlaying = function() { return $(this.playerSelector).hasClass('top_audio_player_playing'); };
'use strict'; /* global Connector */ var trackInfo = null; function updateTrackInfo() { trackInfo = JSON.parse(localStorage.getItem('audio_v10_track')); } /** * Decodes HTML entities in given text string * @param {String} str String with HTML entities * @return {String} Decoded string */ var decodeHtmlEntity = function(str) { if (str === null) { return null; } return str.replace(/&#(\d+);/g, function(match, dec) { return String.fromCharCode(dec); }); }; Connector.artistTrackSelector = '.top_audio_player_title'; Connector.playerSelector = '#top_audio_player'; Connector.getArtist = function () { updateTrackInfo(); return decodeHtmlEntity(trackInfo[4]); }; Connector.getTrack = function () { updateTrackInfo(); return decodeHtmlEntity(trackInfo[3]); }; Connector.getCurrentTime = function () { updateTrackInfo(); var progress = parseFloat(localStorage.getItem('audio_v10_progress')); return Math.round(parseInt(trackInfo[5])*progress); }; Connector.getDuration = function () { updateTrackInfo(); return parseInt(trackInfo[5]); }; Connector.isPlaying = function() { return $(this.playerSelector).hasClass('top_audio_player_playing'); };
Fix replace of undefined error
import rootDomain from '../../../lib/rootDomain'; export function isPostNSFW(post) { if (!post || !post.title) { return false; } return !!post.title.match(/nsf[wl]/gi) || post.over_18; } export function postShouldRenderMediaFullbleed(post) { const postHint = post.post_hint; const media = post.media; return !!(postHint && postHint !== 'link' && postHint !== 'self' || media && media.oembed && media.oembed.type !== 'rich' || rootDomain(post.cleanUrl) === 'imgur.com' && post.preview); } export function isPostDomainExternal(post) { return post.domain !== `self.${post.subreddit}`; } export function cleanPostDomain(domain) { return (domain || '').replace(/\.com$/, ''); } export function cleanPostHREF(href) { return (href || '').replace(/https?:\/\/i.imgur.com/, 'https://imgur.com'); }
import rootDomain from '../../../lib/rootDomain'; export function isPostNSFW(post) { if (!post || !post.title) { return false; } return !!post.title.match(/nsf[wl]/gi) || post.over_18; } export function postShouldRenderMediaFullbleed(post) { const postHint = post.post_hint; const media = post.media; return !!(postHint && postHint !== 'link' && postHint !== 'self' || media && media.oembed && media.oembed.type !== 'rich' || rootDomain(post.cleanUrl) === 'imgur.com' && post.preview); } export function isPostDomainExternal(post) { return post.domain !== `self.${post.subreddit}`; } export function cleanPostDomain(domain) { return domain.replace(/\.com$/, ''); } export function cleanPostHREF(href) { return href.replace(/https?:\/\/i.imgur.com/, 'https://imgur.com'); }
test(auth): Fix tests for new header
import pytest from zeus import factories from zeus.auth import AuthenticationFailed from zeus.api.authentication import ApiTokenAuthentication def test_no_header(app): with app.test_request_context('/'): assert not ApiTokenAuthentication().authenticate() def test_invalid_authentication_type(app): with app.test_request_context('/', headers={'Authorization': 'foobar'}): assert not ApiTokenAuthentication().authenticate() def test_invalid_token(app): with app.test_request_context('/', headers={'Authorization': 'Bearer: foobar'}): with pytest.raises(AuthenticationFailed): ApiTokenAuthentication().authenticate() def test_expired_token(app): api_token = factories.ApiTokenFactory(expired=True) with app.test_request_context( '/', headers={'Authorization': 'Bearer: {}'.format(api_token.access_token)} ): with pytest.raises(AuthenticationFailed): ApiTokenAuthentication().authenticate() def test_valid_token(app, default_api_token): with app.test_request_context( '/', headers={'Authorization': 'Bearer: {}'.format(default_api_token.access_token)} ): tenant = ApiTokenAuthentication().authenticate() assert tenant.token_id == default_api_token.id
import pytest from zeus import factories from zeus.auth import AuthenticationFailed from zeus.api.authentication import ApiTokenAuthentication def test_no_header(app): with app.test_request_context('/'): assert not ApiTokenAuthentication().authenticate() def test_invalid_authentication_type(app): with app.test_request_context('/', headers={'Authentication': 'foobar'}): assert not ApiTokenAuthentication().authenticate() def test_invalid_token(app): with app.test_request_context('/', headers={'Authentication': 'Bearer: foobar'}): with pytest.raises(AuthenticationFailed): ApiTokenAuthentication().authenticate() def test_expired_token(app): api_token = factories.ApiTokenFactory(expired=True) with app.test_request_context( '/', headers={'Authentication': 'Bearer: {}'.format(api_token.access_token)} ): with pytest.raises(AuthenticationFailed): ApiTokenAuthentication().authenticate() def test_valid_token(app, default_api_token): with app.test_request_context( '/', headers={'Authentication': 'Bearer: {}'.format(default_api_token.access_token)} ): tenant = ApiTokenAuthentication().authenticate() assert tenant.token_id == default_api_token.id
Add first time attender helper
Template.wizardReview.onCreated(function () { // Get reference to template instance const instance = this; // Get form data as instance variable instance.registration = instance.data.wizard.mergedData(); }); Template.wizardReview.helpers({ 'registration': function () { // Get reference to template instance const instance = Template.instance(); // Get registration from template instance return instance.registration; }, 'accommodationsFee': function () { // Get reference to template instance const instance = Template.instance(); // Get registration data const registration = instance.registration; // Adjust attributes of registration data to match accommodations fee function registration.type = registration.registrationType; registration.ageGroup = calculateAgeGroup(registration.age); // Calculate accommodations fee const accommodationsFee = calculateAccommodationsFee(registration); return accommodationsFee; }, 'firstTimeAttenderDiscount': function () { // Get reference to template instance const instance = Template.instance(); // Get registration const registration = instance.registration; // Calculate first time attender discount if (registration.firstTimeAttender) { return firstTimeAttenderDiscount; } } });
Template.wizardReview.onCreated(function () { // Get reference to template instance const instance = this; // Get form data as instance variable instance.registration = instance.data.wizard.mergedData(); }); Template.wizardReview.helpers({ 'registration': function () { // Get reference to template instance const instance = Template.instance(); // Get registration from template instance return instance.registration; }, 'accommodationsFee': function () { // Get reference to template instance const instance = Template.instance(); // Get registration data const registration = instance.registration; // Adjust attributes of registration data to match accommodations fee function registration.type = registration.registrationType; registration.ageGroup = calculateAgeGroup(registration.age); // Calculate accommodations fee const accommodationsFee = calculateAccommodationsFee(registration); return accommodationsFee; } });
Revert "Adding Nightly System Add-ons to the ignore list." This reverts commit f86891186615932846d56b74cf901132b16a324a.
// Tracking categories. export const VIDEO_CATEGORY = 'Discovery Video'; export const NAVIGATION_CATEGORY = 'Discovery Navigation'; // Action types. export const DISCO_RESULTS = 'DISCO_RESULTS'; // Keys for extensions and theme data in the discovery pane JSON blob. export const DISCO_DATA_THEME = 'theme'; export const DISCO_DATA_EXTENSION = 'extension'; export const DISCO_DATA_UNKNOWN = 'unknown'; // Built-in extensions and themes to ignore. export const DISCO_DATA_GUID_IGNORE_LIST = [ '{972ce4c6-7e08-4474-a285-3208198ce6fd}', // Default theme. 'e10srollout@mozilla.org', // e10s 'firefox@getpocket.com', // Pocket 'loop@mozilla.org', // Firefox Hello 'aushelper@mozilla.org', // Application Update Service Helper 'webcompat@mozilla.org', // Web Compat ];
// Tracking categories. export const VIDEO_CATEGORY = 'Discovery Video'; export const NAVIGATION_CATEGORY = 'Discovery Navigation'; // Action types. export const DISCO_RESULTS = 'DISCO_RESULTS'; // Keys for extensions and theme data in the discovery pane JSON blob. export const DISCO_DATA_THEME = 'theme'; export const DISCO_DATA_EXTENSION = 'extension'; export const DISCO_DATA_UNKNOWN = 'unknown'; // Built-in extensions and themes to ignore. export const DISCO_DATA_GUID_IGNORE_LIST = [ '{972ce4c6-7e08-4474-a285-3208198ce6fd}', // Default theme. 'e10srollout@mozilla.org', // e10s 'firefox@getpocket.com', // Pocket 'loop@mozilla.org', // Firefox Hello 'aushelper@mozilla.org', // Application Update Service Helper 'webcompat@mozilla.org', // Web Compat 'flyweb@mozilla.org', // FlyWeb 'formautofill@mozilla.org', // Form Autofill 'presentation@mozilla.org', // Presentation 'shield-recipe-client@mozilla.org', // Shield Recipe Client ];
2821: Call to extract was missing param. It wasn't setting the form_ids and, as a result, always showing all questions (Using ALL for the form_ids).
// ELMO.Report.EditPane (function(ns, klass) { // constructor ns.EditPane = klass = function() { } klass.prototype.build = function() { // get refs this.cont = $("div.report_edit_pane." + this.id); this.error_box = this.cont.find("div.error_box") } klass.prototype.show = function() { this.cont.show(); } klass.prototype.hide = function() { this.cont.hide(); } klass.prototype.broadcast_change = function(attrib) { this.extract(true); this.parent_view.broadcast_change(attrib); } klass.prototype.show_validation_errors = function() { var fields = this.fields_for_validation_errors ? this.fields_for_validation_errors() : []; var errors = []; if (this.report) for (var i = 0; i < fields.length; i++) errors = errors.concat(this.report.errors.get(fields[i])); this.has_errors = errors.length > 0; this.error_box.html(errors.join("<br/>")); this.error_box[this.has_errors ? "show" : "hide"](); } }(ELMO.Report));
// ELMO.Report.EditPane (function(ns, klass) { // constructor ns.EditPane = klass = function() { } klass.prototype.build = function() { // get refs this.cont = $("div.report_edit_pane." + this.id); this.error_box = this.cont.find("div.error_box") } klass.prototype.show = function() { this.cont.show(); } klass.prototype.hide = function() { this.cont.hide(); } klass.prototype.broadcast_change = function(attrib) { this.extract(); this.parent_view.broadcast_change(attrib); } klass.prototype.show_validation_errors = function() { var fields = this.fields_for_validation_errors ? this.fields_for_validation_errors() : []; var errors = []; if (this.report) for (var i = 0; i < fields.length; i++) errors = errors.concat(this.report.errors.get(fields[i])); this.has_errors = errors.length > 0; this.error_box.html(errors.join("<br/>")); this.error_box[this.has_errors ? "show" : "hide"](); } }(ELMO.Report));
Update the PyPI version to 0.2.23.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.23', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='0.2.22', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Address review feedback on footnotes - RubyString Be more succinct and explicit when converting to RubyString
package org.asciidoctor.jruby.ast.impl; import org.jruby.RubyStruct; import org.asciidoctor.ast.Footnote; import org.jruby.javasupport.JavaEmbedUtils; public class FootnoteImpl implements Footnote { private static final String INDEX_KEY_NAME = "index"; private static final String ID_KEY_NAME = "id"; private static final String TEXT_KEY_NAME = "text"; private Long index; private String id; private String text; private static Object aref(RubyStruct s, String key) { return JavaEmbedUtils.rubyToJava(s.aref(s.getRuntime().newString(key))); } public static Footnote getInstance(Long index, String id, String text) { FootnoteImpl footnote = new FootnoteImpl(); footnote.index = index; footnote.id = id; footnote.text = text; return footnote; } public static Footnote getInstance(RubyStruct rubyFootnote) { return FootnoteImpl.getInstance( (Long) aref(rubyFootnote, INDEX_KEY_NAME), (String) aref(rubyFootnote, ID_KEY_NAME), (String) aref(rubyFootnote, TEXT_KEY_NAME)); } @Override public Long getIndex() { return index; } @Override public String getId() { return id; } @Override public String getText() { return text; } }
package org.asciidoctor.jruby.ast.impl; import org.jruby.RubyStruct; import org.asciidoctor.ast.Footnote; import org.jruby.javasupport.JavaEmbedUtils; public class FootnoteImpl implements Footnote { private static final String INDEX_KEY_NAME = "index"; private static final String ID_KEY_NAME = "id"; private static final String TEXT_KEY_NAME = "text"; private Long index; private String id; private String text; private static Object aref(RubyStruct s, String key) { return JavaEmbedUtils.rubyToJava(s.aref(JavaEmbedUtils.javaToRuby(s.getRuntime(), key))); } public static Footnote getInstance(Long index, String id, String text) { FootnoteImpl footnote = new FootnoteImpl(); footnote.index = index; footnote.id = id; footnote.text = text; return footnote; } public static Footnote getInstance(RubyStruct rubyFootnote) { return FootnoteImpl.getInstance( (Long) aref(rubyFootnote, INDEX_KEY_NAME), (String) aref(rubyFootnote, ID_KEY_NAME), (String) aref(rubyFootnote, TEXT_KEY_NAME)); } @Override public Long getIndex() { return index; } @Override public String getId() { return id; } @Override public String getText() { return text; } }
Add some verbose to know if we process things
import sys import os import numpy as np from skcycling.utils import load_power_from_fit from skcycling.power_profile import Rpp # The first input argument corresponding to the data path data_path = sys.argv[1] # The second input argument is the storage directory storage_path = sys.argv[2] # We can create a list of all the *.fit files present inside that directory # Create a list with the files to considered filenames = [] for root, dirs, files in os.walk(data_path): for file in files: if file.endswith('.fit'): filenames.append(os.path.join(root, file)) max_duration_rpp = 300 rpp_rider = Rpp(max_duration_rpp=max_duration_rpp) # Open each file and fit for idx_file, filename in enumerate(filenames): print 'Process file #{} over {}'.format(idx_file+1, len(filenames)) # Open the file power_ride = load_power_from_fit(filename) # Fit the ride rpp_rider.fit(power_ride) # Create a directory to store the data if it is not existing if not os.path.exists(storage_path): os.makedirs(storage_path) # Store the data somewhere np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
import sys import os import numpy as np from skcycling.utils import load_power_from_fit from skcycling.power_profile import Rpp # The first input argument corresponding to the data path data_path = sys.argv[1] # The second input argument is the storage directory storage_path = sys.argv[2] # We can create a list of all the *.fit files present inside that directory # Create a list with the files to considered filenames = [] for root, dirs, files in os.walk(data_path): for file in files: if file.endswith('.fit'): filenames.append(os.path.join(root, file)) max_duration_rpp = 300 rpp_rider = Rpp(max_duration_rpp=max_duration_rpp) # Open each file and fit for filename in filenames: # Open the file power_ride = load_power_from_fit(filename) # Fit the ride rpp_rider.fit(power_ride) # Create a directory to store the data if it is not existing if not os.path.exists(storage_path): os.makedirs(storage_path) # Store the data somewhere np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
Fix test flakiness by changing timeout to a longer value Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
import pytest from gaphor.misc.gidlethread import GIdleThread def counter(count): for x in range(count): yield x @pytest.fixture def gidle_counter(request): # Setup GIdle Thread with 0.05 sec timeout t = GIdleThread(counter(request.param)) t.start() assert t.is_alive() wait_result = t.wait(0.05) yield wait_result # Teardown GIdle Thread t.interrupt() @pytest.mark.parametrize(argnames="gidle_counter", argvalues=[20000], indirect=True) def test_wait_with_timeout(gidle_counter): # GIVEN a long coroutine thread # WHEN waiting short timeout # THEN timeout is True assert gidle_counter @pytest.mark.parametrize(argnames="gidle_counter", argvalues=[2], indirect=True) def test_wait_until_finished(gidle_counter): # GIVEN a short coroutine thread # WHEN wait for coroutine to finish # THEN coroutine finished assert not gidle_counter
import pytest from gaphor.misc.gidlethread import GIdleThread def counter(count): for x in range(count): yield x @pytest.fixture def gidle_counter(request): # Setup GIdle Thread with 0.02 sec timeout t = GIdleThread(counter(request.param)) t.start() assert t.is_alive() wait_result = t.wait(0.02) yield wait_result # Teardown GIdle Thread t.interrupt() @pytest.mark.parametrize(argnames="gidle_counter", argvalues=[20000], indirect=True) def test_wait_with_timeout(gidle_counter): # GIVEN a long coroutine thread # WHEN waiting short timeout # THEN timeout is True assert gidle_counter @pytest.mark.parametrize(argnames="gidle_counter", argvalues=[2], indirect=True) def test_wait_until_finished(gidle_counter): # GIVEN a short coroutine thread # WHEN wait for coroutine to finish # THEN coroutine finished assert not gidle_counter
Add watch target for gulp
const gulp = require('gulp'); const butternut = require('gulp-butternut'); const coffee = require('gulp-coffee'); const mocha = require('gulp-mocha'); gulp.task('coffee', function() { gulp.src('./src/*.coffee') .pipe(coffee({bare: true})) .pipe(gulp.dest('./target/')); }); gulp.task('compress', function (cb) { gulp.src('./target/*.js') .pipe(butternut({file: 'default.js'})) .pipe(gulp.dest('Contents/Scripts')); }); gulp.task('test', () => gulp .src('./test/*.coffee', {read: false}) .pipe(mocha({reporter: 'spec', compilers: 'coffee:coffee-script/register'})) ); gulp.task('watch', function() { gulp.watch('./src/*.coffee', ['default']); }); gulp.task('default', [ 'coffee', 'test', 'compress' ]);
const gulp = require('gulp'); const butternut = require('gulp-butternut'); const coffee = require('gulp-coffee'); const mocha = require('gulp-mocha'); gulp.task('coffee', function() { gulp.src('./src/*.coffee') .pipe(coffee({bare: true})) .pipe(gulp.dest('./target/')); }); gulp.task('compress', function (cb) { gulp.src('./target/*.js') .pipe(butternut({file: 'default.js'})) .pipe(gulp.dest('Contents/Scripts')); }); gulp.task('test', () => gulp .src('./test/*.coffee', {read: false}) .pipe(mocha({reporter: 'spec', compilers: 'coffee:coffee-script/register'})) ); gulp.task('default', [ 'coffee', 'test', 'compress' ]);
Use the right module name. ;)
from setuptools import setup # patch distutils if it can't cope with the "classifiers" or "download_url" # keywords (prior to python 2.3.0). from distutils.dist import DistributionMetadata if not hasattr(DistributionMetadata, 'classifiers'): DistributionMetadata.classifiers = None if not hasattr(DistributionMetadata, 'download_url'): DistributionMetadata.download_url = None setup( name='charade', version='1.1', description='Universal encoding detector', long_description=open('README.rst').read(), author='Mark Pilgrim', author_email='mark@diveintomark.org', url='https://github.com/sigmavirus24/charade', license="LGPL", platforms=['POSIX', 'Windows'], keywords=['encoding', 'i18n', 'xml'], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public" " License (LGPL)", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic", ], scripts=['bin/chardetect.py'], packages=['charade'] )
from setuptools import setup # patch distutils if it can't cope with the "classifiers" or "download_url" # keywords (prior to python 2.3.0). from distutils.dist import DistributionMetadata if not hasattr(DistributionMetadata, 'classifiers'): DistributionMetadata.classifiers = None if not hasattr(DistributionMetadata, 'download_url'): DistributionMetadata.download_url = None setup( name='charade', version='1.1', description='Universal encoding detector', long_description=open('README.rst').read(), author='Mark Pilgrim', author_email='mark@diveintomark.org', url='https://github.com/sigmavirus24/charade', license="LGPL", platforms=['POSIX', 'Windows'], keywords=['encoding', 'i18n', 'xml'], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public" " License (LGPL)", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic", ], scripts=['bin/chardetect.py'], packages=['chardet'] )
Update import in GAE template
// +build appengine package main import ( "net/http" "sync" "time" _ "gnd.la/blobstore/driver/gcs" // enable Google Could Storage blobstore driver _ "gnd.la/cache/driver/memcache" // enable memcached cache driver _ "gnd.la/commands" // required for make-assets command // Uncomment the following line to use Google Cloud SQL //_ "gnd.la/orm/driver/mysql" ) var ( wg sync.WaitGroup ) func _app_engine_app_init() { // Make sure App is initialized before the rest // of this function runs. for App == nil { time.Sleep(5 * time.Millisecond) } if err := App.Prepare(); err != nil { panic(err) } http.Handle("/", App) wg.Done() } // Only executed on the development server. Required for // precompiling assets. func main() { wg.Wait() } func init() { wg.Add(1) go _app_engine_app_init() }
// +build appengine package main import ( "net/http" "sync" "time" _ "gnd.la/admin" // required for make-assets command _ "gnd.la/blobstore/driver/gcs" // enable Google Could Storage blobstore driver _ "gnd.la/cache/driver/memcache" // enable memcached cache driver // Uncomment the following line to use Google Cloud SQL //_ "gnd.la/orm/driver/mysql" ) var ( wg sync.WaitGroup ) func _app_engine_app_init() { // Make sure App is initialized before the rest // of this function runs. for App == nil { time.Sleep(5 * time.Millisecond) } if err := App.Prepare(); err != nil { panic(err) } http.Handle("/", App) wg.Done() } // Only executed on the development server. Required for // precompiling assets. func main() { wg.Wait() } func init() { wg.Add(1) go _app_engine_app_init() }
feat: Check that currentIndex is in indices list
var React = require('react'); var findIndex = require('lodash/array/findIndex'); var utils = require('../../lib/widgetUtils.js'); function indexSelector({container = null, indices = null}) { var IndexSelector = require('../../components/IndexSelector'); var containerNode = utils.getContainerNode(container); var usage = 'Usage: indexSelector({container, indices})'; if (container === null || indices === null) { throw new Error(usage); } return { init: function(state, helper) { var currentIndex = helper.getIndex(); var isIndexInList = findIndex(indices, {'name': currentIndex}) !== -1; if (!isIndexInList) { throw new Error('[stats]: Index ' + currentIndex + ' not present in `indices`'); } }, render: function(results, state, helper) { React.render( <IndexSelector currentIndex={helper.getIndex()} indices={indices} setIndex={helper.setIndex.bind(helper)} />, containerNode ); } }; } module.exports = indexSelector;
var React = require('react'); var utils = require('../../lib/widgetUtils.js'); function indexSelector({container = null, indices = null}) { var IndexSelector = require('../../components/IndexSelector'); var containerNode = utils.getContainerNode(container); var usage = 'Usage: indexSelector({container, indices})'; if (container === null || indices === null) { throw new Error(usage); } return { render: function(results, state, helper) { React.render( <IndexSelector currentIndex={helper.getIndex()} indices={indices} setIndex={helper.setIndex.bind(helper)} />, containerNode ); } }; } module.exports = indexSelector;
Speed up for a while
import os import time from crawl import crawl import tweepy class TwitterAPI: """ Class for accessing the Twitter API. Requires API credentials to be available in environment variables. These will be set appropriately if the bot was created with init.sh included with the heroku-twitterbot-starter """ def __init__(self): consumer_key = os.environ.get('TWITTER_CONSUMER_KEY') consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) access_token = os.environ.get('TWITTER_ACCESS_TOKEN') access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(auth) def tweet(self, message): """Send a tweet""" self.api.update_status(message) if __name__ == "__main__": twitter = TwitterAPI() while True: tweet = crawl() if tweet: twitter.tweet(tweet) time.sleep(60) # 6 hours #time.sleep(21600) # 6 hours
import os import time from crawl import crawl import tweepy class TwitterAPI: """ Class for accessing the Twitter API. Requires API credentials to be available in environment variables. These will be set appropriately if the bot was created with init.sh included with the heroku-twitterbot-starter """ def __init__(self): consumer_key = os.environ.get('TWITTER_CONSUMER_KEY') consumer_secret = os.environ.get('TWITTER_CONSUMER_SECRET') auth = tweepy.OAuthHandler(consumer_key, consumer_secret) access_token = os.environ.get('TWITTER_ACCESS_TOKEN') access_token_secret = os.environ.get('TWITTER_ACCESS_TOKEN_SECRET') auth.set_access_token(access_token, access_token_secret) self.api = tweepy.API(auth) def tweet(self, message): """Send a tweet""" self.api.update_status(message) if __name__ == "__main__": twitter = TwitterAPI() while True: tweet = crawl() if tweet: twitter.tweet(tweet) time.sleep(21600) # 6 hours
Fix has no attribute on templatetags image_obj
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} if getattr(image, 'flip'): new['flip'] = image.flip if getattr(image, 'flop'): new['flop'] = image.flop if getattr(image, 'halign'): new['halign'] = image.halign if getattr(image, 'valign'): new['valign'] = image.valign if getattr(image, 'fit_in'): new['fit_in'] = image.fit_in if getattr(image, 'smart'): new['smart'] = image.smart kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import template from ..generate import image_url as url register = template.Library() @register.simple_tag def image_url(image_url, **kwargs): return url(image_url=image_url, **kwargs) @register.simple_tag def image_obj(image, **kwargs): new = {} new['flip'] = image.flip new['flop'] = image.flop if image.halign: new['halign'] = image.halign if image.valign: new['valign'] = image.valign new['fit_in'] = image.fit_in new['smart'] = image.smart kwargs = dict(new, **kwargs) return url(image_url=image.image.url, **kwargs)
Support for angular + API added.
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/index.html') except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
from flask import Flask, render_template, abort, redirect, url_for from flask.ext.script import Manager from jinja2 import TemplateNotFound app = Flask(__name__) app.config['TESTING'] = True manager = Manager(app) @app.route('/', endpoint='frontend-index') def root(): # Redirect Base URL for the real Index Page. return redirect(url_for('frontend-pages', page='index')) @app.route('/<page>', endpoint='frontend-pages') def show(page='index'): """ Try to Deliver a page. :param page: name of the page :return: template. """ try: return render_template('pages/%s.html' % page) except (TemplateNotFound,): abort(404) if __name__ == '__main__': manager.run()
Change bool_formatter() to be backward compatible with bootstrap2
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s icon-%s"></span>' % (glyph, glyph)) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
from jinja2 import Markup from flask.ext.admin._compat import text_type def null_formatter(view, value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(view, value): """ Return empty string for `None` value :param value: Value to check """ return '' def bool_formatter(view, value): """ Return check icon if value is `True` or empty string otherwise. :param value: Value to check """ glyph = 'ok-circle' if value else 'minus-sign' return Markup('<span class="glyphicon glyphicon-%s"></span>' % glyph) def list_formatter(view, values): """ Return string with comma separated values :param values: Value to check """ return u', '.join(text_type(v) for v in values) BASE_FORMATTERS = { type(None): empty_formatter, bool: bool_formatter, list: list_formatter, }
Change bbox values in example
var polygon = require('turf-polygon'); /** * Takes a bbox and returns the equivalent polygon feature. * * @module turf/bbox-polygon * @param {Array} bbox - Array of bounding box coordinates in the form: ```[xLow, yLow, xHigh, yHigh]``` * @return {Polygon} poly - A GeoJSON Polygon of the bounding box * @example * var bbox = [-97.52, 35.460, -97.5, 35.468]; * * var poly = turf.bboxPoly(bbox); * * //=poly */ module.exports = function(bbox){ var lowLeft = [bbox[0], bbox[1]]; var topLeft = [bbox[0], bbox[3]]; var topRight = [bbox[2], bbox[3]]; var lowRight = [bbox[2], bbox[1]]; var poly = polygon([[ lowLeft, lowRight, topRight, topLeft, lowLeft ]]); return poly; }
var polygon = require('turf-polygon'); /** * Takes a bbox and returns the equivalent polygon feature. * * @module turf/bbox-polygon * @param {Array} bbox - Array of bounding box coordinates in the form: ```[xLow, yLow, xHigh, yHigh]``` * @return {Polygon} poly - A GeoJSON Polygon of the bounding box * @example * var bbox = [0,0,10,10]; * * var poly = turf.bboxPoly(bbox); * * //=poly */ module.exports = function(bbox){ var lowLeft = [bbox[0], bbox[1]]; var topLeft = [bbox[0], bbox[3]]; var topRight = [bbox[2], bbox[3]]; var lowRight = [bbox[2], bbox[1]]; var poly = polygon([[ lowLeft, lowRight, topRight, topLeft, lowLeft ]]); return poly; }
Mark ol.format.filter.Spatial as abstract class Add missing abstract class description for class ol.format.filter.Spatial like in all other abstract classes.
goog.provide('ol.format.filter.Spatial'); goog.require('ol'); goog.require('ol.format.filter.Filter'); /** * @classdesc * Abstract class; normally only used for creating subclasses and not instantiated in apps. * Represents a spatial operator to test whether a geometry-valued property * relates to a given geometry. * * @constructor * @param {!string} tagName The XML tag name for this filter. * @param {!string} geometryName Geometry name to use. * @param {!ol.geom.Geometry} geometry Geometry. * @param {string=} opt_srsName SRS name. No srsName attribute will be * set on geometries when this is not provided. * @extends {ol.format.filter.Filter} * @api */ ol.format.filter.Spatial = function(tagName, geometryName, geometry, opt_srsName) { ol.format.filter.Filter.call(this, tagName); /** * @public * @type {!string} */ this.geometryName = geometryName || 'the_geom'; /** * @public * @type {ol.geom.Geometry} */ this.geometry = geometry; /** * @public * @type {string|undefined} */ this.srsName = opt_srsName; }; ol.inherits(ol.format.filter.Spatial, ol.format.filter.Filter);
goog.provide('ol.format.filter.Spatial'); goog.require('ol'); goog.require('ol.format.filter.Filter'); /** * @classdesc * Represents a spatial operator to test whether a geometry-valued property * relates to a given geometry. * * @constructor * @param {!string} tagName The XML tag name for this filter. * @param {!string} geometryName Geometry name to use. * @param {!ol.geom.Geometry} geometry Geometry. * @param {string=} opt_srsName SRS name. No srsName attribute will be * set on geometries when this is not provided. * @extends {ol.format.filter.Filter} * @api */ ol.format.filter.Spatial = function(tagName, geometryName, geometry, opt_srsName) { ol.format.filter.Filter.call(this, tagName); /** * @public * @type {!string} */ this.geometryName = geometryName || 'the_geom'; /** * @public * @type {ol.geom.Geometry} */ this.geometry = geometry; /** * @public * @type {string|undefined} */ this.srsName = opt_srsName; }; ol.inherits(ol.format.filter.Spatial, ol.format.filter.Filter);
Add support for linux with File.separator
package org.apache.maven.siteindexer.mojo; import java.io.File; import java.io.IOException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.siteindexer.Indexer; /** * This goal will build the index. * * @goal index * @aggregator * */ public class IndexerMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { Indexer indexer = new Indexer(getLog()); try { getLog().info("Maven Site Index"); getLog().info("------------------------------"); getLog().info("building index.js..."); indexer.buildIndex( "target"+ File.separator +"site"+ File.separator, "target" + File.separator + "site" + File.separator + "js" + File.separator + "index.js"); getLog().info("done."); } catch (IOException e) { getLog().error(e); } } }
package org.apache.maven.siteindexer.mojo; import java.io.IOException; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.siteindexer.Indexer; /** * This goal will build the index. * * @goal index * @aggregator * */ public class IndexerMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { Indexer indexer = new Indexer(getLog()); try { getLog().info("Maven Site Index"); getLog().info("------------------------------"); getLog().info("building index.js..."); indexer.buildIndex( "target"+ File.separator +"site"+ File.separator, "target" + File.separator + "site" + File.separator + "js" + File.separator + "index.js"); getLog().info("done."); } catch (IOException e) { getLog().error(e); } } }
Fix docblock so child entities fluent setters wont break
<?php namespace Kunstmaan\AdminBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * The Abstract ORM entity */ abstract class AbstractEntity implements EntityInterface { /** * @ORM\Id * @ORM\Column(type="bigint") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set id * * @param int $id The unique identifier * * @return $this */ public function setId($id) { $this->id = $id; return $this; } /** * Return string representation of entity * * @return string */ public function __toString() { return "" . $this->getId(); } }
<?php namespace Kunstmaan\AdminBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * The Abstract ORM entity */ abstract class AbstractEntity implements EntityInterface { /** * @ORM\Id * @ORM\Column(type="bigint") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set id * * @param int $id The unique identifier * * @return AbstractEntity */ public function setId($id) { $this->id = $id; return $this; } /** * Return string representation of entity * * @return string */ public function __toString() { return "" . $this->getId(); } }
[BUGFIX] Use local/bin/deployer for media move
<?php namespace Deployer; task('media:move', function () { if (null === input()->getArgument('stage')) { throw new \RuntimeException("The target instance is required for media:move command. [Error code: 1488149866477]"); } if (null !== input()->getArgument('targetStage')) { $targetInstanceName = input()->getArgument('targetStage'); if ($targetInstanceName == 'live') { throw new \RuntimeException( "FORBIDDEN: For security its forbidden to move media to live instance!" ); } if ($targetInstanceName == 'local') { throw new \RuntimeException( "FORBIDDEN: For synchro local media use: \ndep media:pull " . $targetInstanceName ); } } else { throw new \RuntimeException( "You must set the target instance the media will be copied to as second parameter." ); } $targetServer = get('current_server')->get('server')['name']; runLocally('{{bin/php}} {{local/bin/deployer}} media:pull ' . get('server')['name']); runLocally('{{bin/php}} {{local/bin/deployer}} media:push ' . $targetServer); })->desc('Synchronize media between instances.');
<?php namespace Deployer; task('media:move', function () { if (null === input()->getArgument('stage')) { throw new \RuntimeException("The target instance is required for media:move command. [Error code: 1488149866477]"); } if (null !== input()->getArgument('targetStage')) { $targetInstanceName = input()->getArgument('targetStage'); if ($targetInstanceName == 'live') { throw new \RuntimeException( "FORBIDDEN: For security its forbidden to move media to live instance!" ); } if ($targetInstanceName == 'local') { throw new \RuntimeException( "FORBIDDEN: For synchro local media use: \ndep media:pull " . $targetInstanceName ); } } else { throw new \RuntimeException( "You must set the target instance the media will be copied to as second parameter." ); } $targetServer = get('current_server')->get('server')['name']; runLocally('{{bin/php}} {{bin/deployer}} media:pull ' . get('server')['name']); runLocally('{{bin/php}} {{bin/deployer}} media:push ' . $targetServer); })->desc('Synchronize media between instances.');
Check all the todos and not just one
import { expect } from 'chai'; import { addTodo } from './common.js'; describe('App', function() { beforeEach(function() { addTodo('buy cheddar'); addTodo('buy chorizo'); addTodo('buy bacon'); }); describe('todos', function() { it('should not be marked as completed after being added', function() { // We can use getAttribute without map after // https://github.com/webdriverio/wdio-sync/issues/43 is fixed. const states = $$('.todo .toggle').map(c => c.getAttribute('checked')); expect(states).to.have.length(3); expect(states.every(state => state === 'true')).to.be.false; }); it('should be marked as completed when checking them', function() { $$('.todo .toggle').forEach(toggle => toggle.click()); const states = browser.elements('input[type=checkbox]').getAttribute('checked'); expect(states).to.have.length(3); expect(states.every(state => state === 'true')).to.be.true; }); }); });
import { expect } from 'chai'; import { addTodo } from './common.js'; describe('App', function() { beforeEach(function() { addTodo('buy cheddar'); addTodo('buy chorizo'); addTodo('buy bacon'); }); describe('todos', function() { it('should not be marked as completed after being added', function() { // We can use getAttribute without map after // https://github.com/webdriverio/wdio-sync/issues/43 is fixed. const states = $$('.todo .toggle').map(c => c.getAttribute('checked')); expect(states).to.have.length(3); expect(states.every(state => state === 'true')).to.be.false; }); it('should be marked as completed when checking them', function() { browser.element('.todo=buy chorizo').click('.toggle'); expect(browser.element('.todo=buy chorizo').element('.toggle') .getAttribute('checked')).to.equal('true'); }); }); });
[FIX] Use absolute imports on opnerp.addons
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2011-2012 Camptocamp SA # # 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/>. # ############################################################################## from openerp.osv import fields from openerp.addons.base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2011-2012 Camptocamp SA # # 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/>. # ############################################################################## from openerp.osv import fields from base_geoengine import geo_model class ResPartner(geo_model.GeoModel): """Add geo_point to partner using a function filed""" _name = "res.partner" _inherit = "res.partner" _columns = { 'geo_point': fields.geo_point('Addresses coordinate') }
Fix LibNotify notification promise not resolving
import { main } from "config"; import NotificationProvider from "./NotificationProvider"; import which from "utils/node/fs/which"; import { spawn } from "child_process"; const { "display-name": displayName } = main; export default class NotificationProviderLibNotify extends NotificationProvider { constructor( exec ) { super(); this.exec = exec; } static test() { return which( "notify-send" ); } notify( data ) { return new Promise( ( resolve, reject ) => { let params = [ "--app-name", displayName, "--icon", data.icon, data.title, NotificationProvider.getMessageAsString( data.message ) ]; let notification = spawn( this.exec, params ); notification.once( "error", reject ); notification.once( "exit", code => code === 0 ? resolve() : reject( new Error( "Could not display notification" ) ) ); }); } } NotificationProviderLibNotify.platforms = { linux: "growl" };
import { main } from "config"; import NotificationProvider from "./NotificationProvider"; import which from "utils/node/fs/which"; import { spawn } from "child_process"; const { "display-name": displayName } = main; export default class NotificationProviderLibNotify extends NotificationProvider { constructor( exec ) { super(); this.exec = exec; } static test() { return which( "notify-send" ); } notify( data ) { return new Promise( ( resolve, reject ) => { let params = [ "--app-name", displayName, "--icon", data.icon, data.title, NotificationProvider.getMessageAsString( data.message ) ]; let notification = spawn( this.exec, params ); notification.once( "error", reject ); notification.once( "exit", code => code === 0 ? resolve : reject ); }); } } NotificationProviderLibNotify.platforms = { linux: "growl" };
Add change to ship both pyparsing and pyparsing_py3 modules.
#!/usr/bin/env python """Setup script for the pyparsing module distribution.""" from distutils.core import setup from pyparsing import __version__ setup(# Distribution meta-data name = "pyparsing", version = __version__, description = "Python parsing module", author = "Paul McGuire", author_email = "ptmcg@users.sourceforge.net", url = "http://pyparsing.wikispaces.com/", download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203", license = "MIT License", py_modules = ["pyparsing", "pyparsing_py3"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
#!/usr/bin/env python """Setup script for the pyparsing module distribution.""" from distutils.core import setup from pyparsing import __version__ setup(# Distribution meta-data name = "pyparsing", version = __version__, description = "Python parsing module", author = "Paul McGuire", author_email = "ptmcg@users.sourceforge.net", url = "http://pyparsing.wikispaces.com/", download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203", license = "MIT License", py_modules = ["pyparsing"], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', ] )
Make travis run all migrations before running tests
<?php function migrate( $sql_array = [] ) { if ( file_exists( '../../config/config-local.php' ) ) { require_once '../../config/config-local.php'; } else { require_once '../../config/config.php'; } require_once '../../models/database.php'; require_once '../../models/db.php'; global $config; $config = getConfig()[ getEnv( 'ENVIRONMENT' ) ]; dbInit(); foreach ( $sql_array as $sql ) { try { $res = db( $sql ); } catch ( DBException $e ) { die( "Migration failed. SQL query died with the following error: " . mysql_error() . "\n" ); } } echo "Migration successful.\n"; } ?>
<?php function migrate( $sql_array = [] ) { require_once '../../config/config-local.php'; require_once '../../models/database.php'; require_once '../../models/db.php'; global $config; $config = getConfig()[ getEnv( 'ENVIRONMENT' ) ]; dbInit(); foreach ( $sql_array as $sql ) { try { $res = db( $sql ); } catch ( DBException $e ) { die( "Migration failed. SQL query died with the following error: " . mysql_error() . "\n" ); } } echo "Migration successful.\n"; } ?>
Correct mocked response from Asana API
import json from .oauth import OAuth2Test class AsanaOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.asana.AsanaOAuth2' user_data_url = 'https://app.asana.com/api/1.0/users/me' expected_username = 'erlich@bachmanity.com' access_token_body = json.dumps({ 'access_token': 'aviato', 'token_type': 'bearer' }) # https://asana.com/developers/api-reference/users user_data_body = json.dumps({ 'data': { 'id': 12345, 'name': 'Erlich Bachman', 'email': 'erlich@bachmanity.com', 'photo': None, 'workspaces': [ { 'id': 123456, 'name': 'Pied Piper' } ] } }) def test_login(self): self.do_login() def test_partial_pipeline(self): self.do_partial_pipeline()
import json from .oauth import OAuth2Test class AsanaOAuth2Test(OAuth2Test): backend_path = 'social_core.backends.asana.AsanaOAuth2' user_data_url = 'https://app.asana.com/api/1.0/users/me' expected_username = 'erlich@bachmanity.com' access_token_body = json.dumps({ 'access_token': 'aviato', 'token_type': 'bearer' }) user_data_body = json.dumps({ 'id': 12345, 'name': 'Erlich Bachman', 'email': 'erlich@bachmanity.com', 'photo': None, 'workspaces': [ { 'id': 123456, 'name': 'Pied Piper' } ] }) def test_login(self): self.do_login() def test_partial_pipeline(self): self.do_partial_pipeline()
Refresh data for the user settings page when it is being accessed Fix #1281
'use strict'; angular.module('<%=angularAppName%>') .controller('SettingsController', function ($scope, Principal, Auth) { $scope.success = null; $scope.error = null; Principal.identity(true).then(function(account) { $scope.settingsAccount = account; }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; });
'use strict'; angular.module('<%=angularAppName%>') .controller('SettingsController', function ($scope, Principal, Auth) { $scope.success = null; $scope.error = null; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity().then(function(account) { $scope.settingsAccount = account; }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; });
Fix JS showing just one photo
var initialize = function() { var root = $('.item'); if (root.length) { var photos = root.find('.item__photos'); if (photos.length) { photos.magnificPopup({ type: 'image', delegate: '.item__photos__photo', gallery: { enabled: true }, preload: [1, 2], zoom: { enabled: true }, duration: 300, easing: 'ease-in-out' }); } if ($('.item__photos__photo').length) { $('.item__photo').on('click', function (e) { e.preventDefault(); $('.item__photos').magnificPopup('open'); }); } else { $('.item__photo').magnificPopup({ type: 'image', zoom: { enabled: true }, duration: 300, easing: 'ease-in-out' }); } } }; $(initialize); $(document).on('page:load', initialize);
var initialize = function() { var root = $('.item'); if (root.length) { var photos = root.find('.item__photos'); if (photos.length) { photos.magnificPopup({ type: 'image', delegate: '.item__photos__photo', gallery: { enabled: true }, preload: [1, 2], zoom: { enabled: true }, duration: 300, easing: 'ease-in-out' }); } if ($('.item__photos__photo').length) { $('.item__photo').on('click', function (e) { e.preventDefault(); $('.item__photos').magnificPopup('open'); }); } else { $('.item__photos__photo').magnificPopup({ type: 'image', zoom: { enabled: true }, duration: 300, easing: 'ease-in-out' }); } } }; $(initialize); $(document).on('page:load', initialize);
Make SQLite the default test setup
from binder import Sqlite3Connection from binder import MysqlConnection import os # sqlite3 _bindertest_dir = os.path.dirname( __file__ ) DBFILE = os.path.join(_bindertest_dir, "test.db3") def connect_sqlite3(read_only=None): return Sqlite3Connection(DBFILE, read_only) # MySQL - modify as needed MYSQL_TESTDB = { "host": "localhost", "user": "bindertest", "passwd": "binderpassword", "db": "bindertestdb", } def connect_mysql(read_only=None, isolation_level=None): d = dict(MYSQL_TESTDB) d['read_only'] = read_only if isolation_level: d['isolation_level'] = isolation_level return MysqlConnection(**d) # Test DB - modify as needed connect = connect_sqlite3 #connect = connect_mysql
from binder import Sqlite3Connection from binder import MysqlConnection import os # sqlite3 _bindertest_dir = os.path.dirname( __file__ ) DBFILE = os.path.join(_bindertest_dir, "test.db3") def connect_sqlite3(read_only=None): return Sqlite3Connection(DBFILE, read_only) # MySQL - modify as needed MYSQL_TESTDB = { "host": "localhost", "user": "bindertest", "passwd": "binderpassword", "db": "bindertestdb", } def connect_mysql(read_only=None, isolation_level=None): d = dict(MYSQL_TESTDB) d['read_only'] = read_only if isolation_level: d['isolation_level'] = isolation_level return MysqlConnection(**d) # Test DB - modify as needed #connect = connect_sqlite3 connect = connect_mysql
Add all sorts of mongolab stuff
var express = require('express'); var mongoose = require('mongoose'); var app = express(); // connect to mongo database named "bolt" // mongoose.connect('mongodb://localhost/bolt'); mongoose.connect('mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp'); // mongoose.connect(process.env.MONGOLAB_URI, function (error) { // if (error) console.error(error); // else console.log('mongo connected'); // }); // MONGOLAB_URI: mongodb://heroku_l3g4r0kp:61docmam4tnk026c51bhc5hork@ds029605.mongolab.com:29605/heroku_l3g4r0kp // Also maybe the MONGOLAB_URI: mongodb://elliotaplant:bolt1738@ds029605.mongolab.com:29605/heroku_l3g4r0kp // API key: kyYsvLVM95SVVl9EKZ-dbfX0LzejuVJf // uesrname: elliotaplant // password: bolt1738 // configure our server with all the middleware and routing require('./config/middleware.js')(app, express); require('./config/routes.js')(app, express); // start listening to requests on port 8000 var port = Number(process.env.PORT || 8000); app.listen(port, function() { console.log(`server listening on port ${port}`); }); // export our app for testing and flexibility, required by index.js module.exports = app; //test
var express = require('express'); var mongoose = require('mongoose'); var app = express(); // connect to mongo database named "bolt" mongoose.connect('mongodb://localhost/bolt'); mongoose.connect(process.env.MONGOLAB_URI, function (error) { if (error) console.error(error); else console.log('mongo connected'); }); // API key: kyYsvLVM95SVVl9EKZ-dbfX0LzejuVJf // configure our server with all the middleware and routing require('./config/middleware.js')(app, express); require('./config/routes.js')(app, express); // start listening to requests on port 8000 var port = Number(process.env.PORT || 8000); app.listen(port, function() { console.log(`server listening on port ${port}`); }); // export our app for testing and flexibility, required by index.js module.exports = app; //test
Use __DIR__ as PHP < 5.3 is not supported
<?php require __DIR__ . '/../vendor/autoload.php'; class JadePHPTest extends PHPUnit_Framework_TestCase { static private $skipped = array( // Here is the remain to implement list 'inheritance.extend.mixins', 'mixin.attrs', 'mixin.block-tag-behaviour', 'mixin.blocks', 'mixin.merge', 'tag.interpolation' ); public function caseProvider() { static $rawResults = null; if(is_null($rawResults)) { $rawResults = get_tests_results(); $rawResults = $rawResults['results']; } return $rawResults; } /** * @dataProvider caseProvider */ public function testStringGeneration($name, $input, $expected) { if(! in_array($name, static::$skipped)) { $this->assertSame($input, $expected, $name); } } }
<?php require dirname(__FILE__) . '/../vendor/autoload.php'; class JadePHPTest extends PHPUnit_Framework_TestCase { static private $skipped = array( // Here is the remain to implement list 'inheritance.extend.mixins', 'mixin.attrs', 'mixin.block-tag-behaviour', 'mixin.blocks', 'mixin.merge', 'tag.interpolation' ); public function caseProvider() { static $rawResults = null; if(is_null($rawResults)) { $rawResults = get_tests_results(); $rawResults = $rawResults['results']; } return $rawResults; } /** * @dataProvider caseProvider */ public function testStringGeneration($name, $input, $expected) { if(! in_array($name, static::$skipped)) { $this->assertSame($input, $expected, $name); } } }
Fix mistake with socket constructor
#!/usr/bin/env python import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) sock.sendall(json.dumps(result)) print (json.dumps(result))
#!/usr/bin/env python import json import socket import sys if len(sys.argv) < 4: print("Error: Usage <register-result> <client> <name> <output> <status> <ttl>") sys.exit(128) check_client = sys.argv[1] check_name = sys.argv[2] check_output = sys.argv[3] check_status = int(sys.argv[4]) check_ttl = int(sys.argv[5]) if len(sys.argv) > 5 else 90000 # Our result dict result = dict() result['source'] = check_client result['name'] = check_name result['output'] = check_output result['status'] = check_status result['ttl'] = check_ttl # TCP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 3030) sock.connect(server_address) print (json.dumps(result)) socket.sendall(json.dumps(result))
Check setup.py desc when packaging
import os from invocations.docs import docs, www, sites, watch_docs from invocations.testing import test, coverage, integration, watch_tests from invocations.packaging import vendorize, release from invoke import Collection from invoke.util import LOG_FORMAT ns = Collection( test, coverage, integration, vendorize, release, www, docs, sites, watch_docs, watch_tests ) ns.configure({ 'tests': { 'logformat': LOG_FORMAT, 'package': 'invoke', }, 'packaging': { 'sign': True, 'wheel': True, 'check_desc': True, # Because of PyYAML's dual source nonsense =/ 'dual_wheels': True, 'changelog_file': os.path.join( www.configuration()['sphinx']['source'], 'changelog.rst', ), }, })
import os from invocations.docs import docs, www, sites, watch_docs from invocations.testing import test, coverage, integration, watch_tests from invocations.packaging import vendorize, release from invoke import Collection from invoke.util import LOG_FORMAT ns = Collection( test, coverage, integration, vendorize, release, www, docs, sites, watch_docs, watch_tests ) ns.configure({ 'tests': { 'logformat': LOG_FORMAT, 'package': 'invoke', }, 'packaging': { 'sign': True, 'wheel': True, # Because of PyYAML's dual source nonsense =/ 'dual_wheels': True, 'changelog_file': os.path.join( www.configuration()['sphinx']['source'], 'changelog.rst', ), }, })
Clean up destroyed modal properly
/** @jsx React.DOM */ define([ "jquery", "React" ], function($, React) { return React.createClass({ destroy: function(event) { if (event.target.className === "modal" || event.target.className === "modal-dialog") { var domNode = this.getDOMNode(); // TODO(ssorallen): Why does this need to unmount from the parentNode? // If it is unmounted from `domNode`, the second render throws an // invariant exception. React.unmountComponentAtNode(domNode.parentNode); $(domNode).remove(); } }, render: function() { return ( <div> <div className="modal" onClick={this.destroy}> <div className="modal-dialog"> <div className="modal-content"> {this.props.children} </div> </div> </div> <div className="modal-backdrop fade in"></div> </div> ); } }); });
/** @jsx React.DOM */ define([ "React" ], function(React) { return React.createClass({ destroy: function(event) { if (event.target.className === "modal" || event.target.className === "modal-dialog") { var domNode = this.getDOMNode(); React.unmountComponentAtNode(domNode); $(domNode).remove(); } }, render: function() { return ( <div> <div className="modal" onClick={this.destroy}> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-body"> {this.props.children} </div> </div> </div> </div> <div className="modal-backdrop fade in"></div> </div> ); } }); });
Add feed id as a parameter
package main import ( "net/http" "fmt" "encoding/json" ) func handlePing(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") } func handleRequest(w http.ResponseWriter, r *http.Request) { type Input struct { FeedId string `json:"feed_id"` FeedUrl string `json:"feed_url"` } if r.Method != http.MethodPost { http.Error(w, "Not allowed", http.StatusMethodNotAllowed) return } var inputs []Input err := json.NewDecoder(r.Body).Decode(&inputs) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } for _, input := range inputs { fmt.Fprintf(w, "%s", input.FeedUrl) } } func init() { http.HandleFunc("/ping", handlePing) http.HandleFunc("/handle", handleRequest) }
package main import ( "net/http" "fmt" "encoding/json" ) func handlePing(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") } func handleRequest(w http.ResponseWriter, r *http.Request) { type Input struct { FeedUrl string `json:"feed_url"` } if r.Method != http.MethodPost { http.Error(w, "Not allowed", http.StatusMethodNotAllowed) return } var inputs []Input err := json.NewDecoder(r.Body).Decode(&inputs) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } for _, input := range inputs { fmt.Fprintf(w, "%s", input.FeedUrl) } } func init() { http.HandleFunc("/ping", handlePing) http.HandleFunc("/handle", handleRequest) }
Remove call to async callback.
import { goToUrl, getElementText, getPageHTML, getPageTitle, findPageElements } from "../helper"; describe("eQ Author", () => { describe("navigate to the Homepage", () => { beforeAll(() => { goToUrl("http://localhost:3000/"); }); it("displays page title", () => { expect(getPageTitle()).toEqual("eQ Author Prototype"); }); it("displays select to begin", () => { expect(getPageHTML("#root")).toContain("Select to begin"); }); it("presents user with buttons to create or load survey", () => { const buttons = findPageElements("button"); expect(buttons.length).toEqual(2); expect(getElementText(buttons[0])).toEqual("Create survey"); expect(getElementText(buttons[1])).toEqual("Load survey"); }); }); });
import { goToUrl, getElementText, getPageHTML, getPageTitle, findPageElements } from "../helper"; describe("eQ Author", () => { describe("navigate to the Homepage", () => { beforeAll(() => { goToUrl("http://localhost:3000/"); }); it("displays page title", done => { expect(getPageTitle()).toEqual("eQ Author Prototype"); done(); }); it("displays select to begin", done => { expect(getPageHTML("#root")).toContain("Select to begin"); done(); }); it("presents user with buttons to create or load survey", done => { const buttons = findPageElements("button"); expect(buttons.length).toEqual(2); expect(getElementText(buttons[0])).toEqual("Create survey"); expect(getElementText(buttons[1])).toEqual("Load survey"); done(); }); }); });
Increase timeout for weather net fetch.
var nodeHelper = require('node_helper'), request = require('request'), console = require('console'), TemplateHandler = require('../shared/template_handler.js'); module.exports = nodeHelper.create({ start: function() { var th = new TemplateHandler(this.expressApp, this.name, this.path); th.installTemplateHandler(); }, socketNotificationReceived: function(notification, payload) { if (notification == 'download') { var self = this; request({url: payload, timeout: 300 * 1000}, (error, response, body) => { if (error) { console.log(error); self.sendSocketNotification('error', error); return; } if (response.statusCode != 200) { console.log('weather response status code ' + response.statusCode); self.sendSocketNotification('error500', response); return; } self.sendSocketNotification('download', body); }); } } });
var nodeHelper = require('node_helper'), request = require('request'), console = require('console'), TemplateHandler = require('../shared/template_handler.js'); module.exports = nodeHelper.create({ start: function() { var th = new TemplateHandler(this.expressApp, this.name, this.path); th.installTemplateHandler(); }, socketNotificationReceived: function(notification, payload) { if (notification == 'download') { var self = this; request({url: payload, timeout: 30 * 1000}, (error, response, body) => { if (error) { console.log(error); self.sendSocketNotification('error', error); return; } if (response.statusCode != 200) { console.log('weather response status code ' + response.statusCode); self.sendSocketNotification('error500', response); return; } self.sendSocketNotification('download', body); }); } } });
Add missin character in define.
<?php /** * Define Constants. */ define('TEMPLATE_DIR', get_template_directory()); define('TEMPLATE_URI', get_template_directory_uri()); define('ADMIN_DIR', TEMPLATE_DIR.'/admin'); define('ADMIN_URL', TEMPLATE_URI.'/admin'); define('AUTHOR', 'Vincent Klaiber'); define('AUTHOR_URL', 'http://vinkla.com'); define('LOGIN_IMAGE_PATH', TEMPLATE_DIR.'/images/admin-login-logo.png'); define('LOGIN_HEADER_URL', get_site_url()); define('TINYMCE_BLOCKFORMATS', implode(',', [ 'p', 'h2', 'h3' ])); define('TINYMCE_DISABLED', implode(',', [ 'strikethrough', 'underline', 'forecolor', 'justifyfull' ])); /** * Load Admin Components. */ require ADMIN_DIR.'/admin-remove.php'; require ADMIN_DIR.'/admin-functions.php'; require ADMIN_DIR.'/admin-acf.php';
<?php /** * Define Constants. */ define('TEMPLATE_DIR', get_template_directory()); define('TEMPLATE_URI', get_template_directory_uri()); define('ADMIN_DIR', TEMPLATE_DIR.'/admin'); define('ADMIN_URL', TEMPLATE_URI.'/admin'); define('AUTHOR', 'Vincent Klaiber'); define('AUTHOR_URL', 'http://vinkla.com'); define('LOGIN_IMAGE_PATH', TEMPLATE_DIR.'/images/admin-login-logo.png'); define('LOGIN_HEADER_URL', get_site_url()); define('TINYMCE_BLOCKFORMATS', implode(',', [ 'p', 'h2', 'h3' ])); define('TINYMCE_DISABLED', implode(',', [ 'strikethrough', 'underline', 'forecolor', 'justifyfull' ]); /** * Load Admin Components. */ require ADMIN_DIR.'/admin-remove.php'; require ADMIN_DIR.'/admin-functions.php'; require ADMIN_DIR.'/admin-acf.php';
Add description to the help message.
package musician101.common.java.minecraft.sponge.command; import org.spongepowered.api.text.Text.Literal; import org.spongepowered.api.text.Texts; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import javax.annotation.Nonnull; import java.util.Arrays; public class SpongeHelpCommand extends AbstractSpongeCommand { private final AbstractSpongeCommand mainCommand; public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source) { super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null); this.mainCommand = mainCommand; } @Nonnull @Override public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException { source.sendMessage(Texts.of(mainCommand.getUsage(source), mainCommand.getShortDescription(source))); mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get())); return CommandResult.success(); } }
package musician101.common.java.minecraft.sponge.command; import org.spongepowered.api.text.Text.Literal; import org.spongepowered.api.text.Texts; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import javax.annotation.Nonnull; import java.util.Arrays; public class SpongeHelpCommand extends AbstractSpongeCommand { private final AbstractSpongeCommand mainCommand; public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source) { super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null); this.mainCommand = mainCommand; } @Nonnull @Override public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException { source.sendMessage(Texts.of()); source.sendMessage(mainCommand.getUsage(source)); mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get())); return CommandResult.success(); } }
Change minimimum required PHP version to 5.3.23 - Remove [] array notation
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\ApiProblem\Factory; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use ZF\ApiProblem\Listener\ApiProblemListener; class ApiProblemListenerFactory implements FactoryInterface { /** * {@inheritDoc} * @return ApiProblemListener */ public function createService(ServiceLocatorInterface $serviceLocator) { $filters = null; $config = array(); if ($serviceLocator->has('Config')) { $config = $serviceLocator->get('Config'); } if (isset($config['zf-api-problem']['accept_filters'])) { $filters = $config['zf-api-problem']['accept_filters']; } return new ApiProblemListener($filters); } }
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\ApiProblem\Factory; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use ZF\ApiProblem\Listener\ApiProblemListener; class ApiProblemListenerFactory implements FactoryInterface { /** * {@inheritDoc} * @return ApiProblemListener */ public function createService(ServiceLocatorInterface $serviceLocator) { $filters = null; $config = []; if ($serviceLocator->has('Config')) { $config = $serviceLocator->get('Config'); } if (isset($config['zf-api-problem']['accept_filters'])) { $filters = $config['zf-api-problem']['accept_filters']; } return new ApiProblemListener($filters); } }
Bring the image in immediately so the frame doesn't move
// JS Goes here - ES6 supported var $ = window.jQuery; $(document).ready(function() { $(".carousel").slick({ infinite: true, speed: 0, slidesToShow: 1, prevArrow: "<button class='heart-arrow heart-left'><img src='/images/assets/heart-left.png'></button>", nextArrow: "<button class='heart-arrow heart-right'><img src='/images/assets/heart-right.png'></button>", }); var $carousel = $(".carousel"); $(document).on("keydown", function(e) { if (e.keyCode === 37) { $carousel.slick("slickPrev"); } if (e.keyCode === 39) { $carousel.slick("slickNext"); } }); $(".get-married h1").animate({ marginLeft: "0px" }, { duration: 1500, done: function() { $(".i-left, .i-right").css({ visibility: "visible" }); $(".i-right, .i-left").animate({ left: 0 }, { duration: 1000, done: function() { window.confettify(); } }); } }); });
// JS Goes here - ES6 supported var $ = window.jQuery; $(document).ready(function() { $(".carousel").slick({ infinite: true, speed: 500, slidesToShow: 1, prevArrow: "<button class='heart-arrow heart-left'><img src='/images/assets/heart-left.png'></button>", nextArrow: "<button class='heart-arrow heart-right'><img src='/images/assets/heart-right.png'></button>", }); var $carousel = $(".carousel"); $(document).on("keydown", function(e) { if (e.keyCode === 37) { $carousel.slick("slickPrev"); } if (e.keyCode === 39) { $carousel.slick("slickNext"); } }); $(".get-married h1").animate({ marginLeft: "0px" }, { duration: 1500, done: function() { $(".i-left, .i-right").css({ visibility: "visible" }); $(".i-right, .i-left").animate({ left: 0 }, { duration: 1000, done: function() { window.confettify(); } }); } }); });
Update person addition test to create address book inside test func + import needed classes from the package
from unittest import TestCase from address_book import AddressBook, Person class AddressBookTestCase(TestCase): def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) address_book.add_person(person) self.assertIn(person, address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
from unittest import TestCase class AddressBookTestCase(TestCase): def test_add_person(self): person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) self.address_book.add_person(person) self.assertIn(person, self.address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
Fix apiKey not being assigned.
/** * index.js * Client entry point. * * @author Francis Brito <fr.br94@gmail.com> * @license MIT */ 'use strict'; /** * Client * Provides methods to access PrintHouse's API. * * @param {String} apiKey API key identifying account owner. * @param {Object} opts Contains options to be passed to the client */ var Client = function Client(apiKey, opts) { opts = opts || {}; if (!apiKey) { throw new Error('No API key provided.'); } this._endpoint = opts.endpoint || Client.DEFAULT_API_URL; this._version = opts.version || Client.DEFAULT_API_VERSION; this._apiKey = apiKey; }; /** * Default API endpoint. * Used if no API endpoint is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_URL = 'http://printhouse.io/api'; /** * Default API version. * Used if no API version is passed in opts parameter when constructing a client. * * @type {Number} */ Client.DEFAULT_API_VERSION = 1; /** * Client#getProducts * Retrieves a list of print products. * * @param {Object} filter Key/value pairs to filter products. * @param {Function} fn Callback. */ Client.prototype.getProducts = function getProducts(filter, fn) { fn(null, [{kind: ''}]); }; module.exports = { Client: Client };
/** * index.js * Client entry point. * * @author Francis Brito <fr.br94@gmail.com> * @license MIT */ 'use strict'; /** * Client * Provides methods to access PrintHouse's API. * * @param {String} apiKey API key identifying account owner. * @param {Object} opts Contains options to be passed to the client */ var Client = function Client(apiKey, opts) { opts = opts || {}; if (!apiKey) { throw new Error('No API key provided.'); } this._endpoint = opts.endpoint || Client.DEFAULT_API_URL; this._version = opts.version || Client.DEFAULT_API_VERSION; }; /** * Default API endpoint. * Used if no API endpoint is passed in opts parameter when constructing a client. * * @type {String} */ Client.DEFAULT_API_URL = 'http://printhouse.io/api'; /** * Default API version. * Used if no API version is passed in opts parameter when constructing a client. * * @type {Number} */ Client.DEFAULT_API_VERSION = 1; /** * Client#getProducts * Retrieves a list of print products. * * @param {Object} filter Key/value pairs to filter products. * @param {Function} fn Callback. */ Client.prototype.getProducts = function getProducts(filter, fn) { fn(null, [{kind: ''}]); }; module.exports = { Client: Client };
Convert usage of phpcs to a library.
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsArguments = array( 'standard' => array(__DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0, ); $phpcsViolations = $phpcsCLI->process($phpcsArguments); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCommand = './vendor/bin/phpcs --standard=' . __DIR__ . '/vendor/dominionenterprises/dws-coding-standard/DWS -n src tests *.php'; passthru($phpcsCommand, $returnStatus); if ($returnStatus !== 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
Remove unnecessary assignment of static variables
import * as THREE from 'three'; import UberObject from './UberObject'; const Mesh = UberObject(THREE.Mesh); class ZClippedMesh extends Mesh { constructor(geometry, material) { super(geometry, material); this.castShadow = true; this.receiveShadow = true; } static _mvLength = new THREE.Vector3(); static _center = new THREE.Vector3(); static _modelView = new THREE.Matrix4(); _onBeforeRender(renderer, scene, camera) { Mesh.prototype._onBeforeRender.call(this, renderer, scene, camera); const geo = this.geometry; const { material } = this; if (!geo.zClip || !material.uberOptions) { return; } const zClipCoef = 0.5; const modelView = ZClippedMesh._modelView; const mvLength = ZClippedMesh._mvLength; const center = ZClippedMesh._center; modelView.multiplyMatrices(this.matrixWorld, camera.matrixWorldInverse); const s = mvLength.setFromMatrixColumn(modelView, 0).length(); center.copy(geo.boundingSphere.center); this.localToWorld(center); material.uberOptions.zClipValue = camera.position.z - center.z - s * (zClipCoef * geo.boundingSphere.radius); } } export default ZClippedMesh;
import * as THREE from 'three'; import UberObject from './UberObject'; const Mesh = UberObject(THREE.Mesh); class ZClippedMesh extends Mesh { constructor(geometry, material) { super(geometry, material); this.castShadow = true; this.receiveShadow = true; } static _mvLength = new THREE.Vector3(); static _center = new THREE.Vector3(); static _modelView = new THREE.Matrix4(); _onBeforeRender(renderer, scene, camera) { Mesh.prototype._onBeforeRender.call(this, renderer, scene, camera); const geo = this.geometry; const { material } = this; if (!geo.zClip || !material.uberOptions) { return; } const zClipCoef = 0.5; let modelView = ZClippedMesh._modelView; const mvLength = ZClippedMesh._mvLength; let center = ZClippedMesh._center; modelView = modelView.multiplyMatrices(this.matrixWorld, camera.matrixWorldInverse); const s = mvLength.setFromMatrixColumn(modelView, 0).length(); center = center.copy(geo.boundingSphere.center); this.localToWorld(center); material.uberOptions.zClipValue = camera.position.z - center.z - s * (zClipCoef * geo.boundingSphere.radius); } } export default ZClippedMesh;
Remove `fonts` gulp task from default task Doesn't need to run every time.
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('default', ['sass'], function () { }); gulp.task('sass', function () { return gulp.src('./styles/warriormachines_2016/theme/sass/app.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css')); }); gulp.task('fonts', function() { gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}') .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts')); }); gulp.task('sass:watch', function () { gulp.watch('./styles/warriormachines_2016/theme/sass/app.scss', ['sass']); });
'use strict'; var gulp = require('gulp'); var sass = require('gulp-sass'); gulp.task('default', ['sass', 'fonts'], function () { }); gulp.task('sass', function () { return gulp.src('./styles/warriormachines_2016/theme/sass/app.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/css')); }); gulp.task('fonts', function() { gulp.src('./node_modules/font-awesome/fonts/**/*.{eot,svg,ttf,woff,woff2}') .pipe(gulp.dest('./styles/warriormachines_2016/theme/gulp-generated/fonts')); }); gulp.task('sass:watch', function () { gulp.watch('./styles/warriormachines_2016/theme/sass/app.scss', ['sass']); });
Add null logic to asHTML(...)
/*- * #%L * SciJava polyglot kernel for Jupyter. * %% * Copyright (C) 2017 Hadrien Mary * %% * 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. * #L% */ package org.scijava.notebook.converter; import org.scijava.convert.ConvertService; import org.scijava.notebook.converter.output.HTMLFriendlyNotebookOutput; import org.scijava.notebook.converter.output.HTMLNotebookOutput; import org.scijava.plugin.Parameter; /** * Base class for converters to {@link HTMLNotebookOutput} and subclasses. * * @author Curtis Rueden */ public abstract class HTMLNotebookOutputConverter<I, O extends HTMLNotebookOutput> extends NotebookOutputConverter<I, O> { @Parameter private ConvertService convertService; /** Gets an HTML string representing the given object. */ protected String asHTML(final Object o) { final HTMLFriendlyNotebookOutput converted = convertService.convert(o, HTMLFriendlyNotebookOutput.class); return converted == null ? "&lt;none&gt;" : converted.toHTML(); } }
/*- * #%L * SciJava polyglot kernel for Jupyter. * %% * Copyright (C) 2017 Hadrien Mary * %% * 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. * #L% */ package org.scijava.notebook.converter; import org.scijava.convert.ConvertService; import org.scijava.notebook.converter.output.HTMLFriendlyNotebookOutput; import org.scijava.notebook.converter.output.HTMLNotebookOutput; import org.scijava.plugin.Parameter; /** * Base class for converters to {@link HTMLNotebookOutput} and subclasses. * * @author Curtis Rueden */ public abstract class HTMLNotebookOutputConverter<I, O extends HTMLNotebookOutput> extends NotebookOutputConverter<I, O> { @Parameter private ConvertService convertService; /** Gets an HTML string representing the given object. */ protected String asHTML(final Object o) { return convertService.convert(o, HTMLFriendlyNotebookOutput.class).toHTML(); } }
Add python3 support in example
from __future__ import print_function from itertools import chain try: from itertools import imap except ImportError: # if python 3 imap = map import karld from karld.path import i_walk_csv_paths def main(): """ Consume many csv files as if one. """ import pathlib input_dir = pathlib.Path('test_data/things_kinds') # # Use a generator expression # iterables = (karld.io.i_get_csv_data(data_path) # for data_path in i_walk_csv_paths(str(input_dir))) # # or a generator map. iterables = imap(karld.io.i_get_csv_data, i_walk_csv_paths(str(input_dir))) items = chain.from_iterable(iterables) for item in items: print(item[0], item[1]) if __name__ == "__main__": main()
from __future__ import print_function from itertools import chain from itertools import imap import karld from karld.path import i_walk_csv_paths def main(): """ Consume many csv files as if one. """ import pathlib input_dir = pathlib.Path('test_data/things_kinds') # # Use a generator expression # iterables = (karld.io.i_get_csv_data(data_path) # for data_path in i_walk_csv_paths(str(input_dir))) # # or a generator map. iterables = imap(karld.io.i_get_csv_data, i_walk_csv_paths(str(input_dir))) items = chain.from_iterable(iterables) for item in items: print(item[0], item[1]) if __name__ == "__main__": main()
Add long_description to package metadata for display by PyPI
# encoding: utf-8 from setuptools import setup with open('README.md') as f: long_description = f.read() setup( name="django-minio-storage", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", long_description=long_description, long_description_content_type='text/markdown', author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage", packages=[ "minio_storage", "minio_storage/management/", "minio_storage/management/commands/", ], setup_requires=["setuptools_scm"], install_requires=["django>=1.11", "minio>=4.0.21"], extras_require={"test": ["coverage", "requests"]}, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Framework :: Django", ], )
# encoding: utf-8 from setuptools import setup setup( name="django-minio-storage", license="MIT", use_scm_version=True, description="Django file storage using the minio python client", author="Tom Houlé", author_email="tom@kafunsho.be", url="https://github.com/py-pa/django-minio-storage", packages=[ "minio_storage", "minio_storage/management/", "minio_storage/management/commands/", ], setup_requires=["setuptools_scm"], install_requires=["django>=1.11", "minio>=4.0.21"], extras_require={"test": ["coverage", "requests"]}, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Framework :: Django", ], )
Add some files to Legion
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool): """ Tool info for Legion (https://github.com/Alan32Liu/Principes). """ REQUIRED_PATHS = [ "legion-sv", "Legion.py", "__VERIFIER.c", "__VERIFIER_assume.c", "__VERIFIER_assume.instr.s", "__trace_jump.s", "__trace_buffered.c", "tracejump.py", "lib", ] def executable(self): return util.find_executable("legion-sv") def version(self, executable): return self._version_from_tool(executable) def name(self): return "Legion"
""" BenchExec is a framework for reliable benchmarking. This file is part of BenchExec. Copyright (C) 2007-2015 Dirk Beyer All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool): """ Tool info for Legion (https://github.com/Alan32Liu/Principes). """ REQUIRED_PATHS = [ "legion-sv", "Legion.py", "__VERIFIER.c", "__trace_jump.s", "tracejump.py", "lib", ] def executable(self): return util.find_executable("legion-sv") def version(self, executable): return self._version_from_tool(executable) def name(self): return "Legion"
Make the basicflatmap example be a wordcount example
/** * Illustrates a simple flatMap in Java to extract the words */ package com.oreilly.learningsparkexamples.java; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; public class BasicFlatMap { public static void main(String[] args) throws Exception { if (args.length != 2) { throw new Exception("Usage BasicFlatMap sparkMaster inputFile"); } JavaSparkContext sc = new JavaSparkContext( args[0], "basicflatmap", System.getenv("SPARK_HOME"), System.getenv("JARS")); JavaRDD<String> rdd = sc.textFile(args[1]); JavaRDD<String> words = rdd.flatMap( new FlatMapFunction<String, String>() { public Iterable<String> call(String x) { return Arrays.asList(x.split(" ")); }}); Map<String, Long> result = words.countByValue(); for (Entry<String, Long> entry: result.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } }
/** * Illustrates a simple flatMap in Java to extract the words */ package com.oreilly.learningsparkexamples.java; import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; public class BasicFlatMap { public static void main(String[] args) throws Exception { if (args.length != 2) { throw new Exception("Usage BasicFlatMap sparkMaster inputFile"); } JavaSparkContext sc = new JavaSparkContext( args[0], "basicflatmap", System.getenv("SPARK_HOME"), System.getenv("JARS")); JavaRDD<String> rdd = sc.textFile(args[1]); JavaRDD<String> result = rdd.flatMap( new FlatMapFunction<String, String>() { public Iterable<String> call(String x) { return Arrays.asList(x.split(" ")); }}); System.out.println(StringUtils.join(result.collect(), ",")); } }
Make log `touch` error more human-readable.
'use strict'; const mkdirp = require('mkdirp'); const path = require('path'); const pify = require('pify'); const touch = require('touch'); const winston = require('winston'); /** * @module service/logger * * {@link https://www.npmjs.com/package/winston} */ /** * Log file directory. * * @const {string} */ const LOG_DIR = '/var/log/coinstac'; /** * Log file name. * * @const {string} */ const LOG_BASE = 'application.log'; /** * Logger instance. * * @type {winston.Logger} */ const logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true, level: 'info', }), ], }); /** * Set up file transport async. If an error occurs the executable will catch the * unhandled rejection and shut the server down. */ pify(mkdirp)(LOG_DIR) .then(() => pify(touch)(path.join(LOG_DIR, LOG_BASE))) .catch(() => { throw new Error( `Couldn't create log file: ${path.join(LOG_DIR, LOG_BASE)}` ); }) .then(() => { logger.add(winston.transports.File, { filename: path.join(LOG_DIR, LOG_BASE), level: 'silly', silent: false, }); }); module.exports = logger;
'use strict'; const mkdirp = require('mkdirp'); const path = require('path'); const pify = require('pify'); const touch = require('touch'); const winston = require('winston'); /** * @module service/logger * * {@link https://www.npmjs.com/package/winston} */ /** * Log file directory. * * @const {string} */ const LOG_DIR = '/var/log/coinstac'; /** * Log file name. * * @const {string} */ const LOG_BASE = 'application.log'; /** * Logger instance. * * @type {winston.Logger} */ const logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true, level: 'info', }), ], }); /** * Set up file transport async. If an error occurs the executable will catch the * unhandled rejection and shut the server down. */ pify(mkdirp)(LOG_DIR) .then(() => { return new Promise((resolve, reject) => { touch(path.join(LOG_DIR, LOG_BASE), error => { if (error) { reject(error); } else { resolve(); } }); }); }) .then(() => { logger.add(winston.transports.File, { filename: path.join(LOG_DIR, LOG_BASE), level: 'silly', silent: false, }); }); module.exports = logger;
Update the example test suite
from seleniumbase import BaseCase class MyTestSuite(BaseCase): def test_1(self): self.open("http://xkcd.com/1663/") self.find_text("Garden", "div#ctitle", timeout=3) for p in xrange(4): self.click('a[rel="next"]') self.find_text("Algorithms", "div#ctitle", timeout=3) def test_2(self): # This test will fail self.open("http://xkcd.com/1675/") raise Exception("FAKE EXCEPTION: This test fails on purpose.") def test_3(self): self.open("http://xkcd.com/1406/") self.find_text("Universal Converter Box", "div#ctitle", timeout=3) self.open("http://xkcd.com/608/") self.find_text("Form", "div#ctitle", timeout=3) def test_4(self): # This test will fail self.open("http://xkcd.com/1670/") self.find_element("FakeElement.DoesNotExist", timeout=0.5)
from seleniumbase import BaseCase class MyTestSuite(BaseCase): def test_1(self): self.open("http://xkcd.com/1663/") for p in xrange(4): self.click('a[rel="next"]') self.find_text("Algorithms", "div#ctitle", timeout=3) def test_2(self): # This test will fail self.open("http://xkcd.com/1675/") raise Exception("FAKE EXCEPTION: This test fails on purpose.") def test_3(self): self.open("http://xkcd.com/1406/") self.find_text("Universal Converter Box", "div#ctitle", timeout=3) self.open("http://xkcd.com/608/") self.find_text("Form", "div#ctitle", timeout=3) def test_4(self): # This test will fail self.open("http://xkcd.com/1670/") self.find_element("FakeElement.DoesNotExist", timeout=0.5)