patch
stringlengths
17
31.2k
y
int64
1
1
oldf
stringlengths
0
2.21M
idx
int64
1
1
id
int64
4.29k
68.4k
msg
stringlengths
8
843
proj
stringclasses
212 values
lang
stringclasses
9 values
@@ -53,7 +53,7 @@ public class ProtocGapicPluginGeneratorTest { model.getFiles().stream().map(ProtoFile::getProto).collect(Collectors.toList())) // Only the file to generate a client for (don't generate dependencies) .addFileToGenerate("multiple_services.proto") - .setParameter("language=java") + .setParameter("language=java,transport=grpc") .build(); CodeGeneratorResponse response = ProtocGeneratorMain.generate(codeGeneratorRequest);
1
/* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.codegen.gapic; import com.google.api.codegen.CodegenTestUtil; import com.google.api.codegen.ProtocGeneratorMain; import com.google.api.codegen.protoannotations.GapicCodeGeneratorAnnotationsTest; import com.google.api.tools.framework.model.Model; import com.google.api.tools.framework.model.ProtoFile; import com.google.api.tools.framework.model.testing.TestDataLocator; import com.google.common.truth.Truth; import com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest; import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse; import java.util.stream.Collectors; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class ProtocGapicPluginGeneratorTest { private static String[] protoFiles = {"multiple_services.proto"}; private static TestDataLocator testDataLocator; private static Model model; @ClassRule public static TemporaryFolder tempDir = new TemporaryFolder(); @BeforeClass public static void startUp() { testDataLocator = TestDataLocator.create(GapicCodeGeneratorAnnotationsTest.class); testDataLocator.addTestDataSource(CodegenTestUtil.class, "testsrc/common"); model = CodegenTestUtil.readModel(testDataLocator, tempDir, protoFiles, new String[] {}); } @Test public void testGenerator() { CodeGeneratorRequest codeGeneratorRequest = CodeGeneratorRequest.newBuilder() // All proto files, including dependencies .addAllProtoFile( model.getFiles().stream().map(ProtoFile::getProto).collect(Collectors.toList())) // Only the file to generate a client for (don't generate dependencies) .addFileToGenerate("multiple_services.proto") .setParameter("language=java") .build(); CodeGeneratorResponse response = ProtocGeneratorMain.generate(codeGeneratorRequest); // TODO(andrealin): Look into setting these up as baseline files. Truth.assertThat(response).isNotNull(); Truth.assertThat(response.getError()).isEmpty(); Truth.assertThat(response.getFileCount()).isEqualTo(15); Truth.assertThat(response.getFile(0).getContent()).contains("DecrementerServiceClient"); } @Test public void testFailingGenerator() { CodeGeneratorRequest codeGeneratorRequest = CodeGeneratorRequest.newBuilder() .addAllProtoFile( model.getFiles().stream().map(ProtoFile::getProto).collect(Collectors.toList())) // File does not exist. .addFileToGenerate("fuuuuudge.proto") .build(); CodeGeneratorResponse response = ProtocGeneratorMain.generate(codeGeneratorRequest); Truth.assertThat(response).isNotNull(); Truth.assertThat(response.getError()).isNotEmpty(); } }
1
30,879
can we also test for `transport=rest`?
googleapis-gapic-generator
java
@@ -182,7 +182,9 @@ abstract class AbstractSolrBackendFactory implements FactoryInterface */ protected function createBackend(Connector $connector) { + $config = $this->config->get($this->mainConfig); $backend = new $this->backendClass($connector); + $backend->setPageSize($config->Index->record_batch_size); $backend->setQueryBuilder($this->createQueryBuilder()); $backend->setSimilarBuilder($this->createSimilarBuilder()); if ($this->logger) {
1
<?php /** * Abstract factory for SOLR backends. * * PHP version 7 * * Copyright (C) Villanova University 2013. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package Search * @author David Maus <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Site */ namespace VuFind\Search\Factory; use Interop\Container\ContainerInterface; use Laminas\Config\Config; use Laminas\ServiceManager\Factory\FactoryInterface; use VuFind\Search\Solr\DeduplicationListener; use VuFind\Search\Solr\FilterFieldConversionListener; use VuFind\Search\Solr\HideFacetValueListener; use VuFind\Search\Solr\HierarchicalFacetListener; use VuFind\Search\Solr\InjectConditionalFilterListener; use VuFind\Search\Solr\InjectHighlightingListener; use VuFind\Search\Solr\InjectSpellingListener; use VuFind\Search\Solr\MultiIndexListener; use VuFind\Search\Solr\V3\ErrorListener as LegacyErrorListener; use VuFind\Search\Solr\V4\ErrorListener; use VuFindSearch\Backend\BackendInterface; use VuFindSearch\Backend\Solr\Backend; use VuFindSearch\Backend\Solr\Connector; use VuFindSearch\Backend\Solr\HandlerMap; use VuFindSearch\Backend\Solr\LuceneSyntaxHelper; use VuFindSearch\Backend\Solr\QueryBuilder; use VuFindSearch\Backend\Solr\SimilarBuilder; /** * Abstract factory for SOLR backends. * * @category VuFind * @package Search * @author David Maus <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Site */ abstract class AbstractSolrBackendFactory implements FactoryInterface { /** * Logger. * * @var \Laminas\Log\LoggerInterface */ protected $logger; /** * Superior service manager. * * @var ContainerInterface */ protected $serviceLocator; /** * Primary configuration file identifier. * * @var string */ protected $mainConfig = 'config'; /** * Search configuration file identifier. * * @var string */ protected $searchConfig; /** * Facet configuration file identifier. * * @var string */ protected $facetConfig; /** * YAML searchspecs filename. * * @var string */ protected $searchYaml; /** * VuFind configuration reader * * @var \VuFind\Config\PluginManager */ protected $config; /** * Solr core name * * @var string */ protected $solrCore = ''; /** * Solr field used to store unique identifiers * * @var string */ protected $uniqueKey = 'id'; /** * Solr connector class * * @var string */ protected $connectorClass = Connector::class; /** * Solr backend class * * @var string */ protected $backendClass = Backend::class; /** * Constructor */ public function __construct() { } /** * Create service * * @param ContainerInterface $sm Service manager * @param string $name Requested service name (unused) * @param array $options Extra options (unused) * * @return Backend * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __invoke(ContainerInterface $sm, $name, array $options = null) { $this->serviceLocator = $sm; $this->config = $this->serviceLocator ->get(\VuFind\Config\PluginManager::class); if ($this->serviceLocator->has(\VuFind\Log\Logger::class)) { $this->logger = $this->serviceLocator->get(\VuFind\Log\Logger::class); } $connector = $this->createConnector(); $backend = $this->createBackend($connector); $this->createListeners($backend); return $backend; } /** * Create the SOLR backend. * * @param Connector $connector Connector * * @return Backend */ protected function createBackend(Connector $connector) { $backend = new $this->backendClass($connector); $backend->setQueryBuilder($this->createQueryBuilder()); $backend->setSimilarBuilder($this->createSimilarBuilder()); if ($this->logger) { $backend->setLogger($this->logger); } return $backend; } /** * Create listeners. * * @param Backend $backend Backend * * @return void */ protected function createListeners(Backend $backend) { $events = $this->serviceLocator->get('SharedEventManager'); // Load configurations: $config = $this->config->get($this->mainConfig); $search = $this->config->get($this->searchConfig); $facet = $this->config->get($this->facetConfig); // Highlighting $this->getInjectHighlightingListener($backend, $search)->attach($events); // Conditional Filters if (isset($search->ConditionalHiddenFilters) && $search->ConditionalHiddenFilters->count() > 0 ) { $this->getInjectConditionalFilterListener($search)->attach($events); } // Spellcheck if ($config->Spelling->enabled ?? true) { $dictionaries = ($config->Spelling->simple ?? false) ? ['basicSpell'] : ['default', 'basicSpell']; $spellingListener = new InjectSpellingListener($backend, $dictionaries); $spellingListener->attach($events); } // Apply field stripping if applicable: if (isset($search->StripFields) && isset($search->IndexShards)) { $strip = $search->StripFields->toArray(); foreach ($strip as $k => $v) { $strip[$k] = array_map('trim', explode(',', $v)); } $mindexListener = new MultiIndexListener( $backend, $search->IndexShards->toArray(), $strip, $this->loadSpecs() ); $mindexListener->attach($events); } // Apply deduplication if applicable: if (isset($search->Records->deduplication)) { $this->getDeduplicationListener( $backend, $search->Records->deduplication )->attach($events); } // Attach hierarchical facet listener: $this->getHierarchicalFacetListener($backend)->attach($events); // Apply legacy filter conversion if necessary: $facets = $this->config->get($this->facetConfig); if (!empty($facets->LegacyFields)) { $filterFieldConversionListener = new FilterFieldConversionListener( $facets->LegacyFields->toArray() ); $filterFieldConversionListener->attach($events); } // Attach hide facet value listener: if ($hfvListener = $this->getHideFacetValueListener($backend, $facet)) { $hfvListener->attach($events); } // Attach error listeners for Solr 3.x and Solr 4.x (for backward // compatibility with VuFind 1.x instances). $legacyErrorListener = new LegacyErrorListener($backend); $legacyErrorListener->attach($events); $errorListener = new ErrorListener($backend); $errorListener->attach($events); } /** * Get the Solr core. * * @return string */ protected function getSolrCore() { return $this->solrCore; } /** * Get the Solr URL. * * @param string $config name of configuration file (null for default) * * @return string|array */ protected function getSolrUrl($config = null) { $url = $this->config->get($config ?? $this->mainConfig)->Index->url; $core = $this->getSolrCore(); if (is_object($url)) { return array_map( function ($value) use ($core) { return "$value/$core"; }, $url->toArray() ); } return "$url/$core"; } /** * Get all hidden filter settings. * * @return array */ protected function getHiddenFilters() { $search = $this->config->get($this->searchConfig); $hf = []; // Hidden filters if (isset($search->HiddenFilters)) { foreach ($search->HiddenFilters as $field => $value) { $hf[] = sprintf('%s:"%s"', $field, $value); } } // Raw hidden filters if (isset($search->RawHiddenFilters)) { foreach ($search->RawHiddenFilters as $filter) { $hf[] = $filter; } } return $hf; } /** * Create the SOLR connector. * * @return Connector */ protected function createConnector() { $config = $this->config->get($this->mainConfig); $searchConfig = $this->config->get($this->searchConfig); $defaultFields = $searchConfig->General->default_record_fields ?? '*'; $handlers = [ 'select' => [ 'fallback' => true, 'defaults' => ['fl' => $defaultFields], 'appends' => ['fq' => []], ], 'terms' => [ 'functions' => ['terms'], ], ]; foreach ($this->getHiddenFilters() as $filter) { array_push($handlers['select']['appends']['fq'], $filter); } $connector = new $this->connectorClass( $this->getSolrUrl(), new HandlerMap($handlers), $this->uniqueKey ); $connector->setTimeout( isset($config->Index->timeout) ? $config->Index->timeout : 30 ); if ($this->logger) { $connector->setLogger($this->logger); } if ($this->serviceLocator->has(\VuFindHttp\HttpService::class)) { $connector->setProxy( $this->serviceLocator->get(\VuFindHttp\HttpService::class) ); } return $connector; } /** * Create the query builder. * * @return QueryBuilder */ protected function createQueryBuilder() { $specs = $this->loadSpecs(); $config = $this->config->get($this->mainConfig); $defaultDismax = isset($config->Index->default_dismax_handler) ? $config->Index->default_dismax_handler : 'dismax'; $builder = new QueryBuilder($specs, $defaultDismax); // Configure builder: $search = $this->config->get($this->searchConfig); $caseSensitiveBooleans = isset($search->General->case_sensitive_bools) ? $search->General->case_sensitive_bools : true; $caseSensitiveRanges = isset($search->General->case_sensitive_ranges) ? $search->General->case_sensitive_ranges : true; $helper = new LuceneSyntaxHelper( $caseSensitiveBooleans, $caseSensitiveRanges ); $builder->setLuceneHelper($helper); return $builder; } /** * Create the similar records query builder. * * @return SimilarBuilder */ protected function createSimilarBuilder() { return new SimilarBuilder( $this->config->get($this->searchConfig), $this->uniqueKey ); } /** * Load the search specs. * * @return array */ protected function loadSpecs() { return $this->serviceLocator->get(\VuFind\Config\SearchSpecsReader::class) ->get($this->searchYaml); } /** * Get a deduplication listener for the backend * * @param BackendInterface $backend Search backend * @param bool $enabled Whether deduplication is enabled * * @return DeduplicationListener */ protected function getDeduplicationListener(BackendInterface $backend, $enabled) { return new DeduplicationListener( $backend, $this->serviceLocator, $this->searchConfig, 'datasources', $enabled ); } /** * Get a hide facet value listener for the backend * * @param BackendInterface $backend Search backend * @param Config $facet Configuration of facets * * @return mixed null|HideFacetValueListener */ protected function getHideFacetValueListener( BackendInterface $backend, Config $facet ) { if (!isset($facet->HideFacetValue) || ($facet->HideFacetValue->count()) == 0 ) { return null; } return new HideFacetValueListener( $backend, $facet->HideFacetValue->toArray() ); } /** * Get a hierarchical facet listener for the backend * * @param BackendInterface $backend Search backend * * @return HierarchicalFacetListener */ protected function getHierarchicalFacetListener(BackendInterface $backend) { return new HierarchicalFacetListener( $backend, $this->serviceLocator, $this->facetConfig ); } /** * Get a highlighting listener for the backend * * @param BackendInterface $backend Search backend * @param Config $search Search configuration * * @return InjectHighlightingListener */ protected function getInjectHighlightingListener(BackendInterface $backend, Config $search ) { $fl = isset($search->General->highlighting_fields) ? $search->General->highlighting_fields : '*'; return new InjectHighlightingListener($backend, $fl); } /** * Get a Conditional Filter Listener * * @param Config $search Search configuration * * @return InjectConditionalFilterListener */ protected function getInjectConditionalFilterListener(Config $search) { $listener = new InjectConditionalFilterListener( $search->ConditionalHiddenFilters->toArray() ); $listener->setAuthorizationService( $this->serviceLocator ->get(\LmcRbacMvc\Service\AuthorizationService::class) ); return $listener; } }
1
30,188
If record_batch_size is not set in config.ini, this code will trigger a notice about an undefined value. I would suggest either wrapping the setPageSize() call in an `if (!empty(...)) {` check, or else providing a default value in the set call (i.e. `$config->Index->record_batch_size ?? 100`).
vufind-org-vufind
php
@@ -1,6 +1,6 @@ <script type="text/javascript"> window.analytics||(window.analytics=[]),window.analytics.methods=["identify","track","trackLink","trackForm","trackClick","trackSubmit","page","pageview","ab","alias","ready","group","on","once","off"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var method=window.analytics.methods[i];window.analytics[method]=window.analytics.factory(method)}window.analytics.load=function(t){var a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"d2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)},window.analytics.SNIPPET_VERSION="2.0.8", - window.analytics.load("2nexpdgku3"); + window.analytics.load(<%= ENV['SEGMENT_KEY']%>); window.analytics.page(); </script>
1
<script type="text/javascript"> window.analytics||(window.analytics=[]),window.analytics.methods=["identify","track","trackLink","trackForm","trackClick","trackSubmit","page","pageview","ab","alias","ready","group","on","once","off"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var method=window.analytics.methods[i];window.analytics[method]=window.analytics.factory(method)}window.analytics.load=function(t){var a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"d2dq2ahtl5zl1z.cloudfront.net/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)},window.analytics.SNIPPET_VERSION="2.0.8", window.analytics.load("2nexpdgku3"); window.analytics.page(); </script> <% if signed_in? %> <%= render 'shared/signed_in_analytics' %> <% end %>
1
9,132
I didn't realize we were hardcoding this, thanks for moving it to an env value.
thoughtbot-upcase
rb
@@ -99,7 +99,7 @@ module.exports = function fileItem (props) { } </h4> <div class="UppyDashboardItem-status"> - ${file.data.size && html`<div class="UppyDashboardItem-statusSize">${prettyBytes(file.data.size)}</div>`} + ${isNaN(file.data.size) ? '' : html`<div class="UppyDashboardItem-statusSize">${prettyBytes(file.data.size)}</div>`} ${file.source && html`<div class="UppyDashboardItem-sourceIcon"> ${acquirers.map(acquirer => { if (acquirer.id === file.source) return html`<span title="${props.i18n('fileSource')}: ${acquirer.name}">${acquirer.icon()}</span>`
1
const html = require('yo-yo') const { getETA, getSpeed, prettyETA, getFileNameAndExtension, truncateString, copyToClipboard } = require('../../core/Utils') const prettyBytes = require('prettier-bytes') const FileItemProgress = require('./FileItemProgress') const getFileTypeIcon = require('./getFileTypeIcon') const { iconEdit, iconCopy, iconRetry } = require('./icons') module.exports = function fileItem (props) { const file = props.file const acquirers = props.acquirers const isProcessing = file.progress.preprocess || file.progress.postprocess const isUploaded = file.progress.uploadComplete && !isProcessing && !file.error const uploadInProgressOrComplete = file.progress.uploadStarted || isProcessing const uploadInProgress = (file.progress.uploadStarted && !file.progress.uploadComplete) || isProcessing const isPaused = file.isPaused || false const error = file.error || false const fileName = getFileNameAndExtension(file.meta.name).name const truncatedFileName = props.isWide ? truncateString(fileName, 15) : fileName const onPauseResumeCancelRetry = (ev) => { if (isUploaded) return if (error) { props.retryUpload(file.id) return } if (props.resumableUploads) { props.pauseUpload(file.id) } else { props.cancelUpload(file.id) } } return html`<li class="UppyDashboardItem ${uploadInProgress ? 'is-inprogress' : ''} ${isProcessing ? 'is-processing' : ''} ${isUploaded ? 'is-complete' : ''} ${isPaused ? 'is-paused' : ''} ${error ? 'is-error' : ''} ${props.resumableUploads ? 'is-resumable' : ''}" id="uppy_${file.id}" title="${file.meta.name}"> <div class="UppyDashboardItem-preview"> <div class="UppyDashboardItem-previewInnerWrap" style="background-color: ${getFileTypeIcon(file.type).color}"> ${file.preview ? html`<img alt="${file.name}" src="${file.preview}">` : html`<div class="UppyDashboardItem-previewIconWrap"> <span class="UppyDashboardItem-previewIcon" style="color: ${getFileTypeIcon(file.type).color}">${getFileTypeIcon(file.type).icon}</span> <svg class="UppyDashboardItem-previewIconBg" width="72" height="93" viewBox="0 0 72 93"><g><path d="M24.08 5h38.922A2.997 2.997 0 0 1 66 8.003v74.994A2.997 2.997 0 0 1 63.004 86H8.996A2.998 2.998 0 0 1 6 83.01V22.234L24.08 5z" fill="#FFF"/><path d="M24 5L6 22.248h15.007A2.995 2.995 0 0 0 24 19.244V5z" fill="#E4E4E4"/></g></svg> </div>` } </div> <div class="UppyDashboardItem-progress"> <button class="UppyDashboardItem-progressBtn" type="button" title="${isUploaded ? 'upload complete' : props.resumableUploads ? file.isPaused ? 'resume upload' : 'pause upload' : 'cancel upload' }" onclick=${onPauseResumeCancelRetry}> ${error ? iconRetry() : FileItemProgress({ progress: file.progress.percentage, fileID: file.id }) } </button> ${props.showProgressDetails ? html`<div class="UppyDashboardItem-progressInfo" title="${props.i18n('fileProgress')}" aria-label="${props.i18n('fileProgress')}"> ${!file.isPaused && !isUploaded ? html`<span>${prettyETA(getETA(file.progress))} ・ ↑ ${prettyBytes(getSpeed(file.progress))}/s</span>` : null } </div>` : null } </div> </div> <div class="UppyDashboardItem-info"> <h4 class="UppyDashboardItem-name" title="${fileName}"> ${file.uploadURL ? html`<a href="${file.uploadURL}" target="_blank"> ${file.extension ? truncatedFileName + '.' + file.extension : truncatedFileName} </a>` : file.extension ? truncatedFileName + '.' + file.extension : truncatedFileName } </h4> <div class="UppyDashboardItem-status"> ${file.data.size && html`<div class="UppyDashboardItem-statusSize">${prettyBytes(file.data.size)}</div>`} ${file.source && html`<div class="UppyDashboardItem-sourceIcon"> ${acquirers.map(acquirer => { if (acquirer.id === file.source) return html`<span title="${props.i18n('fileSource')}: ${acquirer.name}">${acquirer.icon()}</span>` })} </div>` } </div> ${!uploadInProgressOrComplete ? html`<button class="UppyDashboardItem-edit" type="button" aria-label="Edit file" title="Edit file" onclick=${(e) => props.showFileCard(file.id)}> ${iconEdit()}</button>` : null } ${file.uploadURL ? html`<button class="UppyDashboardItem-copyLink" type="button" aria-label="Copy link" title="Copy link" onclick=${() => { copyToClipboard(file.uploadURL, props.i18n('copyLinkToClipboardFallback')) .then(() => { props.log('Link copied to clipboard.') props.info(props.i18n('copyLinkToClipboardSuccess'), 'info', 3000) }) .catch(props.log) }}>${iconCopy()}</button>` : null } </div> <div class="UppyDashboardItem-action"> ${!isUploaded ? html`<button class="UppyDashboardItem-remove" type="button" aria-label="Remove file" title="Remove file" onclick=${() => props.removeFile(file.id)}> <svg class="UppyIcon" width="22" height="21" viewBox="0 0 18 17"> <ellipse cx="8.62" cy="8.383" rx="8.62" ry="8.383"/> <path stroke="#FFF" fill="#FFF" d="M11 6.147L10.85 6 8.5 8.284 6.15 6 6 6.147 8.35 8.43 6 10.717l.15.146L8.5 8.578l2.35 2.284.15-.146L8.65 8.43z"/> </svg> </button>` : null } </div> </li>` }
1
10,142
We are trying to support IE 10-11, so we'll need a polyfill for this one, I think.
transloadit-uppy
js
@@ -38,6 +38,9 @@ const { useSelect, useDispatch } = Data; function ResetButton( { children } ) { const postResetURL = useSelect( ( select ) => select( CORE_SITE ).getAdminURL( 'googlesitekit-splash', { notification: 'reset_success' } ) ); + const isNavigating = useSelect( ( select ) => select( CORE_LOCATION ).isNavigating() ); + const navigatingURL = useSelect( ( select ) => select( CORE_LOCATION ).getNavigateURL() ); + const [ dialogActive, setDialogActive ] = useState( false ); useEffect( () => {
1
/** * ResetButton component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; import { Fragment, useState, useEffect, useCallback, createInterpolateElement } from '@wordpress/element'; import { ESCAPE } from '@wordpress/keycodes'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { clearWebStorage } from '../util'; import Dialog from './Dialog'; import Modal from './Modal'; import Link from './Link'; import { CORE_SITE } from '../googlesitekit/datastore/site/constants'; import { CORE_LOCATION } from '../googlesitekit/datastore/location/constants'; const { useSelect, useDispatch } = Data; function ResetButton( { children } ) { const postResetURL = useSelect( ( select ) => select( CORE_SITE ).getAdminURL( 'googlesitekit-splash', { notification: 'reset_success' } ) ); const [ dialogActive, setDialogActive ] = useState( false ); useEffect( () => { const handleCloseModal = ( event ) => { if ( ESCAPE === event.keyCode ) { // Only close the modal if the "Escape" key is pressed. setDialogActive( false ); } }; if ( dialogActive ) { // When the dialogActive changes and it is set to true(has opened), add the event listener. global.addEventListener( 'keyup', handleCloseModal, false ); } // Remove the event listener when the dialog is removed; there's no need // to have it attached when it won't be used. return () => { if ( dialogActive ) { // When the dialogActive is true(is open) and its value changes, remove the event listener. global.removeEventListener( 'keyup', handleCloseModal ); } }; }, [ dialogActive ] ); const { reset } = useDispatch( CORE_SITE ); const { navigateTo } = useDispatch( CORE_LOCATION ); const handleUnlinkConfirm = useCallback( async () => { await reset(); clearWebStorage(); navigateTo( postResetURL ); }, [ reset, postResetURL ] ); const toggleDialogActive = useCallback( () => { setDialogActive( ! dialogActive ); }, [ dialogActive ] ); const openDialog = useCallback( () => { setDialogActive( true ); }, [] ); return ( <Fragment> <Link className="googlesitekit-reset-button" onClick={ openDialog } inherit > { children || __( 'Reset Site Kit', 'google-site-kit' ) } </Link> <Modal> <Dialog dialogActive={ dialogActive } handleConfirm={ handleUnlinkConfirm } handleDialog={ toggleDialogActive } title={ __( 'Reset Site Kit', 'google-site-kit' ) } subtitle={ createInterpolateElement( __( `Resetting will disconnect all users and remove all Site Kit settings and data within WordPress. <br />You and any other users who wish to use Site Kit will need to reconnect to restore access.`, 'google-site-kit' ), { br: <br />, } ) } confirmButton={ __( 'Reset', 'google-site-kit' ) } danger /> </Modal> </Fragment> ); } export default ResetButton;
1
35,547
It looks like there's a new `isNavigatingTo( url )` selector for this very purpose so let's use this here instead. This way we just need to use the one selector rather than two. Let's assign that to a similar-named variable here (e.g. `isNavigatingToPostResetURL`) rather than the prop it's used with.
google-site-kit-wp
js
@@ -29,8 +29,8 @@ namespace lbann { -void im2col(const Mat& im, - Mat& col, +void im2col(const AbsMat& im, + AbsMat& col, const int num_channels, const int im_num_dims, const int * im_dims,
1
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <[email protected]> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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. //////////////////////////////////////////////////////////////////////////////// #include "lbann/utils/im2col.hpp" #include "lbann/utils/exception.hpp" namespace lbann { void im2col(const Mat& im, Mat& col, const int num_channels, const int im_num_dims, const int * im_dims, const int * im_pads, const int * window_dims, const int * window_strides) { // Input and output parameters const int col_height = col.Height(); const int col_width = col.Width(); const DataType *__restrict__ im_buffer = im.LockedBuffer(); DataType *__restrict__ col_buffer = col.Buffer(); // im2col parameters std::vector<int> offset_start(im_num_dims); std::vector<int> offset_end(im_num_dims); std::vector<int> offset_stride(im_num_dims); std::vector<int> offset_num(im_num_dims); for(int d = 0; d < im_num_dims; ++d) { offset_start[d] = -im_pads[d]; offset_end[d] = im_dims[d] + im_pads[d] - window_dims[d] + 1; offset_stride[d] = window_strides[d]; offset_num[d] = (offset_end[d] - offset_start[d] + offset_stride[d] - 1) / offset_stride[d]; } #ifdef LBANN_DEBUG const int im_size = im.Height(); // Check matrix dimensions const int expected_im_size = std::accumulate(im_dims, im_dims + im_num_dims, num_channels, std::multiplies<int>()); const int expected_col_height = std::accumulate(window_dims, window_dims + im_num_dims, num_channels, std::multiplies<int>()); const int expected_col_width = std::accumulate(offset_num.begin(), offset_num.end(), 1, std::multiplies<int>()); if(im_size != expected_im_size || im.Width() != 1) { std::stringstream ss; ss << "im2col: im matrix has invalid dimensions " << "(expected " << expected_im_size << " x " << 1 << ", " << "found " << im_size << " x " << im.Width() << ")"; throw lbann_exception(ss.str()); } if(col_height != expected_col_height || col_width != expected_col_width) { std::stringstream ss; ss << "im2col: col matrix has invalid dimensions " << "(expected " << expected_col_height << " x " << expected_col_width << ", " << "found " << col_height << " x " << col_width << ")"; throw lbann_exception(ss.str()); } #endif // LBANN_DEBUG // Call optimized routine for 1x1 im2col std::vector<int> zeros(im_num_dims, 0), ones(im_num_dims, 1); if(std::equal(im_pads, im_pads + im_num_dims, zeros.begin()) && std::equal(window_dims, window_dims + im_num_dims, ones.begin()) && std::equal(window_strides, window_strides + im_num_dims, ones.begin())) { im2col_1x1(im_buffer, col_buffer, num_channels, im_num_dims, im_dims); return; } // Call optimized routine for 2D data if(im_num_dims == 2) { im2col_2d(im_buffer, col_buffer, im_dims[1], im_dims[0], im_pads[1], im_pads[0], num_channels, window_dims[1], window_dims[0], window_strides[1], window_strides[0]); return; } // Iterate through col matrix columns #pragma omp parallel for for(int col_col = 0; col_col < col_width; ++col_col) { // Initialize arrays std::vector<int> offset_pos(im_num_dims); std::vector<int> window_pos(im_num_dims); // Get position of current offset int col_col_remainder = col_col; for(int d = im_num_dims-1; d >= 0; --d) { const int offset = col_col_remainder % offset_num[d]; offset_pos[d] = offset_start[d] + offset * offset_stride[d]; col_col_remainder /= offset_num[d]; } // Iterate through col matrix entries for(int col_row = 0; col_row < col_height; ++col_row) { const int col_index = col_row + col_col * col_height; // Get position in window and channel int col_row_remainder = col_row; for(int d = im_num_dims-1; d >= 0; --d) { window_pos[d] = col_row_remainder % window_dims[d]; col_row_remainder /= window_dims[d]; } const int channel = col_row_remainder; // Get im matrix entry bool im_pos_valid = true; int im_index = channel; for(int d = 0; d < im_num_dims; ++d) { const int im_pos = offset_pos[d] + window_pos[d]; im_pos_valid = im_pos_valid && 0 <= im_pos && im_pos < im_dims[d]; im_index = im_pos + im_index * im_dims[d]; } // Copy im matrix entry to col matrix if valid col_buffer[col_index] = (im_pos_valid ? im_buffer[im_index] : DataType(0)); } } } void col2im(const Mat& col, Mat& im, const int num_channels, const int im_num_dims, const int * im_dims, const int * im_pads, const int * window_dims, const int * window_strides) { // Input and output parameters const DataType *__restrict__ col_buffer = col.LockedBuffer(); DataType *__restrict__ im_buffer = im.Buffer(); // col2im parameters std::vector<int> offset_start(im_num_dims); std::vector<int> offset_end(im_num_dims); std::vector<int> offset_stride(im_num_dims); std::vector<int> offset_num(im_num_dims); for(int d = 0; d < im_num_dims; ++d) { offset_start[d] = -im_pads[d]; offset_end[d] = im_dims[d] + im_pads[d] - window_dims[d] + 1; offset_stride[d] = window_strides[d]; offset_num[d] = (offset_end[d] - offset_start[d] + offset_stride[d] - 1) / offset_stride[d]; } #ifdef LBANN_DEBUG const int im_size = im.Height(); const int col_height = col.Height(); const int col_width = col.Width(); // Check matrix dimensions const int expected_im_size = std::accumulate(im_dims, im_dims + im_num_dims, num_channels, std::multiplies<int>()); const int expected_col_height = std::accumulate(window_dims, window_dims + im_num_dims, num_channels, std::multiplies<int>()); const int expected_col_width = std::accumulate(offset_num.begin(), offset_num.end(), 1, std::multiplies<int>()); if(im_size != expected_im_size || im.Width() != 1) { std::stringstream ss; ss << "im2col: im matrix has invalid dimensions " << "(expected " << expected_im_size << " x " << 1 << ", " << "found " << im_size << " x " << im.Width() << ")"; throw lbann_exception(ss.str()); } if(col_height != expected_col_height || col_width != expected_col_width) { std::stringstream ss; ss << "im2col: col matrix has invalid dimensions " << "(expected " << expected_col_height << " x " << expected_col_width << ", " << "found " << col_height << " x " << col_width << ")"; throw lbann_exception(ss.str()); } #endif // LBANN_DEBUG // Call optimized routine for 1x1 col2im std::vector<int> zeros(im_num_dims, 0), ones(im_num_dims, 1); if(std::equal(im_pads, im_pads + im_num_dims, zeros.begin()) && std::equal(window_dims, window_dims + im_num_dims, ones.begin()) && std::equal(window_strides, window_strides + im_num_dims, ones.begin())) { col2im_1x1(col_buffer, im_buffer, num_channels, im_num_dims, im_dims); return; } // Call optimized routine for 2D data if(im_num_dims == 2) { col2im_2d(col_buffer, im_buffer, im_dims[1], im_dims[0], im_pads[1], im_pads[0], num_channels, window_dims[1], window_dims[0], window_strides[1], window_strides[0]); return; } // Default algorithm col2im(col, im, num_channels, im_num_dims, im_dims, im_pads, window_dims, window_strides, std::plus<DataType>()); } void col2im(const Mat& col, Mat& im, const int num_channels, const int im_num_dims, const int * im_dims, const int * im_pads, const int * window_dims, const int * window_strides, std::function<DataType(const DataType&,const DataType&)> reduction_op) { // Input and output parameters const int col_height = col.Height(); const int im_size = im.Height(); const DataType *__restrict__ col_buffer = col.LockedBuffer(); DataType *__restrict__ im_buffer = im.Buffer(); // im2col parameters std::vector<int> offset_start(im_num_dims); std::vector<int> offset_end(im_num_dims); std::vector<int> offset_stride(im_num_dims); std::vector<int> offset_num(im_num_dims); for(int d = 0; d < im_num_dims; ++d) { offset_start[d] = -im_pads[d]; offset_end[d] = im_dims[d] + im_pads[d] - window_dims[d] + 1; offset_stride[d] = window_strides[d]; offset_num[d] = (offset_end[d] - offset_start[d] + offset_stride[d] - 1) / offset_stride[d]; } // Call optimized routine for 1x1 col2im std::vector<int> zeros(im_num_dims, 0), ones(im_num_dims, 1); if(std::equal(im_pads, im_pads + im_num_dims, zeros.begin()) && std::equal(window_dims, window_dims + im_num_dims, ones.begin()) && std::equal(window_strides, window_strides + im_num_dims, ones.begin())) { col2im_1x1(col_buffer, im_buffer, num_channels, im_num_dims, im_dims); return; } // Iterate through im matrix entries #pragma omp parallel for for(int im_index = 0; im_index < im_size; ++im_index) { // Initialize arrays std::vector<int> im_pos(im_num_dims); std::vector<int> first_offset(im_num_dims); std::vector<int> last_offset(im_num_dims); std::vector<int> offset(im_num_dims); // Get position of im matrix entry int im_index_remainder = im_index; for(int d = im_num_dims-1; d >= 0; --d) { im_pos[d] = im_index_remainder % im_dims[d]; im_index_remainder /= im_dims[d]; } const int channel = im_index_remainder; // Initialize im matrix entry DataType im_entry = 0; bool im_entry_initialized = false; bool offsets_finished = false; // Get window offsets containing im matrix entry for(int d = 0; d < im_num_dims; ++d) { first_offset[d] = (im_pos[d] - offset_start[d] - window_dims[d] + offset_stride[d]) / offset_stride[d]; first_offset[d] = std::max(first_offset[d], 0); last_offset[d] = (im_pos[d] - offset_start[d]) / offset_stride[d]; last_offset[d] = std::min(last_offset[d], offset_num[d] - 1); offset[d] = first_offset[d]; if(first_offset[d] > last_offset[d]) { offsets_finished = true; } } // Iterate through window offsets containing im matrix entry while(!offsets_finished) { // Get col matrix entry corresponding to im matrix entry int col_row = channel; int col_col = 0; for(int d = 0; d < im_num_dims; ++d) { const int window_pos = im_pos[d] - (offset_start[d] + offset[d] * offset_stride[d]); col_row = window_pos + col_row * window_dims[d]; col_col = offset[d] + col_col * offset_num[d]; } const int col_index = col_row + col_col * col_height; // Add col matrix entry to im matrix entry const DataType col_entry = col_buffer[col_index]; im_entry = (im_entry_initialized ? reduction_op(im_entry, col_entry) : col_entry); im_entry_initialized = true; // Move to next window offset ++offset[im_num_dims-1]; for(int d = im_num_dims-1; d >= 1; --d) { if(offset[d] > last_offset[d]) { offset[d] = first_offset[d]; ++offset[d-1]; } } offsets_finished = offset[0] > last_offset[0]; } // Update output entry im_buffer[im_index] = im_entry; } } void im2col_1x1(const DataType * input_buffer, DataType * output_buffer, const int num_channels, const int num_input_dims, const int * input_dims) { const int spatial_size = std::accumulate(input_dims, input_dims + num_input_dims, 1, std::multiplies<int>()); const Mat input_matrix(spatial_size, num_channels, input_buffer, spatial_size); Mat output_matrix(num_channels, spatial_size, output_buffer, num_channels); El::Transpose(input_matrix, output_matrix); } void im2col_2d(const DataType *__restrict__ input_buffer, DataType *__restrict__ output_buffer, const int input_dim_x, const int input_dim_y, const int input_pad_x, const int input_pad_y, const int num_channels, const int window_dim_x, const int window_dim_y, const int offset_stride_x, const int offset_stride_y) { // im2col parameters const int offset_start_x = -input_pad_x; const int offset_start_y = -input_pad_y; const int offset_end_x = input_dim_x + input_pad_x - window_dim_x + 1; const int offset_end_y = input_dim_y + input_pad_y - window_dim_y + 1; const int offset_num_x = (offset_end_x - offset_start_x + offset_stride_x - 1) / offset_stride_x; const int offset_num_y = (offset_end_y - offset_start_y + offset_stride_y - 1) / offset_stride_y; const int output_height = num_channels * window_dim_x * window_dim_y; // Iterate through output matrix entries #pragma omp parallel for collapse(5) for(int offset_y = 0; offset_y < offset_num_y; ++offset_y) { for(int offset_x = 0; offset_x < offset_num_x; ++offset_x) { for(int channel = 0; channel < num_channels; ++channel) { for(int window_pos_y = 0; window_pos_y < window_dim_y; ++window_pos_y) { for(int window_pos_x = 0; window_pos_x < window_dim_x; ++window_pos_x) { // Get input entry const int offset_pos_y = offset_start_y + offset_y * offset_stride_y; const int offset_pos_x = offset_start_x + offset_x * offset_stride_x; const int input_pos_y = offset_pos_y + window_pos_y; const int input_pos_x = offset_pos_x + window_pos_x; const int input_index = (input_pos_x + input_pos_y * input_dim_x + channel * input_dim_x * input_dim_y); const bool input_pos_valid = (0 <= input_pos_y && input_pos_y < input_dim_y && 0 <= input_pos_x && input_pos_x < input_dim_x); // Get output entry const int output_row = (window_pos_x + window_pos_y * window_dim_x + channel * window_dim_x * window_dim_y); const int output_col = offset_x + offset_y * offset_num_x; const int output_index = output_row + output_col * output_height; // Copy input entry to output entry if valid output_buffer[output_index] = input_pos_valid ? input_buffer[input_index] : DataType(0); } } } } } } void col2im_1x1(const DataType * input_buffer, DataType * output_buffer, const int num_channels, const int num_output_dims, const int * output_dims) { const int spatial_size = std::accumulate(output_dims, output_dims + num_output_dims, 1, std::multiplies<int>()); const Mat input_matrix(num_channels, spatial_size, input_buffer, num_channels); Mat output_matrix(spatial_size, num_channels, output_buffer, spatial_size); El::Transpose(input_matrix, output_matrix); } void col2im_2d(const DataType *__restrict__ input_buffer, DataType *__restrict__ output_buffer, const int output_dim_x, const int output_dim_y, const int output_pad_x, const int output_pad_y, const int num_channels, const int window_dim_x, const int window_dim_y, const int offset_stride_x, const int offset_stride_y) { // col2im parameters const int offset_start_x = -output_pad_x; const int offset_start_y = -output_pad_y; const int offset_end_x = output_dim_x + output_pad_x - window_dim_x + 1; const int offset_end_y = output_dim_y + output_pad_y - window_dim_y + 1; const int offset_num_x = (offset_end_x - offset_start_x + offset_stride_x - 1) / offset_stride_x; const int offset_num_y = (offset_end_y - offset_start_y + offset_stride_y - 1) / offset_stride_y; const int input_height = num_channels * window_dim_x * window_dim_y; // Iterate through output entries #pragma omp parallel for collapse(3) for(int channel = 0; channel < num_channels; ++channel) { for(int output_pos_y = 0; output_pos_y < output_dim_y; ++output_pos_y) { for(int output_pos_x = 0; output_pos_x < output_dim_x; ++output_pos_x) { // Get output entry const int output_index = (output_pos_x + output_pos_y * output_dim_x + channel * output_dim_x * output_dim_y); DataType output_entry = 0; // Get window offsets containing output entry const int offset_x_lower = (output_pos_x - offset_start_x - window_dim_x + offset_stride_x) / offset_stride_x; const int offset_y_lower = (output_pos_y - offset_start_y - window_dim_y + offset_stride_y) / offset_stride_y; const int offset_x_upper = (output_pos_x - offset_start_x) / offset_stride_x; const int offset_y_upper = (output_pos_y - offset_start_y) / offset_stride_y; const int first_offset_x = std::max(offset_x_lower, 0); const int first_offset_y = std::max(offset_y_lower, 0); const int last_offset_x = std::min(offset_x_upper, offset_num_x - 1); const int last_offset_y = std::min(offset_y_upper, offset_num_y - 1); // Iterate through window offsets for(int offset_y = first_offset_y; offset_y <= last_offset_y; ++offset_y) { const int window_pos_y = output_pos_y - (offset_start_y + offset_y * offset_stride_y); for(int offset_x = first_offset_x; offset_x <= last_offset_x; ++offset_x) { const int window_pos_x = output_pos_x - (offset_start_x + offset_x * offset_stride_x); // Get input entry const int input_row = (window_pos_x + window_pos_y * window_dim_x + channel * window_dim_x * window_dim_y); const int input_col = offset_x + offset_y * offset_num_x; const int input_index = input_row + input_col * input_height; // Add input entry to output entry output_entry += input_buffer[input_index]; } } // Update output entry output_buffer[output_index] = output_entry; } } } } } // namespace lbann
1
12,526
I think im2col should only accommodate CPUMat.
LLNL-lbann
cpp
@@ -24,6 +24,8 @@ from google.cloud.forseti.notifier.notifiers import cscc_notifier from google.cloud.forseti.notifier.notifiers.inventory_summary import InventorySummary from google.cloud.forseti.services.inventory.storage import DataAccess from google.cloud.forseti.services.scanner import dao as scanner_dao +from google.cloud.forseti.common.util.email.email_factory import EmailFactory +from google.cloud.forseti.notifier.notifiers import email_violations # pylint: enable=line-too-long
1
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Notifier runner.""" import importlib import inspect # pylint: disable=line-too-long from google.cloud.forseti.common.util import logger from google.cloud.forseti.common.util import string_formats from google.cloud.forseti.notifier.notifiers.base_notification import BaseNotification from google.cloud.forseti.notifier.notifiers import cscc_notifier from google.cloud.forseti.notifier.notifiers.inventory_summary import InventorySummary from google.cloud.forseti.services.inventory.storage import DataAccess from google.cloud.forseti.services.scanner import dao as scanner_dao # pylint: enable=line-too-long LOGGER = logger.get_logger(__name__) # pylint: disable=inconsistent-return-statements def find_notifiers(notifier_name): """Get the first class in the given sub module Args: notifier_name (str): Name of the notifier. Return: class: The class in the sub module """ try: module = importlib.import_module( 'google.cloud.forseti.notifier.notifiers.{0}'.format( notifier_name)) for filename in dir(module): obj = getattr(module, filename) if inspect.isclass(obj) \ and issubclass(obj, BaseNotification) \ and obj is not BaseNotification: return obj except ImportError: LOGGER.exception('Can\'t import notifier %s', notifier_name) # pylint: enable=inconsistent-return-statements def convert_to_timestamp(violations): """Convert violation created_at_datetime to timestamp string. Args: violations (dict): List of violations as dict with created_at_datetime. Returns: list: List of violations as dict with created_at_datetime converted to timestamp string. """ for violation in violations: violation['created_at_datetime'] = ( violation['created_at_datetime'].strftime( string_formats.TIMESTAMP_TIMEZONE)) return violations # pylint: disable=too-many-branches,too-many-statements def run(inventory_index_id, scanner_index_id, progress_queue, service_config=None): """Run the notifier. Entry point when the notifier is run as a library. Args: inventory_index_id (int64): Inventory index id. scanner_index_id (int64): Scanner index id. progress_queue (Queue): The progress queue. service_config (ServiceConfig): Forseti 2.0 service configs. Returns: int: Status code. """ # pylint: disable=too-many-locals global_configs = service_config.get_global_config() notifier_configs = service_config.get_notifier_config() with service_config.scoped_session() as session: if scanner_index_id: inventory_index_id = ( DataAccess.get_inventory_index_id_by_scanner_index_id( session, scanner_index_id)) else: if not inventory_index_id: inventory_index_id = ( DataAccess.get_latest_inventory_index_id(session)) scanner_index_id = scanner_dao.get_latest_scanner_index_id( session, inventory_index_id) if not scanner_index_id: LOGGER.error( 'No success or partial success scanner index found for ' 'inventory index: "%s".', str(inventory_index_id)) else: # get violations violation_access = scanner_dao.ViolationAccess(session) violations = violation_access.list( scanner_index_id=scanner_index_id) violations_as_dict = [] for violation in violations: violations_as_dict.append( scanner_dao.convert_sqlalchemy_object_to_dict(violation)) violations_as_dict = convert_to_timestamp(violations_as_dict) violation_map = scanner_dao.map_by_resource(violations_as_dict) for retrieved_v in violation_map: log_message = ( 'Retrieved {} violations for resource \'{}\''.format( len(violation_map[retrieved_v]), retrieved_v)) LOGGER.info(log_message) progress_queue.put(log_message) # build notification notifiers notifiers = [] for resource in notifier_configs['resources']: if violation_map.get(resource['resource']) is None: log_message = 'Resource \'{}\' has no violations'.format( resource['resource']) progress_queue.put(log_message) LOGGER.info(log_message) continue if not resource['should_notify']: LOGGER.debug('Not notifying for: %s', resource['resource']) continue for notifier in resource['notifiers']: log_message = ( 'Running \'{}\' notifier for resource \'{}\''.format( notifier['name'], resource['resource'])) progress_queue.put(log_message) LOGGER.info(log_message) chosen_pipeline = find_notifiers(notifier['name']) notifiers.append(chosen_pipeline( resource['resource'], inventory_index_id, violation_map[resource['resource']], global_configs, notifier_configs, notifier['configuration'])) # Run the notifiers. for notifier in notifiers: notifier.run() # Run the CSCC notifier. violation_configs = notifier_configs.get('violation') if violation_configs: if violation_configs.get('cscc').get('enabled'): source_id = violation_configs.get('cscc').get('source_id') if source_id: # beta mode LOGGER.debug( 'Running CSCC notifier with beta API. source_id: ' '%s', source_id) (cscc_notifier.CsccNotifier(inventory_index_id) .run(violations_as_dict, source_id=source_id)) else: # alpha mode LOGGER.debug('Running CSCC notifier with alpha API.') gcs_path = ( violation_configs.get('cscc').get('gcs_path')) mode = violation_configs.get('cscc').get('mode') organization_id = ( violation_configs.get('cscc').get( 'organization_id')) (cscc_notifier.CsccNotifier(inventory_index_id) .run(violations_as_dict, gcs_path, mode, organization_id)) InventorySummary(service_config, inventory_index_id).run() log_message = 'Notification completed!' progress_queue.put(log_message) progress_queue.put(None) LOGGER.info(log_message) return 0 # pylint: enable=too-many-branches,too-many-statements
1
32,995
alpha sort the imports
forseti-security-forseti-security
py
@@ -1067,7 +1067,7 @@ fpga_result mmio_error(struct RASCommandLine *rasCmdLine) if ( rasCmdLine->function >0 ) function = rasCmdLine->bus; - snprintf(sysfs_path, sizeof(sysfs_path), + snprintf_s_iiii(sysfs_path, sizeof(sysfs_path), DEVICEID_PATH,0,bus,device,function); result = sysfs_read_u64(sysfs_path, &value);
1
// Copyright(c) 2017, Intel Corporation // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <errno.h> #include <stdbool.h> #include <malloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <uuid/uuid.h> #include "safe_string/safe_string.h" #include "opae/fpga.h" #include "types_int.h" #include "common_int.h" // SYSFS FME Errors #define FME_SYSFS_FME_ERRORS "errors/fme-errors/errors" #define FME_SYSFS_PCIE0_ERRORS "errors/pcie0_errors" #define FME_SYSFS_PCIE1_ERRORS "errors/pcie1_errors" #define FME_SYSFS_BBS_ERRORS "errors/bbs_errors" #define FME_SYSFS_GBS_ERRORS "errors/gbs_errors" #define FME_SYSFS_WARNING_ERRORS "errors/warning_errors" #define FME_SYSFS_NONFATAL_ERRORS "errors/nonfatal_errors" #define FME_SYSFS_CATFATAL_ERRORS "errors/catfatal_errors" #define FME_SYSFS_INJECT_ERROR "errors/inject_error" #define FME_SYSFS_ERR_REVISION "errors/revision" #define PORT_SYSFS_ERR "errors/errors" #define PORT_SYSFS_ERR_CLEAR "errors/clear" // SYFS Thermal #define FME_SYSFS_THERMAL_MGMT_TEMP "thermal_mgmt/temperature" #define FME_SYSFS_THERMAL_MGMT_THRESHOLD_TRIP "thermal_mgmt/threshold_trip" // SYSFS Power #define FME_SYSFS_POWER_MGMT_CONSUMED "power_mgmt/consumed" // MMIO scratchpad #define PORT_SCRATCHPAD0 0x0028 #define NLB_CSR_SCRATCHPAD (0x40000 + 0x0104 ) #define PORT_MMIO_LEN (0x40000 + 0x0512 ) #define MMO_WRITE64_VALUE 0xF1F1F1F1F1F1F1F1 #define MMO_WRITE32_VALUE 0xF1F1F1 #define FPGA_CSR_LEN 64 #define DEVICEID_PATH "/sys/bus/pci/devices/%04x:%02x:%02x.%d/device" #define FPGA_PORT_RES_PATH "/sys/bus/pci/devices/%04x:%02x:%02x.%d/resource2" #define FPGA_SET_BIT(val, index) val |= (1 << index) #define FPGA_CLEAR_BIT(val, index) val &= ~(1 << index) #define FPGA_TOGGLE_BIT(val, index) val ^= (1 << index) #define FPGA_BIT_IS_SET(val, index) (((val) >> (index)) & 1) /* Type definitions */ typedef struct { uint32_t uint[16]; } cache_line; int usleep(unsigned); #ifndef CL # define CL(x) ((x) * 64) #endif // CL #ifndef LOG2_CL # define LOG2_CL 6 #endif // LOG2_CL #ifndef MB # define MB(x) ((x) * 1024 * 1024) #endif // MB #define CACHELINE_ALIGNED_ADDR(p) ((p) >> LOG2_CL) #define LPBK1_BUFFER_SIZE MB(1) #define LPBK1_BUFFER_ALLOCATION_SIZE MB(2) #define LPBK1_DSM_SIZE MB(2) #define CSR_SRC_ADDR 0x0120 #define CSR_DST_ADDR 0x0128 #define CSR_CTL 0x0138 #define CSR_CFG 0x0140 #define CSR_NUM_LINES 0x0130 #define DSM_STATUS_TEST_COMPLETE 0x40 #define CSR_AFU_DSM_BASEL 0x0110 #define CSR_AFU_DSM_BASEH 0x0114 /* SKX-P NLB0 AFU_ID */ #define SKX_P_NLB0_AFUID "D8424DC4-A4A3-C413-F89E-433683F9040B" static const char * const FME_ERROR[] = { "Fabric error detected", \ "Fabric fifo under / overflow error detected", \ "KTI CDC Parity Error detected", \ "KTI CDC Parity Error detected", \ "IOMMU Parity error detected", \ "AFU PF/VF access mismatch detected", \ "Indicates an MBP event error detected", \ }; static const char * const PCIE0_ERROR[] = { "TLP format/type error detected", \ "TTLP MW address error detected", \ "TLP MW length error detected", \ "TLP MR address error detected", \ "TLP MR length error detected", \ "TLP CPL tag error detected", \ "TLP CPL status error detected", \ "TLP CPL timeout error detected", \ "CCI bridge parity error detected", \ "TLP with EP error detected", \ }; static const char * const PCIE1_ERROR[] = { "TLP format/type error detected", \ "TTLP MW address error detected", \ "TLP MW length error detected", \ "TLP MR address error detected", \ "TLP MR length error detected", \ "TLP CPL tag error detected", \ "TLP CPL status error detected", \ "TLP CPL timeout error detected", \ "CCI bridge parity error detected", \ "TLP with EP error detected", \ }; static const char * const RAS_NONFATAL_ERROR [] = { "Temperature threshold triggered AP1 detected", \ "Temperature threshold triggered AP2 detected", \ "PCIe error detected", \ "AFU port Fatal error detected", \ "ProcHot event error detected", \ "AFU PF/VF access mismatch error detected", \ "Injected Warning Error detected", \ "Reserved", \ "Reserved", \ "Temperature threshold triggered AP6 detected", \ "Power threshold triggered AP1 error detected", \ "Power threshold triggered AP2 error detected", \ "MBP event error detected", \ }; static const char * const RAS_CATFATAL_ERROR[] = { "KTI link layer error detected.", \ "tag-n-cache error detected.", \ "CCI error detected.", \ "KTI protocol error detected.", \ "Fatal DRAM error detected", \ "IOMMU fatal parity error detected.", \ "Fabric fatal error detected", \ "Poison error from any of PCIe ports detected", \ "Injected Fatal Error detected", \ "Catastrophic CRC error detected", \ "Catastrophic thermal runaway event detected", \ "Injected Catastrophic Error detected", \ }; static const char * const RAS_INJECT_ERROR[] = { "Set Catastrophic error .", \ "Set Fatal error.", \ "Ser Non-fatal error .", \ }; static const char * const RAS_GBS_ERROR [] = { "Temperature threshold triggered AP1 detected", \ "Temperature threshold triggered AP2 detected", \ "PCIe error detected", \ "AFU port Fatal error detected", \ "ProcHot event error detected", \ "AFU PF/VF access mismatch error detected", \ "Injected Warning Error detected", \ "Poison error from any of PCIe ports detected", \ "GBS CRC errordetected ", \ "Temperature threshold triggered AP6 detected", \ "Power threshold triggered AP1 error detected", \ "Power threshold triggered AP2 error detected", \ "MBP event error detected", \ }; static const char * const RAS_BBS_ERROR[] = { "KTI link layer error detected.", \ "tag-n-cache error detected.", \ "CCI error detected.", \ "KTI protocol error detected.", \ "Fatal DRAM error detected", \ "IOMMU fatal parity error detected.", \ "Fabric fatal error detected", \ "Poison error from any of PCIe ports detected", \ "Injected Fatal Error detected", \ "Catastrophic CRC error detected", \ "Catastrophic thermal runaway event detected", \ "Injected Catastrophic Error detected", \ }; static const char * const RAS_WARNING_ERROR[] = { "Green bitstream fatal event error detected.", \ }; static const char * const PORT_ERROR[] = { "Tx Channel 0 overflow error detected.", \ "Tx Channel 0 invalid request encodingr error detected.", \ "Tx Channel 0 cl_len=3 not supported error detected.", \ "Tx Channel 0 request with cl_len=2 does NOT have a 2CL aligned address error detected.", \ "Tx Channel 0 request with cl_len=4 does NOT have a 4CL aligned address error detected.", \ "RSVD.", "RSVD.", "RSVD.","RSVD.",\ "AFU MMIO RD received while PORT is in reset error detected", \ "AFU MMIO WR received while PORT is in reset error detected", \ "RSVD.", "RSVD.", "RSVD.", "RSVD.", "RSVD.",\ "Tx Channel 1 invalid request encoding error detected", \ "Tx Channel 1 cl_len=3 not supported error detected.", \ "Tx Channel 1 request with cl_len=2 does NOT have a 2CL aligned address error detected", \ "Tx Channel 1 request with cl_len=4 does NOT have a 4CL aligned address error detected", \ "Tx Channel 1 insufficient data payload Error detected", \ "Tx Channel 1 data payload overrun error detected", \ "Tx Channel 1 incorrect address on subsequent payloads error detected", \ "Tx Channel 1 Non-zero SOP detected for requests!=WrLine_* error detected", \ "Tx Channel 1 Illegal VC_SEL. Atomic request is only supported on VL0 error detected", \ "RSVD.", "RSVD.", "RSVD.", "RSVD.", "RSVD.", "RSVD.", "RSVD.",\ "MMIO TimedOut error detected", \ "Tx Channel 2 fifo overflo error detected", \ "MMIO Read response received, with no matching request pending error detected", \ "RSVD.", "RSVD.", "RSVD.", "RSVD.", "RSVD.", \ "Number of pending requests: counter overflow error detected", \ "Request with Address violating SMM range error detected", \ "Request with Address violating second SMM range error detected", \ "Request with Address violating ME stolen range", \ "Request with Address violating Generic protected range error detected ", \ "Request with Address violating Legacy Range Low error detected", \ "Request with Address violating Legacy Range High error detected", \ "Request with Address violating VGA memory range error detected", \ "Page Fault error detected", \ "PMR Erro error detected", \ "AP6 event detected ", \ "VF FLR detected on port when PORT configured in PF access mode error detected ", \ }; // RAS Error Inject CSR struct ras_inject_error { union { uint64_t csr; struct { /* Catastrophic error */ uint64_t catastrophicr_error : 1; /* Fatal error */ uint64_t fatal_error : 1; /* Non-fatal error */ uint64_t nonfatal_error : 1; /* Reserved */ uint64_t rsvd : 61; }; }; }; #define GETOPT_STRING ":hB:D:F:S:PQRNTCEGHIO" struct option longopts[] = { {"help", no_argument, NULL, 'h'}, {"bus-number", required_argument, NULL, 'B'}, {"device-number", required_argument, NULL, 'D'}, {"function-number", required_argument, NULL, 'F'}, {"socket-number", required_argument, NULL, 'S'}, {"print-error", no_argument, NULL, 'P'}, {"catast-error", no_argument, NULL, 'Q'}, {"fatal-error", no_argument, NULL, 'R'}, {"nofatal-error", no_argument, NULL, 'N'}, {"thermal-trip", no_argument, NULL, 'T'}, {"clearinj-error", no_argument, NULL, 'C'}, {"mwaddress-error", no_argument, NULL, 'E'}, {"mraddress-error", no_argument, NULL, 'G'}, {"mwlength-error", no_argument, NULL, 'H'}, {"mrlength-error", no_argument, NULL, 'I'}, {"pagefault-error", no_argument, NULL, 'O'}, {0,0,0,0} }; // RAS Command line struct struct RASCommandLine { uint32_t flags; #define RASAPP_CMD_FLAG_HELP 0x00000001 #define RASAPP_CMD_FLAG_VERSION 0x00000002 #define RASAPP_CMD_PARSE_ERROR 0x00000003 #define RASAPP_CMD_FLAG_BUS 0x00000008 #define RASAPP_CMD_FLAG_DEV 0x00000010 #define RASAPP_CMD_FLAG_FUNC 0x00000020 #define RASAPP_CMD_FLAG_SOCKET 0x00000040 int bus; int device; int function; int socket; bool print_error; bool catast_error; bool fatal_error; bool nonfatal_error; bool clear_injerror; bool mwaddress_error; bool mraddress_error; bool mwlength_error; bool mrlength_error; bool pagefault_error; }; struct RASCommandLine rasCmdLine = { 0, -1, -1, -1, -1, false, false, false, false,false, false, false, false, false, false}; // RAS Command line input help void RASAppShowHelp() { printf("Usage:\n"); printf("./ras \n"); printf("<Bus> --bus=<BUS NUMBER> " "OR -B=<BUS NUMBER>\n"); printf("<Device> --device=<DEVICE NUMBER> " "OR -D=<DEVICE NUMBER>\n"); printf("<Function> --function=<FUNCTION NUMBER> " "OR -F=<FUNCTION NUMBER>\n"); printf("<Socket> --socket=<socket NUMBER> " " OR -S=<SOCKET NUMBER>\n"); printf("<Print Error> --print-error OR -P \n"); printf("<Catast Error> --catast-error OR -Q \n"); printf("<Fatal Error> --fatal-error OR -R \n"); printf("<NoFatal Error> --nofatal-error OR -N \n"); printf("<Clear Inj Error> --clearinj-error OR -C \n"); printf("<MW Address error> --mwaddress-error OR -E \n"); printf("<MR Address error> --mwaddress-error OR -G \n"); printf("<MW Length error> --mwlength-error OR -H \n"); printf("<MR Length error> --mrlength-error OR -I \n"); printf("<Page Fault Error> --pagefault-error OR -O \n"); printf("\n"); } /* * macro to check return codes, print error message, and goto cleanup label * NOTE: this changes the program flow (uses goto)! */ #define ON_ERR_GOTO(res, label, desc) \ do { \ if ((res) != FPGA_OK) { \ print_err((desc), (res)); \ goto label; \ } \ } while (0) void print_err(const char *s, fpga_result res) { fprintf(stderr, "Error %s: %s\n", s, fpgaErrStr(res)); } fpga_result print_ras_errors(fpga_token token); fpga_result print_pwr_temp(fpga_token token); fpga_result clear_inject_ras_errors(fpga_token token, struct RASCommandLine *rasCmdLine); fpga_result inject_ras_errors(fpga_token token, struct RASCommandLine *rasCmdLine); fpga_result mmio_error(struct RASCommandLine *rasCmdLine); fpga_result print_port_errors(fpga_token token); fpga_result clear_port_errors(fpga_token token); fpga_result page_fault_errors(); int ParseCmds(struct RASCommandLine *rasCmdLine, int argc, char *argv[]); int main( int argc, char** argv ) { fpga_result result = 0; fpga_properties filter = NULL; fpga_token fme_token ; uint32_t num_matches = 1; // Parse command line if ( argc < 2 ) { RASAppShowHelp(); return 1; } else if ( 0!= ParseCmds(&rasCmdLine, argc, argv) ) { FPGA_ERR( "Error scanning command line \n."); return 2; } printf(" ------- Command line Input Start ---- \n \n"); printf(" Bus : %d\n", rasCmdLine.bus); printf(" Device : %d \n", rasCmdLine.device); printf(" Function : %d \n", rasCmdLine.function); printf(" Socket : %d \n", rasCmdLine.socket); printf(" Print Error : %d \n", rasCmdLine.print_error); printf(" Catas Error : %d \n", rasCmdLine.catast_error); printf(" Fatal Error : %d \n", rasCmdLine.fatal_error); printf(" NonFatal Error : %d \n", rasCmdLine.nonfatal_error); printf(" Clear Error : %d \n", rasCmdLine.clear_injerror); printf(" MW Address Error : %d \n", rasCmdLine.mwaddress_error); printf(" MR Address Error : %d \n", rasCmdLine.mraddress_error); printf(" MW Length Error : %d \n", rasCmdLine.mwlength_error); printf(" MR Length Error : %d \n", rasCmdLine.mrlength_error); printf(" Page Fault Error : %d \n", rasCmdLine.pagefault_error); printf(" ------- Command line Input END ---- \n\n"); // Enum FPGA device result = fpgaGetProperties(NULL, &filter); ON_ERR_GOTO(result, out_exit, "creating properties object"); result = fpgaPropertiesSetObjectType(filter, FPGA_DEVICE); ON_ERR_GOTO(result, out_destroy_prop, "setting object type"); if (rasCmdLine.bus >0){ result = fpgaPropertiesSetBus(filter, rasCmdLine.bus); ON_ERR_GOTO(result, out_destroy_prop, "setting bus"); } if (rasCmdLine.device >0) { result = fpgaPropertiesSetDevice(filter, rasCmdLine.device); ON_ERR_GOTO(result, out_destroy_prop, "setting device"); } if (rasCmdLine.function >0){ result = fpgaPropertiesSetFunction(filter, rasCmdLine.function); ON_ERR_GOTO(result, out_destroy_prop, "setting function"); } if (rasCmdLine.socket >0){ result = fpgaPropertiesSetSocketID(filter, rasCmdLine.socket); ON_ERR_GOTO(result, out_destroy_prop, "setting socket"); } result = fpgaEnumerate(&filter, 1, &fme_token,1, &num_matches); ON_ERR_GOTO(result, out_destroy_prop, "enumerating FPGAs"); if (num_matches < 1) { fprintf(stderr, "FPGA Resource not found.\n"); result = fpgaDestroyProperties(&filter); return FPGA_INVALID_PARAM; } fprintf(stderr, "FME Resource found.\n"); // Inject error if (rasCmdLine.catast_error || rasCmdLine.fatal_error || rasCmdLine.nonfatal_error) { // Inject RAS ERROR result = inject_ras_errors(fme_token,&rasCmdLine); if (result != FPGA_OK) { FPGA_ERR("Failed to print fme errors"); goto out_destroy_prop; } } // inject MMIO error if ( (rasCmdLine.mwaddress_error == true) || (rasCmdLine.mraddress_error == true) || (rasCmdLine.mwlength_error == true) || (rasCmdLine.mrlength_error == true) ) { result = mmio_error(&rasCmdLine); if (result != FPGA_OK) { FPGA_ERR("Failed set MMIO errors"); goto out_destroy_prop; } } // Clear Inject Error if (rasCmdLine.clear_injerror ) { // clear RAS ERROR result = clear_inject_ras_errors(fme_token,&rasCmdLine); if (result != FPGA_OK) { FPGA_ERR("Failed to clear inject errors"); goto out_destroy_prop; } // clear Port ERROR result = clear_port_errors(fme_token); if (result != FPGA_OK) { FPGA_ERR("Failed to clear port errors"); goto out_destroy_prop; } } if (rasCmdLine.pagefault_error) { // Page fault error result = page_fault_errors(); if (result != FPGA_OK) { FPGA_ERR("Failed to trigger page fault errors"); goto out_destroy_prop; } } sleep(1); if (rasCmdLine.print_error) { // Print RAS Error result = print_ras_errors(fme_token); if (result != FPGA_OK) { FPGA_ERR("Failed to print fme errors"); goto out_destroy_prop; } // Print port Error result = print_port_errors(fme_token); if (result != FPGA_OK) { FPGA_ERR("Failed to print port errors"); goto out_destroy_prop; } // Print power and temp result = print_pwr_temp(fme_token); if (result != FPGA_OK) { FPGA_ERR("Failed to get power and temp"); goto out_destroy_prop; } } /* Destroy properties object */ out_destroy_prop: result = fpgaDestroyProperties(&filter); ON_ERR_GOTO(result, out_exit, "destroying properties object"); out_exit: return result; } // Print Error fpga_result print_errors(fpga_token token, const char * err_path, const char * const* err_strings, int size) { struct _fpga_token *_token = 0; int i = 0; uint64_t value = 0; char syfs_path[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } if(err_path == NULL || err_strings == NULL) { FPGA_ERR("Invalid input sting"); return FPGA_INVALID_PARAM; } snprintf_s_ss(syfs_path, sizeof(syfs_path), "%s/%s", _token->sysfspath, err_path ); // Read error. result = sysfs_read_u64(syfs_path, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to get errors"); return result; } printf(" CSR : 0x%lx \n", value); for (i = 0; i < FPGA_CSR_LEN; i++) { if ((i < size) && FPGA_BIT_IS_SET(value, i)) { printf("\t %s \n", err_strings[i]); } } return result; } // prints RAS errors fpga_result print_ras_errors(fpga_token token) { struct _fpga_token *_token = 0; uint64_t revision = 0; char syfs_path[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } printf("\n ==========================================\n"); printf(" ----------- PRINT FME ERROR START-------- \n \n"); // get revision snprintf_s_ss(syfs_path, sizeof(syfs_path), "%s/%s", _token->sysfspath, FME_SYSFS_ERR_REVISION ); // Read revision. result = sysfs_read_u64(syfs_path, &revision); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme revison"); return result; } printf(" fme error revison : %ld \n", revision); // Revision 0 if( revision == 1 ) { // Non Fatal Error printf("\n ------- Non Fatal error ------------ \n"); result = print_errors(token, FME_SYSFS_NONFATAL_ERRORS, RAS_NONFATAL_ERROR, sizeof(RAS_NONFATAL_ERROR) /sizeof(RAS_NONFATAL_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme non fatal errors"); return result; } // Fatal Error printf("\n ------- Fatal error ------------ \n"); result = print_errors(token, FME_SYSFS_CATFATAL_ERRORS, RAS_CATFATAL_ERROR, sizeof(RAS_CATFATAL_ERROR) /sizeof(RAS_CATFATAL_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme fatal errors"); return result; } // Injected error printf("\n ------- Injected error ------------ \n"); result = print_errors(token, FME_SYSFS_INJECT_ERROR, RAS_INJECT_ERROR, sizeof(RAS_INJECT_ERROR) /sizeof(RAS_INJECT_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme Injected errors"); return result; } // FME error printf("\n ------- FME error ------------ \n"); result = print_errors(token, FME_SYSFS_FME_ERRORS, FME_ERROR, sizeof(FME_ERROR) /sizeof(FME_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme errors"); return result; } // PCIe0 error printf("\n ------- PCIe0 error ------------ \n"); result = print_errors(token, FME_SYSFS_PCIE0_ERRORS, PCIE0_ERROR, sizeof(PCIE0_ERROR) /sizeof(PCIE0_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get pcie0 errors"); return result; } // PCIe1 error printf("\n ------- PCIe1 error ------------ \n"); result = print_errors(token, FME_SYSFS_PCIE1_ERRORS, PCIE1_ERROR, sizeof(PCIE1_ERROR) /sizeof(PCIE1_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get pcie1 errors"); return result; } // Revision 0 } else if( revision == 0){ // GBS Error printf("\n ------- GBS error ------------ \n"); result = print_errors(token, FME_SYSFS_GBS_ERRORS, RAS_GBS_ERROR, sizeof(RAS_GBS_ERROR) /sizeof(RAS_GBS_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme gbs errors"); return result; } // BBS Error printf("\n ------- BBS error ------------ \n"); result = print_errors(token, FME_SYSFS_BBS_ERRORS, RAS_BBS_ERROR, sizeof(RAS_BBS_ERROR) /sizeof(RAS_BBS_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme bbs errors"); return result; } // Injected error printf("\n ------- Injected error ------------ \n"); result = print_errors(token, FME_SYSFS_INJECT_ERROR, RAS_INJECT_ERROR, sizeof(RAS_INJECT_ERROR) /sizeof(RAS_INJECT_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme Injected errors"); return result; } // FME error printf("\n ------- FME error ------------ \n"); result = print_errors(token, FME_SYSFS_FME_ERRORS, FME_ERROR, sizeof(FME_ERROR) /sizeof(FME_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme errors"); return result; } // PCIe0 error printf("\n ------- PCIe0 error ------------ \n"); result = print_errors(token, FME_SYSFS_PCIE0_ERRORS, PCIE0_ERROR, sizeof(PCIE0_ERROR) /sizeof(PCIE0_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get pcie0 errors"); return result; } // PCIe1 error printf("\n ------- PCIe1 error ------------ \n"); result = print_errors(token, FME_SYSFS_PCIE1_ERRORS, PCIE1_ERROR, sizeof(PCIE1_ERROR) /sizeof(PCIE1_ERROR[0])); if (result != FPGA_OK) { FPGA_ERR("Failed to get pcie1 errors"); return result; } } else { printf("\n Invalid FME Error Revision \n"); } printf("\n ----------- PRINT FME ERROR END----------\n"); printf(" ========================================== \n \n"); return result; } // prints PORT errors fpga_result print_port_errors(fpga_token token) { struct _fpga_token *_token = 0; int i = 0; uint64_t value = 0; int size = 0; char sysfs_port[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; char *p = 0; int device_id = 0; _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } printf("\n ==========================================\n"); printf(" ----------- PRINT PORT ERROR START-------- \n \n"); p = strstr(_token->sysfspath, FPGA_SYSFS_FME); if (NULL == p) return FPGA_INVALID_PARAM; p = strrchr(_token->sysfspath, '.'); if (NULL == p) return FPGA_INVALID_PARAM; device_id = atoi(p + 1); snprintf_s_iis(sysfs_port, SYSFS_PATH_MAX, SYSFS_FPGA_CLASS_PATH SYSFS_AFU_PATH_FMT"/%s", device_id, device_id,PORT_SYSFS_ERR); // Read port error. result = sysfs_read_u64(sysfs_port, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme errors"); return result; } printf("\n \n Port error CSR : 0x%lx \n", value); size = sizeof(PORT_ERROR) /sizeof(PORT_ERROR[0]); for (i = 0; i < 64; i++) { if ( FPGA_BIT_IS_SET(value, i) && (i < size)) { printf("\t %s \n", PORT_ERROR[i]); } } printf("\n ----------- PRINT PORT ERROR END----------\n"); printf(" ========================================== \n \n"); return result; } // clear PORT errors fpga_result clear_port_errors(fpga_token token) { struct _fpga_token *_token = 0; uint64_t value = 0; char sysfs_port[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; char *p = 0; int device_id = 0; _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } printf(" ----------- Clear port error-------- \n \n"); p = strstr(_token->sysfspath, FPGA_SYSFS_FME); if (NULL == p) return FPGA_INVALID_PARAM; p = strrchr(_token->sysfspath, '.'); if (NULL == p) return FPGA_INVALID_PARAM; device_id = atoi(p + 1); snprintf_s_iis(sysfs_port, SYSFS_PATH_MAX, SYSFS_FPGA_CLASS_PATH SYSFS_AFU_PATH_FMT"/%s", device_id, device_id,PORT_SYSFS_ERR); // Read port error. result = sysfs_read_u64(sysfs_port, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to get port errors"); return result; } printf("\n \n Port error CSR : 0x%lx \n", value); snprintf_s_iis(sysfs_port, SYSFS_PATH_MAX, SYSFS_FPGA_CLASS_PATH SYSFS_AFU_PATH_FMT"/%s", device_id, device_id,PORT_SYSFS_ERR_CLEAR); result = sysfs_write_u64(sysfs_port, value); if (result != FPGA_OK) { FPGA_ERR("Failed to write errors"); } return result; } // Inject RAS errors fpga_result inject_ras_errors(fpga_token token, struct RASCommandLine *rasCmdLine) { struct _fpga_token *_token = NULL; struct ras_inject_error inj_error = {{0}}; char sysfs_path[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } printf("----------- INJECT ERROR START -------- \n \n"); snprintf_s_ss(sysfs_path, sizeof(sysfs_path), "%s/%s", _token->sysfspath, FME_SYSFS_INJECT_ERROR); result = sysfs_read_u64(sysfs_path, &inj_error.csr); if (result != FPGA_OK) { FPGA_ERR("Failed to get fme errors"); return result; } printf("inj_error.csr: %ld \n", inj_error.csr); if (rasCmdLine->catast_error ) { inj_error.catastrophicr_error = 1; } if (rasCmdLine->fatal_error ) { inj_error.fatal_error = 1; } if (rasCmdLine->nonfatal_error ) { inj_error.nonfatal_error = 1; } printf("inj_error.csr: %ld \n", inj_error.csr); result = sysfs_write_u64(sysfs_path ,inj_error.csr); if (result != FPGA_OK) { FPGA_ERR("Failed to write RAS inject errors"); return result; } printf("----------- INJECT ERROR END-------- \n \n"); return result; } // Clear Inject RAS errors fpga_result clear_inject_ras_errors(fpga_token token, struct RASCommandLine *rasCmdLine) { struct _fpga_token *_token = NULL; struct ras_inject_error inj_error = {{0}}; char sysfs_path[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; UNUSED_PARAM(rasCmdLine); _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } snprintf_s_ss(sysfs_path, sizeof(sysfs_path), "%s/%s", _token->sysfspath, FME_SYSFS_INJECT_ERROR); result = sysfs_read_u64(sysfs_path, &inj_error.csr); if (result != FPGA_OK) { FPGA_ERR("Failed to read inject error"); return result; } printf(" Clear inj_error.csr: 0x%lx \n", inj_error.csr); result = sysfs_write_u64(sysfs_path ,0x0); if (result != FPGA_OK) { FPGA_ERR("Failed to clear inject errors"); return result; } return result; } // Print FPGA power and temperature fpga_result print_pwr_temp(fpga_token token) { struct _fpga_token *_token = 0; uint64_t value = 0; char sysfs_path[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; _token = (struct _fpga_token*)token; if (_token == NULL) { FPGA_ERR("Token not found"); return FPGA_INVALID_PARAM; } printf("\n ----------- POWER & THERMAL -------------\n"); printf(" ========================================== \n \n"); snprintf_s_ss(sysfs_path, sizeof(sysfs_path), "%s/%s", _token->sysfspath, FME_SYSFS_POWER_MGMT_CONSUMED); result = sysfs_read_u64(sysfs_path, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to get power consumed"); return result; } printf(" Power consumed : %lu watts \n",value); snprintf_s_ss(sysfs_path, sizeof(sysfs_path), "%s/%s", _token->sysfspath, FME_SYSFS_THERMAL_MGMT_TEMP); result = sysfs_read_u64(sysfs_path, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to get temperature"); return result; } printf(" Temperature : %lu Centigrade \n",value ); snprintf_s_ss(sysfs_path, sizeof(sysfs_path), "%s/%s", _token->sysfspath, FME_SYSFS_THERMAL_MGMT_THRESHOLD_TRIP); result = sysfs_read_u64(sysfs_path, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to get temperature"); return result; } printf(" Thermal Trip : %lu Centigrade \n",value ); printf("\n ----------- POWER & THERMAL -------------\n"); printf(" ========================================== \n \n"); return result; } // MMIO erros fpga_result mmio_error(struct RASCommandLine *rasCmdLine) { char sysfs_path[SYSFS_PATH_MAX] = {0}; fpga_result result = FPGA_OK; int bus = 0; int device = 0; int function = 0; uint64_t value = 0; int fd = 0; uint8_t *ptr = 0; if (rasCmdLine == NULL ) { FPGA_ERR("Invalid input "); return FPGA_INVALID_PARAM; } if ( rasCmdLine->bus >0 ) bus = rasCmdLine->bus; if ( rasCmdLine->device >0 ) device = rasCmdLine->bus; if ( rasCmdLine->function >0 ) function = rasCmdLine->bus; snprintf(sysfs_path, sizeof(sysfs_path), DEVICEID_PATH,0,bus,device,function); result = sysfs_read_u64(sysfs_path, &value); if (result != FPGA_OK) { FPGA_ERR("Failed to read Device id"); return result; } if(value != FPGA_INTEGRATED_DEVICEID) { FPGA_ERR("Failed to read Device id"); return FPGA_NOT_SUPPORTED; } snprintf(sysfs_path, sizeof(sysfs_path), FPGA_PORT_RES_PATH,0,bus,device,function); fd = open(sysfs_path, O_RDWR); if (fd < 0) { FPGA_ERR("Failed to open FPGA PCIE BAR2"); return FPGA_EXCEPTION; } ptr = mmap(NULL, PORT_MMIO_LEN, PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0); if (ptr == MAP_FAILED ) { FPGA_ERR("Failed to map FPGA PCIE BAR2"); result = FPGA_EXCEPTION; goto out_close ; } // Memory Write length error if(rasCmdLine->mwlength_error) { FPGA_DBG("Memory Write length error \n"); *((volatile uint64_t *) (ptr + PORT_SCRATCHPAD0+3)) = (uint16_t)MMO_WRITE64_VALUE; } // Memory Read length error if(rasCmdLine->mrlength_error) { FPGA_DBG(" Memory Read length error \n"); value = *((volatile uint64_t *) (ptr + PORT_SCRATCHPAD0+3)); FPGA_DBG(" Memory Read length value %lx\n",value); } // Memory Read addresss error if(rasCmdLine->mraddress_error) { FPGA_DBG("Memory Read addresss error \n"); value = *((volatile uint16_t *) (ptr + NLB_CSR_SCRATCHPAD +3)); FPGA_DBG("Memory Read addresss value %lx\n",value); value = *((volatile uint64_t *) (ptr + PORT_SCRATCHPAD0+3)); FPGA_DBG("Memory Read addresss value %lx\n",value); } // Memory Write addresss error if(rasCmdLine->mwaddress_error) { FPGA_DBG("Memory Write addresss error \n"); *((volatile uint16_t *) (ptr + NLB_CSR_SCRATCHPAD +3)) = (uint16_t)MMO_WRITE32_VALUE; } if(ptr) munmap(ptr, PORT_MMIO_LEN); out_close: if(fd >=0) close(fd); return result; } // page fault errors fpga_result page_fault_errors() { fpga_properties filter = NULL; fpga_token accelerator_token; fpga_handle accelerator_handle; fpga_guid guid; uint32_t num_matches; volatile uint64_t *dsm_ptr = NULL; volatile uint64_t *input_ptr = NULL; volatile uint64_t *output_ptr = NULL; uint64_t dsm_wsid; uint64_t input_wsid; uint64_t output_wsid; fpga_result res = FPGA_OK; if (uuid_parse(SKX_P_NLB0_AFUID, guid) < 0) { fprintf(stderr, "Error parsing guid '%s'\n", SKX_P_NLB0_AFUID); goto out_exit; } /* Look for accelerator with MY_ACCELERATOR_ID */ res = fpgaGetProperties(NULL, &filter); ON_ERR_GOTO(res, out_exit, "creating properties object"); res = fpgaPropertiesSetObjectType(filter, FPGA_ACCELERATOR); ON_ERR_GOTO(res, out_destroy_prop, "setting object type"); res = fpgaPropertiesSetGUID(filter, guid); ON_ERR_GOTO(res, out_destroy_prop, "setting GUID"); if (rasCmdLine.bus >0){ res = fpgaPropertiesSetBus(filter, rasCmdLine.bus); ON_ERR_GOTO(res, out_destroy_prop, "setting bus"); } if (rasCmdLine.device >0) { res = fpgaPropertiesSetDevice(filter, rasCmdLine.device); ON_ERR_GOTO(res, out_destroy_prop, "setting device"); } if (rasCmdLine.function >0){ res = fpgaPropertiesSetFunction(filter, rasCmdLine.function); ON_ERR_GOTO(res, out_destroy_prop, "setting function"); } res = fpgaEnumerate(&filter, 1, &accelerator_token, 1, &num_matches); ON_ERR_GOTO(res, out_destroy_prop, "enumerating accelerators"); if (num_matches < 1) { fprintf(stderr, "accelerator not found.\n"); res = fpgaDestroyProperties(&filter); return FPGA_INVALID_PARAM; } /* Open accelerator and map MMIO */ res = fpgaOpen(accelerator_token, &accelerator_handle, FPGA_OPEN_SHARED); ON_ERR_GOTO(res, out_destroy_tok, "opening accelerator"); res = fpgaMapMMIO(accelerator_handle, 0, NULL); ON_ERR_GOTO(res, out_close, "mapping MMIO space"); /* Allocate buffers */ res = fpgaPrepareBuffer(accelerator_handle, LPBK1_DSM_SIZE, (void **)&dsm_ptr, &dsm_wsid, 0); ON_ERR_GOTO(res, out_close, "allocating DSM buffer"); res = fpgaPrepareBuffer(accelerator_handle, LPBK1_BUFFER_ALLOCATION_SIZE, (void **)&input_ptr, &input_wsid, 0); ON_ERR_GOTO(res, out_free_dsm, "allocating input buffer"); res = fpgaPrepareBuffer(accelerator_handle, LPBK1_BUFFER_ALLOCATION_SIZE, (void **)&output_ptr, &output_wsid, 0); ON_ERR_GOTO(res, out_free_input, "allocating output buffer"); printf("Running Test\n"); /* Initialize buffers */ memset((void *)dsm_ptr, 0, LPBK1_DSM_SIZE); memset((void *)input_ptr, 0xAF, LPBK1_BUFFER_SIZE); memset((void *)output_ptr, 0xBE, LPBK1_BUFFER_SIZE); cache_line *cl_ptr = (cache_line *)input_ptr; for (uint32_t i = 0; i < LPBK1_BUFFER_SIZE / CL(1); ++i) { cl_ptr[i].uint[15] = i+1; /* set the last uint in every cacheline */ } /* Reset accelerator */ res = fpgaReset(accelerator_handle); ON_ERR_GOTO(res, out_free_output, "resetting accelerator"); /* Program DMA addresses */ uint64_t iova; res = fpgaGetIOAddress(accelerator_handle, dsm_wsid, &iova); ON_ERR_GOTO(res, out_free_output, "getting DSM IOVA"); res = fpgaWriteMMIO64(accelerator_handle, 0, CSR_AFU_DSM_BASEL, iova); ON_ERR_GOTO(res, out_free_output, "writing CSR_AFU_DSM_BASEL"); res = fpgaWriteMMIO32(accelerator_handle, 0, CSR_CTL, 0); ON_ERR_GOTO(res, out_free_output, "writing CSR_CFG"); res = fpgaWriteMMIO32(accelerator_handle, 0, CSR_CTL, 1); ON_ERR_GOTO(res, out_free_output, "writing CSR_CFG"); res = fpgaGetIOAddress(accelerator_handle, input_wsid, &iova); ON_ERR_GOTO(res, out_free_output, "getting input IOVA"); // Free Input buffer res = fpgaReleaseBuffer(accelerator_handle, input_wsid); res = fpgaWriteMMIO64(accelerator_handle, 0, CSR_SRC_ADDR, CACHELINE_ALIGNED_ADDR(iova)); ON_ERR_GOTO(res, out_free_output, "writing CSR_SRC_ADDR"); res = fpgaGetIOAddress(accelerator_handle, output_wsid, &iova); ON_ERR_GOTO(res, out_free_output, "getting output IOVA"); res = fpgaWriteMMIO64(accelerator_handle, 0, CSR_DST_ADDR, CACHELINE_ALIGNED_ADDR(iova)); ON_ERR_GOTO(res, out_free_output, "writing CSR_DST_ADDR"); res = fpgaWriteMMIO32(accelerator_handle, 0, CSR_NUM_LINES, LPBK1_BUFFER_SIZE / CL(1)); ON_ERR_GOTO(res, out_free_output, "writing CSR_NUM_LINES"); res = fpgaWriteMMIO32(accelerator_handle, 0, CSR_CFG, 0x42000); ON_ERR_GOTO(res, out_free_output, "writing CSR_CFG"); /* Start the test */ res = fpgaWriteMMIO32(accelerator_handle, 0, CSR_CTL, 3); ON_ERR_GOTO(res, out_free_output, "writing CSR_CFG"); /* Wait for test completion */ usleep(10000); /* Stop the device */ res = fpgaWriteMMIO32(accelerator_handle, 0, CSR_CTL, 7); ON_ERR_GOTO(res, out_free_output, "writing CSR_CFG"); printf("Done Running Test\n"); /* Release buffers */ out_free_output: res = fpgaReleaseBuffer(accelerator_handle, output_wsid); ON_ERR_GOTO(res, out_free_input, "releasing output buffer"); out_free_input: // res = fpgaReleaseBuffer(accelerator_handle, input_wsid); // ON_ERR_GOTO(res, out_free_dsm, "releasing input buffer"); out_free_dsm: res = fpgaReleaseBuffer(accelerator_handle, dsm_wsid); ON_ERR_GOTO(res, out_unmap, "releasing DSM buffer"); /* Unmap MMIO space */ out_unmap: res = fpgaUnmapMMIO(accelerator_handle, 0); ON_ERR_GOTO(res, out_close, "unmapping MMIO space"); /* Release accelerator */ out_close: res = fpgaClose(accelerator_handle); ON_ERR_GOTO(res, out_destroy_tok, "closing accelerator"); /* Destroy token */ out_destroy_tok: res = fpgaDestroyToken(&accelerator_token); ON_ERR_GOTO(res, out_destroy_prop, "destroying token"); /* Destroy properties object */ out_destroy_prop: res = fpgaDestroyProperties(&filter); ON_ERR_GOTO(res, out_exit, "destroying properties object"); out_exit: return res; } // parse Input command line int ParseCmds(struct RASCommandLine *rasCmdLine, int argc, char *argv[]) { int getopt_ret = 0; int option_index = 0; char *endptr = NULL; while( -1 != ( getopt_ret = getopt_long(argc, argv, GETOPT_STRING, longopts, &option_index))){ const char *tmp_optarg = optarg; if ((optarg) && ('=' == *tmp_optarg)){ ++tmp_optarg; } switch(getopt_ret){ case 'h': // Command line help RASAppShowHelp(); return -2; break; case 'B': // bus number if (tmp_optarg == NULL ) break; endptr = NULL; rasCmdLine->bus = strtol(tmp_optarg, &endptr, 0); break; case 'D': // Device number if (tmp_optarg == NULL ) break; endptr = NULL; rasCmdLine->device = strtol(tmp_optarg, &endptr, 0); break; case 'F': // Function number if (tmp_optarg == NULL ) break; endptr = NULL; rasCmdLine->function = strtol(tmp_optarg, &endptr, 0); break; case 'S': // Socket number if (tmp_optarg == NULL ) break; endptr = NULL; rasCmdLine->socket = strtol(tmp_optarg, &endptr, 0); break; case 'P': // Print Errors rasCmdLine->print_error = true; break; case 'Q': // Set Cast error rasCmdLine->catast_error = true; break; case 'R': // Set Fatal error rasCmdLine->fatal_error = true; break; case 'O': // Set page fault error rasCmdLine->pagefault_error = true; break; case 'N': // Set Non Fatal error rasCmdLine->nonfatal_error = true; break; case 'C': // Clear Injected Error rasCmdLine->clear_injerror = true; break; case 'E': // Set MW Address error rasCmdLine->mwaddress_error = true; break; case 'G': // Set MR Address error rasCmdLine->mraddress_error = true; break; case 'H': // Set MW Length error rasCmdLine->mwlength_error = true; break; case 'I': // Set MR Length error rasCmdLine->mrlength_error = true; break; case ':': /* missing option argument */ printf("Missing option argument.\n"); return -1; case '?': default: /* invalid option */ printf("Invalid cmdline options.\n"); return -1; } } return 0; }
1
14,917
Can you explain why is this necessary? Is `snprintf()` with four integer arguments unsafe?
OPAE-opae-sdk
c
@@ -219,7 +219,19 @@ def internal_keyDownEvent(vkCode,scanCode,extended,injected): for k in range(256): keyStates[k]=ctypes.windll.user32.GetKeyState(k) charBuf=ctypes.create_unicode_buffer(5) + # First try getting the keyboard layout from the thread with the focus (input thread) hkl=ctypes.windll.user32.GetKeyboardLayout(focus.windowThreadID) + if not hkl: + log.debug("Failed to fetch keyboard layout from focus, trying layout from last detected change") + # Some threads, such as for Windows consoles + # Do not allow getKeyboardLayout to work. + # Therefore, use the cached keyboard layout from the last inputLangChange detected by NVDA + # on the foreground object. + hkl = getattr(api.getForegroundObject(), '_lastDetectedKeyboardLayoutChange', 0) + if not hkl: + log.debug("No layout cached, falling back to layout of NVDA main thread") + # As a last resort, use the keyboard layout of NVDA's main thread. + hkl = ctypes.windll.user32.GetKeyboardLayout(core.mainThreadId) # In previous Windows builds, calling ToUnicodeEx would destroy keyboard buffer state and therefore cause the app to not produce the right WM_CHAR message. # However, ToUnicodeEx now can take a new flag of 0x4, which stops it from destroying keyboard state, thus allowing us to safely call it here. res=ctypes.windll.user32.ToUnicodeEx(vkCode,scanCode,keyStates,charBuf,len(charBuf),0x4,hkl)
1
# -*- coding: UTF-8 -*- #keyboardHandler.py #A part of NonVisual Desktop Access (NVDA) #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2006-2017 NV Access Limited, Peter Vágner, Aleksey Sadovoy, Babbage B.V. """Keyboard support""" import ctypes import sys import time import re import wx import winVersion import winUser import vkCodes import eventHandler import speech import ui from keyLabels import localizedKeyLabels from logHandler import log import queueHandler import config import api import winInputHook import inputCore import tones import core from contextlib import contextmanager import threading ignoreInjected=False # Fake vk codes. # These constants should be assigned to the name that NVDA will use for the key. VK_WIN = "windows" VK_NVDA = "NVDA" #: Keys which have been trapped by NVDA and should not be passed to the OS. trappedKeys=set() #: Tracks the number of keys passed through by request of the user. #: If -1, pass through is disabled. #: If 0 or higher then key downs and key ups will be passed straight through. passKeyThroughCount=-1 #: The last key down passed through by request of the user. lastPassThroughKeyDown = None #: The last NVDA modifier key that was pressed with no subsequent key presses. lastNVDAModifier = None #: When the last NVDA modifier key was released. lastNVDAModifierReleaseTime = None #: Indicates that the NVDA modifier's special functionality should be bypassed until a key is next released. bypassNVDAModifier = False #: The modifiers currently being pressed. currentModifiers = set() #: A counter which is incremented each time a key is pressed. #: Note that this may be removed in future, so reliance on it should generally be avoided. #: @type: int keyCounter = 0 #: The current sticky NVDa modifier key. stickyNVDAModifier = None #: Whether the sticky NVDA modifier is locked. stickyNVDAModifierLocked = False _ignoreInjectionLock = threading.Lock() @contextmanager def ignoreInjection(): """Context manager that allows ignoring injected keys temporarily by using a with statement.""" global ignoreInjected with _ignoreInjectionLock: ignoreInjected=True yield ignoreInjected=False def passNextKeyThrough(): global passKeyThroughCount if passKeyThroughCount==-1: passKeyThroughCount=0 def isNVDAModifierKey(vkCode,extended): if config.conf["keyboard"]["useNumpadInsertAsNVDAModifierKey"] and vkCode==winUser.VK_INSERT and not extended: return True elif config.conf["keyboard"]["useExtendedInsertAsNVDAModifierKey"] and vkCode==winUser.VK_INSERT and extended: return True elif config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"] and vkCode==winUser.VK_CAPITAL: return True else: return False SUPPORTED_NVDA_MODIFIER_KEYS = ("capslock", "numpadinsert", "insert") def getNVDAModifierKeys(): keys=[] if config.conf["keyboard"]["useExtendedInsertAsNVDAModifierKey"]: keys.append(vkCodes.byName["insert"]) if config.conf["keyboard"]["useNumpadInsertAsNVDAModifierKey"]: keys.append(vkCodes.byName["numpadinsert"]) if config.conf["keyboard"]["useCapsLockAsNVDAModifierKey"]: keys.append(vkCodes.byName["capslock"]) return keys def internal_keyDownEvent(vkCode,scanCode,extended,injected): """Event called by winInputHook when it receives a keyDown. """ gestureExecuted=False try: global lastNVDAModifier, lastNVDAModifierReleaseTime, bypassNVDAModifier, passKeyThroughCount, lastPassThroughKeyDown, currentModifiers, keyCounter, stickyNVDAModifier, stickyNVDAModifierLocked # Injected keys should be ignored in some cases. if injected and (ignoreInjected or not config.conf['keyboard']['handleInjectedKeys']): return True keyCode = (vkCode, extended) if passKeyThroughCount >= 0: # We're passing keys through. if lastPassThroughKeyDown != keyCode: # Increment the pass key through count. # We only do this if this isn't a repeat of the previous key down, as we don't receive key ups for repeated key downs. passKeyThroughCount += 1 lastPassThroughKeyDown = keyCode return True keyCounter += 1 stickyKeysFlags = winUser.getSystemStickyKeys().dwFlags if stickyNVDAModifier and not stickyKeysFlags & winUser.SKF_STICKYKEYSON: # Sticky keys has been disabled, # so clear the sticky NVDA modifier. currentModifiers.discard(stickyNVDAModifier) stickyNVDAModifier = None stickyNVDAModifierLocked = False gesture = KeyboardInputGesture(currentModifiers, vkCode, scanCode, extended) if not (stickyKeysFlags & winUser.SKF_STICKYKEYSON) and (bypassNVDAModifier or (keyCode == lastNVDAModifier and lastNVDAModifierReleaseTime and time.time() - lastNVDAModifierReleaseTime < 0.5)): # The user wants the key to serve its normal function instead of acting as an NVDA modifier key. # There may be key repeats, so ensure we do this until they stop. bypassNVDAModifier = True gesture.isNVDAModifierKey = False lastNVDAModifierReleaseTime = None if gesture.isNVDAModifierKey: lastNVDAModifier = keyCode if stickyKeysFlags & winUser.SKF_STICKYKEYSON: if keyCode == stickyNVDAModifier: if stickyKeysFlags & winUser.SKF_TRISTATE and not stickyNVDAModifierLocked: # The NVDA modifier is being locked. stickyNVDAModifierLocked = True if stickyKeysFlags & winUser.SKF_AUDIBLEFEEDBACK: tones.beep(1984, 60) return False else: # The NVDA modifier is being unlatched/unlocked. stickyNVDAModifier = None stickyNVDAModifierLocked = False if stickyKeysFlags & winUser.SKF_AUDIBLEFEEDBACK: tones.beep(496, 60) return False else: # The NVDA modifier is being latched. if stickyNVDAModifier: # Clear the previous sticky NVDA modifier. currentModifiers.discard(stickyNVDAModifier) stickyNVDAModifierLocked = False stickyNVDAModifier = keyCode if stickyKeysFlags & winUser.SKF_AUDIBLEFEEDBACK: tones.beep(1984, 60) else: # Another key was pressed after the last NVDA modifier key, so it should not be passed through on the next press. lastNVDAModifier = None if gesture.isModifier: if gesture.speechEffectWhenExecuted in (gesture.SPEECHEFFECT_PAUSE, gesture.SPEECHEFFECT_RESUME) and keyCode in currentModifiers: # Ignore key repeats for the pause speech key to avoid speech stuttering as it continually pauses and resumes. return True currentModifiers.add(keyCode) elif stickyNVDAModifier and not stickyNVDAModifierLocked: # A non-modifier was pressed, so unlatch the NVDA modifier. currentModifiers.discard(stickyNVDAModifier) stickyNVDAModifier = None try: inputCore.manager.executeGesture(gesture) gestureExecuted=True trappedKeys.add(keyCode) if canModifiersPerformAction(gesture.generalizedModifiers): # #3472: These modifiers can perform an action if pressed alone # and we've just consumed the main key. # Send special reserved vkcode (0xff) to at least notify the app's key state that something happendd. # This allows alt and windows to be bound to scripts and # stops control+shift from switching keyboard layouts in cursorManager selection scripts. KeyboardInputGesture((),0xff,0,False).send() return False except inputCore.NoInputGestureAction: if gesture.isNVDAModifierKey: # Never pass the NVDA modifier key to the OS. trappedKeys.add(keyCode) return False except: log.error("internal_keyDownEvent", exc_info=True) finally: # #6017: handle typed characters in Win10 RS2 and above where we can't detect typed characters in-process # This code must be in the 'finally' block as code above returns in several places yet we still want to execute this particular code. focus=api.getFocusObject() from NVDAObjects.behaviors import KeyboardHandlerBasedTypedCharSupport if ( # This is only possible in Windows 10 1607 and above winVersion.isWin10(1607) # And we only want to do this if the gesture did not result in an executed action and not gestureExecuted # and not if this gesture is a modifier key and not isNVDAModifierKey(vkCode,extended) and not vkCode in KeyboardInputGesture.NORMAL_MODIFIER_KEYS and ( # Either of # We couldn't inject in-process, and its not a legacy console window without keyboard support. # console windows have their own specific typed character support. (not focus.appModule.helperLocalBindingHandle and focus.windowClassName!='ConsoleWindowClass') # or the focus is within a UWP app, where WM_CHAR never gets sent or focus.windowClassName.startswith('Windows.UI.Core') #Or this is a console with keyboard support, where WM_CHAR messages are doubled or isinstance(focus, KeyboardHandlerBasedTypedCharSupport) ) ): keyStates=(ctypes.c_byte*256)() for k in range(256): keyStates[k]=ctypes.windll.user32.GetKeyState(k) charBuf=ctypes.create_unicode_buffer(5) hkl=ctypes.windll.user32.GetKeyboardLayout(focus.windowThreadID) # In previous Windows builds, calling ToUnicodeEx would destroy keyboard buffer state and therefore cause the app to not produce the right WM_CHAR message. # However, ToUnicodeEx now can take a new flag of 0x4, which stops it from destroying keyboard state, thus allowing us to safely call it here. res=ctypes.windll.user32.ToUnicodeEx(vkCode,scanCode,keyStates,charBuf,len(charBuf),0x4,hkl) if res>0: for ch in charBuf[:res]: eventHandler.queueEvent("typedCharacter",focus,ch=ch) return True def internal_keyUpEvent(vkCode,scanCode,extended,injected): """Event called by winInputHook when it receives a keyUp. """ try: global lastNVDAModifier, lastNVDAModifierReleaseTime, bypassNVDAModifier, passKeyThroughCount, lastPassThroughKeyDown, currentModifiers # Injected keys should be ignored in some cases. if injected and (ignoreInjected or not config.conf['keyboard']['handleInjectedKeys']): return True keyCode = (vkCode, extended) if passKeyThroughCount >= 1: if lastPassThroughKeyDown == keyCode: # This key has been released. lastPassThroughKeyDown = None passKeyThroughCount -= 1 if passKeyThroughCount == 0: passKeyThroughCount = -1 return True if lastNVDAModifier and keyCode == lastNVDAModifier: # The last pressed NVDA modifier key is being released and there were no key presses in between. # The user may want to press it again quickly to pass it through. lastNVDAModifierReleaseTime = time.time() # If we were bypassing the NVDA modifier, stop doing so now, as there will be no more repeats. bypassNVDAModifier = False if keyCode != stickyNVDAModifier: currentModifiers.discard(keyCode) # help inputCore manage its sayAll state for keyboard modifiers -- inputCore itself has no concept of key releases if not currentModifiers: inputCore.manager.lastModifierWasInSayAll=False if keyCode in trappedKeys: trappedKeys.remove(keyCode) return False except: log.error("", exc_info=True) return True #Register internal key press event with operating system def initialize(): """Initialises keyboard support.""" winInputHook.initialize() winInputHook.setCallbacks(keyDown=internal_keyDownEvent,keyUp=internal_keyUpEvent) def terminate(): winInputHook.terminate() def getInputHkl(): """Obtain the hkl currently being used for input. This retrieves the hkl from the thread of the focused window. """ focus = api.getFocusObject() if focus: thread = focus.windowThreadID else: thread = 0 return winUser.user32.GetKeyboardLayout(thread) def canModifiersPerformAction(modifiers): """Determine whether given generalized modifiers can perform an action if pressed alone. For example, alt activates the menu bar if it isn't modifying another key. """ if inputCore.manager.isInputHelpActive: return False control = shift = other = False for vk, ext in modifiers: if vk in (winUser.VK_MENU, VK_WIN): # Alt activates the menu bar. # Windows activates the Start Menu. return True elif vk == winUser.VK_CONTROL: control = True elif vk == winUser.VK_SHIFT: shift = True elif (vk, ext) not in trappedKeys : # Trapped modifiers aren't relevant. other = True if control and shift and not other: # Shift+control switches keyboard layouts. return True return False class KeyboardInputGesture(inputCore.InputGesture): """A key pressed on the traditional system keyboard. """ #: All normal modifier keys, where modifier vk codes are mapped to a more general modifier vk code or C{None} if not applicable. #: @type: dict NORMAL_MODIFIER_KEYS = { winUser.VK_LCONTROL: winUser.VK_CONTROL, winUser.VK_RCONTROL: winUser.VK_CONTROL, winUser.VK_CONTROL: None, winUser.VK_LSHIFT: winUser.VK_SHIFT, winUser.VK_RSHIFT: winUser.VK_SHIFT, winUser.VK_SHIFT: None, winUser.VK_LMENU: winUser.VK_MENU, winUser.VK_RMENU: winUser.VK_MENU, winUser.VK_MENU: None, winUser.VK_LWIN: VK_WIN, winUser.VK_RWIN: VK_WIN, VK_WIN: None, } #: All possible toggle key vk codes. #: @type: frozenset TOGGLE_KEYS = frozenset((winUser.VK_CAPITAL, winUser.VK_NUMLOCK, winUser.VK_SCROLL)) #: All possible keyboard layouts, where layout names are mapped to localised layout names. #: @type: dict LAYOUTS = { # Translators: One of the keyboard layouts for NVDA. "desktop": _("desktop"), # Translators: One of the keyboard layouts for NVDA. "laptop": _("laptop"), } @classmethod def getVkName(cls, vkCode, isExtended): if isinstance(vkCode, str): return vkCode name = vkCodes.byCode.get((vkCode, isExtended)) if not name and isExtended is not None: # Whether the key is extended doesn't matter for many keys, so try None. name = vkCodes.byCode.get((vkCode, None)) return name if name else "" def __init__(self, modifiers, vkCode, scanCode, isExtended): #: The keyboard layout in which this gesture was created. #: @type: str self.layout = config.conf["keyboard"]["keyboardLayout"] self.modifiers = modifiers = set(modifiers) # Don't double up if this is a modifier key repeat. modifiers.discard((vkCode, isExtended)) if vkCode in (winUser.VK_DIVIDE, winUser.VK_MULTIPLY, winUser.VK_SUBTRACT, winUser.VK_ADD) and winUser.getKeyState(winUser.VK_NUMLOCK) & 1: # Some numpad keys have the same vkCode regardless of numlock. # For these keys, treat numlock as a modifier. modifiers.add((winUser.VK_NUMLOCK, False)) self.generalizedModifiers = set((self.NORMAL_MODIFIER_KEYS.get(mod) or mod, extended) for mod, extended in modifiers) self.vkCode = vkCode self.scanCode = scanCode self.isExtended = isExtended super(KeyboardInputGesture, self).__init__() def _get_bypassInputHelp(self): # #4226: Numlock must always be handled normally otherwise the Keyboard controller and Windows can get out of synk wih each other in regard to this key state. return self.vkCode==winUser.VK_NUMLOCK def _get_isNVDAModifierKey(self): return isNVDAModifierKey(self.vkCode, self.isExtended) def _get_isModifier(self): return self.vkCode in self.NORMAL_MODIFIER_KEYS or self.isNVDAModifierKey def _get_mainKeyName(self): if self.isNVDAModifierKey: return "NVDA" name = self.getVkName(self.vkCode, self.isExtended) if name: return name if 32 < self.vkCode < 128: return chr(self.vkCode).lower() if self.vkCode == vkCodes.VK_PACKET: # Unicode character from non-keyboard input. return chr(self.scanCode) vkChar = winUser.user32.MapVirtualKeyExW(self.vkCode, winUser.MAPVK_VK_TO_CHAR, getInputHkl()) if vkChar>0: if vkChar == 43: # "+" # A gesture identifier can't include "+" except as a separator. return "plus" return chr(vkChar).lower() if self.vkCode == 0xFF: # #3468: This key is unknown to Windows. # GetKeyNameText often returns something inappropriate in these cases # due to disregarding the extended flag. return "unknown_%02x" % self.scanCode return winUser.getKeyNameText(self.scanCode, self.isExtended) def _get_modifierNames(self): modTexts = [] for modVk, modExt in self.generalizedModifiers: if isNVDAModifierKey(modVk, modExt): modTexts.append("NVDA") else: modTexts.append(self.getVkName(modVk, None)) return modTexts def _get__keyNamesInDisplayOrder(self): return tuple(self.modifierNames) + (self.mainKeyName,) def _get_displayName(self): return "+".join( # Translators: Reported for an unknown key press. # %s will be replaced with the key code. _("unknown %s") % key[8:] if key.startswith("unknown_") else localizedKeyLabels.get(key.lower(), key) for key in self._keyNamesInDisplayOrder) def _get_identifiers(self): keyName = "+".join(self._keyNamesInDisplayOrder) return ( u"kb({layout}):{key}".format(layout=self.layout, key=keyName), u"kb:{key}".format(key=keyName) ) def _get_shouldReportAsCommand(self): if self.isExtended and winUser.VK_VOLUME_MUTE <= self.vkCode <= winUser.VK_VOLUME_UP: # Don't report volume controlling keys. return False if self.vkCode == 0xFF: # #3468: This key is unknown to Windows. # This could be for an event such as gyroscope movement, # so don't report it. return False if self.vkCode in self.TOGGLE_KEYS: # #5490: Dont report for keys that toggle on off. # This is to avoid them from being reported twice: once by the 'speak command keys' feature, # and once to announce that the state has changed. return False return not self.isCharacter def _get_isCharacter(self): # Aside from space, a key name of more than 1 character is a potential command and therefore is not a character. if self.vkCode != winUser.VK_SPACE and len(self.mainKeyName) > 1: return False # If this key has modifiers other than shift, it is a command and not a character; e.g. shift+f is a character, but control+f is a command. modifiers = self.generalizedModifiers if modifiers and (len(modifiers) > 1 or tuple(modifiers)[0][0] != winUser.VK_SHIFT): return False return True def _get_speechEffectWhenExecuted(self): if inputCore.manager.isInputHelpActive: return self.SPEECHEFFECT_CANCEL if self.isExtended and winUser.VK_VOLUME_MUTE <= self.vkCode <= winUser.VK_VOLUME_UP: return None if self.vkCode == 0xFF: # #3468: This key is unknown to Windows. # This could be for an event such as gyroscope movement, # so don't interrupt speech. return None if not config.conf['keyboard']['speechInterruptForCharacters'] and (not self.shouldReportAsCommand or self.vkCode in (winUser.VK_SHIFT, winUser.VK_LSHIFT, winUser.VK_RSHIFT)): return None if self.vkCode==winUser.VK_RETURN and not config.conf['keyboard']['speechInterruptForEnter']: return None if self.vkCode in (winUser.VK_SHIFT, winUser.VK_LSHIFT, winUser.VK_RSHIFT): return self.SPEECHEFFECT_RESUME if speech.isPaused else self.SPEECHEFFECT_PAUSE return self.SPEECHEFFECT_CANCEL def reportExtra(self): if self.vkCode in self.TOGGLE_KEYS: core.callLater(30, self._reportToggleKey) def _reportToggleKey(self): toggleState = winUser.getKeyState(self.vkCode) & 1 key = self.mainKeyName ui.message(u"{key} {state}".format( key=localizedKeyLabels.get(key.lower(), key), state=_("on") if toggleState else _("off"))) def send(self): keys = [] for vk, ext in self.generalizedModifiers: if vk == VK_WIN: if winUser.getKeyState(winUser.VK_LWIN) & 32768 or winUser.getKeyState(winUser.VK_RWIN) & 32768: # Already down. continue vk = winUser.VK_LWIN elif winUser.getKeyState(vk) & 32768: # Already down. continue keys.append((vk, 0, ext)) keys.append((self.vkCode, self.scanCode, self.isExtended)) with ignoreInjection(): if winUser.getKeyState(self.vkCode) & 32768: # This key is already down, so send a key up for it first. winUser.keybd_event(self.vkCode, self.scanCode, self.isExtended + 2, 0) # Send key down events for these keys. for vk, scan, ext in keys: winUser.keybd_event(vk, scan, ext, 0) # Send key up events for the keys in reverse order. for vk, scan, ext in reversed(keys): winUser.keybd_event(vk, scan, ext + 2, 0) if not queueHandler.isPendingItems(queueHandler.eventQueue): # We want to guarantee that by the time that # this function returns,the keyboard input generated # has been injected and NVDA has received and processed it. time.sleep(0.01) wx.Yield() @classmethod def fromName(cls, name): """Create an instance given a key name. @param name: The key name. @type name: str @return: A gesture for the specified key. @rtype: L{KeyboardInputGesture} """ keyNames = name.split("+") keys = [] for keyName in keyNames: if keyName == "plus": # A key name can't include "+" except as a separator. keyName = "+" if keyName == VK_WIN: vk = winUser.VK_LWIN ext = False elif keyName.lower() == VK_NVDA.lower(): vk, ext = getNVDAModifierKeys()[0] elif len(keyName) == 1: ext = False requiredMods, vk = winUser.VkKeyScanEx(keyName, getInputHkl()) if requiredMods & 1: keys.append((winUser.VK_SHIFT, False)) if requiredMods & 2: keys.append((winUser.VK_CONTROL, False)) if requiredMods & 4: keys.append((winUser.VK_MENU, False)) # Not sure whether we need to support the Hankaku modifier (& 8). else: vk, ext = vkCodes.byName[keyName.lower()] if ext is None: ext = False keys.append((vk, ext)) if not keys: raise ValueError return cls(keys[:-1], vk, 0, ext) RE_IDENTIFIER = re.compile(r"^kb(?:\((.+?)\))?:(.*)$") @classmethod def getDisplayTextForIdentifier(cls, identifier): layout, keys = cls.RE_IDENTIFIER.match(identifier).groups() dispSource = None if layout: try: # Translators: Used when describing keys on the system keyboard with a particular layout. # %s is replaced with the layout name. # For example, in English, this might produce "laptop keyboard". dispSource = _("%s keyboard") % cls.LAYOUTS[layout] except KeyError: pass if not dispSource: # Translators: Used when describing keys on the system keyboard applying to all layouts. dispSource = _("keyboard, all layouts") keys = set(keys.split("+")) names = [] main = None try: # If present, the NVDA key should appear first. keys.remove("nvda") names.append("NVDA") except KeyError: pass for key in keys: try: # vkCodes.byName values are (vk, ext) vk = vkCodes.byName[key][0] except KeyError: # This could be a fake vk. vk = key label = localizedKeyLabels.get(key, key) if vk in cls.NORMAL_MODIFIER_KEYS: names.append(label) else: # The main key must be last, so handle that outside the loop. main = label names.append(main) return dispSource, "+".join(names) inputCore.registerGestureSource("kb", KeyboardInputGesture) def injectRawKeyboardInput(isPress, code, isExtended): """Inject raw input from a system keyboard that is not handled natively by Windows. For example, this might be used for input from a QWERTY keyboard on a braille display. NVDA will treat the key as if it had been pressed on a normal system keyboard. If it is not handled by NVDA, it will be sent to the operating system. @param isPress: Whether the key is being pressed. @type isPress: bool @param code: The scan code (PC set 1) of the key. @type code: int @param isExtended: Whether this is an extended key. @type isExtended: bool """ mapScan = code if isExtended: # Change what we pass to MapVirtualKeyEx, but don't change what NVDA gets. mapScan |= 0xE000 vkCode = winUser.user32.MapVirtualKeyExW(mapScan, winUser.MAPVK_VSC_TO_VK_EX, getInputHkl()) if isPress: shouldSend = internal_keyDownEvent(vkCode, code, isExtended, False) else: shouldSend = internal_keyUpEvent(vkCode, code, isExtended, False) if shouldSend: flags = 0 if not isPress: flags |= 2 if isExtended: flags |= 1 with ignoreInjection(): winUser.keybd_event(vkCode, code, flags, None) wx.Yield()
1
28,140
How likely would it be that the keyboard layout for the NVDA main thread differs from the keyboard layout of the currently focused app?
nvaccess-nvda
py
@@ -198,6 +198,10 @@ class Driver extends webdriver.WebDriver { * @return {!Driver} A new driver instance. */ static createSession(options, service = getDefaultService()) { + if (!service) { + service = getDefaultService(); + } + let client = service.start().then(url => new http.HttpClient(url)); let executor = new http.Executor(client);
1
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview Defines a {@linkplain Driver WebDriver} client for * Microsoft's Edge web browser. Before using this module, * you must download and install the latest * [MicrosoftEdgeDriver](http://go.microsoft.com/fwlink/?LinkId=619687) server. * Ensure that the MicrosoftEdgeDriver is on your * [PATH](http://en.wikipedia.org/wiki/PATH_%28variable%29). * * There are three primary classes exported by this module: * * 1. {@linkplain ServiceBuilder}: configures the * {@link ./remote.DriverService remote.DriverService} * that manages the [MicrosoftEdgeDriver] child process. * * 2. {@linkplain Options}: defines configuration options for each new * MicrosoftEdgeDriver session, such as which * {@linkplain Options#setProxy proxy} to use when starting the browser. * * 3. {@linkplain Driver}: the WebDriver client; each new instance will control * a unique browser session. * * __Customizing the MicrosoftEdgeDriver Server__ <a id="custom-server"></a> * * By default, every MicrosoftEdge session will use a single driver service, * which is started the first time a {@link Driver} instance is created and * terminated when this process exits. The default service will inherit its * environment from the current process. * You may obtain a handle to this default service using * {@link #getDefaultService getDefaultService()} and change its configuration * with {@link #setDefaultService setDefaultService()}. * * You may also create a {@link Driver} with its own driver service. This is * useful if you need to capture the server's log output for a specific session: * * var edge = require('selenium-webdriver/edge'); * * var service = new edge.ServiceBuilder() * .setPort(55555) * .build(); * * var options = new edge.Options(); * // configure browser options ... * * var driver = edge.Driver.createSession(options, service); * * Users should only instantiate the {@link Driver} class directly when they * need a custom driver service configuration (as shown above). For normal * operation, users should start MicrosoftEdge using the * {@link ./builder.Builder selenium-webdriver.Builder}. * * [MicrosoftEdgeDriver]: https://msdn.microsoft.com/en-us/library/mt188085(v=vs.85).aspx */ 'use strict'; const fs = require('fs'); const util = require('util'); const http = require('./http'); const io = require('./io'); const portprober = require('./net/portprober'); const promise = require('./lib/promise'); const remote = require('./remote'); const Symbols = require('./lib/symbols'); const webdriver = require('./lib/webdriver'); const {Browser, Capabilities} = require('./lib/capabilities'); const EDGEDRIVER_EXE = 'MicrosoftWebDriver.exe'; /** * _Synchronously_ attempts to locate the edge driver executable on the current * system. * * @return {?string} the located executable, or `null`. */ function locateSynchronously() { return process.platform === 'win32' ? io.findInPath(EDGEDRIVER_EXE, true) : null; } /** * Class for managing MicrosoftEdgeDriver specific options. */ class Options extends Capabilities { /** * @param {(Capabilities|Map<string, ?>|Object)=} other Another set of * capabilities to initialize this instance from. */ constructor(other = undefined) { super(other); this.setBrowserName(Browser.EDGE); } } /** * Creates {@link remote.DriverService} instances that manage a * MicrosoftEdgeDriver server in a child process. */ class ServiceBuilder extends remote.DriverService.Builder { /** * @param {string=} opt_exe Path to the server executable to use. If omitted, * the builder will attempt to locate the MicrosoftEdgeDriver on the current * PATH. * @throws {Error} If provided executable does not exist, or the * MicrosoftEdgeDriver cannot be found on the PATH. */ constructor(opt_exe) { let exe = opt_exe || locateSynchronously(); if (!exe) { throw Error( 'The ' + EDGEDRIVER_EXE + ' could not be found on the current PATH. ' + 'Please download the latest version of the MicrosoftEdgeDriver from ' + 'https://www.microsoft.com/en-us/download/details.aspx?id=48212 and ' + 'ensure it can be found on your PATH.'); } super(exe); // Binding to the loopback address will fail if not running with // administrator privileges. Since we cannot test for that in script // (or can we?), force the DriverService to use "localhost". this.setHostname('localhost'); } /** * Enables verbose logging. * @return {!ServiceBuilder} A self reference. */ enableVerboseLogging() { return this.addArguments('--verbose'); } } /** @type {remote.DriverService} */ var defaultService = null; /** * Sets the default service to use for new MicrosoftEdgeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ function setDefaultService(service) { if (defaultService && defaultService.isRunning()) { throw Error( 'The previously configured EdgeDriver service is still running. ' + 'You must shut it down before you may adjust its configuration.'); } defaultService = service; } /** * Returns the default MicrosoftEdgeDriver service. If such a service has * not been configured, one will be constructed using the default configuration * for an MicrosoftEdgeDriver executable found on the system PATH. * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. */ function getDefaultService() { if (!defaultService) { defaultService = new ServiceBuilder().build(); } return defaultService; } /** * Creates a new WebDriver client for Microsoft's Edge. */ class Driver extends webdriver.WebDriver { /** * Creates a new browser session for Microsoft's Edge browser. * * @param {(Capabilities|Options)=} options The configuration options. * @param {remote.DriverService=} service The session to use; will use * the {@linkplain #getDefaultService default service} by default. * @return {!Driver} A new driver instance. */ static createSession(options, service = getDefaultService()) { let client = service.start().then(url => new http.HttpClient(url)); let executor = new http.Executor(client); options = options || new Options(); return /** @type {!Driver} */(super.createSession( executor, options, () => service.kill())); } /** * This function is a no-op as file detectors are not supported by this * implementation. * @override */ setFileDetector() {} } // PUBLIC API exports.Driver = Driver; exports.Options = Options; exports.ServiceBuilder = ServiceBuilder; exports.getDefaultService = getDefaultService; exports.setDefaultService = setDefaultService; exports.locateSynchronously = locateSynchronously;
1
15,395
Would you mind removing the default parameter above? (I doubt I'll ever use defaults again since you still have to protect against callers explicitly passing `null` or `undefined`)
SeleniumHQ-selenium
rb
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
10
Edit dataset card