text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Make sure tests don't fail when integration tests not loaded
<?php namespace { require __DIR__.'/../vendor/autoload.php'; } namespace Cache\IntegrationTests { // PSR-6 integration tests if (!class_exists('Cache\IntegrationTests\CachePoolTest')) { class CachePoolTest extends \PHPUnit_Framework_TestCase { public function testIncomplete() { $this->markTestIncomplete( 'Missing dependencies. Please run: '. 'composer require --dev cache/integration-tests:dev-master' ); } } } // PSR-16 integration tests if (!class_exists('Cache\IntegrationTests\SimpleCacheTest')) { class SimpleCacheTest extends \PHPUnit_Framework_TestCase { public function testIncomplete() { $this->markTestIncomplete( 'Missing dependencies. Please run: '. 'composer require --dev cache/integration-tests:dev-master' ); } } } }
<?php namespace { require __DIR__.'/../vendor/autoload.php'; } namespace Cache\IntegrationTests { if (!class_exists('Cache\IntegrationTests\CachePoolTest')) { class CachePoolTest extends \PHPUnit_Framework_TestCase { public function testIncomplete() { $this->markTestIncomplete( 'Missing dependencies. Please run: '. 'composer require --dev cache/integration-tests:dev-master' ); } } } }
Use more descriptive example passphrase
<?php // A very simple helper script used to generate self-signed certificates. // Accepts the CN and an optional passphrase to encrypt the private key. // // $ php examples/99-generate-self-signed.php localhost my-secret-passphrase > secret.pem // certificate details (Distinguished Name) // (OpenSSL applies defaults to missing fields) $dn = array( "commonName" => isset($argv[1]) ? $argv[1] : "localhost", // "countryName" => "AU", // "stateOrProvinceName" => "Some-State", // "localityName" => "London", // "organizationName" => "Internet Widgits Pty Ltd", // "organizationalUnitName" => "R&D", // "emailAddress" => "admin@example.com" ); // create certificate which is valid for ~10 years $privkey = openssl_pkey_new(); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 3650); // export public and (optionally encrypted) private key in PEM format openssl_x509_export($cert, $out); echo $out; $passphrase = isset($argv[2]) ? $argv[2] : null; openssl_pkey_export($privkey, $out, $passphrase); echo $out;
<?php // A very simple helper script used to generate self-signed certificates. // Accepts the CN and an optional passphrase to encrypt the private key. // // $ php examples/99-generate-self-signed.php localhost swordfish > secret.pem // certificate details (Distinguished Name) // (OpenSSL applies defaults to missing fields) $dn = array( "commonName" => isset($argv[1]) ? $argv[1] : "localhost", // "countryName" => "AU", // "stateOrProvinceName" => "Some-State", // "localityName" => "London", // "organizationName" => "Internet Widgits Pty Ltd", // "organizationalUnitName" => "R&D", // "emailAddress" => "admin@example.com" ); // create certificate which is valid for ~10 years $privkey = openssl_pkey_new(); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 3650); // export public and (optionally encrypted) private key in PEM format openssl_x509_export($cert, $out); echo $out; $passphrase = isset($argv[2]) ? $argv[2] : null; openssl_pkey_export($privkey, $out, $passphrase); echo $out;
ESLint: Allow async functions in tests
module.exports = { parserOptions: { 'ecmaVersion': 2017, }, env: { 'embertest': true }, extends: [ 'eslint:recommended', 'plugin:ember-suave/recommended' ], globals: { '$': true, 'addOfflineUsersForElectron': true, 'attachCustomForm': true, 'authenticateUser': true, 'checkCustomFormIsDisplayed': true, 'checkCustomFormIsFilled': true, 'checkCustomFormIsFilledAndReadonly': true, 'createCustomFormForType': true, 'fillCustomForm': true, 'invalidateSession': true, 'require': true, 'runWithPouchDump': true, 'select': true, 'selectDate': true, 'typeAheadFillIn': true, 'wait': true, 'waitToAppear': true, 'waitToDisappear': true }, rules: { 'camelcase': 0, 'ember-suave/no-direct-property-access': 0, 'ember-suave/require-access-in-comments': 0, 'no-console': 0 } };
module.exports = { env: { 'embertest': true }, extends: [ 'eslint:recommended', 'plugin:ember-suave/recommended' ], globals: { '$': true, 'addOfflineUsersForElectron': true, 'attachCustomForm': true, 'authenticateUser': true, 'checkCustomFormIsDisplayed': true, 'checkCustomFormIsFilled': true, 'checkCustomFormIsFilledAndReadonly': true, 'createCustomFormForType': true, 'fillCustomForm': true, 'invalidateSession': true, 'require': true, 'runWithPouchDump': true, 'select': true, 'selectDate': true, 'typeAheadFillIn': true, 'wait': true, 'waitToAppear': true, 'waitToDisappear': true }, rules: { 'camelcase': 0, 'ember-suave/no-direct-property-access': 0, 'ember-suave/require-access-in-comments': 0, 'no-console': 0 } };
Fix the invalid use of Link component
import React from 'react' import classnames from 'classnames' import classes from './Users.scss' import { userPoolId } from 'utils/settings' export default class Users extends React.Component { render () { const region = userPoolId.match(/^[a-z0-9-]+/) if (!region) { console.warn('user pool id has unexpected format:', region) } const linkToUsersPage = `https://${region}.console.aws.amazon.com/cognito/users?region=${region}#/pool/${userPoolId}/users` return (<div className={classnames(classes.layout, 'mdl-grid')}> <div className='mdl-cell mdl-cell--12-col'> <h4>Users</h4> </div> <div className='mdl-cell mdl-cell--12-col'> Operations like creating a user are not supported here. Access <a href={linkToUsersPage} className={classes.link}> Users page at Amazon Cognito </a> for these operations. </div> </div>) } }
import React from 'react' import classnames from 'classnames' import { Link } from 'react-router' import classes from './Users.scss' import { userPoolId } from 'utils/settings' export default class Users extends React.Component { render () { const region = userPoolId.match(/^[a-z0-9-]+/) if (!region) { console.warn('user pool id has unexpected format:', region) } const linkToUsersPage = `https://${region}.console.aws.amazon.com/cognito/users?region=${region}#/pool/${userPoolId}/users` return (<div className={classnames(classes.layout, 'mdl-grid')}> <div className='mdl-cell mdl-cell--12-col'> <h4>Users</h4> </div> <div className='mdl-cell mdl-cell--12-col'> Operations like creating a user are not supported here. Access <Link to={linkToUsersPage} className={classes.link}> Users page at Amazon Cognito </Link> for these operations. </div> </div>) } }
Revert "remove redundatn end points" This reverts commit 4703d26683e4b58510ff25c112dbf2a7fef8b689.
var local = 'http://localhost:55881' var dev = 'https://dev-api-streetsupport.azurewebsites.net' var staging = 'https://staging-api-streetsupport.azurewebsites.net' var live = 'https://live-api-streetsupport.azurewebsites.net' var env = require('./env') var envs = [local, dev, staging, live] var domainRoot = envs[env] var p = function (url) { return domainRoot + url } module.exports = { serviceProviders: p('/v2/service-providers/'), allServiceProviders: p('/v1/all-service-providers/'), serviceCategories: p('/v2/service-categories/'), categoryServiceProviders: p('/v2/categorised-service-providers/show/'), categoryServiceProvidersByDay: p('/v2/timetabled-service-providers/show/'), organisation: p('/v2/service-providers/show/'), needs: p('/v1/service-provider-needs/'), createVolunteerEnquiry: p('/v1/volunteer-enquiries/'), createOfferOfItems: p('/v1/offers-of-items/'), joinStreetSupportApplications: p('/v1/join-street-support-applications/'), offerSponsorship: p('/v1/sponsorship-offers/'), servicesByCategory: p('/v2/service-categories/'), newlyRegisteredProviders: p('/v1/newly-registered-providers'), cities: p('/v1/cities/') }
var local = 'http://localhost:55881' var dev = 'https://dev-api-streetsupport.azurewebsites.net' var staging = 'https://staging-api-streetsupport.azurewebsites.net' var live = 'https://live-api-streetsupport.azurewebsites.net' var env = require('./env') var envs = [local, dev, staging, live] var domainRoot = envs[env] var p = function (url) { return domainRoot + url } module.exports = { serviceProviders: p('/v2/service-providers/'), allServiceProviders: p('/v1/all-service-providers/'), serviceCategories: p('/v2/service-categories/'), organisation: p('/v2/service-providers/show/'), needs: p('/v1/service-provider-needs/'), createVolunteerEnquiry: p('/v1/volunteer-enquiries/'), createOfferOfItems: p('/v1/offers-of-items/'), joinStreetSupportApplications: p('/v1/join-street-support-applications/'), offerSponsorship: p('/v1/sponsorship-offers/'), servicesByCategory: p('/v2/service-categories/'), newlyRegisteredProviders: p('/v1/newly-registered-providers'), cities: p('/v1/cities/') }
Add example of using the getCurrentUser method in JS API Pop up a warning when the current user tries to submit another user's change. Bug: issue 461 Change-Id: I4a4c39093d07000ba1c9bc7d6da05e48815f603f
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Gerrit.install(function(self) { function onShowChange(c, r) { console.log("Show change: " + c.id + ", revision: " + r.name); } function onSubmitSomeoneElsesChange(c, r) { var u = self.getCurrentUser(); if (u._account_id != c.owner._account_id) { return confirm("Really submit change:\n" + c.id + "\n" + "revision: " + r.name + "\n" + "from: " + c.owner.name + "?"); } return true; } function onHistory(t) { console.log("History: " + t); } Gerrit.on('showchange', onShowChange); Gerrit.on('submitchange', onSubmitSomeoneElsesChange); Gerrit.on('history', onHistory); });
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Gerrit.install(function(self) { function onShowChange(c, r) { console.log("Show change: " + c.id + ", revision: " + r.name); } function onSubmitChange(c, r) { return confirm("Really submit change:\n" + c.id + "\n" + "revision: " + r.name + "?"); } function onHistory(t) { console.log("History: " + t); } Gerrit.on('showchange', onShowChange); Gerrit.on('submitchange', onSubmitChange); Gerrit.on('history', onHistory); });
Add and track video-end time
$('video').each( function() { var video = this; var nodes = []; var time = 0; $('.videosync').not('video').each(function(){ var $this = $(this); $this.hide(); nodes.push({ start: this.getAttribute('data-videosync-start'), end: this.getAttribute('data-videosync-end'), element: $this, }); }); video.addEventListener('timeupdate',function(){ time = parseInt(video.currentTime); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if ((time >= node.start) && (node.end ? time < node.end : true)) { node.element.show(); } else if (((time < node.start) || (node.end ? time >= node.end : false))) { node.element.hide(); } } }, false); });
$('video').each( function() { var video = this; var nodes = []; var time = 0; $('.videosync').not('video').each(function(){ var $this = $(this); $this.hide(); nodes.push({ start: this.getAttribute('data-videosync-start'), end: this.getAttribute('data-videosync-end'), element: $this, }); }); video.addEventListener('timeupdate',function(){ time = parseInt(video.currentTime); for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (time >= node.start) { node.element.show(); } } }, false); });
Set SITE_ID=1 in tests (corresponds to that in the test fixtures)
import os, sys from django.conf import settings # -- Setup Django configuration appropriately TESTDIR = os.path.abspath(os.path.dirname(__file__)) settings.MODULE_DIR = TESTDIR settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh') settings.SITE_ID = 1 # The CSRF middleware prevents the Django test client from working, so # disable it. settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) try: settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.csrf.middleware.CsrfMiddleware') except IndexError: pass # -- Test cases from test_functional import * from test_docstring import * from test_toctreecache import * # -- Allow Django test command to find the script tests test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'tests') sys.path.append(test_dir) from test_pydoc_tool import *
import os, sys from django.conf import settings # -- Setup Django configuration appropriately TESTDIR = os.path.abspath(os.path.dirname(__file__)) settings.MODULE_DIR = TESTDIR settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh') # The CSRF middleware prevents the Django test client from working, so # disable it. settings.MIDDLEWARE_CLASSES = list(settings.MIDDLEWARE_CLASSES) try: settings.MIDDLEWARE_CLASSES.remove( 'django.contrib.csrf.middleware.CsrfMiddleware') except IndexError: pass # -- Test cases from test_functional import * from test_docstring import * from test_toctreecache import * # -- Allow Django test command to find the script tests test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'tests') sys.path.append(test_dir) from test_pydoc_tool import *
Sort constant names alphabetically in docstring
""" Contains astronomical and physical constants for use in Astropy or other places. The package contains a `~astropy.constants.cgs` and `~astropy.constants.si` module that define constants in CGS and SI units, respectively. A typical use case might be:: from astropy.constants.cgs import c ... define the mass of something you want the rest energy of as m ... E = m*c**2 """ from . import cgs from . import si from .constant import Constant # Update the docstring to include a list of units from the si module __doc__ += """ The following constants are defined in `~astropy.constants.cgs` and `~astropy.constants.si` . """ for nm, val in sorted(si.__dict__.iteritems()): if isinstance(val, Constant): __doc__ += ' * ' + nm + '\n ' + val.name + '\n' del nm, val __doc__ += '\n'
""" Contains astronomical and physical constants for use in Astropy or other places. The package contains a `~astropy.constants.cgs` and `~astropy.constants.si` module that define constants in CGS and SI units, respectively. A typical use case might be:: from astropy.constants.cgs import c ... define the mass of something you want the rest energy of as m ... E = m*c**2 """ from . import cgs from . import si from .constant import Constant # Update the docstring to include a list of units from the si module __doc__ += """ The following constants are defined in `~astropy.constants.cgs` and `~astropy.constants.si` . """ for nm, val in si.__dict__.iteritems(): if isinstance(val, Constant): __doc__ += ' * ' + nm + '\n ' + val.name + '\n' del nm, val __doc__ += '\n'
Rename pin->pins; update serialized name
package com.chrisdempewolf.responses.pin; import com.google.gson.annotations.SerializedName; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Pins implements Iterable<Pin> { @SerializedName("data") private final List<Pin> pins; public Pins(Pin[] pins) { this.pins = Arrays.asList(pins); } @Override public Iterator<Pin> iterator() { return pins.iterator(); } public List<Pin> getPins() { return pins; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pins pins = (Pins) o; return !(this.pins != null ? !this.pins.equals(pins.pins) : pins.pins != null); } @Override public int hashCode() { return pins != null ? pins.hashCode() : 0; } @Override public String toString() { return "Pins{" + "pins=" + pins + '}'; } }
package com.chrisdempewolf.responses.pin; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class Pins implements Iterable<Pin> { private final List<Pin> pin; public Pins(Pin[] pin) { this.pin = Arrays.asList(pin); } @Override public Iterator<Pin> iterator() { return pin.iterator(); } public List<Pin> getPin() { return pin; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pins pins = (Pins) o; return !(pin != null ? !pin.equals(pins.pin) : pins.pin != null); } @Override public int hashCode() { return pin != null ? pin.hashCode() : 0; } @Override public String toString() { return "Pins{" + "pin=" + pin + '}'; } }
Create deletePost function and import/wire up deletePost action creator
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost, deletePost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } onDeleteClick() { const { id } = this.props.match.params; this.props.deletePost(id); } render() { const { post } = this.props; if (!post) { return (<div>Loading...</div>); } return( <div> <Link to="/">Back to Index</Link> <button className="btn btn-danger pull-xs-right" onClick={this.onDeleteClick.bind(this)} > Delete Post </button> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } render() { const { post } = this.props; if (!post) { return (<div>Loading...</div>); } return( <div> <Link to="/">Back to Index</Link> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost })(PostsShow);
Add Office and Technical Room to unit type
/* * * Copyright 2012-2014 Eurocommercial Properties NV * * * 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.estatio.dom.asset; import org.estatio.dom.TitledEnum; import org.estatio.dom.utils.StringUtils; public enum UnitType implements TitledEnum { BOUTIQUE, CINEMA, DEHOR, EXTERNAL, HYPERMARKET, MEDIUM, OFFICE, SERVICES, STORAGE, TECHNICAL_ROOM, VIRTUAL; public String title() { return StringUtils.enumTitle(name()); } }
/* * * Copyright 2012-2014 Eurocommercial Properties NV * * * 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.estatio.dom.asset; import org.estatio.dom.TitledEnum; import org.estatio.dom.utils.StringUtils; public enum UnitType implements TitledEnum { BOUTIQUE, STORAGE, MEDIUM, HYPERMARKET, EXTERNAL, DEHOR, CINEMA, SERVICES, VIRTUAL; public String title() { return StringUtils.enumTitle(name()); } }
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-type-scale/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-type-scale/tachyons-type-scale.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_type-scale.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/type-scale/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/scale/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-type-scale/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-type-scale/tachyons-type-scale.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_type-scale.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/type-scale/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/scale/index.html', html)
Exclude environment variables which are not defined
var util = require('util'); var DECLARATION = 'window.__env__ = window.__env__ || {};\n', TEMPLATE = function(name) { if (typeof process.env[name] !== 'undefined') { var tmpl = 'window.__env__[\'%s\'] = %s;\n'; return util.format(tmpl, name, process.env[name]); } else { return ''; } }; var createEnvPreprocessor = function(args, config, logger, helper) { var log = logger.create('preprocessor.env'), names = config.envPreprocessor || []; log.info('Publishing variables: ', names); return function(content, file, done) { var envContent = DECLARATION; for (var i in names) { envContent += TEMPLATE(names[i]); } done(envContent + '\n' + content); }; }; module.exports = { 'preprocessor:env': ['factory', createEnvPreprocessor] };
var util = require('util'); var DECLARATION = 'window.__env__ = window.__env__ || {};\n', TEMPLATE = function(name) { var tmpl = 'window.__env__[\'%s\'] = \'%s\';\n' return util.format(tmpl, name, process.env[name]); }; var createEnvPreprocessor = function(args, config, logger, helper) { var log = logger.create('preprocessor.env'), names = config.envPreprocessor || []; log.info('Publishing variables: ', names); return function(content, file, done) { var envContent = DECLARATION; for (var i in names) { envContent += TEMPLATE(names[i]); } done(envContent + '\n' + content); }; }; module.exports = { 'preprocessor:env': ['factory', createEnvPreprocessor] };
Fix error in element name for showing unauthorized alert using jQuery
/** * Created by Omnius on 6/27/16. */ const submitForm = () => { // TODO: Supposedly needs sanitation using ESAPI.encoder().encodeForJavascript() or some other sanitation // mechanism on inputUsername and inputPassword const username = $('#inputUsername').val(); const password = $('#inputPassword').val(); $.ajax({ type: 'GET', beforeSend: function (request) { request.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password)); }, url: '/auth/basic', processData: false, success: function(data, textStatus, jQxhr){ $('#formLogin').attr('action', '/user/welcome'); $('#formLogin').submit(); }, error: function (xhr, textStatus, errorThrown) { if (xhr.status === 401) { $('#alertUnauthorized').removeClass('hidden'); } } }); };
/** * Created by Omnius on 6/27/16. */ const submitForm = () => { // TODO: Supposedly needs sanitation using ESAPI.encoder().encodeForJavascript() or some other sanitation // mechanism on inputUsername and inputPassword const username = $('#inputUsername').val(); const password = $('#inputPassword').val(); $.ajax({ type: 'GET', beforeSend: function (request) { request.setRequestHeader('Authorization', 'Basic ' + btoa(username + ':' + password)); }, url: '/auth/basic', processData: false, success: function(data, textStatus, jQxhr){ $('#formLogin').attr('action', '/user/welcome'); $('#formLogin').submit(); }, error: function (xhr, textStatus, errorThrown) { if (xhr.status === 401) { $('#formUnauthorized').removeClass('hidden'); } } }); };
Update ServiceProvider & build tools
<?php namespace Onderdelen\Dashboard; use Illuminate\Support\ServiceProvider; class DashboardServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
<?php namespace Dashboard; use Illuminate\Support\ServiceProvider; class DashboardServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { // } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
Delete not needed nested block
/* * This file is part of the WordPress Standard project. * * Copyright (c) 2015-2016 LIN3S <info@lin3s.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Gorka Laucirica <gorka.lauzirika@gmail.com> * @author Beñat Espiña <bespina@lin3s.com> */ 'use strict'; (function ($) { var $allLinks = $('a, button, .cookies__actions .button'), $window = $(window), scrollTop = 400; if (!localStorage.getItem('cookies')) { $('.cookies').addClass('cookies--visible'); } function acceptCookies() { localStorage.setItem('cookies', true); $('.cookies').removeClass('cookies--visible'); } $allLinks.click(function () { acceptCookies(); }); $window.on('scroll', function () { if (typeof window.requestAnimationFrame !== 'undefined') { if ($(this).scrollTop() > scrollTop) { window.requestAnimationFrame(acceptCookies); } } else if ($(this).scrollTop() > scrollTop) { acceptCookies(); } }); }(jQuery));
/* * This file is part of the WordPress Standard project. * * Copyright (c) 2015-2016 LIN3S <info@lin3s.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author Gorka Laucirica <gorka.lauzirika@gmail.com> * @author Beñat Espiña <bespina@lin3s.com> */ 'use strict'; (function ($) { var $allLinks = $('a, button, .cookies__actions .button'), $window = $(window), scrollTop = 400; if (!localStorage.getItem('cookies')) { $('.cookies').addClass('cookies--visible'); } function acceptCookies() { localStorage.setItem('cookies', true); $('.cookies').removeClass('cookies--visible'); } $allLinks.click(function () { acceptCookies(); }); $window.on('scroll', function () { if (typeof window.requestAnimationFrame !== 'undefined') { if ($(this).scrollTop() > scrollTop) { window.requestAnimationFrame(acceptCookies); } } else { if ($(this).scrollTop() > scrollTop) { acceptCookies(); } } }); }(jQuery));
Reorder action functions: no functional change
function setCurrentUser(currentUser) { return { type: 'SET_CURRENT_USER', currentUser, }; } function clearCurrentUser() { return { type: 'CLEAR_CURRENT_USER', }; } function setCurrentPerms(currentPerms) { return { type: 'SET_CURRENT_PERMS', currentPerms, }; } function setLocale(locale) { return { type: 'SET_LOCALE', locale, }; } function setOkapiToken(token) { return { type: 'SET_OKAPI_TOKEN', token, }; } function clearOkapiToken() { return { type: 'CLEAR_OKAPI_TOKEN', }; } function authFailure() { return { type: 'AUTH_FAILURE', }; } function clearAuthFailure() { return { type: 'CLEAR_AUTH_FAILURE', }; } export { setCurrentUser, clearCurrentUser, setCurrentPerms, setLocale, setOkapiToken, clearOkapiToken, authFailure, clearAuthFailure };
function setCurrentUser(currentUser) { return { type: 'SET_CURRENT_USER', currentUser, }; } function setCurrentPerms(currentPerms) { return { type: 'SET_CURRENT_PERMS', currentPerms, }; } function clearCurrentUser() { return { type: 'CLEAR_CURRENT_USER', }; } function setLocale(locale) { return { type: 'SET_LOCALE', locale, }; } function setOkapiToken(token) { return { type: 'SET_OKAPI_TOKEN', token, }; } function clearOkapiToken() { return { type: 'CLEAR_OKAPI_TOKEN', }; } function authFailure() { return { type: 'AUTH_FAILURE', }; } function clearAuthFailure() { return { type: 'CLEAR_AUTH_FAILURE', }; } export { setCurrentUser, setCurrentPerms, setLocale, clearCurrentUser, setOkapiToken, clearOkapiToken, authFailure, clearAuthFailure };
Add more fields to the DrawingInstructions
package svg // InstructionType tells our path drawing library which function it has // to call type InstructionType int // These are instruction types that we use with our path drawing library const ( PathInstruction InstructionType = iota MoveInstruction CircleInstruction CurveInstruction LineInstruction HLineInstruction CloseInstruction ) // DrawingInstruction contains enough information that a simple drawing // library can draw the shapes contained in an SVG file. // // The struct contains all necessary fields but only the ones needed (as // indicated byt the InstructionType) will be non-nil. type DrawingInstruction struct { Kind InstructionType M *Tuple C1 *Tuple C2 *Tuple T *Tuple Radius *float64 StrokeWidth *float64 Fill *string Stroke *string }
package svg // InstructionType tells our path drawing library which function it has // to call type InstructionType int // These are instruction types that we use with our path drawing library const ( PathInstruction InstructionType = iota MoveInstruction CircleInstruction CurveInstruction LineInstruction HLineInstruction CloseInstruction ) // DrawingInstruction contains enough information that a simple drawing // library can draw the shapes contained in an SVG file. // // The struct contains all necessary fields but only the ones needed (as // indicated byt the InstructionType) will be non-nil. type DrawingInstruction struct { Kind InstructionType M *Tuple C1 *Tuple C2 *Tuple T *Tuple Radius *float64 Fill *string StrokeWidth *float64 }
Fix the order of parameters to hasAccess, which broke all topic changing when +t was set
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(targetChannel.name, self.ircd.servconfig["channel_minimum_level"]["TOPIC"]): user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, targetChannel.name, ":You do not have access to change the topic on this channel") return {} return data class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): if "channel_minimum_level" not in self.ircd.servconfig: self.ircd.servconfig["channel_minimum_level"] = {} if "TOPIC" not in self.ircd.servconfig["channel_minimum_level"]: self.ircd.servconfig["channel_minimum_level"]["TOPIC"] = "o" return { "modes": { "cnt": TopiclockMode() } } def cleanup(self): self.ircd.removeMode("cnt")
from twisted.words.protocols import irc from txircd.modbase import Mode class TopiclockMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "TOPIC": return data if "topic" not in data: return data targetChannel = data["targetchan"] if "t" in targetChannel.mode and not user.hasAccess(self.ircd.servconfig["channel_minimum_level"]["TOPIC"], targetChannel.name): user.sendMessage(irc.ERR_CHANOPRIVSNEEDED, targetChannel.name, ":You do not have access to change the topic on this channel") return {} return data class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): if "channel_minimum_level" not in self.ircd.servconfig: self.ircd.servconfig["channel_minimum_level"] = {} if "TOPIC" not in self.ircd.servconfig["channel_minimum_level"]: self.ircd.servconfig["channel_minimum_level"]["TOPIC"] = "o" return { "modes": { "cnt": TopiclockMode() } } def cleanup(self): self.ircd.removeMode("cnt")
Fix bug when unloading/disabling add-on Bug reported by umage: Trying to unload/disable the add-on with one of its windows still open would freeze Firefox and render it unable to quit other than by killing the process. Now, we preemptively close all our windows on unload.
/* 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/. */ const { Windows } = require("./util/windows"); const { windowMediator } = require("./util/functions"); const system = require("sdk/system"); const extensionPrefs = require("sdk/simple-prefs"); if (37 < system.version) { let domainUrlPattern = extensionPrefs.prefs['domainUrlPattern']; console.log("Firefox 38 or newer detected, checking URL Patterns"); console.log("URL Patterns: "+domainUrlPattern); if ("[\\\u0022*\\\u0022]" == domainUrlPattern) { console.warn("URL Patterns stored in old(cfx) format; correcting."); let domainUrlPattern = "[\"*\"]" console.log("URL Patterns (Corrected): "+domainUrlPattern); extensionPrefs.prefs['domainUrlPattern'] = domainUrlPattern; } } require("./patch/bug-78414"); exports.main = function(options, callbacks) { Windows.addEventListener("keydown", Windows.handleKeyPress); }; exports.onUnload = function(reason) { if (windowMediator.getMostRecentWindow("Keybinder:URLPatterns")) { windowMediator.getMostRecentWindow("Keybinder:URLPatterns").window.close(); } if (windowMediator.getMostRecentWindow("Keybinder:config")) { windowMediator.getMostRecentWindow("Keybinder:config").window.close(); } if (windowMediator.getMostRecentWindow("Keybinder:CustomXUL")) { windowMediator.getMostRecentWindow("Keybinder:CustomXUL").window.close(); } Windows.removeEventListener("keydown", Windows.handleKeyPress); };
/* 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/. */ const { Windows } = require("./util/windows"); const system = require("sdk/system"); const extensionPrefs = require("sdk/simple-prefs"); if (37 < system.version) { let domainUrlPattern = extensionPrefs.prefs['domainUrlPattern']; console.log("Firefox 38 or newer detected, checking URL Patterns"); console.log("URL Patterns: "+domainUrlPattern); if ("[\\\u0022*\\\u0022]" == domainUrlPattern) { console.warn("URL Patterns stored in old(cfx) format; correcting."); let domainUrlPattern = "[\"*\"]" console.log("URL Patterns (Corrected): "+domainUrlPattern); extensionPrefs.prefs['domainUrlPattern'] = domainUrlPattern; } } require("./patch/bug-78414"); exports.main = function(options, callbacks) { Windows.addEventListener("keydown", Windows.handleKeyPress); }; exports.onUnload = function(reason) { Windows.removeEventListener("keydown", Windows.handleKeyPress); };
Use data from controller instead of querying in the view; Lowercase team name for detail page
@extends('layouts/app') @section('title') Teams | {{ config('app.name') }} @endsection @section('content') @component('layouts/title') Teams @endcomponent <div class="row"> @foreach ($teams as $team) <div class="col-xs-12 col-sm-6 col-md-4"> <div class="card card-teams"> <div class="card-body"> <h5 class="card-title"><b>{{ $team->name }}</b></h5> <p class="card-text">{{ $team->short_description }}</p> <a href="{{ route('teams.show', strtolower($team->name)) }}" class="btn btn-primary">More Info</a> </div> </div> </div> @endforeach </div> @endsection
@extends('layouts/app') @section('title') Teams | {{ config('app.name') }} @endsection @section('content') @component('layouts/title') Teams @endcomponent <div class="row"> @foreach (\App\Team::visible()->orderBy('name', 'asc')->get() as $team) <div class="col-xs-12 col-sm-6 col-md-4"> <div class="card card-teams"> <div class="card-body"> <h5 class="card-title"><b>{{ $team->name }}</b></h5> <p class="card-text">{{ $team->short_description }}</p> <a href="{{ route('teams.show', $team->id) }}" class="btn btn-primary">More Info</a> </div> </div> </div> @endforeach </div> @endsection
Use http instead of https
# Copyright 2014-2019 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds functionality for generating printable documents using LibreOffice and the `appy.pod <http://appyframework.org/pod.html>`__ package. See also :ref:`lino.admin.appypod` and :doc:`/specs/appypod`. """ import six from lino.api import ad, _ class Plugin(ad.Plugin): verbose_name = _("Appy POD") def get_requirements(self, site): try: import appy # leave unchanged if it is already installed except ImportError: if six.PY3: # yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" yield "svn+http://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" else: yield "appy" def get_used_libs(self, html=None): try: # ~ import appy from appy import version version = version.verbose except ImportError: version = self.site.not_found_msg yield ("Appy", version, "http://appyframework.org/pod.html")
# Copyright 2014-2019 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds functionality for generating printable documents using LibreOffice and the `appy.pod <http://appyframework.org/pod.html>`__ package. See also :ref:`lino.admin.appypod` and :doc:`/specs/appypod`. """ import six from lino.api import ad, _ class Plugin(ad.Plugin): verbose_name = _("Appy POD") def get_requirements(self, site): try: import appy # leave unchanged if it is already installed except ImportError: if six.PY3: # yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" yield "svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" else: yield "appy" def get_used_libs(self, html=None): try: # ~ import appy from appy import version version = version.verbose except ImportError: version = self.site.not_found_msg yield ("Appy", version, "http://appyframework.org/pod.html")
Add a length argument for InterleavingMethod.interleave and multileave
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, k, a, b): ''' k: the maximum length of resultant interleaving a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, k, *lists): ''' k: the maximum length of resultant multileaving *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
class InterleavingMethod(object): ''' Interleaving ''' def interleave(self, a, b): ''' a: a list of document IDs b: a list of document IDs Return an instance of Ranking ''' raise NotImplementedError() def multileave(self, *lists): ''' *lists: lists of document IDs Return an instance of Ranking ''' raise NotImplementedError() def evaluate(self, ranking, clicks): ''' ranking: an instance of Ranking generated by Balanced.interleave clicks: a list of indices clicked by a user Return one of the following tuples: - (1, 0): Ranking 'a' won - (0, 1): Ranking 'b' won - (0, 0): Tie ''' raise NotImplementedError()
Add handling for a closed entitymanager
package org.amc.dao; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceUnit; import org.apache.log4j.Logger; /** * Fetches and holds a reference to the Persistence EntityManager * @author adrian * */ public abstract class DAO { private static Logger logger=Logger.getLogger(DAO.class); private EntityManagerFactory emf; private EntityManager em; private final String PERSISTENCE_UNIT_NAME="myDatabase"; public DAO() { emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); em=emf.createEntityManager(); } @PersistenceUnit(name = PERSISTENCE_UNIT_NAME) public void setEm(EntityManager em) { logger.info("EntityManager set to "+em.toString()); this.em = em; } /** * * @return EntityManager for subclass to use */ protected EntityManager getEntityManager() { //Reopen the EntityManager if closed if(em!=null && !em.isOpen()) { em=emf.createEntityManager(); } return em; } @Override public void finalize() { //close EntityManager if(em!=null && em.isOpen()) em.close(); //close EntityManagerFactory if(emf!=null && emf.isOpen()) emf.close(); } }
package org.amc.dao; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceUnit; import org.apache.log4j.Logger; /** * Fetches and holds a reference to the Persistence EntityManager * @author adrian * */ public abstract class DAO { private static Logger logger=Logger.getLogger(DAO.class); private EntityManagerFactory emf; private EntityManager em; private final String PERSISTENCE_UNIT_NAME="myDatabase"; public DAO() { emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); em=emf.createEntityManager(); } @PersistenceUnit(name = PERSISTENCE_UNIT_NAME) public void setEm(EntityManager em) { logger.info("EntityManager set to "+em.toString()); this.em = em; } /** * * @return EntityManager for subclass to use */ protected EntityManager getEntityManager() { return em; } }
Fix tests to use HTTPS. PasteUtilTest.testGetPasteKeyFromUrl() used HTTP, not HTTPS.
package com.github.kennedyoliveira.pastebin4j.api; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; /** * @author Kennedy Oliveira */ public class PasteUtilTest { @Test public void testGetPasteKeyFromUrl() throws Exception { final String pasteBinUrl = "https://pastebin.com/NCSQ6k9N"; assertThat("NCSQ6k9N", is(equalTo(PasteUtil.getPasteKeyFromUrl(pasteBinUrl)))); } @Test public void testGetPasteKeyFromUrlNullCase() throws Exception { assertThat(PasteUtil.getPasteKeyFromUrl(null), is(nullValue())); } @Test public void testGetPasteKeyFromInvalidUrl() throws Exception { try { PasteUtil.getPasteKeyFromUrl("http//google.com"); fail("Should throwed IllegalArgumentException"); } catch (Exception e) { } } }
package com.github.kennedyoliveira.pastebin4j.api; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; /** * @author Kennedy Oliveira */ public class PasteUtilTest { @Test public void testGetPasteKeyFromUrl() throws Exception { final String pasteBinUrl = "http://pastebin.com/NCSQ6k9N"; assertThat("NCSQ6k9N", is(equalTo(PasteUtil.getPasteKeyFromUrl(pasteBinUrl)))); } @Test public void testGetPasteKeyFromUrlNullCase() throws Exception { assertThat(PasteUtil.getPasteKeyFromUrl(null), is(nullValue())); } @Test public void testGetPasteKeyFromInvalidUrl() throws Exception { try { PasteUtil.getPasteKeyFromUrl("http//google.com"); fail("Should throwed IllegalArgumentException"); } catch (Exception e) { } } }
Add handling of invalid values Values that are not defined in the data dictionary will be replaced by None.
import pandas as pd from .datadicts import diary def read_diary_file(path_to_file): return pd.read_csv( path_to_file, delimiter='\t', converters=_column_name_to_type_mapping(diary), low_memory=False # some columns seem to have mixed types ) def _column_name_to_type_mapping(module): mapping = {} for member in module.Variable: try: module.__dict__[member.name] mapping[member.name] = _enum_converter(module.__dict__[member.name]) except KeyError: pass # nothing to do; there is no enum return mapping def _enum_converter(enumcls): def enum_converter(value): if value == ' ': return None else: try: value = enumcls(value) except ValueError as ve: print(ve) return None else: return value return enum_converter
import pandas as pd from .datadicts import diary def read_diary_file(path_to_file): return pd.read_csv( path_to_file, delimiter='\t', nrows=50, converters=_column_name_to_type_mapping(diary), low_memory=False # some columns seem to have mixed types ) def _column_name_to_type_mapping(module): mapping = {} for member in module.Variable: try: module.__dict__[member.name] mapping[member.name] = _enum_converter(module.__dict__[member.name]) except KeyError: pass # nothing to do; there is no enum return mapping def _enum_converter(enumcls): def enum_converter(value): if value == ' ': return None else: return enumcls(value) return enum_converter
SimPreconstrainedFileStream: Fix a bug that leads to failures in pickling.
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def __getstate__(self): d = super().__getstate__() d['preconstraining_handler'] = None return d
from angr.state_plugins.plugin import SimStatePlugin from angr.storage.file import SimFileStream class SimPreconstrainedFileStream(SimFileStream): def __init__(self, name, preconstraining_handler=None, **kwargs): super().__init__(name, **kwargs) self.preconstraining_handler = preconstraining_handler self._attempted_preconstraining = False def read(self, pos, size, **kwargs): if not self._attempted_preconstraining: self._attempted_preconstraining = True self.preconstraining_handler(self) return super().read(pos, size, **kwargs) @SimStatePlugin.memo def copy(self, memo): copied = super().copy(memo) copied.preconstraining_handler = self.preconstraining_handler copied._attempted_preconstraining = self._attempted_preconstraining return copied
Fix missing ref from hop db
class HopDB(object): def __init__(self): super(HopDB, self).__init__() self.hops = {} # prefix -> hop self.installed_prefix = [] def add_hop(self, prefix, next_hop): self.hops.setdefault(prefix, next_hop) def get_nexthop(self, prefix): self.hops.get(prefix) def is_prefix_installed(self, prefix): return (prefix in self.installed_prefix) def get_uninstalled_prefix_list(self): result = [prefix for prefix in self.hops.keys() if (prefix not in self.installed_prefix)] return result def install_prefix(self, prefix): self.installed_prefix.append(prefix) def get_all_prefixes(self): return self.hops.keys()
class HopDB(object): def __init__(self): super(HopDB, self).__init__() self.hops = {} # prefix -> hop self.installed_prefix = [] def add_hop(self, prefix, next_hop): self.hops.setdefault(prefix, next_hop) def get_nexthop(self, prefix): self.hops.get(prefix) def is_prefix_installed(self, prefix): return (prefix in self.installed_prefix) def get_uninstalled_prefix_list(self): result = [prefix for prefix in self.hops.keys() if (prefix not in self.installed_prefix)] return result def install_prefix(self, prefix): self.installed_prefix.append(prefix) def get_all_prefixes(self): return hops.keys()
Include name field in range form
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled', 'name') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
from django import forms from cyder.base.eav.forms import get_eav_form from cyder.base.mixins import UsabilityFormMixin from cyder.cydhcp.range.models import Range, RangeAV from cyder.cydns.forms import ViewChoiceForm class RangeForm(ViewChoiceForm, UsabilityFormMixin): class Meta: model = Range exclude = ('start_upper', 'start_lower', 'end_upper', 'end_lower') fields = ('network', 'ip_type', 'range_type', 'start_str', 'end_str', 'domain', 'is_reserved', 'allow', 'views', 'dhcpd_raw_include', 'dhcp_enabled') widgets = {'views': forms.CheckboxSelectMultiple, 'range_type': forms.RadioSelect, 'ip_type': forms.RadioSelect} exclude = 'range_usage' def __init__(self, *args, **kwargs): super(RangeForm, self).__init__(*args, **kwargs) self.fields['dhcpd_raw_include'].label = "DHCP Config Extras" self.fields['dhcpd_raw_include'].widget.attrs.update( {'cols': '80', 'style': 'display: none;width: 680px'}) RangeAVForm = get_eav_form(RangeAV, Range)
Fix confirmation page id again.
@extends('layouts.default') @section('content') <h1>Successfully created "{{ $sprint->title }}"</h1> <ul> <li> {{ link_to( $_ENV['PHABRICATOR_URL'] . 'project/view/' . $sprint->phabricator_id, $sprint->title . ' on Phabricator' ) }} </li> <li> {{ link_to_route( 'sprint_path', $sprint->title . ' on Phragile', $sprint->phabricator_id ) }} </li> <li> {{ link_to_route( 'project_path', $sprint->project->title . ' on Phragile', $sprint->project->slug ) }} </li> </ul> @stop
@extends('layouts.default') @section('content') <h1>Successfully created "{{ $sprint->title }}"</h1> <ul> <li> {{ link_to( $_ENV['PHABRICATOR_URL'] . 'project/view/' . $sprint->phabricator_id, $sprint->title . ' on Phabricator' ) }} </li> <li> {{ link_to_route( 'sprint_path', $sprint->title . ' on Phragile', $sprint->phid ) }} </li> <li> {{ link_to_route( 'project_path', $sprint->project->title . ' on Phragile', $sprint->project->slug ) }} </li> </ul> @stop
Add capability to start test logging
package golog var Global *LevelLogger = &LevelLogger{ &loggerImpl{&defaultLogOuters, flag_minloglevel}, } func Info(vals ...interface{}) { Global.Info(vals...) } func Infof(f string, args ...interface{}) { Global.Infof(f, args...) } func Infoc(closure func() string) { Global.Warningc(closure) } func Warning(vals ...interface{}) { Global.Warning(vals...) } func Warningf(f string, args ...interface{}) { Global.Warningf(f, args...) } func Warningc(closure func() string) { Global.Errorc(closure) } func Error(vals ...interface{}) { Global.Error(vals...) } func Errorf(f string, args ...interface{}) { Global.Errorf(f, args...) } func Errorc(closure func() string) { Global.Errorc(closure) } func Fatal(vals ...interface{}) { Global.Fatal(vals...) } func Fatalf(f string, args ...interface{}) { Global.Fatalf(f, args...) } func Fatalc(closure func() string) { Global.Fatalc(closure) } func StartTestLogging(t TestController) { defaultLogOuters.AddLogOuter("testing", NewTestLogOuter(t)) } func StopTestLogging() { defaultLogOuters.RemoveLogOuter("testing") }
package golog var Global *LevelLogger = &LevelLogger{ &loggerImpl{&defaultLogOuters, flag_minloglevel}, } func Info(vals ...interface{}) { Global.Info(vals...) } func Infof(f string, args ...interface{}) { Global.Infof(f, args...) } func Infoc(closure func() string) { Global.Warningc(closure) } func Warning(vals ...interface{}) { Global.Warning(vals...) } func Warningf(f string, args ...interface{}) { Global.Warningf(f, args...) } func Warningc(closure func() string) { Global.Errorc(closure) } func Error(vals ...interface{}) { Global.Error(vals...) } func Errorf(f string, args ...interface{}) { Global.Errorf(f, args...) } func Errorc(closure func() string) { Global.Errorc(closure) } func Fatal(vals ...interface{}) { Global.Fatal(vals...) } func Fatalf(f string, args ...interface{}) { Global.Fatalf(f, args...) } func Fatalc(closure func() string) { Global.Fatalc(closure) }
Update to ES6 for fun
'use strict'; const fs = require('fs'); const through = require('through'); // File input & output given as arguments const from = process.argv[2]; const to = process.argv[3]; // Benchmarking const startTime = Date.now(); // Raise the buffer limits const streamOpts = {highWaterMark: Math.pow(2, 16)}; // Create file streams var source = fs.createReadStream(__dirname + '/' + from, streamOpts); var destination = fs.createWriteStream(__dirname + '/' + to, streamOpts); // Pipe data from read-stream to write- and end-functions source.pipe(through(write, end)); /** * Write buffer data to file * @param {Buffer} buf Buffer of a readable stream's data */ function write (buf) { destination.write(parse(buf)); } /** * Parse buffer data. * Replaces semicolons with commas. * @param {Buffer} buf Buffer of a readable stream's data * @return {String} Parsed Buffer as a String */ function parse (buf) { return buf.toString().replace(/;/g, ','); } /** * Finished writing */ function end () { console.log('Finished parsing'); console.log(`Parsing took (ms): ${(Date.now() - startTime)}`); }
var fs = require('fs'); var through = require('through'); // File input & output given as arguments var from = process.argv[2]; var to = process.argv[3]; // Benchmarking var startTime = Date.now(); // Raise the buffer limits var readOpts = {highWaterMark: Math.pow(2,16)}; var writeOpts = {highWaterMark: Math.pow(2,16)}; // Create file streams var source = fs.createReadStream(__dirname + '/' + from, readOpts); var destination = fs.createWriteStream(__dirname + '/' + to, writeOpts); // Pipe data from read-stream to write- and end-functions source.pipe(through(write, end)); /** * Write buffer data to file * @param {Buffer} buf Buffer of a readable stream's data */ function write (buf) { destination.write(parse(buf)); } /** * Parse buffer data. * Replaces semicolons with commas. * @param {Buffer} buf Buffer of a readable stream's data * @return {String} Parsed Buffer as a String */ function parse (buf) { return buf.toString().replace(/;/g, ','); } /** * Finished writing */ function end () { console.log('Finished parsing'); console.log('Parsing took (ms): ' + (Date.now() - startTime)); }
SEAMFACES-94: Add @Named to producer for ExternalContext
package org.jboss.seam.faces.environment; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Named; /** * <p> * A producer which retrieves the {@link ExternalContext} for the current * request of the JavaServer Faces application by calling * {@link FacesContext#getExternalContext()} and stores the result as a * request-scoped bean instance. * </p> * * <p> * This producer allows the {@link ExternalContext} to be injected: * </p> * * <pre> * &#064;Inject * ExternalContext ctx; * </pre> * * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * @author Dan Allen */ public class ExternalContextProducer { @Named @Produces @RequestScoped public ExternalContext getExternalContext(final FacesContext context) { return context.getExternalContext(); } }
package org.jboss.seam.faces.environment; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; /** * <p> * A producer which retrieves the {@link ExternalContext} for the current * request of the JavaServer Faces application by calling * {@link FacesContext#getExternalContext()} and stores the result as a * request-scoped bean instance. * </p> * * <p> * This producer allows the {@link ExternalContext} to be injected: * </p> * * <pre> * &#064;Inject * ExternalContext ctx; * </pre> * * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> * @author Dan Allen */ public class ExternalContextProducer { @Produces @RequestScoped public ExternalContext getExternalContext(final FacesContext context) { return context.getExternalContext(); } }
Examples: Fix mock sensor randomization code
// This mock sensor implementation triggers an event with some data every once in a while var emitter = require( "events" ).EventEmitter, possibleStrings = [ "Helsinki", "Espoo", "Tampere", "Oulu", "Mikkeli", "Ii" ]; // Return a random integer between 0 and @upperLimit function randomInteger( upperLimit ) { return Math.round( Math.random() * upperLimit ); } module.exports = function mockSensor() { var returnValue = new emitter(), trigger = function() { var someValue = Math.round( Math.random() * 42 ), someOtherValue = possibleStrings[ randomInteger( possibleStrings.length - 1 ) ]; returnValue.emit( "change", { someValue: someValue, someOtherValue: someOtherValue } ); setTimeout( trigger, randomInteger( 1000 ) + 1000 ); }; setTimeout( trigger, randomInteger( 1000 ) + 1000 ); return returnValue; };
// This mock sensor implementation triggers an event with some data every once in a while var emitter = require( "events" ).EventEmitter, possibleStrings = [ "Helsinki", "Espoo", "Tampere", "Oulu", "Mikkeli", "Ii" ]; // Return a random integer between 0 and @upperLimit function randomInteger( upperLimit ) { return Math.round( ( 1 + Math.random() ) * upperLimit ); } module.exports = function mockSensor() { var returnValue = new emitter(), trigger = function() { returnValue.emit( "change", { someValue: Math.round( Math.random() * 42 ), someOtherValue: possibleStrings[ randomInteger( possibleStrings.length - 1 ) ] } ); setTimeout( trigger, randomInteger( 1000 ) + 1000 ); }; setTimeout( trigger, randomInteger( 1000 ) + 1000 ); return returnValue; };
Change comparison parameter in example
import pprint import maec.bindings.maec_bundle as maec_bundle_binding from maec.bundle.bundle import Bundle # Matching properties dictionary match_on_dictionary = {'FileObjectType': ['full_name'], 'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'], 'WindowsMutexObjectType': ['name']} # Parse in the input Bundle documents and create their python-maec Bundle class representations bundle1 = Bundle.from_obj(maec_bundle_binding.parse("zeus_threatexpert_maec.xml")) bundle2 = Bundle.from_obj(maec_bundle_binding.parse("zeus_anubis_maec.xml")) # Perform the comparison and get the results comparison_results = Bundle.compare([bundle1, bundle2], match_on = match_on_dictionary, case_sensitive = False) # Pretty print the common and unique Objects print "******Common Objects:*******\n" pprint.pprint(comparison_results.get_common()) print "****************************" print "******Unique Objects:*******\n" pprint.pprint(comparison_results.get_unique()) print "****************************"
import pprint import maec.bindings.maec_bundle as maec_bundle_binding from maec.bundle.bundle import Bundle # Matching properties dictionary match_on_dictionary = {'FileObjectType': ['file_name'], 'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'], 'WindowsMutexObjectType': ['name']} # Parse in the input Bundle documents and create their python-maec Bundle class representations bundle1 = Bundle.from_obj(maec_bundle_binding.parse("zeus_anubis_maec.xml")) bundle2 = Bundle.from_obj(maec_bundle_binding.parse("zeus_threatexpert_maec.xml")) # Perform the comparison and get the results comparison_results = Bundle.compare([bundle1, bundle2], match_on = match_on_dictionary, case_sensitive = False) # Pretty print the common and unique Objects print "******Common Objects:*******\n" pprint.pprint(comparison_results.get_common()) print "****************************" print "******Unique Objects:*******\n" pprint.pprint(comparison_results.get_unique()) print "****************************"
Validate checkout_to_type on asset checkout
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class AssetCheckoutRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ "assigned_user" => 'required_without_all:assigned_asset,assigned_location', "assigned_asset" => 'required_without_all:assigned_user,assigned_location|different:'.$this->id, "assigned_location" => 'required_without_all:assigned_user,assigned_asset', "checkout_to_type" => 'required|in:asset,location,user' ]; return $rules; } }
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class AssetCheckoutRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ "assigned_user" => 'required_without_all:assigned_asset,assigned_location', "assigned_asset" => 'required_without_all:assigned_user,assigned_location|different:'.$this->id, "assigned_location" => 'required_without_all:assigned_user,assigned_asset', ]; return $rules; } }
Add a return value to overwritten res.json() for chaining. This commit adds the return value, i.e. the `res`-object, to the overwritten `res.json()` method to allow chaining like 'res.json({ hello: 'world', body: 'This is pretty printed json' }).end();
"use strict"; /** * pretty json middleware. * * - `always`: prettify response without query, if it's specified true. (default: false) * - `query`: query-string parameter name for pretty response. (default: none) * - `spaces`: pretty print spaces. (default: 2) * * @param {object} option * @return {function} */ module.exports = function(option) { option = option || {}; var always = option.always || false; var query = option.query; var spaces = option.spaces || 2; return function(req, res, next) { if (always === true || typeof req.query[query] !== 'undefined') { res.json = function(body) { // content-type if (!res.get('Content-Type')) { res.set('Content-Type', 'application/json'); } return res.send(JSON.stringify(body, null, spaces)); } } next(); } };
"use strict"; /** * pretty json middleware. * * - `always`: prettify response without query, if it's specified true. (default: false) * - `query`: query-string parameter name for pretty response. (default: none) * - `spaces`: pretty print spaces. (default: 2) * * @param {object} option * @return {function} */ module.exports = function(option) { option = option || {}; var always = option.always || false; var query = option.query; var spaces = option.spaces || 2; return function(req, res, next) { if (always === true || typeof req.query[query] !== 'undefined') { res.json = function(body) { // content-type if (!res.get('Content-Type')) { res.set('Content-Type', 'application/json'); } res.send(JSON.stringify(body, null, spaces)); } } next(); } };
Exit the process if there is a compile error in a production build
const fs = require('fs'); const Encore = require('@symfony/webpack-encore'); const { paths, js: { entries, vendor } } = JSON.parse(fs.readFileSync('./package.json')).config; const env = process.env.NODE_ENV === 'production' ? 'production' : 'dev'; Encore.configureRuntimeEnvironment(env); Encore // directory where all compiled assets will be stored .setOutputPath(paths.dist.js) // what's the public path to this directory (relative to your project's document root dir) .setPublicPath('/') // empty the outputPath dir before each build .cleanupOutputBeforeBuild() .enableSourceMaps(!Encore.isProduction()) // Split vendor assets from the entries .createSharedEntry('vendor', vendor) // create hashed filenames (e.g. app.abc123.css) .enableVersioning(); // Dynamically load entry points entries.forEach((entry) => { Encore.addEntry(entry.replace('.js', ''), `${paths.source.js}/${entry}`); }); // Check for errors and exit the process if (env === 'production') { Encore.addPlugin(function () { // eslint-disable-line func-names, needed to expose `this` this.plugin('done', (stats) => { if (stats.compilation.errors && stats.compilation.errors.length) { throw new Error('webpack build failed'); } }); }); } // export the final configuration module.exports = Encore.getWebpackConfig();
const fs = require('fs'); const Encore = require('@symfony/webpack-encore'); const { paths, js: { entries, vendor } } = JSON.parse(fs.readFileSync('./package.json')).config; const env = process.env.NODE_ENV === 'production' ? 'production' : 'dev'; Encore.configureRuntimeEnvironment(env); Encore // directory where all compiled assets will be stored .setOutputPath(paths.dist.js) // what's the public path to this directory (relative to your project's document root dir) .setPublicPath('/') // empty the outputPath dir before each build .cleanupOutputBeforeBuild() .enableSourceMaps(!Encore.isProduction()) // Split vendor assets from the entries .createSharedEntry('vendor', vendor) // create hashed filenames (e.g. app.abc123.css) .enableVersioning(); // Dynamically load entry points entries.forEach((entry) => { Encore.addEntry(entry.replace('.js', ''), `${paths.source.js}/${entry}`); }); const config = Encore.getWebpackConfig(); config.bail = true; console.log(config); // export the final configuration module.exports = config;
Check if not stdClass before casting to float
<?php namespace Ups\Entity; class Charges { public $CurrencyCode; public $MonetaryValue; public $Code; public $Description; public $SubType; function __construct($response = null) { if (null != $response) { if (isset($response->CurrencyCode)) { $this->CurrencyCode = $response->CurrencyCode; } if (isset($response->MonetaryValue) && !$response->MonetaryValue instanceof \stdClass) { $this->MonetaryValue = (float)$response->MonetaryValue; } if (isset($response->Code)) { $this->Code = $response->Code; } if (isset($response->Description)) { $this->Description = $response->Description; } if (isset($response->SubType)) { $this->SubType = $response->SubType; } } } }
<?php namespace Ups\Entity; class Charges { public $CurrencyCode; public $MonetaryValue; public $Code; public $Description; public $SubType; function __construct($response = null) { if (null != $response) { if (isset($response->CurrencyCode)) { $this->CurrencyCode = $response->CurrencyCode; } if (isset($response->MonetaryValue)) { $this->MonetaryValue = (float)$response->MonetaryValue; } if (isset($response->Code)) { $this->Code = $response->Code; } if (isset($response->Description)) { $this->Description = $response->Description; } if (isset($response->SubType)) { $this->SubType = $response->SubType; } } } }
Add charset to HTML5 doc (and make more XHTML friendly)
<!DOCTYPE html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script> </head><body></body> </html>
<!doctype html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script>
Use MySQL database backend in Travis CI.
# Settings used for running tests in Travis # # Load default settings # noinspection PyUnresolvedReferences from settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'alexia_test', # Of pad naar sqlite3 database # Hieronder negeren voor sqlite3 'USER': 'travis', 'PASSWORD': '', 'HOST': '', # Leeg voor localhost 'PORT': '', # Leeg is default } } SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
# Settings used for running tests in Travis # # Load default settings # noinspection PyUnresolvedReferences from settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'alexia_test', # Of pad naar sqlite3 database # Hieronder negeren voor sqlite3 'USER': '', 'PASSWORD': '', 'HOST': '', # Leeg voor localhost 'PORT': '', # Leeg is default } } SECRET_KEY = 'zBCMvM1BwLtlkoXf1mbgCo3W60j2UgIPhevmEJ9cMPft2JtUk5'
Make it more obvious that you need to use a local repository as an argument, not a url
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
Add docker ssh user to hyperv config
/* Copyright (C) 2016 Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cluster import ( "github.com/docker/machine/drivers/hyperv" "github.com/docker/machine/libmachine/drivers" "github.com/jimmidyson/minishift/pkg/minikube/constants" ) func createHypervHost(config MachineConfig) drivers.Driver { d := hyperv.NewDriver(constants.MachineName, constants.Minipath) d.Boot2DockerURL = config.MinikubeISO d.MemSize = config.Memory d.CPU = config.CPUs d.DiskSize = int(config.DiskSize) d.SSHUser = "docker" return d }
/* Copyright (C) 2016 Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cluster import ( "github.com/docker/machine/drivers/hyperv" "github.com/docker/machine/libmachine/drivers" "github.com/jimmidyson/minishift/pkg/minikube/constants" ) func createHypervHost(config MachineConfig) drivers.Driver { d := hyperv.NewDriver(constants.MachineName, constants.Minipath) d.Boot2DockerURL = config.MinikubeISO d.MemSize = config.Memory d.CPU = config.CPUs d.DiskSize = int(config.DiskSize) return d }
Fix legend gradient label text to use update set.
import {Perc, Label, GuideLabelStyle} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendLabelRole} from '../marks/roles'; import {addEncode} from '../encode/encode-util'; var alignExpr = 'datum.' + Perc + '<=0?"left"' + ':datum.' + Perc + '>=1?"right":"center"'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero }; addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'baseline', config.gradientLabelBaseline); addEncode(enter, 'limit', config.gradientLabelLimit); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1}, text: {field: Label} }; enter.x = update.x = { field: Perc, mult: config.gradientWidth }; enter.y = update.y = { value: config.gradientHeight, offset: config.gradientLabelOffset }; enter.align = update.align = {signal: alignExpr}; return guideMark(TextMark, LegendLabelRole, GuideLabelStyle, Perc, dataRef, encode, userEncode); }
import {Perc, Label, GuideLabelStyle} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendLabelRole} from '../marks/roles'; import {addEncode} from '../encode/encode-util'; var alignExpr = 'datum.' + Perc + '<=0?"left"' + ':datum.' + Perc + '>=1?"right":"center"'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, text: {field: Label} }; addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'baseline', config.gradientLabelBaseline); addEncode(enter, 'limit', config.gradientLabelLimit); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Perc, mult: config.gradientWidth }; enter.y = update.y = { value: config.gradientHeight, offset: config.gradientLabelOffset }; enter.align = update.align = {signal: alignExpr}; return guideMark(TextMark, LegendLabelRole, GuideLabelStyle, Perc, dataRef, encode, userEncode); }
Update python versions we care about
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-glitter-news', version='0.1', description='Django Glitter News for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-glitter-news', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], packages=find_packages(), install_requires=[ 'django-glitter', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], license='BSD 3-Clause', )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-glitter-news', version='0.1', description='Django Glitter News for Django', long_description=open('README.rst').read(), url='https://github.com/blancltd/django-glitter-news', maintainer='Blanc Ltd', maintainer_email='studio@blanc.ltd.uk', platforms=['any'], packages=find_packages(), install_requires=[ 'django-glitter', ], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], license='BSD 3-Clause', )
Use importNode to avoid issues cloning a template with custom elements in it.
/* * A minimal set of helper functions to go on top of polymer-micro: * * 1. <template> instantiation * 2. Polymer-style automatic node finding */ (function() { // Polymer-style automatic node finding. // See https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#node-finding. // This feature is not available in polymer-micro, so we provide a basic // version of this ourselves. function createReferencesToNodesWithIds(instance) { instance.$ = {}; var nodesWithIds = instance.root.querySelectorAll('[id]'); [].forEach.call(nodesWithIds, function(node) { var id = node.getAttribute('id'); instance.$[id] = node; }); } window.MinimalComponent = { // Use polymer-micro created callback to initialize the component. created: function() { if (this.template) { // Instantiate template. this.root = this.createShadowRoot(); var clone = document.importNode(this.template.content, true); this.root.appendChild(clone); // Create this.$.<id> properties. createReferencesToNodesWithIds(this); } // Initialize property values from attributes. this._marshalAttributes(); }, get ownerDocument() { // Support both polyfilled and native HTML Imports. var currentScript = document._currentScript || document.currentScript; return currentScript.ownerDocument; } }; })();
/* * A minimal set of helper functions to go on top of polymer-micro: * * 1. <template> instantiation * 2. Polymer-style automatic node finding */ (function() { // Polymer-style automatic node finding. // See https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#node-finding. // This feature is not available in polymer-micro, so we provide a basic // version of this ourselves. function createReferencesToNodesWithIds(instance) { instance.$ = {}; var nodesWithIds = instance.root.querySelectorAll('[id]'); [].forEach.call(nodesWithIds, function(node) { var id = node.getAttribute('id'); instance.$[id] = node; }); } window.MinimalComponent = { // Use polymer-micro created callback to initialize the component. created: function() { if (this.template) { // Instantiate template. this.root = this.createShadowRoot(); this.root.appendChild(this.template.content.cloneNode(true)); // Create this.$.<id> properties. createReferencesToNodesWithIds(this); } // Initialize property values from attributes. this._marshalAttributes(); }, get ownerDocument() { // Support both polyfilled and native HTML Imports. var currentScript = document._currentScript || document.currentScript; return currentScript.ownerDocument; } }; })();
[Readability] Store SQL query into variable
<?php /** * @title Advertisement Model Class. * * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Mvc / Model */ namespace PH7\Framework\Mvc\Model; defined('PH7') or exit('Restricted access'); use PH7\DbTableName; use PH7\Framework\Mvc\Model\Engine\Db; class Ads extends Engine\Model { /** * Adding an Advertisement Click. * * @param int $iAdsId * * @return void */ public static function setClick($iAdsId) { $sSql = 'UPDATE' . Db::prefix(DbTableName::AD) . 'SET clicks = clicks+1 WHERE adsId = :id LIMIT 1'; $rStmt = Db::getInstance()->prepare($sSql); $rStmt->bindValue(':id', $iAdsId, \PDO::PARAM_INT); $rStmt->execute(); Db::free($rStmt); } }
<?php /** * @title Advertisement Model Class. * * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2013-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / Framework / Mvc / Model */ namespace PH7\Framework\Mvc\Model; defined('PH7') or exit('Restricted access'); use PH7\DbTableName; use PH7\Framework\Mvc\Model\Engine\Db; class Ads extends Engine\Model { /** * Adding an Advertisement Click. * * @param int $iAdsId * * @return void */ public static function setClick($iAdsId) { $rStmt = Db::getInstance()->prepare('UPDATE' . Db::prefix(DbTableName::AD) . 'SET clicks = clicks+1 WHERE adsId = :id LIMIT 1'); $rStmt->bindValue(':id', $iAdsId, \PDO::PARAM_INT); $rStmt->execute(); Db::free($rStmt); } }
Remove not relevant TODO comment
/** * Copyright 2012 Ronen Hamias, Anton Kharenko * * 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.socketio.netty.serialization; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; public final class JsonObjectMapperProvider { private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } public static ObjectMapper getObjectMapper(){ return objectMapper; } /** * Don't let anyone instantiate this class. */ private JsonObjectMapperProvider() {} }
/** * Copyright 2012 Ronen Hamias, Anton Kharenko * * 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.socketio.netty.serialization; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; // TODO: check support with Gson public final class JsonObjectMapperProvider { private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } public static ObjectMapper getObjectMapper(){ return objectMapper; } /** * Don't let anyone instantiate this class. */ private JsonObjectMapperProvider() {} }
Change View According to model Changes
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from game.models import Location class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): return Location.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' def get_context_data(self, **kwargs): l_pk = self.kwargs['pk'] Location.objects.filter(pk=l_pk).update(visited = True) context = super(LocationDetailView, self).get_context_data(**kwargs) return context
from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from game.models import * class LocationListView(ListView): template_name = 'game/location_list.html' context_object_name = 'location_list' def get_queryset(self): return Detail.objects.all() def get_context_data(self, **kwargs): context = super(LocationListView, self).get_context_data(**kwargs) return context class LocationDetailView(DetailView): model = Location context_object_name = 'location_detail' def get_context_data(self, **kwargs): context = super(LocationDetailView, self).get_context_data(**kwargs) context['detail_info'] = Detail.objects.all() return context
Change default encoding for json
package com.pyknic.servicekit.encode; import com.google.gson.Gson; import com.pyknic.servicekit.Service; import java.util.Map; /** * An encoder that parses the result of a service to the json format. * <p> * This class should not be instantiated directly but passed as a class * reference to the {@link Service} annotation to be instantiated * through reflection. * <p> * This class is stateless and instances can therefore safely be shared. * * @author Emil Forslund */ public final class JsonEncoder implements Encoder { private final static String MIME = "application/json"; @Override public <T> String apply(Map<String, Object> params, T response) { final Gson gson = new Gson(); return gson.toJson(response); } @Override public String getMimeType() { return MIME; } public JsonEncoder() {} }
package com.pyknic.servicekit.encode; import com.google.gson.Gson; import com.pyknic.servicekit.Service; import java.util.Map; /** * An encoder that parses the result of a service to the json format. * <p> * This class should not be instantiated directly but passed as a class * reference to the {@link Service} annotation to be instantiated * through reflection. * <p> * This class is stateless and instances can therefore safely be shared. * * @author Emil Forslund */ public final class JsonEncoder implements Encoder { private final static String MIME = "application/x-json"; @Override public <T> String apply(Map<String, Object> params, T response) { final Gson gson = new Gson(); return gson.toJson(response); } @Override public String getMimeType() { return MIME; } public JsonEncoder() {} }
Decrease timeout to make app start faster
const CACHE = 'network-or-cache' const TIMEOUT = 50 self.addEventListener('install', evt => { console.log('Service worker is being installed.') }) self.addEventListener('activate', evt => { console.log('Service worker is being activated.') }); self.addEventListener('fetch', evt => { evt.respondWith(fromNetwork(evt.request, TIMEOUT).catch(() => { return fromCache(evt.request) })) }) function fromNetwork(request, timeout) { return new Promise((fulfill, reject) => { const timeoutId = setTimeout(reject, timeout) fetch(request).then(response => { clearTimeout(timeoutId) if(!response || response.status !== 200 || request.method !== 'GET') { return fulfill(response) } // IMPORTANT: Clone the response. A response is a stream // and because we want the browser to consume the response // as well as the cache consuming the response, we need // to clone it so we have two streams. const responseToCache = response.clone() caches.open(CACHE) .then(cache => { cache.put(request, responseToCache); }) return fulfill(response) }, reject) }) } function fromCache(request) { return caches.open(CACHE).then(cache => { return cache.match(request).then(matching => { return matching || Promise.reject('no-match') }) }) }
const CACHE = 'network-or-cache' self.addEventListener('install', evt => { console.log('Service worker is being installed.') }) self.addEventListener('activate', evt => { console.log('Service worker is being activated.') }); self.addEventListener('fetch', evt => { evt.respondWith(fromNetwork(evt.request, 500).catch(() => { return fromCache(evt.request) })) }) function fromNetwork(request, timeout) { return new Promise((fulfill, reject) => { const timeoutId = setTimeout(reject, timeout) fetch(request).then(response => { clearTimeout(timeoutId) if(!response || response.status !== 200 || request.method !== 'GET') { return fulfill(response) } // IMPORTANT: Clone the response. A response is a stream // and because we want the browser to consume the response // as well as the cache consuming the response, we need // to clone it so we have two streams. const responseToCache = response.clone() caches.open(CACHE) .then(cache => { cache.put(request, responseToCache); }) return fulfill(response) }, reject) }) } function fromCache(request) { return caches.open(CACHE).then(cache => { return cache.match(request).then(matching => { return matching || Promise.reject('no-match') }) }) }
Remove redundant 'api' from URL
from flask import Flask, request import subprocess import uuid import os import re import json app = Flask(__name__) @app.route('/v1/', methods=["GET"]) def lint(): id = uuid.uuid4() filename = os.path.join("tmp", "{}.md".format(id)) with open(filename, "w+") as f: f.write(request.values['text']) out = subprocess.check_output("proselint {}".format(filename), shell=True) r = re.compile( "(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)") out2 = sorted([r.search(line).groupdict() for line in out.splitlines()]) return json.dumps(out2) if __name__ == '__main__': app.debug = True app.run()
from flask import Flask, request import subprocess import uuid import os import re import json app = Flask(__name__) @app.route('/api/v1/', methods=["GET"]) def lint(): id = uuid.uuid4() filename = os.path.join("tmp", "{}.md".format(id)) with open(filename, "w+") as f: f.write(request.values['text']) out = subprocess.check_output("proselint {}".format(filename), shell=True) r = re.compile( "(?:.*).md:(?P<line>\d*):(?P<column>\d*): (?P<err>\w{6}) (?P<msg>.*)") out2 = sorted([r.search(line).groupdict() for line in out.splitlines()]) return json.dumps(out2) if __name__ == '__main__': app.debug = True app.run()
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(); } }
Fix double messaging for multi opening
// Author: Daniel G (oscar-daniel.gonzalez@hp.com) // Reserved for comms chrome.runtime.onMessage.addListener(function(msg) { alert("Popup - Yo I got a message!"); console.debug(msg); }); // Inject tridion_ext into page var scr = document.createElement('script'); scr.type="text/javascript"; scr.src= chrome.extension.getURL('js/tridion_ext.js'); document.head.appendChild(scr); window.addEventListener("message", function(event) { // We only accept messages from ourselves if (event.source != window) return; switch(event.data.action){ case "open_item" : case "init_levels": chrome.runtime.sendMessage(event.data); break; case "get_publishable_batches": get_publishable_batches(); default: break; } }, false); function get_publishable_batches(){ // Get all publishable batches console.debug("gettin publishable batches!"); chrome.storage.local.get(null,(storage)=>{ if(!storage.cust_batches) return; var publishable_batches = []; storage.cust_batches.forEach((cust_batch)=>{ if(cust_batch.publishable) publishable_batches.push(cust_batch); }); window.postMessage({"action":"publishable_batches", "data": publishable_batches},"*"); }) }
// Author: Daniel G (oscar-daniel.gonzalez@hp.com) // Reserved for comms chrome.runtime.onMessage.addListener(function(msg) { alert("Popup - Yo I got a message!"); console.debug(msg); }); // Inject tridion_ext into page var scr = document.createElement('script'); scr.type="text/javascript"; scr.src= chrome.extension.getURL('js/tridion_ext.js'); document.head.appendChild(scr); window.addEventListener("message", function(event) { // We only accept messages from ourselves if (event.source != window) return; switch(event.data.action){ case "open_item" : case "init_levels": chrome.runtime.sendMessage(event.data); break; case "get_publishable_batches": get_publishable_batches(); default: break; } if (event.data.action && (event.data.action == "open_item" || event.data.action == "init_levels")) chrome.runtime.sendMessage(event.data); }, false); function get_publishable_batches(){ // Get all publishable batches console.debug("gettin publishable batches!"); chrome.storage.local.get(null,(storage)=>{ if(!storage.cust_batches) return; var publishable_batches = []; storage.cust_batches.forEach((cust_batch)=>{ if(cust_batch.publishable) publishable_batches.push(cust_batch); }); window.postMessage({"action":"publishable_batches", "data": publishable_batches},"*"); }) }
Fix fullscreen to work also with first level items
angular.module('sgApp') .controller('ElementCtrl', function($scope, $stateParams, $state, $rootScope, Styleguide) { var section = $stateParams.section.split('.'), reference, modifier; if (section.length == 3) { modifier = section[2]; reference = section[0] + '.' + section[1]; } else { reference = $stateParams.section; } Styleguide.get() .success(function(data) { var result = data.sections.filter(function(item) { return reference == item.reference; }), element = result[0]; if (modifier) { element = element.modifiers[modifier - 1]; } $scope.section = element; }) .error(function() { console.log('error'); }); });
angular.module('sgApp') .controller('ElementCtrl', function($scope, $stateParams, $state, $rootScope, Styleguide) { var section = $stateParams.section.split('.'), reference = section[0] + '.' + section[1], modifier = section[2]; Styleguide.get() .success(function(data) { var result = data.sections.filter(function(item) { return reference == item.reference; }), element = result[0]; if (modifier) { element = element.modifiers[modifier - 1]; } $scope.section = element; }) .error(function() { console.log('error'); }); });
Rework string concatenation with join and format Signed-off-by: Alwed <b03a9dbc84dbfcd49b3dd10dfbe7e015dc04cee5@t-online.de>
#!/usr/bin/env python3 try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: print(''.join((d[0], ' … ')), end='', flush=True) flt = '(&{0}(|(mail={1}*)(cn={1}*)))'.format(FILTER, argv[1]) conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) print('{:d} entries found!'.format(len(entries))) for i in entries: for m in i.mail.values: print('{}\t{}\t{}'.format(m, i.cn[0], i.entry_dn)) except Exception as e: print('Error: {}: {}'.format(type(e).__name__, e)) exit(1)
#!/usr/bin/env python3 try: from sys import argv import ldap3 LDAPDIRS = [ ('ldaps://ldappv.rwth-aachen.de', 'ou=People,dc=rwth-aachen,dc=de') ] FILTER = '(mail=*)' ATTRS = ['cn', 'mail'] print('Searching … ', end='', flush=True) entries = [] for d in LDAPDIRS: with ldap3.Connection(d[0], auto_bind=True) as conn: print(d[0] + ' … ', end='', flush=True) flt = '(&' + FILTER + \ '(|(mail=' + argv[1] + '*)(cn=' + argv[1] + '*)))' conn.search(d[1], flt, attributes=ATTRS) entries.extend(conn.entries) if len(entries) == 0: print('No entries found!') exit(1) print(str(len(entries)) + ' entries found!') for i in entries: for m in i.mail.values: print(m + '\t' + i.cn[0] + '\t' + i.entry_dn) except Exception as e: print("Error: " + type(e).__name__ + ": " + str(e)) exit(1)
Fix day 8 to paint front-to-back
from collections import Counter from typing import Iterable, TextIO import numpy # type: ignore def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]: chunk_size = width * height content = next(data).strip() for pos in range(0, len(content), chunk_size): yield numpy.array([int(c) for c in content[pos:pos + chunk_size]]) def part1(data: TextIO) -> int: best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0]) return best_layer[1] * best_layer[2] def format_row(row: Iterable[int]) -> str: return ''.join('#' if p == 1 else ' ' for p in row) def part2(data: TextIO) -> str: background = numpy.zeros(25 * 6, numpy.int8) background.fill(2) for layer in parse_layers(25, 6, data): mask = background == 2 background[mask] = layer[mask] return '\n'.join(format_row(row) for row in background.reshape(6, 25))
from collections import Counter from typing import Iterable, TextIO import numpy # type: ignore def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]: chunk_size = width * height content = next(data).strip() for pos in range(0, len(content), chunk_size): yield numpy.array([int(c) for c in content[pos:pos + chunk_size]]) def part1(data: TextIO) -> int: best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0]) return best_layer[1] * best_layer[2] def format_row(row: Iterable[int]) -> str: return ''.join('#' if p == 1 else ' ' for p in row) def part2(data: TextIO) -> str: layers = list(parse_layers(25, 6, data)) background = numpy.zeros(25 * 6, numpy.int8) for layer in reversed(layers): background[layer != 2] = layer[layer != 2] return '\n'.join(format_row(row) for row in background.reshape(6, 25))
Set timeout on pca test
import pytest @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) p.plot(n_components=2, switch_y=True) p.plot(n_components=2, switch_x=True) p.plot(n_components=3, switch_z=True) p.plot_pca_vs_max_features(n_components=4) p.plot_pca_vs_max_features(step=50000)
[infra] Add .bat to pub command on Windows #32656 Change-Id: I3a34bf2c81676eea0ab112a8aad701962590a6c3 Reviewed-on: https://dart-review.googlesource.com/55165 Commit-Queue: Alexander Thomas <29642742b6693024c89de8232f2e2542cf7eedf7@google.com> Reviewed-by: William Hesse <a821cddceae7dc400f272e3cb1a72f400f9fed6d@google.com>
#!/usr/bin/env python # Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import subprocess import sys import shutil import tempfile PUBSPEC = """name: pub_integration_test dependencies: shelf: test: """ def Main(): out_dir = 'xcodebuild' if sys.platform == 'darwin' else 'out' extension = '' if not sys.platform == 'win32' else '.bat' pub = os.path.abspath( '%s/ReleaseX64/dart-sdk/bin/pub%s' % (out_dir, extension)) working_dir = tempfile.mkdtemp() try: pub_cache_dir = working_dir + '/pub_cache' env = os.environ.copy() env['PUB_CACHE'] = pub_cache_dir with open(working_dir + '/pubspec.yaml', 'w') as pubspec_yaml: pubspec_yaml.write(PUBSPEC) exit_code = subprocess.call([pub, 'get'], cwd=working_dir, env=env) if exit_code is not 0: return exit_code exit_code = subprocess.call([pub, 'upgrade'], cwd=working_dir, env=env) if exit_code is not 0: return exit_code finally: shutil.rmtree(working_dir); if __name__ == '__main__': sys.exit(Main())
#!/usr/bin/env python # Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import subprocess import sys import shutil import tempfile PUBSPEC = """name: pub_integration_test dependencies: shelf: test: """ def Main(): out_dir = 'xcodebuild' if sys.platform == 'darwin' else 'out' pub = os.path.abspath('%s/ReleaseX64/dart-sdk/bin/pub' % out_dir) working_dir = tempfile.mkdtemp() try: pub_cache_dir = working_dir + '/pub_cache' env = { 'PUB_CACHE': pub_cache_dir } with open(working_dir + '/pubspec.yaml', 'w') as pubspec_yaml: pubspec_yaml.write(PUBSPEC) exit_code = subprocess.call([pub, 'get'], cwd=working_dir, env=env) if exit_code is not 0: return exit_code exit_code = subprocess.call([pub, 'upgrade'], cwd=working_dir, env=env) if exit_code is not 0: return exit_code finally: shutil.rmtree(working_dir); if __name__ == '__main__': sys.exit(Main())
Fix crash/panic when in wrong directory. Resolves #26, closes #32 and closes #27
package app import ( "fmt" "os" "path/filepath" "regexp" "sync" "github.com/stevenjack/cig/output" "github.com/stevenjack/cig/repo" ) func Handle(repoList map[string]string, projectTypeToCheck string, filter string, output_channel chan output.Payload) { var wg sync.WaitGroup for projectType, path := range repoList { if projectTypeToCheck == "" || projectTypeToCheck == projectType { output_channel <- output.Print(fmt.Sprintf("\nChecking '%s' (%s) repos...", projectType, path)) visit := func(visitedPath string, info os.FileInfo, err error) error { if err != nil { output_channel <- output.Error(fmt.Sprintf("- %s", err.Error())) return nil } matched, _ := regexp.MatchString(filter, visitedPath) if info.IsDir() && (filter == "" || matched) { wg.Add(1) go repo.Check(path, visitedPath, output_channel, &wg) } return nil } err := filepath.Walk(path, visit) if err != nil { output_channel <- output.FatalError(err.Error()) } } wg.Wait() } wg.Wait() }
package app import ( "fmt" "os" "path/filepath" "regexp" "sync" "github.com/stevenjack/cig/output" "github.com/stevenjack/cig/repo" ) func Handle(repoList map[string]string, projectTypeToCheck string, filter string, output_channel chan output.Payload) { var wg sync.WaitGroup for projectType, path := range repoList { if projectTypeToCheck == "" || projectTypeToCheck == projectType { output_channel <- output.Print(fmt.Sprintf("\nChecking '%s' (%s) repos...", projectType, path)) visit := func(visitedPath string, info os.FileInfo, err error) error { matched, _ := regexp.MatchString(filter, visitedPath) if info.IsDir() && (filter == "" || matched) { wg.Add(1) go repo.Check(path, visitedPath, output_channel, &wg) } return nil } err := filepath.Walk(path, visit) if err != nil { output_channel <- output.FatalError(err.Error()) } } wg.Wait() } wg.Wait() }
Fix to work correctly if we are already in the directory of the lcad file.
#!/usr/bin/env python """ .. module:: lcad_to_ldraw :synopsis: Generates a ldraw format file from a lcad model. .. moduleauthor:: Hazen Babcock """ import os import sys import lcad_language.interpreter as interpreter if (len(sys.argv)<2): print "usage: <lcad file> <ldraw file (optional)>" exit() # Generate parts. with open(sys.argv[1]) as fp: # Change current working directory to the location of the lcad file. cur_dir = os.getcwd() if not (os.path.dirname(sys.argv[1]) == ""): os.chdir(os.path.dirname(sys.argv[1])) parts = interpreter.execute(fp.read()).getParts() os.chdir(cur_dir) print "Model has", len(parts), "parts." # Save. if (len(sys.argv) == 3): ldraw_fname = sys.argv[2] else: ldraw_fname = sys.argv[1][:-4] + "dat" with open(ldraw_fname, "w") as fp: fp.write("0 // Do not edit, automatically generated by openlcad from " + os.path.basename(sys.argv[1]) + "\n") for part in parts: fp.write(part.toLDraw() + "\n") print "Done."
#!/usr/bin/env python """ .. module:: lcad_to_ldraw :synopsis: Generates a ldraw format file from a lcad model. .. moduleauthor:: Hazen Babcock """ import os import sys import lcad_language.interpreter as interpreter if (len(sys.argv)<2): print "usage: <lcad file> <ldraw file (optional)>" exit() # Generate parts. with open(sys.argv[1]) as fp: # Change current working directory to the location of the lcad file. cur_dir = os.getcwd() os.chdir(os.path.dirname(sys.argv[1])) parts = interpreter.execute(fp.read()).getParts() os.chdir(cur_dir) print "Model has", len(parts), "parts." # Save. if (len(sys.argv) == 3): ldraw_fname = sys.argv[2] else: ldraw_fname = sys.argv[1][:-4] + "dat" with open(ldraw_fname, "w") as fp: fp.write("0 // Do not edit, automatically generated by openlcad from " + os.path.basename(sys.argv[1]) + "\n") for part in parts: fp.write(part.toLDraw() + "\n") print "Done."
Add more user milestones!! :tada:
<?php /** * @author Pierre-Henry Soria <hi@ph7.me> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; class UserMilestoneCore { const NUMBER_USERS = [ 100, 500, 1000, 2500, 5000, 7500, 10000, 25000, 50000, 100000, 250000, 500000, 1000000 // Congrats! ]; /** @var UserCoreModel */ private $oUserModel; public function __construct(UserCoreModel $oUserModel) { $this->oUserModel = $oUserModel; } /** * @return bool */ public function isTotalUserReached() { return in_array($this->oUserModel->total(), self::NUMBER_USERS, true); } }
<?php /** * @author Pierre-Henry Soria <hi@ph7.me> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; class UserMilestoneCore { const NUMBER_USERS = [ 500, 1000, 5000, 10000, 25000, 50000, 100000, 500000, 1000000 // Congrats! ]; /** @var UserCoreModel */ private $oUserModel; public function __construct(UserCoreModel $oUserModel) { $this->oUserModel = $oUserModel; } /** * @return bool */ public function isTotalUserReached() { return in_array($this->oUserModel->total(), self::NUMBER_USERS, true); } }
Refactor URL imports and paths
from django.conf.urls import url from . import views app_name = 'signage' urlpatterns = [ url(r'^display/(?P<pk>\d+)/$', views.DisplayDetail.as_view(), name='display'), url(r'^display/create/$', views.DisplayCreate.as_view(), name='display_create'), url(r'^display/(?P<pk>\d+)/delete/$', views.DisplayDelete.as_view(), name='display_delete'), url(r'^display/(?P<pk>\d+)/update/$', views.DisplayUpdate.as_view(), name='display_update'), url(r'^displays/$', views.DisplayList.as_view(), name='display_list'), url(r'^slide/create/$', views.SlideCreate.as_view(), name='slide_create'), url(r'^slide/(?P<pk>\d+)/delete/$', views.SlideDelete.as_view(), name='slide_delete'), url(r'^slide/(?P<pk>\d+)/update/$', views.SlideUpdate.as_view(), name='slide_update'), url(r'^slides/$', views.SlideList.as_view(), name='slide_list'), ]
from django.conf.urls import url from .views import DisplayCreate from .views import DisplayDelete from .views import DisplayDetail from .views import DisplayList from .views import DisplayUpdate from .views import SlideCreate from .views import SlideDelete from .views import SlideList from .views import SlideUpdate app_name = 'signage' urlpatterns = [ url(r'^(?P<pk>\d+)/$', DisplayDetail.as_view(), name='display'), url(r'^displays/$', DisplayList.as_view(), name='display_list'), url(r'^displays/create/$', DisplayCreate.as_view(), name='display_create'), url(r'^displays/delete/(?P<pk>\d+)/$', DisplayDelete.as_view(), name='display_delete'), url(r'^displays/update/(?P<pk>\d+)/$', DisplayUpdate.as_view(), name='display_update'), url(r'^slides/$', SlideList.as_view(), name='slide_list'), url(r'^slides/create/$', SlideCreate.as_view(), name='slide_create'), url(r'^slides/delete/(?P<pk>\d+)/$', SlideDelete.as_view(), name='slide_delete'), url(r'^slides/update/(?P<pk>\d+)/$', SlideUpdate.as_view(), name='slide_update'), ]
Use `set_defaults` of subparser to launch scripts
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Module to bundle plotting scripts `activate-global-python-argcomplete` must be run to enable auto completion """ import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts', dest='used_subparser', ) module_subparser = {} for module_str in plotter.__all__: module = __import__('plotter.' + module_str, fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) module_subparser[module_str].set_defaults(run=module.main) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() args.run(args)
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Module to bundle plotting scripts `activate-global-python-argcomplete` must be run to enable auto completion """ import argparse import argcomplete import plotter def parse_arguments(): """Argument Parser, providing available scripts""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers( title = 'plotter', description = 'available plotting scripts' ) module_subparser = {} for module_str in plotter.__all__: module = __import__('.'.join(('plotter', module_str)), fromlist=module_str) module_subparser[module_str] = subparsers.add_parser( module_str, parents=[module.get_parser(add_help=False)], help=module.__doc__.split('\n', 1)[0] ) configure = subparsers.add_parser('configure', help='configure this script.') argcomplete.autocomplete(parser) args = parser.parse_args() return args if __name__ == '__main__': args = parse_arguments() from plotter.plotn import main main(args)
Remove '\' condition from test as it will not be in the file path when used on Linux.
import unittest import os from approvaltests.Namer import Namer class NamerTests(unittest.TestCase): def test_class(self): n = Namer() self.assertEqual("NamerTests", n.getClassName()) def test_method(self): n = Namer() self.assertEqual("test_method", n.getMethodName()) def test_file(self): n = Namer() self.assertTrue(os.path.exists(n.getDirectory() + "/NamerTests.py")) def test_basename(self): n = Namer() self.assertTrue(n.get_basename().endswith("NamerTests.test_basename"), n.get_basename()) if __name__ == '__main__': unittest.main()
import unittest import os from approvaltests.Namer import Namer class NamerTests(unittest.TestCase): def test_class(self): n = Namer() self.assertEqual("NamerTests", n.getClassName()) def test_method(self): n = Namer() self.assertEqual("test_method", n.getMethodName()) def test_file(self): n = Namer() self.assertTrue(os.path.exists(n.getDirectory() + "/NamerTests.py")) def test_basename(self): n = Namer() self.assertTrue(n.get_basename().endswith("\\NamerTests.test_basename"), n.get_basename()) if __name__ == '__main__': unittest.main()
Add listBycategory and alistByauthor sidebar selection.
$(document).ready(function() { $('li.top-menu').click(function() { $( this ).toggleClass( "active" ); $(this).next().slideToggle('300'); }); if(Hurad.params.action == "admin_index" || Hurad.params.action == "admin_filter" || Hurad.params.action == "admin_listBycategory" || Hurad.params.action == "admin_listByauthor"){ $('a[href$="'+Hurad.params.controller+'"]').parent().addClass("current"); } else if(Hurad.params.action == "admin_add"){ $('a[href$="'+Hurad.params.controller+'/add"]').parent().addClass("current"); } else if(Hurad.params.action == "admin_prefix"){ $('a[href$="'+Hurad.params.pass+'"]').parent().addClass("current"); } else if(Hurad.params.action == "admin_dashboard"){ $('a[href$="admin"]').parent().addClass("current"); } $('li.current').parents('li.sb').css("display", "list-item"); $('li.current').parents('ul.menu').find( ".top-menu" ).addClass("active"); });
$(document).ready(function() { $('li.top-menu').click(function() { $( this ).toggleClass( "active" ); $(this).next().slideToggle('300'); }); if(Hurad.params.action == "admin_index" || Hurad.params.action == "admin_filter"){ $('a[href$="'+Hurad.params.controller+'"]').parent().addClass("current"); } else if(Hurad.params.action == "admin_add"){ $('a[href$="'+Hurad.params.controller+'/add"]').parent().addClass("current"); } else if(Hurad.params.action == "admin_prefix"){ $('a[href$="'+Hurad.params.pass+'"]').parent().addClass("current"); } else if(Hurad.params.action == "admin_dashboard"){ $('a[href$="admin"]').parent().addClass("current"); } $('li.current').parents('li.sb').css("display", "list-item"); $('li.current').parents('ul.menu').find( ".top-menu" ).addClass("active"); });
Fix non-threadsafe failure in serializer - now using thread local serializer instance.
"""Django DDP utils for DDP messaging.""" from dddp import THREAD_LOCAL as this from django.core.serializers import get_serializer def serializer_factory(): """Make a new DDP serializer.""" return get_serializer('ddp')() def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" serializer = this.get('serializer', serializer_factory) data = serializer.serialize([obj])[0] 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.""" import collections from django.core.serializers import get_serializer _SERIALIZER = None def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" global _SERIALIZER if _SERIALIZER is None: _SERIALIZER = get_serializer('ddp')() data = _SERIALIZER.serialize([obj])[0] 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)
Use ::class keyword when possible
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Console\Tests\Helper; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Helper\TableCellStyle; class TableCellStyleTest extends TestCase { public function testCreateTableCellStyle() { $tableCellStyle = new TableCellStyle(['fg' => 'red']); $this->assertEquals('red', $tableCellStyle->getOptions()['fg']); $this->expectException(\Symfony\Component\Console\Exception\InvalidArgumentException::class); new TableCellStyle(['wrong_key' => null]); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Console\Tests\Helper; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Helper\TableCellStyle; class TableCellStyleTest extends TestCase { public function testCreateTableCellStyle() { $tableCellStyle = new TableCellStyle(['fg' => 'red']); $this->assertEquals('red', $tableCellStyle->getOptions()['fg']); $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); new TableCellStyle(['wrong_key' => null]); } }
Remove yield from on redshift_client
import asyncio import botocore.exceptions from bigcrunch import webapp @asyncio.coroutine def shutdown(): client = webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ClusterNotFound': raise e else: print('Redshift already shutdown') return engine = yield from webapp.create_engine(cluster) with (yield from engine) as conn: db = webapp.Database(conn=conn) sessions = yield from db.running_test_sessions() if sessions == 0: print('shutting down Redshift') yield from cluster_control.destroy() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(shutdown()) loop.close()
import asyncio import botocore.exceptions from bigcrunch import webapp @asyncio.coroutine def shutdown(): client = yield from webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ClusterNotFound': raise e else: print('Redshift already shutdown') return engine = yield from webapp.create_engine(cluster) with (yield from engine) as conn: db = webapp.Database(conn=conn) sessions = yield from db.running_test_sessions() if sessions == 0: print('shutting down Redshift') yield from cluster_control.destroy() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(shutdown()) loop.close()
Add the admin group to the group list data. Fixes the admin group disappearing from the list when updating the display as the result of a search. This group data should probably be managed on the page entirely by the javascript GroupList object, but this seems like the interim method.
<?php /** * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com> * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ $userlistParams = array(); $allGroups=array(); foreach($_["groups"] as $group) { $allGroups[] = $group['name']; } foreach($_["adminGroup"] as $group) { $allGroups[] = $group['name']; } $userlistParams['subadmingroups'] = $allGroups; $userlistParams['allGroups'] = json_encode($allGroups); $items = array_flip($userlistParams['subadmingroups']); unset($items['admin']); $userlistParams['subadmingroups'] = array_flip($items); ?> <div id="app-navigation"> <?php print_unescaped($this->inc('users/part.grouplist')); ?> <div id="app-settings"> <?php print_unescaped($this->inc('users/part.setquota')); ?> </div> </div> <div id="app-content"> <?php print_unescaped($this->inc('users/part.createuser')); ?> <?php print_unescaped($this->inc('users/part.userlist', $userlistParams)); ?> </div>
<?php /** * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com> * This file is licensed under the Affero General Public License version 3 or later. * See the COPYING-README file. */ $userlistParams = array(); $allGroups=array(); foreach($_["groups"] as $group) { $allGroups[] = $group['name']; } $userlistParams['subadmingroups'] = $allGroups; $userlistParams['allGroups'] = json_encode($allGroups); $items = array_flip($userlistParams['subadmingroups']); unset($items['admin']); $userlistParams['subadmingroups'] = array_flip($items); ?> <div id="app-navigation"> <?php print_unescaped($this->inc('users/part.grouplist')); ?> <div id="app-settings"> <?php print_unescaped($this->inc('users/part.setquota')); ?> </div> </div> <div id="app-content"> <?php print_unescaped($this->inc('users/part.createuser')); ?> <?php print_unescaped($this->inc('users/part.userlist', $userlistParams)); ?> </div>
Remove duplication of precondition checks.
package uk.ac.ebi.quickgo.annotation.validation.service; import com.google.common.base.Preconditions; import java.util.Objects; /** * Utility methods related to Database Cross Reference ids. * * @author Tony Wardell * Date: 10/11/2016 * Time: 13:41 * Created with IntelliJ IDEA. */ public class DbCrossReferenceId { private static final String DELIMITER = ":"; public static String db(final String idWithDb) { checkPreconditions(idWithDb); return idWithDb.substring(0, idWithDb.indexOf(":")).trim(); } public static String id(final String idWithDb){ checkPreconditions(idWithDb); return idWithDb.substring(idWithDb.indexOf(":") + 1).trim(); } private static void checkPreconditions(String idWithDb) { Preconditions.checkArgument(Objects.nonNull(idWithDb), "The id should not be null"); Preconditions.checkArgument(idWithDb.contains(DELIMITER), "The id should contain the delimiter %s", DELIMITER); } }
package uk.ac.ebi.quickgo.annotation.validation.service; import com.google.common.base.Preconditions; import java.util.Objects; /** * Utility methods related to Database Cross Reference ids. * * @author Tony Wardell * Date: 10/11/2016 * Time: 13:41 * Created with IntelliJ IDEA. */ public class DbCrossReferenceId { private static final String DELIMITER = ":"; public static String db(final String idWithDb) { Preconditions.checkArgument(Objects.nonNull(idWithDb), "The id should not be null"); Preconditions.checkArgument(idWithDb.contains(DELIMITER), "The id should contain the delimiter %s", DELIMITER); return idWithDb.substring(0, idWithDb.indexOf(":")).trim(); } public static String id(final String idWithDb){ Preconditions.checkArgument(Objects.nonNull(idWithDb), "The id should not be null"); Preconditions.checkArgument(idWithDb.contains(DELIMITER), "The id should contain the delimiter %s", DELIMITER); return idWithDb.substring(idWithDb.indexOf(":") + 1).trim(); } }
Allow CROS (via adding headers)
const path = require('path'); const express = require('express'); const logger = require('winston'); const passport = require('passport'); const bodyParser = require('body-parser'); const bearerAuth = require('./auth/bearer'); const httpHelper = require('sharemyscreen-http-helper'); const user = require('./route/user'); const organization = require('./route/organization/index'); var apiApp = null; var apiRouter = null; function getApp () { logger.info('Initializing api app ...'); apiApp = express(); apiApp.use(bodyParser.json()); apiApp.use(passport.initialize()); apiRouter = express.Router(); bearerAuth.init(); apiRouter.use(passport.authenticate('bearer', { session: false })); apiApp.use(function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type'); next(); }); // Register all routes user.registerRoute(apiRouter); organization.registerRoute(apiRouter); apiApp.use('/v1', apiRouter); apiApp.use('/doc', express.static(path.join(__dirname, '/doc'), {dotfiles: 'allow'})); // Error handler apiApp.use(function (err, req, res, next) { logger.error(err); httpHelper.sendReply(res, httpHelper.error.internalServerError(err)); }); logger.info('Api app initialized'); return apiApp; } module.exports.getApp = getApp;
const path = require('path'); const express = require('express'); const logger = require('winston'); const passport = require('passport'); const bodyParser = require('body-parser'); const bearerAuth = require('./auth/bearer'); const httpHelper = require('sharemyscreen-http-helper'); const user = require('./route/user'); const organization = require('./route/organization/index'); var apiApp = null; var apiRouter = null; function getApp () { logger.info('Initializing api app ...'); apiApp = express(); apiApp.use(bodyParser.json()); apiApp.use(passport.initialize()); apiRouter = express.Router(); bearerAuth.init(); apiRouter.use(passport.authenticate('bearer', { session: false })); // Register all routes user.registerRoute(apiRouter); organization.registerRoute(apiRouter); apiApp.use('/v1', apiRouter); apiApp.use('/doc', express.static(path.join(__dirname, '/doc'), {dotfiles: 'allow'})); // Error handler apiApp.use(function (err, req, res, next) { logger.error(err); httpHelper.sendReply(res, httpHelper.error.internalServerError(err)); }); logger.info('Api app initialized'); return apiApp; } module.exports.getApp = getApp;
Rename Clerking -> Seen by closes #1
""" acute models. """ from django.db.models import fields from opal import models class Demographics(models.Demographics): pass class Location(models.Location): pass class Allergies(models.Allergies): pass class Diagnosis(models.Diagnosis): pass class PastMedicalHistory(models.PastMedicalHistory): pass class Treatment(models.Treatment): pass class Investigation(models.Investigation): pass class Clerking(models.EpisodeSubrecord): _icon = 'fa fa-user' _title = 'Seen by' referrer = fields.CharField(max_length=200, blank=True, null=True) clerked_by = fields.CharField(max_length=200, blank=True, null=True) consultant = fields.CharField(max_length=200, blank=True, null=True) class Plan(models.EpisodeSubrecord): _is_singleton = True _icon = 'fa fa-list-ol' plan = fields.TextField(blank=True, null=True) class Rescuscitation(models.EpisodeSubrecord): _icon = 'fa fa-warning' status = fields.CharField(max_length=200, blank=True, null=True) class NursingNotes(models.EpisodeSubrecord): _icon = 'fa fa-info-circle' notes = fields.TextField(blank=True, null=True) class DischargeDue(models.EpisodeSubrecord): _icon = 'fa fa-calendar' date = fields.DateField(blank=True, null=True)
""" acute models. """ from django.db.models import fields from opal import models class Demographics(models.Demographics): pass class Location(models.Location): pass class Allergies(models.Allergies): pass class Diagnosis(models.Diagnosis): pass class PastMedicalHistory(models.PastMedicalHistory): pass class Treatment(models.Treatment): pass class Investigation(models.Investigation): pass class Clerking(models.EpisodeSubrecord): _icon = 'fa fa-user' referrer = fields.CharField(max_length=200, blank=True, null=True) clerked_by = fields.CharField(max_length=200, blank=True, null=True) consultant = fields.CharField(max_length=200, blank=True, null=True) class Plan(models.EpisodeSubrecord): _is_singleton = True _icon = 'fa fa-list-ol' plan = fields.TextField(blank=True, null=True) class Rescuscitation(models.EpisodeSubrecord): _icon = 'fa fa-warning' status = fields.CharField(max_length=200, blank=True, null=True) class NursingNotes(models.EpisodeSubrecord): _icon = 'fa fa-info-circle' notes = fields.TextField(blank=True, null=True) class DischargeDue(models.EpisodeSubrecord): _icon = 'fa fa-calendar' date = fields.DateField(blank=True, null=True)
Make current language accessible to all views
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); // delay loading this stuff after app has booted, // to allow all modules to load their stuff first (e.g. register views) App::booted(function() { try { // load language $language = App::make('Language'); View::share('language', $language); } catch (\Exception $ex) { } }); } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => $this->namespace], function($router) { require app_path('Http/routes.php'); }); } }
<?php namespace App\Providers; use Illuminate\Routing\Router; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { /** * This namespace is applied to the controller routes in your routes file. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @param \Illuminate\Routing\Router $router * @return void */ public function boot(Router $router) { parent::boot($router); // } /** * Define the routes for the application. * * @param \Illuminate\Routing\Router $router * @return void */ public function map(Router $router) { $router->group(['namespace' => $this->namespace], function($router) { require app_path('Http/routes.php'); }); } }
Add clarifying comment about avoiding pretty printing
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( # Reduce response size by avoiding pretty printing. JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] for word in WORDS: if fragment in word: results.append({ 'word': word, 'category': classify(word), }) return jsonify(results) def classify(word): length = len(word) if length < 7: return 'short' elif length < 10: return 'medium' else: return 'long'
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().split('\n') @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] for word in WORDS: if fragment in word: results.append({ 'word': word, 'category': classify(word), }) return jsonify(results) def classify(word): length = len(word) if length < 7: return 'short' elif length < 10: return 'medium' else: return 'long'
Move externalLink DOM traversal to function Simplify external link tracker by moving DOM traversal into a named function.
(function() { "use strict"; GOVUK.analyticsPlugins = GOVUK.analyticsPlugins || {}; GOVUK.analyticsPlugins.externalLinkTracker = function () { var currentHost = GOVUK.analyticsPlugins.externalLinkTracker.getHostname(), externalLinkSelector = 'a[href^="http"]:not(a[href*="' + currentHost + '"])'; $('body').on('click', externalLinkSelector, trackClickEvent); function trackClickEvent(evt) { var $link = getLinkFromEvent(evt), options = {transport: 'beacon'}, href = $link.attr('href'), linkText = $.trim($link.text()); if (linkText) { options.label = linkText; } GOVUK.analytics.trackEvent('External Link Clicked', href, options); } } function getLinkFromEvent(evt) { var $target = $(evt.target); if (!$target.is('a')) { $target = $target.parents('a'); } return $target; } GOVUK.analyticsPlugins.externalLinkTracker.getHostname = function() { return window.location.hostname; } }());
(function() { "use strict"; GOVUK.analyticsPlugins = GOVUK.analyticsPlugins || {}; GOVUK.analyticsPlugins.externalLinkTracker = function () { var currentHost = GOVUK.analyticsPlugins.externalLinkTracker.getHostname(), externalLinkSelector = 'a[href^="http"]:not(a[href*="' + currentHost + '"])'; $('body').on('click', externalLinkSelector, trackClickEvent); function trackClickEvent(evt) { var $target = $(evt.target), options = {transport: 'beacon'}, href, linkText; if (!$target.is('a')) { $target = $target.parents('a'); } href = $target.attr('href'); linkText = $.trim($target.text()); if (linkText) { options.label = linkText; } GOVUK.analytics.trackEvent('External Link Clicked', href, options); } } GOVUK.analyticsPlugins.externalLinkTracker.getHostname = function() { return window.location.hostname; } }());
Fix root media rewrite rule
<?php /* ------------------------------------------------------------------------ *\ * Rewrite Rules \* ------------------------------------------------------------------------ */ /** * Add various rewrite rules * * @return void */ function __gulp_init_namespace___rewrite_rules(): void { /** * Point to manifest generator at /manifest.json */ add_rewrite_endpoint("manifest", EP_NONE); add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top"); /** * Load offline template at /offline/ */ add_rewrite_endpoint("offline", EP_NONE); add_rewrite_rule("offline/?$", "index.php?offline=true", "top"); /** * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/ * to ensure no 404s occur when critical CSS is included */ add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . '/assets/media/$matches[1]', "top"); } add_action("init", "__gulp_init_namespace___rewrite_rules");
<?php /* ------------------------------------------------------------------------ *\ * Rewrite Rules \* ------------------------------------------------------------------------ */ /** * Add various rewrite rules * * @return void */ function __gulp_init_namespace___rewrite_rules(): void { /** * Point to manifest generator at /manifest.json */ add_rewrite_endpoint("manifest", EP_NONE); add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top"); /** * Load offline template at /offline/ */ add_rewrite_endpoint("offline", EP_NONE); add_rewrite_rule("offline/?$", "index.php?offline=true", "top"); /** * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/ * to ensure no 404s occur when critical CSS is included */ add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . "/assets/media/$1", "top"); } add_action("init", "__gulp_init_namespace___rewrite_rules");
Add the get parameters to the url.
<?php namespace Showpad; use Buzz\Browser; final class BuzzAdapter implements Adapter { /** * @var Browser */ private $browser; /** * Constructor * * @param Browser $browser A Buzz browser instance */ public function __construct(Browser $browser) { $this->browser = $browser; } /** * Send an http request * * @param string $method The HTTP method * @param string $url The url to send the request to * @param array $parameters The parameters for the request (assoc array) * @param array $headers The headers for the request (assoc array) * * return mixed */ public function request($method, $url, array $parameters = null, array $headers = null) { // add query parameters to the url if needed if (isset($parameters['query']) && is_array($parameters['query'])) { $query = parse_url($url, PHP_URL_QUERY); $url .= ($query === null ? '?' : '&') . http_build_query($parameters['query']); } $response = $this->browser->submit($url, $parameters, $method, $headers); return json_decode($response->getContent(), true); } }
<?php namespace Showpad; use Buzz\Browser; final class BuzzAdapter implements Adapter { /** * @var Browser */ private $browser; /** * Constructor * * @param Browser $browser A Buzz browser instance */ public function __construct(Browser $browser) { $this->browser = $browser; } /** * Send an http request * * @param string $method The HTTP method * @param string $url The url to send the request to * @param array $parameters The parameters for the request (assoc array) * @param array $headers The headers for the request (assoc array) * * return mixed */ public function request($method, $url, array $parameters = null, array $headers = null) { $response = $this->browser->submit($url, $parameters, $method, $headers); return json_decode($response->getContent(), true); } }
Rename method to inject step mother
package cuke4duke.internal.jvmclass; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import cuke4duke.StepMother; /** * @author Henning Jensen */ public class GuiceFactory implements ObjectFactory { private final Module module; private final List<Class<?>> classes = new ArrayList<Class<?>>(); private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>(); private Injector injector; public GuiceFactory() throws Throwable { String moduleClassName = System.getProperty("cuke4duke.guiceModule", null); module = (Module) Class.forName(moduleClassName).newInstance(); } public void addClass(Class<?> clazz) { classes.add(clazz); } public void addStepMother(StepMother mother) { // Not supported yet. } public void createObjects() { injector = Guice.createInjector(module); for(Class<?> clazz: classes) { instanceMap.put(clazz, injector.getInstance(clazz)); } } public void disposeObjects() { } public Object getComponent(Class<?> clazz) { return instanceMap.get(clazz); } }
package cuke4duke.internal.jvmclass; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; /** * @author Henning Jensen */ public class GuiceFactory implements ObjectFactory { private final Module module; private final List<Class<?>> classes = new ArrayList<Class<?>>(); private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>(); private Injector injector; public GuiceFactory() throws Throwable { String moduleClassName = System.getProperty("cuke4duke.guiceModule", null); module = (Module) Class.forName(moduleClassName).newInstance(); } public void addClass(Class<?> clazz) { classes.add(clazz); } public void addInstance(Object instance) { } public void createObjects() { injector = Guice.createInjector(module); for(Class<?> clazz: classes) { instanceMap.put(clazz, injector.getInstance(clazz)); } } public void disposeObjects() { } public Object getComponent(Class<?> clazz) { return instanceMap.get(clazz); } }
Hide ASCII container on error
/* * ASCII Camera * http://idevelop.github.com/ascii-camera/ * * Copyright 2013, Andrei Gheorghe (http://github.com/idevelop) * Released under the MIT license */ (function() { var asciiContainer = document.getElementById("ascii"); camera.init({ width: 160, height: 120, fps: 30, mirror: true, onFrame: function(canvas) { ascii.fromCanvas(canvas, { // contrast: 128, callback: function(asciiString) { asciiContainer.innerHTML = asciiString; } }); }, onSuccess: function() { document.getElementById("info").style.display = "none"; }, onError: console.error, onNotSupported: function() { document.getElementById("info").style.display = "none"; asciiContainer.style.display = "none"; document.getElementById("notSupported").style.display = "block"; } }); })();
/* * ASCII Camera * http://idevelop.github.com/ascii-camera/ * * Copyright 2013, Andrei Gheorghe (http://github.com/idevelop) * Released under the MIT license */ (function() { var asciiContainer = document.getElementById("ascii"); camera.init({ width: 160, height: 120, fps: 30, mirror: true, onFrame: function(canvas) { ascii.fromCanvas(canvas, { // contrast: 128, callback: function(asciiString) { asciiContainer.innerHTML = asciiString; } }); }, onSuccess: function() { document.getElementById("info").style.display = "none"; }, onError: console.error, onNotSupported: function() { document.getElementById("info").style.display = "none"; document.getElementById("notSupported").style.display = "block"; } }); })();
Print and exit on error.
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" ) const ( apiURL = "https://domai.nr/api/json/search?client_id=domainr_command_line_app&q=" ) type Result struct { Domain string Availability string } type SearchResults struct { Query string Results []Result } func main() { if len(os.Args) < 2 { fmt.Println("Missing search query. Specify a string to search domainr for.") os.Exit(1) } var query string = os.Args[1] httpResponse, err := http.Get(apiURL + query) if err != nil { fmt.Println(err) os.Exit(1) } defer httpResponse.Body.Close() body, err := ioutil.ReadAll(httpResponse.Body) if err != nil { fmt.Println(err) os.Exit(1) } var sr SearchResults // Decode json string into custom structs. json.Unmarshal(body, &sr) // Print results to stdout fmt.Printf("\n Results for \"%s\"\n\n", sr.Query) for _, result := range sr.Results { var available string switch result.Availability { case "available": available = "✔" default: available = "✘" } fmt.Printf(" %s %s\n", available, result.Domain) } fmt.Printf("\n") }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os" ) type Result struct { Domain string Availability string } type SearchResults struct { Query string Results []Result } func main() { if len(os.Args) < 2 { log.Fatal("Missing search query. Specify a string to search domainr for.") } var query string = os.Args[1] httpResponse, _ := http.Get("https://domai.nr/api/json/search?client_id=domainr_command_line_app&q=" + query) defer httpResponse.Body.Close() body, _ := ioutil.ReadAll(httpResponse.Body) var sr SearchResults // Decode json string into custom structs. json.Unmarshal(body, &sr) // Print results to stdout fmt.Printf("\n Results for \"%s\"\n\n", sr.Query) for _, result := range sr.Results { var available string switch result.Availability { case "available": available = "✔" default: available = "✘" } fmt.Printf(" %s %s\n", available, result.Domain) } fmt.Printf("\n") }
Comment out abstract static function (until we're using PHP 7).
<?php namespace Sil\DevPortal\components; use Sil\DevPortal\components\ApiAxle\Client as ApiAxleClient; trait RepopulateApiAxleTrait { abstract public function createOrUpdateInApiAxle($apiAxle = null); abstract public function getErrors($attribute = null); abstract public function getFriendlyId(); /** * NOTE: PHP < 7 does not allow abstract static functions, but for a class * to use this trait it needs to have a model() function... we just * have no way to enforce that until we get to PHP 7. * abstract public static function model($className = __CLASS__); */ public static function repopulateApiAxle(ApiAxleClient $apiAxle) { $errorsByModel = []; foreach (static::model()->findAll() as $model) { /* @var $model \CActiveRecord */ $result = $model->createOrUpdateInApiAxle($apiAxle); if ( ! $result) { $errorsByModel[$model->getFriendlyId()] = $model->getErrors(); } } return $errorsByModel; } }
<?php namespace Sil\DevPortal\components; use Sil\DevPortal\components\ApiAxle\Client as ApiAxleClient; trait RepopulateApiAxleTrait { abstract public function createOrUpdateInApiAxle($apiAxle = null); abstract public function getErrors($attribute = null); abstract public function getFriendlyId(); abstract public static function model($className = __CLASS__); public static function repopulateApiAxle(ApiAxleClient $apiAxle) { $errorsByModel = []; foreach (static::model()->findAll() as $model) { /* @var $model \CActiveRecord */ $result = $model->createOrUpdateInApiAxle($apiAxle); if ( ! $result) { $errorsByModel[$model->getFriendlyId()] = $model->getErrors(); } } return $errorsByModel; } }
Add strict mode to support generation script
'use strict'; var fs = require('fs'), words = require('./'); fs.writeFileSync('Supported-words.md', 'Supported Words:\n' + '=================\n' + '\n' + '| word | polarity | valence |\n' + '|:----:|:--------:|:-------:|\n' + Object.keys(words).map(function (word) { var valence = words[word]; return '| ' + [ word, valence > 0 ? ':smile:' : ':frowning:', valence > 0 ? '+' + valence : valence ].join(' | ') + ' |'; }).join('\n') + '\n' );
var fs = require('fs'), words = require('./'); fs.writeFileSync('Supported-words.md', 'Supported Words:\n' + '=================\n' + '\n' + '| word | polarity | valence |\n' + '|:----:|:--------:|:-------:|\n' + Object.keys(words).map(function (word) { var valence = words[word]; return '| ' + [ word, valence > 0 ? ':smile:' : ':frowning:', valence > 0 ? '+' + valence : valence ].join(' | ') + ' |'; }).join('\n') + '\n' );
Clean up console log message
// API.AI REQUST // ============================================================================= var request = require('request') function aiRequest(postURL, accessToken, sessionId, message) { request .post({ url: postURL, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Bearer ' + accessToken }, json: { "query": [ message ], "timezone": "Europe/Stockholm", "lang": "en", "sessionId": sessionId } }) .on(`response`, (response) => { console.log(`Response from Api.ai: ` + response.statusCode) }) } module.exports = aiRequest;
// API.AI REQUST // ============================================================================= var request = require('request') function aiRequest(postURL, accessToken, sessionId, message) { request .post({ url: postURL, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Bearer ' + accessToken }, json: { "query": [ message ], "timezone": "Europe/Stockholm", "lang": "en", "sessionId": sessionId } }) .on(`response`, (response) => { console.log(`ai-request response: ` + response.statusCode) }) } module.exports = aiRequest;
Move account error messages below submit button
import React, { PropTypes } from 'react' import Header from 'components/Header' import AccountForm from '../containers/AccountForm' import classes from './AccountView.css' class AccountView extends React.Component { static propTypes = { user: PropTypes.object, viewMode: PropTypes.string.isRequired, errorMessage: PropTypes.string } render () { const { user, errorMessage } = this.props const headerTitle = user ? user.name : (this.props.viewMode === 'login') ? 'Sign In' : 'Create Account' return ( <div className={classes.flexContainer}> <Header title={headerTitle}/> <div className={classes.primary}> <AccountForm/> {errorMessage && <p style={{color:'red'}}>{errorMessage}</p> } </div> </div> ) } } export default AccountView
import React, { PropTypes } from 'react' import Header from 'components/Header' import AccountForm from '../containers/AccountForm' import classes from './AccountView.css' class AccountView extends React.Component { static propTypes = { user: PropTypes.object, viewMode: PropTypes.string.isRequired, errorMessage: PropTypes.string } render () { const { user, errorMessage } = this.props const headerTitle = user ? user.name : (this.props.viewMode === 'login') ? 'Sign In' : 'Create Account' return ( <div className={classes.flexContainer}> <Header title={headerTitle}/> {errorMessage && <p style={{color:'red'}}>{errorMessage}</p> } <div className={classes.primary}> <AccountForm/> </div> </div> ) } } export default AccountView
Fix new name for scan tasks
# Copyright (c) 2013-2016 Quarkslab. # This file is part of IRMA project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License in the top-level directory # of this distribution and at: # # http://www.apache.org/licenses/LICENSE-2.0 # # No part of the project, including this file, may be copied, # modified, propagated, or distributed except according to the # terms contained in the LICENSE file. import celery import config.parser as config from probe.helpers.celerytasks import async_call # declare a new Remote Brain application brain_app = celery.Celery('braintasks') config.conf_brain_celery(brain_app) config.configure_syslog(brain_app) # ============ # Task calls # ============ def register_probe(name, display_name, category, mimetype_regexp): """ send a task to the brain to register local probes""" task = async_call(brain_app, "brain.scan_tasks", "register_probe", args=[name, display_name, category, mimetype_regexp]) return task
# Copyright (c) 2013-2016 Quarkslab. # This file is part of IRMA project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License in the top-level directory # of this distribution and at: # # http://www.apache.org/licenses/LICENSE-2.0 # # No part of the project, including this file, may be copied, # modified, propagated, or distributed except according to the # terms contained in the LICENSE file. import celery import config.parser as config from probe.helpers.celerytasks import async_call # declare a new Remote Brain application brain_app = celery.Celery('braintasks') config.conf_brain_celery(brain_app) config.configure_syslog(brain_app) # ============ # Task calls # ============ def register_probe(name, display_name, category, mimetype_regexp): """ send a task to the brain to register local probes""" task = async_call(brain_app, "brain.tasks", "register_probe", args=[name, display_name, category, mimetype_regexp]) return task
Write check to not log pages when paused - happens in activity-logger module within the debounce page logging function - seems fine here now; may want to move somewhere else later
import debounce from 'lodash/debounce' import { makeRemotelyCallable } from 'src/util/webextensionRPC' import { maybeLogPageVisit } from './log-page-visit' import initPauser from './pause-logging' import { PAUSE_STORAGE_KEY } from '..' const isPaused = async () => (await browser.storage.local.get(PAUSE_STORAGE_KEY))[PAUSE_STORAGE_KEY] || false // Allow logging pause state toggle to be called from other scripts const toggleLoggingPause = initPauser() makeRemotelyCallable({ toggleLoggingPause }) // Debounced functions fro each tab are stored here const tabs = {} // Listens for url changes of the page browser.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => { if (changeInfo.url && tab.url) { // Check if we already have a debounced function for this tab and cancel it if (tabs[tabId]) tabs[tabId].cancel() // Create debounced function and call it tabs[tabId] = debounce(async () => { // Bail-out if logging paused if (await isPaused()) return return maybeLogPageVisit({url: tab.url, tabId: tabId}) }, 10000) tabs[tabId]() } })
import { makeRemotelyCallable } from 'src/util/webextensionRPC' import { maybeLogPageVisit } from './log-page-visit' import initPauser from './pause-logging' import debounce from 'lodash/debounce' // Allow logging pause state toggle to be called from other scripts const toggleLoggingPause = initPauser() makeRemotelyCallable({ toggleLoggingPause }) // Debounced functions fro each tab are stored here const tabs = {} // Listens for url changes of the page browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (changeInfo.url && tab.url) { // Check if we already have a debounced function for this tab and cancel it if (tabs[tabId]) tabs[tabId].cancel() // Create debounced function and call it tabs[tabId] = debounce(() => maybeLogPageVisit({url: tab.url, tabId: tabId}), 10000) tabs[tabId]() } })
Add _cc parameter to tracking codes.
<?php namespace Neuron\Net; use Neuron\Config; /** * Class QueryTrackingParameters * @package Neuron\Net */ class QueryTrackingParameters { /** * @return QueryTrackingParameters */ public static function instance() { static $in; if (!isset($in)) { $in = new self(); // Can we set these from config? if (Config::get('tracking.queryParameters')) { $in->queryParameters = Config::get('tracking.queryParameters'); } } return $in; } public $queryParameters = [ 'utm_abversion', 'utm_referrer', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', '_ga', '_gac', 'pk_vid', '_gl', '_cc' ]; }
<?php namespace Neuron\Net; use Neuron\Config; /** * Class QueryTrackingParameters * @package Neuron\Net */ class QueryTrackingParameters { /** * @return QueryTrackingParameters */ public static function instance() { static $in; if (!isset($in)) { $in = new self(); // Can we set these from config? if (Config::get('tracking.queryParameters')) { $in->queryParameters = Config::get('tracking.queryParameters'); } } return $in; } public $queryParameters = [ 'utm_abversion', 'utm_referrer', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', '_ga', '_gac', 'pk_vid', '_gl' ]; }
Build gmf apps directly into examples-hosted directory
const path = require('path'); const ls = require('ls'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const plugins = []; const entry = {}; const filenamePrefix = process.env.DEV_SERVER ? 'contribs/gmf/apps/' : ''; for (const filename of ls('contribs/gmf/apps/*/index.html')) { const name = path.basename(filename.path); entry[name] = `./${filename.path}/js/Controller.js`; plugins.push( new HtmlWebpackPlugin({ template: filename.full, chunksSortMode: 'manual', filename: filenamePrefix + name + '/index.html', chunks: ['commons', name] }) ); } module.exports = { entry: entry, optimization: { splitChunks: { chunks: 'all', name: 'commons', } }, plugins: plugins, }; if (!process.env.DEV_SERVER) { Object.assign(module.exports, { output: { path: path.resolve(__dirname, '../.build/examples-hosted/contribs/gmf/apps'), }, }); }
const path = require('path'); const ls = require('ls'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const plugins = []; const entry = {}; const filenamePrefix = process.env.DEV_SERVER ? 'contribs/gmf/apps/' : ''; for (const filename of ls('contribs/gmf/apps/*/index.html')) { const name = path.basename(filename.path); entry[name] = `./${filename.path}/js/Controller.js`; plugins.push( new HtmlWebpackPlugin({ template: filename.full, chunksSortMode: 'manual', filename: filenamePrefix + name + '/index.html', chunks: ['commons', name] }) ); } module.exports = { entry: entry, optimization: { splitChunks: { chunks: 'all', name: 'commons', } }, plugins: plugins, }; if (!process.env.DEV_SERVER) { Object.assign(module.exports, { output: { path: path.resolve(__dirname, '../.build/contribs-gmf-apps'), }, }); }
Fix spacing (More OCD, than anything else :S)
package com.techcavern.wavetact.commands.utils; import com.techcavern.wavetact.annot.CMD; import com.techcavern.wavetact.objects.Command; import com.techcavern.wavetact.utils.GeneralUtils; import com.techcavern.wavetact.utils.PermUtils; import org.pircbotx.hooks.events.MessageEvent; public class CheckUserLevel extends Command { @CMD public CheckUserLevel() { super(GeneralUtils.toArray("checkuserlevel level checklevel"), 0, "Checks User Level, 0 arguments"); } @Override public void onCommand(MessageEvent<?> event, String... args) throws Exception { int i = PermUtils.getPermLevel(event.getBot(), event.getUser(), event.getChannel()); if (i == 9001) { event.respond("You are my Master!"); } else if (i == 15) { event.respond("You are a Channel Owner!"); } else if (i == 10) { event.respond("You are a Channel Operator!"); } else if (i == 5) { event.respond("You are a Trusted User!"); } else { event.respond("You are a Regular User!"); } } }
package com.techcavern.wavetact.commands.utils; import com.techcavern.wavetact.annot.CMD; import com.techcavern.wavetact.objects.Command; import com.techcavern.wavetact.utils.GeneralUtils; import com.techcavern.wavetact.utils.PermUtils; import org.pircbotx.hooks.events.MessageEvent; public class CheckUserLevel extends Command { @CMD public CheckUserLevel() { super(GeneralUtils.toArray(" checkuserlevel level checklevel"), 0, "Checks User Level, 0 arguments"); } @Override public void onCommand(MessageEvent<?> event, String... args) throws Exception { int i = PermUtils.getPermLevel(event.getBot(), event.getUser(), event.getChannel()); if (i == 9001) { event.respond("You are my Master!"); } else if (i == 15) { event.respond("You are a Channel Owner!"); } else if (i == 10) { event.respond("You are a Channel Operator!"); } else if (i == 5) { event.respond("You are a Trusted User!"); } else { event.respond("You are a Regular User!"); } } }
Use window to access requirejs
import Ember from 'ember'; const { getOwner, get } = Ember; // Access requirejs global const requirejs = window.requirejs; /** * Unsee a requirejs module if it exists * @param {String} module The requirejs module name */ function requireUnsee(module) { if (requirejs.has(module)) { requirejs.unsee(module); } } export default function clearContainerCache(context, componentName) { const owner = getOwner(context); const config = owner.resolveRegistration('config:environment'); const appName = get(owner, 'base.name') || get(owner, 'application.name'); const modulePrefix = get(config, 'modulePrefix') || appName; const podModulePrefix = get(config, 'podModulePrefix'); // Invalidate regular module requireUnsee(`${modulePrefix}/components/${componentName}`); requireUnsee(`${modulePrefix}/templates/components/${componentName}`); // Invalidate pod modules requireUnsee(`${podModulePrefix}/components/${componentName}/component`); requireUnsee(`${podModulePrefix}/components/${componentName}/template`); }
import Ember from 'ember'; const { getOwner, get } = Ember; /** * Unsee a requirejs module if it exists * @param {String} module The requirejs module name */ function requireUnsee(module) { if (requirejs.has(module)) { requirejs.unsee(module); } } export default function clearContainerCache(context, componentName) { const owner = getOwner(context); const config = owner.resolveRegistration('config:environment'); const appName = get(owner, 'base.name') || get(owner, 'application.name'); const modulePrefix = get(config, 'modulePrefix') || appName; const podModulePrefix = get(config, 'podModulePrefix'); // Invalidate regular module requireUnsee(`${modulePrefix}/components/${componentName}`); requireUnsee(`${modulePrefix}/templates/components/${componentName}`); // Invalidate pod modules requireUnsee(`${podModulePrefix}/components/${componentName}/component`); requireUnsee(`${podModulePrefix}/components/${componentName}/template`); }
Update our MessagingHub.subscribe method arguments
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: Luke Macken <lmacken@redhat.com> class MessagingHub(object): """ A generic messaging hub. This class represents the base functionality of the protocol-level hubs. """ def send_message(self, topic, message): raise NotImplementedError def subscribe(self, topic, callback): raise NotImplementedError
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: Luke Macken <lmacken@redhat.com> class MessagingHub(object): """ A generic messaging hub. This class represents the base functionality of the protocol-level hubs. """ def send_message(self, topic, message): raise NotImplementedError def subscribe(self, topic): raise NotImplementedError
Remove unneccesary raw tag removal
'use strict'; class EscapedIncludeTag { static register(env) { env.addExtension(this.name, new this()); } get tags() { return ['escapedInclude']; } parse(parser, nodes, lexer) { // get the tag token var tok = parser.nextToken(); // parse the args and move after the block end. passing true // as the second arg is required if there are no parentheses var args = parser.parseSignature(null, true); parser.advanceAfterBlockEnd(tok.value); return new nodes.CallExtension(this, 'run', args); }; run(context, templatePath) { var template = context.env.getTemplate(templatePath); var output = template.render(); output = context.env.filters.escape(output); output = context.env.filters.safe(output); return output; } } module.exports = EscapedIncludeTag;
'use strict'; class EscapedIncludeTag { static register(env) { env.addExtension(this.name, new this()); } get tags() { return ['escapedInclude']; } parse(parser, nodes, lexer) { // get the tag token var tok = parser.nextToken(); // parse the args and move after the block end. passing true // as the second arg is required if there are no parentheses var args = parser.parseSignature(null, true); parser.advanceAfterBlockEnd(tok.value); return new nodes.CallExtension(this, 'run', args); }; run(context, templatePath) { var template = context.env.getTemplate(templatePath); var output = template.render(); output = context.env.filters.escape(output); // Remove raw tags var rawMatcher = /{% +raw +%}\n?/; output = context.env.filters.replace(output, rawMatcher, ""); // Remove raw tags var endrawMatcher = /{% +endraw +%}\n?/; output = context.env.filters.replace(output, endrawMatcher, ""); output = context.env.filters.safe(output); return output; } } module.exports = EscapedIncludeTag;
Enable strict mode for Node
#!/usr/bin/env node "use strict"; console.log("Starting bert. Type 'exit' when you're done.") // TODO: run file watcher // TODO: add command line option to specify logs location let logDir = resolveHome('~/.bert/'); // create the log directory if it doesn't already exist createDirectory(logDir); // start `script` var spawn = require('child_process').spawn; // we won't intercept the output to avoid causing user disruption spawn('script', ['-q', '-F', logDir + generateNewLogName()], { stdio: 'inherit' }); // generate new log to avoid name conflicts function generateNewLogName() { // TODO: check directory and add increment for each new session return 'log'; } function createDirectory(dir) { const fs = require('fs'); if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } } // resolve ~ as the user's home directory function resolveHome(filepath) { const path = require('path'); if (filepath[0] === '~') { return path.join(process.env.HOME, filepath.slice(1)); } return filepath; }
#!/usr/bin/env node console.log("Starting bert. Type 'exit' when you're done.") // TODO: run file watcher // TODO: add command line option to specify logs location let logDir = resolveHome('~/.bert/'); // create the log directory if it doesn't already exist createDirectory(logDir); // start `script` var spawn = require('child_process').spawn; // we won't intercept the output to avoid causing user disruption spawn('script', ['-q', '-F', logDir + generateNewLogName()], { stdio: 'inherit' }); // generate new log to avoid name conflicts function generateNewLogName() { // TODO: check directory and add increment for each new session return 'log'; } function createDirectory(dir) { const fs = require('fs'); if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } } // resolve ~ as the user's home directory function resolveHome(filepath) { const path = require('path'); if (filepath[0] === '~') { return path.join(process.env.HOME, filepath.slice(1)); } return filepath; }
Disable connector to run in beast. git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1410 baf6b65b-9124-4dc3-b1c0-01155b4af546
<?php exit; /* connector for Turbellarian estimated execution time: 18 hrs. This connector gets data from website and rank information from a csv file. */ $timestart = microtime(1); include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/TurbellarianAPI'); $GLOBALS['ENV_DEBUG'] = false; $taxa = TurbellarianAPI::get_all_taxa(); $xml = SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . "185.xml"; $OUT = fopen($resource_path, "w+"); fwrite($OUT, $xml); fclose($OUT); $elapsed_time_sec = microtime(1)-$timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec sec \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " min \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n"; exit("\n\n Done processing."); ?>
<?php //exit; /* connector for Turbellarian estimated execution time: 2 hrs. This connector gets data from website and rank information from a csv file. */ $timestart = microtime(1); include_once(dirname(__FILE__) . "/../../config/environment.php"); require_library('connectors/TurbellarianAPI'); $GLOBALS['ENV_DEBUG'] = false; $taxa = TurbellarianAPI::get_all_taxa(); $xml = SchemaDocument::get_taxon_xml($taxa); $resource_path = CONTENT_RESOURCE_LOCAL_PATH . "185.xml"; $OUT = fopen($resource_path, "w+"); fwrite($OUT, $xml); fclose($OUT); $elapsed_time_sec = microtime(1)-$timestart; echo "\n"; echo "elapsed time = $elapsed_time_sec sec \n"; echo "elapsed time = " . $elapsed_time_sec/60 . " min \n"; echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n"; exit("\n\n Done processing."); ?>
Fix config name typo in SetupCheckPygment Summary: Use correct spelling of 'environment.append-paths' so that the current value of the variable will display as expected in the 'pygmentize Not Found' setup issue screen. Test Plan: * Enabled Pygments but haven't installed it * Follow 'unresolved setup issues' link to 'Not Found' screen * See that 'envinronment.append-paths' is None * Set 'environment.append-paths' * See that 'envinronment.append-paths' is still None * Apply this fix * See that 'environment.append-paths' is now '/usr/bin' Reviewers: epriestley Reviewed By: epriestley CC: aran, Korvin Differential Revision: https://secure.phabricator.com/D5555
<?php final class PhabricatorSetupCheckPygment extends PhabricatorSetupCheck { protected function executeChecks() { $pygment = PhabricatorEnv::getEnvConfig('pygments.enabled'); if ($pygment) { list($err) = exec_manual('pygmentize -h'); if ($err) { $summary = pht( 'You enabled pygments but the pygmentize script is not '. 'actually available, your $PATH is probably broken.'); $message = pht( 'The environmental variable $PATH does not contain '. 'pygmentize. You have enabled pygments, which requires '. 'pygmentize to be available in your $PATH variable.'); $this ->newIssue('pygments.enabled') ->setName(pht('pygmentize Not Found')) ->setSummary($summary) ->setMessage($message) ->addPhabricatorConfig('pygments.enabled') ->addPhabricatorConfig('environment.append-paths'); } } } }
<?php final class PhabricatorSetupCheckPygment extends PhabricatorSetupCheck { protected function executeChecks() { $pygment = PhabricatorEnv::getEnvConfig('pygments.enabled'); if ($pygment) { list($err) = exec_manual('pygmentize -h'); if ($err) { $summary = pht( 'You enabled pygments but the pygmentize script is not '. 'actually available, your $PATH is probably broken.'); $message = pht( 'The environmental variable $PATH does not contain '. 'pygmentize. You have enabled pygments, which requires '. 'pygmentize to be available in your $PATH variable.'); $this ->newIssue('pygments.enabled') ->setName(pht('pygmentize Not Found')) ->setSummary($summary) ->setMessage($message) ->addPhabricatorConfig('pygments.enabled') ->addPhabricatorConfig('envinronment.append-paths'); } } } }
Choose a single corpus for a given series,date pair.
from __future__ import print_function import sys from pyspark.sql import SparkSession from pyspark.sql.functions import col, struct, max if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: c19.py <input> <output>", file=sys.stderr) exit(-1) spark = SparkSession.builder.appName('Select c19').getOrCreate() raw = spark.read.option('mergeSchema','true').load(sys.argv[1]) df = raw.filter(col('date') < '1900') spark.conf.set('spark.sql.shuffle.partitions', df.rdd.getNumPartitions() * 2) issues = df.groupBy('series', 'date')\ .agg(max(struct('open', 'corpus'))['corpus'].alias('corpus')) df.join(issues, ['series', 'date', 'corpus'], 'inner')\ .write.save(sys.argv[2]) spark.stop()
from __future__ import print_function import sys from pyspark.sql import SparkSession from pyspark.sql.functions import lit, col, coalesce if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: c19.py <input> <output>", file=sys.stderr) exit(-1) spark = SparkSession.builder.appName('Select c19').getOrCreate() raw = spark.read.option('mergeSchema','true').load(sys.argv[1]) df = raw.filter(col('date') < '1900') opens = df.filter(col('open') == 'true')\ .select('series', 'date', lit(1).alias('inopen')).distinct() df.join(opens, ['series', 'date'], 'left_outer')\ .filter((col('open') == 'true') | col('inopen').isNull())\ .drop('inopen')\ .dropDuplicates(['id'])\ .write.save(sys.argv[2]) spark.stop()
Correct the VPR URL in setting
''' Created on 16 Dec 2013 @author: huyvq ''' from base import * # FOR DEBUG DEBUG = True DEVELOPMENT = True TEMPLATE_DEBUG = DEBUG # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'voer_django', 'USER': 'voer', 'PASSWORD': 'voer', 'HOST': '127.0.0.1', 'PORT': 3306, } } #VPR Address VPR_URL = 'http://voer.edu.vn:2013/1.0/' #VPT Address VPT_URL = 'http://voer.edu.vn:6543/' SITE_URL = 'dev.voer.vn' RECAPTCHA_PUBLIC_KEY = '6Lf__uwSAAAAAPpTMYOLUOBf25clR7fGrqWrpOn0' RECAPTCHA_PRIVATE_KEY = '6Lf__uwSAAAAAPlCihico8fKiAfV09_kbywiI-xx' #STATIC_ROOT = os.path.join(PROJECT_DIR, '_static') COMPRESS_ENABLED = False
''' Created on 16 Dec 2013 @author: huyvq ''' from base import * # FOR DEBUG DEBUG = True DEVELOPMENT = True TEMPLATE_DEBUG = DEBUG # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'voer_django', 'USER': 'voer', 'PASSWORD': 'voer', 'HOST': '127.0.0.1', 'PORT': 3306, } } #VPR Address VPR_URL = 'http://localhost:2013/1.0/' #VPT Address VPT_URL = 'http://voer.edu.vn:6543/' SITE_URL = 'dev.voer.vn' RECAPTCHA_PUBLIC_KEY = '6Lf__uwSAAAAAPpTMYOLUOBf25clR7fGrqWrpOn0' RECAPTCHA_PRIVATE_KEY = '6Lf__uwSAAAAAPlCihico8fKiAfV09_kbywiI-xx' #STATIC_ROOT = os.path.join(PROJECT_DIR, '_static') COMPRESS_ENABLED = False
Add `package *` commands to the list of protected commands. See https://github.com/wp-cli/package-command/issues/10
<?php namespace WP_CLI\Bootstrap; /** * Class DefineProtectedCommands. * * Define the commands that are "protected", meaning that they shouldn't be able * to break due to extension code. * * @package WP_CLI\Bootstrap */ final class DefineProtectedCommands implements BootstrapStep { /** * Process this single bootstrapping step. * * @param BootstrapState $state Contextual state to pass into the step. * * @return BootstrapState Modified state to pass to the next step. */ public function process( BootstrapState $state ) { $commands = $this->get_protected_commands(); $current_command = $this->get_current_command(); foreach ( $commands as $command ) { if ( 0 === strpos( $current_command, $command ) ) { $state->setValue( BootstrapState::IS_PROTECTED_COMMAND, true ); } } return $state; } /** * Get the lost of protected commands. * * @return array */ private function get_protected_commands() { return array( 'cli info', 'package', ); } /** * Get the current command as a string. * * @return string Current command to be executed. */ private function get_current_command() { $runner = new RunnerInstance(); return implode( ' ', (array) $runner()->arguments ); } }
<?php namespace WP_CLI\Bootstrap; /** * Class DefineProtectedCommands. * * Define the commands that are "protected", meaning that they shouldn't be able * to break due to extension code. * * @package WP_CLI\Bootstrap */ final class DefineProtectedCommands implements BootstrapStep { /** * Process this single bootstrapping step. * * @param BootstrapState $state Contextual state to pass into the step. * * @return BootstrapState Modified state to pass to the next step. */ public function process( BootstrapState $state ) { $commands = $this->get_protected_commands(); $current_command = $this->get_current_command(); if ( in_array( $current_command, $commands, true ) ) { $state->setValue( BootstrapState::IS_PROTECTED_COMMAND, true ); } return $state; } /** * Get the lost of protected commands. * * @return array */ private function get_protected_commands() { return array( 'cli info', ); } /** * Get the current command as a string. * * @return string Current command to be executed. */ private function get_current_command() { $runner = new RunnerInstance(); return implode( ' ', (array) $runner()->arguments ); } }