hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a16615e40774cd9764e73918804da622a41a8333 | 19,843 | cc | C++ | cmd/traffic_shell/ConfigUpgradeCmd.cc | syucream/trafficserver | 144b2ef0a80c154ae132c9e73e94a5b4596c2b81 | [
"Apache-2.0"
] | 83 | 2015-01-13T14:44:55.000Z | 2021-10-30T07:57:03.000Z | cmd/traffic_shell/ConfigUpgradeCmd.cc | syucream/trafficserver | 144b2ef0a80c154ae132c9e73e94a5b4596c2b81 | [
"Apache-2.0"
] | 9 | 2015-03-13T15:17:28.000Z | 2017-04-19T08:53:24.000Z | cmd/traffic_shell/ConfigUpgradeCmd.cc | syucream/trafficserver | 144b2ef0a80c154ae132c9e73e94a5b4596c2b81 | [
"Apache-2.0"
] | 50 | 2015-01-29T14:51:38.000Z | 2021-11-10T02:03:35.000Z | /** @file
A brief file description
@section license License
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.
*/
/****************************************************************
* Filename: ConfigUpgradeCmd.cc
* Purpose: This file contains the CLI's "config:write/read/install/upgrade"
command implementation.
*
****************************************************************/
#include <ConfigCmd.h>
#include <CliDisplay.h>
#include <CliMgmtUtils.h>
#include <CliDisplay.h>
#include <CliMgmtUtils.h>
#include <ConfigUpgradeCmd.h>
#include <string.h>
CIFCEntry::CIFCEntry(char *keyword, int counton, const char *string, ...)
{
char Buffer[CONFIG_UPGRADE_BUF_SIZE];
KeyWord = new char[strlen(keyword) + 1];
sprintf(KeyWord, keyword);
CountOn = counton;
va_start(ap, string);
vsprintf(Buffer, string, ap);
va_end(ap);
Input = new char[strlen(Buffer) + 1];
sprintf(Input, Buffer);
Version = NULL;
FileName = NULL;
}
CIFCEntry::~CIFCEntry()
{
if (Version != NULL)
delete[]Version;
if (FileName != NULL)
delete[]FileName;
if (KeyWord != NULL)
delete[]KeyWord;
if (Input != NULL)
delete[]Input;
}
// check IFCVERSION IFCPATH and IFCFILENAME setup
INKError
CIFCEntry::ConfigWriteCheckIFCEnv()
{
char *pathPtr;
char *filenamePtr;
char *versionPtr;
pathPtr = getenv("IFCPATH");
filenamePtr = getenv("IFCFILENAME");
versionPtr = getenv("IFCVERSION");
if (pathPtr == NULL || filenamePtr == NULL || versionPtr == NULL ||
strlen(pathPtr) == 0 || strlen(filenamePtr) == 0 || strlen(versionPtr) == 0) {
return INK_ERR_READ_FILE;
}
FileName = new char[strlen(pathPtr) + strlen(filenamePtr) + 1];
sprintf(FileName, "%s%s", pathPtr, filenamePtr);
Version = new char[strlen(versionPtr) + 1];
sprintf(Version, "%s", versionPtr);
return INK_ERR_OKAY;
}
INKError
CIFCEntry::Cli_NewIFCFile()
{
FILE *Fptr;
Fptr = fopen(FileName, "r+");
if (Fptr != NULL) {
fclose(Fptr);
return INK_ERR_OKAY;
} else { /* need to create new file */
Fptr = fopen(FileName, "w");
if (Fptr == NULL) {
Cli_Error("Error in creating new IFC file\n");
return INK_ERR_WRITE_FILE;
}
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#IFCHEAD FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<TRAFFIC SERVER VERSION>\n");
fprintf(Fptr, "#<BUILD DATE>\n");
fprintf(Fptr, "#<PLATFORM>\n");
fprintf(Fptr, "#<NUMBER OF NODES>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "IfcHead\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#FEATURE FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<FEATURE STRING LIST>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "Feature\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#TAR FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<NUMBER OF TAR FILES>\n");
fprintf(Fptr, "#<LIST OF TAR FILES>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "Tar\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#COMMONTAR FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<NUMBER OF TAR FILES>\n");
fprintf(Fptr, "#<LIST OF TAR FILES>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "CommonTar\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#TAR INFO FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<TAR FILE NAME>:<LIST OF FILES>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "TarInfo\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#BIN GROUP FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<NUMBER OF FILES>\n");
fprintf(Fptr, "#<LIST OF FILES>\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "BinGroup\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#BIN DIR FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of SubDirectories>\n");
fprintf(Fptr, "#<SubDirectory>:<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "BinDir\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#BIN COMMON FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of Files>\n");
fprintf(Fptr, "#<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "BinCommon\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#LIB GROUP FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of Files>\n");
fprintf(Fptr, "#<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "LibGroup\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#LIB DIR FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of SubDirectories>\n");
fprintf(Fptr, "#<SubDirectory>:<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "LibDir\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#LIB COMMON FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of Files>\n");
fprintf(Fptr, "#<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "LibCommon\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#CONFIG GROUP FORMAT>\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of Files>\n");
fprintf(Fptr, "#<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "ConfigGroup\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#CONFIG DIR FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of SubDirectories>\n");
fprintf(Fptr, "#<SubDirectory>:<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "ConfigDir\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#CONFIG COMMON FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of Files>\n");
fprintf(Fptr, "#<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "ConfigCommon\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "############################\n");
fprintf(Fptr, "#COMMON FORMAT\n");
fprintf(Fptr, "#\n");
fprintf(Fptr, "#<Number of Files>\n");
fprintf(Fptr, "#<List of Files>\n");
fprintf(Fptr, "\n");
fprintf(Fptr, "CommonFile\n");
fprintf(Fptr, "0\n");
fprintf(Fptr, "\n");
fclose(Fptr);
return INK_ERR_OKAY;
}
}
int
CIFCEntry::ConfigWriteIFC()
{
FILE *Fptr;
char *filebuffer, *in_buffer;
char *p1;
char OldCountString[CONFIG_UPGRADE_INT_STRING_SIZE];
int Count = -1;
long size, amount_read, addsize;
if (ConfigWriteCheckIFCEnv() == INK_ERR_READ_FILE) {
Cli_Error("Set $IFCVERSION, $IFCPATH and $IFCFILENAME First\n");
return CLI_ERROR;
}
if (Cli_NewIFCFile() == INK_ERR_WRITE_FILE) {
return CLI_ERROR;
}
if ((Fptr = fopen(FileName, "r")) == NULL) {
Cli_Error("ERROR Open IFC File to read\n");
return CLI_ERROR;
}
fseek(Fptr, 0, SEEK_END);
size = ftell(Fptr);
if (size <= 0) {
fclose(Fptr);
Cli_Error("Error Reading IFC File\n");
return CLI_ERROR;
}
filebuffer = new char[size + 1];
fseek(Fptr, 0, SEEK_SET);
amount_read = fread((void *) filebuffer, sizeof(char), size, Fptr);
fclose(Fptr);
filebuffer[size] = '\0';
if (size * (int) sizeof(char) != amount_read) {
Cli_Error("Error Reading IFC File\n");
delete[]filebuffer;
return CLI_ERROR;
}
// look for KeyWord
if ((p1 = strstr(filebuffer, KeyWord)) == NULL) {
delete[]filebuffer;
Cli_Error("Error Finding Keyword\n");
return CLI_ERROR;
}
p1 += strlen(KeyWord);
p1++;
// writeback
Fptr = fopen(FileName, "r+");
fseek(Fptr, p1 - filebuffer, SEEK_SET);
switch (CountOn) {
case 1:
// coverity[secure_coding]
sscanf(p1, "%d\n", &Count);
sprintf(OldCountString, "%d", Count);
p1 += (strlen(OldCountString) + 1);
Count++;
addsize = strlen(Input) + CONFIG_UPGRADE_INT_STRING_SIZE + 2;
in_buffer = new char[addsize + 1];
sprintf(in_buffer, "%d\n%s\n", Count, Input);
in_buffer[addsize] = '\0';
fwrite(in_buffer, sizeof(char), strlen(in_buffer), Fptr);
delete[]in_buffer;
break;
case 0:
fwrite(Input, sizeof(char), strlen(Input), Fptr);
fwrite("\n", sizeof(char), strlen("\n"), Fptr);
break;
default:
Cli_Error("Unexpected Value of CountOn\n");
fclose(Fptr);
delete[]filebuffer;
return CLI_ERROR;
}
fwrite(p1, sizeof(char), size - (p1 - filebuffer), Fptr);
fclose(Fptr);
delete[]filebuffer;
return CLI_OK;
}
//config read subcommand
int
CIFCEntry::ConfigReadIFC()
{
FILE *Fptr;
char *filebuffer;
long size, amount_read;
INKError CLI_CHECK;
if (ConfigWriteCheckIFCEnv() == INK_ERR_READ_FILE) {
Cli_Error("Set $IFCVERSION, $IFCPATH and $IFCFILENAME First\n");
return CLI_ERROR;
}
if ((Fptr = fopen(FileName, "r")) == NULL) {
Cli_Printf("ERROR Opening IFC file for read\n");
return CLI_ERROR;
}
fseek(Fptr, 0, SEEK_END);
size = ftell(Fptr);
if (size <= 0) {
Cli_Error("Error Empty IFC FILE\n", FileName);
fclose(Fptr);
return CLI_ERROR;
}
filebuffer = new char[size + 1];
fseek(Fptr, 0, SEEK_SET);
amount_read = fread((void *) filebuffer, (int) sizeof(char), size, Fptr);
if (size * (int) sizeof(char) != amount_read) {
Cli_Error("Error Reading IFC File\n");
delete[]filebuffer;
return CLI_ERROR;
}
filebuffer[amount_read] = '\0';
fclose(Fptr);
printf("%s\n", filebuffer);
delete[]filebuffer;
return CLI_OK;
}
void
CIFCEntry::PrintEle()
{
printf("%s:%d:%s\n", KeyWord, CountOn, Input);
}
////////////////////////////////////////////////////////////////
// Cmd_ConfigWrite
//
// This is the callback function for the "config:write" command.
//
// Parameters:
// clientData -- information about parsed arguments
// interp -- the Tcl interpreter
// argc -- number of command arguments
// argv -- the command arguments
//
int
Cmd_ConfigWrite(ClientData clientData, Tcl_Interp * interp, int argc, char *argv[])
{
CIFCEntry *EntryPtr;
int CLI_RETURN;
/* call to processArgForCommand must appear at the beginning
* of each command's callback function
*/
if (processArgForCommand(interp, argc, argv) != CLI_OK) {
return CMD_ERROR;
}
if (processHelpCommand(argc, argv) == CLI_OK)
return CMD_OK;
if (cliCheckIfEnabled("config:write") == CLI_ERROR) {
return CMD_ERROR;
}
cli_cmdCallbackInfo *cmdCallbackInfo;
cli_parsedArgInfo *argtable, *infoPtr;
cmdCallbackInfo = (cli_cmdCallbackInfo *) clientData;
argtable = cmdCallbackInfo->parsedArgTable;
infoPtr = argtable;
Cli_Debug("Cmd_ConfigWrite argc %d\n", argc);
if (argtable->parsed_args != CLI_PARSED_ARGV_END) {
switch (argtable->parsed_args) {
case CMD_CONFIG_WRITE_IFC_HEAD:
EntryPtr = new CIFCEntry("IfcHead", 0, "%s\n%s\n%s\n%d", argtable[1].arg_string, argtable[2].arg_string,
argtable[3].arg_string, argtable[4].arg_int);
break;
case CMD_CONFIG_WRITE_FEATURE:
EntryPtr = new CIFCEntry("Feature", 0, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_TAR:
EntryPtr = new CIFCEntry("Tar", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_TAR_INFO:
EntryPtr = new CIFCEntry("TarInfo", 0, "%s:%s", argtable[0].arg_string, argtable[1].arg_string);
break;
case CMD_CONFIG_WRITE_TAR_COMMON:
EntryPtr = new CIFCEntry("CommonTar", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_BIN_DIR:
EntryPtr = new CIFCEntry("BinDir", 1, "%s:%s", argtable[0].arg_string, argtable[1].arg_string);
break;
case CMD_CONFIG_WRITE_BIN_GROUP:
EntryPtr = new CIFCEntry("BinGroup", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_BIN_COMMON:
EntryPtr = new CIFCEntry("BinCommon", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_LIB_DIR:
EntryPtr = new CIFCEntry("LibDir", 1, "%s:%s", argtable[0].arg_string, argtable[1].arg_string);
break;
case CMD_CONFIG_WRITE_LIB_GROUP:
EntryPtr = new CIFCEntry("LibGroup", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_LIB_COMMON:
EntryPtr = new CIFCEntry("LibCommon", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_CONFIG_DIR:
EntryPtr = new CIFCEntry("ConfigDir", 1, "%s:%s", argtable[0].arg_string, argtable[1].arg_string);
break;
case CMD_CONFIG_WRITE_CONFIG_GROUP:
EntryPtr = new CIFCEntry("ConfigGroup", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_CONFIG_COMMON:
EntryPtr = new CIFCEntry("ConfigCommon", 1, argtable[0].arg_string);
break;
case CMD_CONFIG_WRITE_COMMON_FILE:
EntryPtr = new CIFCEntry("CommonFile", 1, argtable[0].arg_string);
}
if (EntryPtr == NULL) {
Cli_Error("Error Allocate Memory\n");
return CLI_ERROR;
} else {
CLI_RETURN = EntryPtr->ConfigWriteIFC();
delete EntryPtr;
return CLI_RETURN;
}
}
Cli_Error(ERR_COMMAND_SYNTAX, cmdCallbackInfo->command_usage);
return CMD_ERROR;
}
////////////////////////////////////////////////////////////////
// CmdArgs_ConfigWrite
//
// Register "config:write" arguments with the Tcl interpreter.
//
int
CmdArgs_ConfigWrite()
{
createArgument("ifc-head", 1, CLI_ARGV_CONST_OPTION,
(char *) NULL, CMD_CONFIG_WRITE_IFC_HEAD, "Specify the head information of ifc file", (char *) NULL);
createArgument("ts-version", CMD_CONFIG_WRITE_IFC_HEAD, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_TS_VERSION, "Specify the version of Traffic Server installed",
(char *) NULL);
createArgument("build-date", CMD_CONFIG_WRITE_TS_VERSION, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_BUILD_DATE, "Specify date of the Traffic Server Build", (char *) NULL);
createArgument("platform", CMD_CONFIG_WRITE_BUILD_DATE, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_PLATFORM, "Specify the platform of installation", (char *) NULL);
createArgument("nodes", CMD_CONFIG_WRITE_PLATFORM, CLI_ARGV_INT,
(char *) NULL, CMD_CONFIG_WRITE_NODES, "Specify the number of node in the cluster", (char *) NULL);
createArgument("feature", 1, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_FEATURE, "Specify the feature string", (char *) NULL);
createArgument("tar", 1, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_TAR, "Specify the tar file list", (char *) NULL);
createArgument("tar-common", 1, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_TAR_COMMON, "Specify the MUST-HAVE tar files", (char *) NULL);
createArgument("tar-info", 1, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_TAR_INFO, "Specify the file contained in this named tar file",
(char *) NULL);
createArgument("filelist", CLI_ARGV_NO_POS, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_FILELIST, "Specify the filelist contained in this named tar file",
(char *) NULL);
createArgument("bin-dir", 1, CLI_ARGV_STRING,
(char *) NULL, CMD_CONFIG_WRITE_BIN_DIR,
"Specify the subdirectories and the files in each of them in bin directory", (char *) NULL);
createArgument("bin-group", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_BIN_GROUP,
"Specify the file listed in the bin directory", (char *) NULL);
createArgument("bin-common", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_BIN_COMMON,
"Specify the MUST-HAVE bin files", (char *) NULL);
createArgument("lib-dir", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_LIB_DIR,
"Specify the subdirectories and the files in each of them in lib directory", (char *) NULL);
createArgument("lib-group", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_LIB_GROUP,
"Specify the file listed in the lib directory", (char *) NULL);
createArgument("lib-common", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_LIB_COMMON,
"Specify the MUST-HAVE lib files", (char *) NULL);
createArgument("config-dir", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_CONFIG_DIR,
"Specify the subdirectories and the files in each of them in the config directory", (char *) NULL);
createArgument("config-group", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_CONFIG_GROUP,
"Specify the file listed in the config directory", (char *) NULL);
createArgument("config-common", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_CONFIG_COMMON,
"Specify the MUST-HAVE config files", (char *) NULL);
createArgument("common-file", 1, CLI_ARGV_STRING, (char *) NULL, CMD_CONFIG_WRITE_COMMON_FILE,
"Specify the MUST-HAVE files", (char *) NULL);
return CLI_OK;
}
////////////////////////////////////////////////////////////////
// Cmd_ConfigRead
//
// This is the callback function for the "config:read" command.
//
// Parameters:
// clientData -- information about parsed arguments
// interp -- the Tcl interpreter
// argc -- number of command arguments
// argv -- the command arguments
//
int
Cmd_ConfigRead(ClientData clientData, Tcl_Interp * interp, int argc, char *argv[])
{
CIFCEntry *EntryPtr;
int CLI_RETURN;
/* call to processArgForCommand must appear at the beginning
* of each command's callback function
*/
if (processArgForCommand(interp, argc, argv) != CLI_OK) {
return CMD_ERROR;
}
if (processHelpCommand(argc, argv) == CLI_OK)
return CMD_OK;
if (cliCheckIfEnabled("config:read") == CLI_ERROR) {
return CMD_ERROR;
}
cli_cmdCallbackInfo *cmdCallbackInfo;
cli_parsedArgInfo *argtable, *infoPtr;
cmdCallbackInfo = (cli_cmdCallbackInfo *) clientData;
argtable = cmdCallbackInfo->parsedArgTable;
infoPtr = argtable;
Cli_Debug("Cmd_ConfigRead argc %d\n", argc);
if (argtable->parsed_args == CLI_PARSED_ARGV_END) {
EntryPtr = new CIFCEntry("", 0, "");
if (EntryPtr == NULL) {
Cli_Error("Error Allocate Memory\n");
return CLI_ERROR;
} else {
CLI_RETURN = EntryPtr->ConfigReadIFC();
delete EntryPtr;
return CLI_RETURN;
}
}
Cli_Error(ERR_COMMAND_SYNTAX, cmdCallbackInfo->command_usage);
return CMD_ERROR;
}
| 31.248819 | 120 | 0.619412 | syucream |
a1661b029b0f15548c8263cb81116c609b9b7812 | 717 | cpp | C++ | src/storage/test/unit/src/model/TemperatureDataModelTest.cpp | karz0n/sensority-collector | 0d71a2855fa7fcff9c11475dbf1832a598421949 | [
"MIT"
] | null | null | null | src/storage/test/unit/src/model/TemperatureDataModelTest.cpp | karz0n/sensority-collector | 0d71a2855fa7fcff9c11475dbf1832a598421949 | [
"MIT"
] | null | null | null | src/storage/test/unit/src/model/TemperatureDataModelTest.cpp | karz0n/sensority-collector | 0d71a2855fa7fcff9c11475dbf1832a598421949 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "storage/model/TemperatureDataModel.hpp"
using namespace testing;
using namespace storage;
static Matcher<TemperatureData>
matchTo(float value, float raw)
{
return AllOf(Field(&TemperatureData::value, FloatEq(value)),
Field(&TemperatureData::raw, FloatEq(raw)));
}
TEST(TemperatureDataModelTest, Parse)
{
const std::string Values{R"([
{"value": 13.5, "raw": 14.7},
{"value": 10.1, "raw": 11.2}
])"};
TemperatureDataModel model;
EXPECT_NO_THROW({ ASSERT_TRUE(model.parse(Values)); });
EXPECT_THAT(model, SizeIs(2));
EXPECT_THAT(model, ElementsAre(matchTo(13.5, 14.7), matchTo(10.1, 11.2)));
}
| 25.607143 | 78 | 0.668061 | karz0n |
a1683771a54c5382ba1be4f8b9bba5f123f39aa9 | 20,557 | cpp | C++ | Tests/UnitTests/ReaderTests/HTKLMFReaderTests.cpp | sunkwei/CNTK | 08691e97707538b110ca71bce4ad06c46d840517 | [
"Intel"
] | null | null | null | Tests/UnitTests/ReaderTests/HTKLMFReaderTests.cpp | sunkwei/CNTK | 08691e97707538b110ca71bce4ad06c46d840517 | [
"Intel"
] | null | null | null | Tests/UnitTests/ReaderTests/HTKLMFReaderTests.cpp | sunkwei/CNTK | 08691e97707538b110ca71bce4ad06c46d840517 | [
"Intel"
] | 1 | 2019-10-24T00:35:07.000Z | 2019-10-24T00:35:07.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "stdafx.h"
#include "Common/ReaderTestHelper.h"
using namespace Microsoft::MSR::CNTK;
namespace Microsoft { namespace MSR { namespace CNTK { namespace Test {
// Fixture specific to the AN4 data
struct AN4ReaderFixture : ReaderFixture
{
AN4ReaderFixture()
: ReaderFixture(
"%CNTK_EXTERNAL_TESTDATA_SOURCE_DIRECTORY%/Speech/AN4Corpus/v0",
"This test uses external data that is not part of the CNTK repository. Environment variable CNTK_EXTERNAL_TESTDATA_SOURCE_DIRECTORY must be set to point to the external test data location. \n Refer to the 'Setting up CNTK on Windows' documentation.)")
{
}
};
struct iVectorFixture : ReaderFixture
{
iVectorFixture()
: ReaderFixture(
"%CNTK_EXTERNAL_TESTDATA_SOURCE_DIRECTORY%/iVector",
"This test uses external data that is not part of the CNTK repository. Environment variable CNTK_EXTERNAL_TESTDATA_SOURCE_DIRECTORY must be set to point to the external test data location. \n Refer to the 'Setting up CNTK on Windows' documentation.)")
{
}
};
// Use SpeechReaderFixture for most tests
// Some of them (e.g. 10, will use different data, thus a different fixture)
BOOST_FIXTURE_TEST_SUITE(ReaderTestSuite, AN4ReaderFixture)
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop1)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop1_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_5_11_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop2)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop2_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop2_12_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop2_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop3)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop3_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop3_13_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop3_Output.txt",
"Simple_Test",
"reader",
randomizeAuto, // epoch size - all available
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop4)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop4_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop4_8_14_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop4_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop5)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop5_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_5_11_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop5_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop6)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop6_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop6_16_17_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop6_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop7)
{
HelperRunReaderTestWithException<float, std::invalid_argument>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop7_Config.cntk",
"Simple_Test",
"reader");
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop8)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop8_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop4_8_14_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop8_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop9)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop9_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop9_19_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop9_Output.txt",
"Simple_Test",
"reader",
2000,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop10)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop10_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop10_20_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop10_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
2,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop11)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop11_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_5_11_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop11_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop12)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop12_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop2_12_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop12_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop13)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop13_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop3_13_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop13_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop14)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop14_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop4_8_14_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop14_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop16)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop16_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop6_16_17_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop16_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop19)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop19_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop9_19_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop19_Output.txt",
"Simple_Test",
"reader",
2000,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop20)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop20_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop10_20_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop20_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
2,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop21_0)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop21_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_0_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_0_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
2);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop21_1)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop21_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_1_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_1_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
1,
2);
};
BOOST_AUTO_TEST_CASE(HTKMLFReaderSimpleDataLoop22)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderSimpleDataLoop22_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop22_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop22_Output.txt",
"Simple_Test",
"reader",
5000,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop1)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop1_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_5_11_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop5)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop5_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_5_11_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop5_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop11)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop11_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop1_5_11_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop11_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop21_0)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop21_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_0_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_0_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
2);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop21_1)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop21_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_1_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop21_1_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
1,
2);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop4)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop4_Config.cntk",
testDataPath() + "/Control/HTKDeserializersSimpleDataLoop4_Control.txt",
testDataPath() + "/Control/HTKDeserializersSimpleDataLoop4_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop8)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop8_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop4_8_14_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop8_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop14)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop14_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop4_8_14_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop14_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop9)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop9_Config.cntk",
testDataPath() + "/Control/HTKDeserializersSimpleDataLoop9_19_Control.txt",
testDataPath() + "/Control/HTKDeserializersSimpleDataLoop9_Output.txt",
"Simple_Test",
"reader",
2000,
500,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop19)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop19_Config.cntk",
testDataPath() + "/Control/HTKDeserializersSimpleDataLoop9_19_Control.txt",
testDataPath() + "/Control/HTKDeserializersSimpleDataLoop19_Output.txt",
"Simple_Test",
"reader",
2000,
500,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop10)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop10_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop10_20_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop10_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
2,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop20)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop20_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop10_20_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop20_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
2,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop3)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop3_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop3_13_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop3_Output.txt",
"Simple_Test",
"reader",
randomizeAuto, // epoch size - all available
1,
2,
1,
0,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializers_NonExistingScpFile)
{
HelperRunReaderTestWithException<float, std::runtime_error>(
testDataPath() + "/Config/HTKDeserializers_NonExistingScpFile.cntk",
"Simple_Test",
"reader");
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop2)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop2_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop2_12_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop2_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_CASE(HTKDeserializersSimpleDataLoop12)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKDeserializersSimpleDataLoop12_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop2_12_Control.txt",
testDataPath() + "/Control/HTKMLFReaderSimpleDataLoop12_Output.txt",
"Simple_Test",
"reader",
500,
250,
2,
1,
1,
0,
1);
};
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(ReaderIVectorTestSuite, iVectorFixture)
BOOST_AUTO_TEST_CASE(HTKNoIVector)
{
auto test = [this](std::vector<std::wstring> additionalParameters)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderNoIVectorSimple_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderNoIVectorSimple_Control.txt",
testDataPath() + "/Control/HTKMLFReaderNoIVectorSimple_Output.txt",
"Simple_Test",
"reader",
400,
30,
1,
1,
1,
0,
1,
false,
false,
true,
additionalParameters);
};
test({});
test({ L"Simple_Test=[reader=[readerType=HTKDeserializers]]" });
};
BOOST_AUTO_TEST_CASE(HTKIVectorFrame)
{
auto test = [this](std::vector<std::wstring> additionalParameters)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderIVectorSimple_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderIVectorSimple_Control.txt",
testDataPath() + "/Control/HTKMLFReaderIVectorSimple_Output.txt",
"Simple_Test",
"reader",
400,
30,
1,
2,
1,
0,
1,
false,
false,
true,
additionalParameters);
};
test({});
test({ L"Simple_Test=[reader=[readerType=HTKDeserializers]]" });
};
BOOST_AUTO_TEST_CASE(HTKIVectorSequence)
{
auto test = [this](std::vector<std::wstring> additionalParameters)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/HTKMLFReaderIVectorSimple_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderIVectorSequenceSimple_Control.txt",
testDataPath() + "/Control/HTKMLFReaderIVectorSequenceSimple_Output.txt",
"Simple_Test",
"reader",
200,
30,
1,
2,
1,
0,
1,
false,
false,
true,
additionalParameters);
};
test({ L"frameMode=false", L"precision=float" });
test({ L"frameMode=false", L"precision=float", L"Simple_Test=[reader=[readerType=HTKDeserializers]]" });
};
BOOST_AUTO_TEST_CASE(HTKIVectorBptt)
{
auto test = [this](std::vector<std::wstring> additionalParameters)
{
HelperRunReaderTest<double>(
testDataPath() + "/Config/HTKMLFReaderIVectorSimple_Config.cntk",
testDataPath() + "/Control/HTKMLFReaderIVectorBpttSimple_Control.txt",
testDataPath() + "/Control/HTKMLFReaderIVectorBpttSimple_Output.txt",
"Simple_Test",
"reader",
400,
30,
1,
2,
1,
0,
1,
false,
false,
true,
additionalParameters);
};
test({ L"frameMode=false", L"truncated=true" });
test({ L"frameMode=false", L"truncated=true", L"Simple_Test=[reader=[readerType=HTKDeserializers]]" });
};
BOOST_AUTO_TEST_SUITE_END()
}
}}}
| 27.445928 | 265 | 0.620373 | sunkwei |
a16838d2d41ace1c21e5d91c4816fe0acc6a2bd5 | 4,562 | hpp | C++ | examples/pppbayestree/gpstk/PZ90Ellipsoid.hpp | shaolinbit/minisam_lib | e2e904d1b6753976de1dee102f0b53e778c0f880 | [
"BSD-3-Clause"
] | 104 | 2019-06-23T14:45:20.000Z | 2022-03-20T12:45:29.000Z | examples/pppbayestree/gpstk/PZ90Ellipsoid.hpp | shaolinbit/minisam_lib | e2e904d1b6753976de1dee102f0b53e778c0f880 | [
"BSD-3-Clause"
] | 2 | 2019-06-28T08:23:23.000Z | 2019-07-17T02:37:08.000Z | examples/pppbayestree/gpstk/PZ90Ellipsoid.hpp | shaolinbit/minisam_lib | e2e904d1b6753976de1dee102f0b53e778c0f880 | [
"BSD-3-Clause"
] | 28 | 2019-06-23T14:45:19.000Z | 2022-03-20T12:45:24.000Z | #pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file PZ90Ellipsoid.hpp
* PZ90.02 model of the Ellipsoid (as defined in table 3.2 of ICD-2008, v5.1).
*/
#ifndef GPSTK_PZ90ELLIPSOID_HPP
#define GPSTK_PZ90ELLIPSOID_HPP
#include "EllipsoidModel.hpp"
namespace gpstk
{
/** @addtogroup geodeticgroup */
//@{
class PZ90Ellipsoid : public EllipsoidModel
{
public:
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return semi-major axis of Earth in meters.
virtual double a() const throw()
{
return 6378136.0;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return semi-major axis of Earth in km.
virtual double a_km() const throw()
{
return a() / 1000.0;
}
/**
* Defined in table 3.2 of the GLONASS ICD-2008 (v5.1)
* @return inverse o flattening (ellipsoid parameter).
*/
virtual double flatteningInverse() const throw()
{
return 298.25784;
}
/**
* Computed from inverse flattening value as given in table 3.2
* of the GLONASS ICD-2008 (v5.1)
* @return flattening (ellipsoid parameter).
*/
virtual double flattening() const throw()
{
return 3.35280373518e-3;
}
// The eccentricity and eccSquared values were computed from the
// flattening value via the formula:
// ecc2 = 1 - (1 - f)^2 = f*(2.0 - f)
// ecc = sqrt(ecc2)
/// @return eccentricity (ellipsoid parameter).
virtual double eccentricity() const throw()
{
return 8.1819106432923e-2;
}
/// @return eccentricity squared (ellipsoid parameter).
virtual double eccSquared() const throw()
{
return 6.69436617748e-3;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return angular velocity of Earth in radians/sec.
virtual double angVelocity() const throw()
{
return 7.292115e-5;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return geocentric gravitational constant in m**3 / s**2
virtual double gm() const throw()
{
return 398600.4418e9;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return geocentric gravitational constant in km**3 / s**2
virtual double gm_km() const throw()
{
return 398600.4418;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return Speed of light in m/s.
virtual double c() const throw()
{
return 299792458;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return Speed of light in km/s
virtual double c_km() const throw()
{
return c()/1000.0;
}
///Defined in table 3.2 of ICD-2008 (v5.1)
/// @return Returns second zonal harmonic of the geopotential.
virtual double j20() const throw()
{
return (-1.08262575e-3);
}
/// Destructor.
virtual ~PZ90Ellipsoid() throw() {};
}; // End of class 'PZ90Ellipsoid'
//@}
} // End of namespace gpstk
#endif // GPSTK_PZ90ELLIPSOID_HPP
| 28.691824 | 79 | 0.599956 | shaolinbit |
a16a61bc3a617bf13d2c3e1558797606a51ccfab | 12,676 | hpp | C++ | ql/experimental/volatility/noarbsabrinterpolation.hpp | elay00/QuantLib | 922e582a0d59f20d5a4480448546942c64490fda | [
"BSD-3-Clause"
] | 1 | 2015-09-21T12:21:33.000Z | 2015-09-21T12:21:33.000Z | ql/experimental/volatility/noarbsabrinterpolation.hpp | klausspanderen/quantlib | 922e582a0d59f20d5a4480448546942c64490fda | [
"BSD-3-Clause"
] | 3 | 2022-03-09T16:19:13.000Z | 2022-03-29T07:33:42.000Z | ql/experimental/volatility/noarbsabrinterpolation.hpp | idreamsfy/QuantLib | d6e44270945d2061364e1b3a8bdb4b4e4cc6bba5 | [
"BSD-3-Clause"
] | null | null | null | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2014 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file noarbsabrinterpolation.hpp
\brief noabr sabr interpolation between discrete points
*/
#ifndef quantlib_noarbsabr_interpolation_hpp
#define quantlib_noarbsabr_interpolation_hpp
#include <ql/experimental/volatility/noarbsabrsmilesection.hpp>
#include <ql/math/interpolations/sabrinterpolation.hpp>
#include <utility>
namespace QuantLib {
namespace detail {
// we can directly use the smile section as the wrapper
typedef NoArbSabrSmileSection NoArbSabrWrapper;
struct NoArbSabrSpecs {
Size dimension() { return 4; }
Real eps() { return 0.000001; }
void defaultValues(std::vector<Real> ¶ms,
std::vector<bool> ¶mIsFixed, const Real &forward,
const Real expiryTime, const std::vector<Real> &addParams) {
SABRSpecs().defaultValues(params, paramIsFixed, forward, expiryTime, addParams);
// check if alpha / beta is admissable, otherwise adjust
// if possible (i.e. not fixed, otherwise an exception will
// be thrown from the model constructor anyway)
Real sigmaI = params[0] * std::pow(forward, params[1] - 1.0);
if (sigmaI < detail::NoArbSabrModel::sigmaI_min) {
if (!paramIsFixed[0])
params[0] = detail::NoArbSabrModel::sigmaI_min * (1.0 + eps()) /
std::pow(forward, params[1] - 1.0);
else {
if (!paramIsFixed[1])
params[1] = 1.0 +
std::log(detail::NoArbSabrModel::sigmaI_min *
(1.0 + eps()) / params[0]) /
std::log(forward);
}
}
if (sigmaI > detail::NoArbSabrModel::sigmaI_max) {
if (!paramIsFixed[0])
params[0] = detail::NoArbSabrModel::sigmaI_max * (1.0 - eps()) /
std::pow(forward, params[1] - 1.0);
else {
if (!paramIsFixed[1])
params[1] = 1.0 +
std::log(detail::NoArbSabrModel::sigmaI_max *
(1.0 - eps()) / params[0]) /
std::log(forward);
}
}
}
void guess(Array &values, const std::vector<bool> ¶mIsFixed,
const Real &forward, const Real expiryTime,
const std::vector<Real> &r, const std::vector<Real> &) {
Size j = 0;
if (!paramIsFixed[1])
values[1] = detail::NoArbSabrModel::beta_min +
(detail::NoArbSabrModel::beta_max -
detail::NoArbSabrModel::beta_min) *
r[j++];
if (!paramIsFixed[0]) {
Real sigmaI = detail::NoArbSabrModel::sigmaI_min +
(detail::NoArbSabrModel::sigmaI_max -
detail::NoArbSabrModel::sigmaI_min) *
r[j++];
sigmaI *= (1.0 - eps());
sigmaI += eps() / 2.0;
values[0] = sigmaI / std::pow(forward, values[1] - 1.0);
}
if (!paramIsFixed[2])
values[2] = detail::NoArbSabrModel::nu_min +
(detail::NoArbSabrModel::nu_max -
detail::NoArbSabrModel::nu_min) *
r[j++];
if (!paramIsFixed[3])
values[3] = detail::NoArbSabrModel::rho_min +
(detail::NoArbSabrModel::rho_max -
detail::NoArbSabrModel::rho_min) *
r[j++];
}
Array inverse(const Array &y, const std::vector<bool> ¶mIsFixed,
const std::vector<Real> ¶ms, const Real forward) {
Array x(4);
x[1] = std::tan((y[1] - detail::NoArbSabrModel::beta_min) /
(detail::NoArbSabrModel::beta_max -
detail::NoArbSabrModel::beta_min) *
M_PI +
M_PI / 2.0);
x[0] = std::tan((y[0] * std::pow(forward, y[1] - 1.0) -
detail::NoArbSabrModel::sigmaI_min) /
(detail::NoArbSabrModel::sigmaI_max -
detail::NoArbSabrModel::sigmaI_min) *
M_PI -
M_PI / 2.0);
x[2] = std::tan((y[2] - detail::NoArbSabrModel::nu_min) /
(detail::NoArbSabrModel::nu_max -
detail::NoArbSabrModel::nu_min) *
M_PI +
M_PI / 2.0);
x[3] = std::tan((y[3] - detail::NoArbSabrModel::rho_min) /
(detail::NoArbSabrModel::rho_max -
detail::NoArbSabrModel::rho_min) *
M_PI +
M_PI / 2.0);
return x;
}
Array direct(const Array &x, const std::vector<bool> ¶mIsFixed,
const std::vector<Real> ¶ms, const Real forward) {
Array y(4);
if (paramIsFixed[1])
y[1] = params[1];
else
y[1] = detail::NoArbSabrModel::beta_min +
(detail::NoArbSabrModel::beta_max -
detail::NoArbSabrModel::beta_min) *
(std::atan(x[1]) + M_PI / 2.0) / M_PI;
// we compute alpha from sigmaI using beta
// if alpha is fixed we have to check if beta is admissable
// and adjust if need be
if (paramIsFixed[0]) {
y[0] = params[0];
Real sigmaI = y[0] * std::pow(forward, y[1] - 1.0);
if (sigmaI < detail::NoArbSabrModel::sigmaI_min) {
y[1] = (1.0 +
std::log(detail::NoArbSabrModel::sigmaI_min *
(1.0 + eps()) / y[0]) /
std::log(forward));
}
if (sigmaI > detail::NoArbSabrModel::sigmaI_max) {
y[1] = (1.0 +
std::log(detail::NoArbSabrModel::sigmaI_max *
(1.0 - eps()) / y[0]) /
std::log(forward));
}
} else {
Real sigmaI = detail::NoArbSabrModel::sigmaI_min +
(detail::NoArbSabrModel::sigmaI_max -
detail::NoArbSabrModel::sigmaI_min) *
(std::atan(x[0]) + M_PI / 2.0) / M_PI;
y[0] = sigmaI / std::pow(forward, y[1] - 1.0);
}
if (paramIsFixed[2])
y[2] = params[2];
else
y[2] = detail::NoArbSabrModel::nu_min +
(detail::NoArbSabrModel::nu_max -
detail::NoArbSabrModel::nu_min) *
(std::atan(x[2]) + M_PI / 2.0) / M_PI;
if (paramIsFixed[3])
y[3] = params[3];
else
y[3] = detail::NoArbSabrModel::rho_min +
(detail::NoArbSabrModel::rho_max -
detail::NoArbSabrModel::rho_min) *
(std::atan(x[3]) + M_PI / 2.0) / M_PI;
return y;
}
Real weight(const Real strike, const Real forward, const Real stdDev,
const std::vector<Real> &addParams) {
return blackFormulaStdDevDerivative(strike, forward, stdDev, 1.0);
}
typedef NoArbSabrWrapper type;
ext::shared_ptr<type> instance(const Time t, const Real &forward,
const std::vector<Real> ¶ms,
const std::vector<Real> &) {
return ext::make_shared<type>(t, forward, params);
}
};
}
//! no arbitrage sabr smile interpolation between discrete volatility points.
class NoArbSabrInterpolation : public Interpolation {
public:
template <class I1, class I2>
NoArbSabrInterpolation(
const I1 &xBegin, // x = strikes
const I1 &xEnd,
const I2 &yBegin, // y = volatilities
Time t, // option expiry
const Real &forward, Real alpha, Real beta, Real nu, Real rho,
bool alphaIsFixed, bool betaIsFixed, bool nuIsFixed, bool rhoIsFixed,
bool vegaWeighted = true,
const ext::shared_ptr<EndCriteria> &endCriteria =
ext::shared_ptr<EndCriteria>(),
const ext::shared_ptr<OptimizationMethod> &optMethod =
ext::shared_ptr<OptimizationMethod>(),
const Real errorAccept = 0.0020, const bool useMaxError = false,
const Size maxGuesses = 50, const Real shift = 0.0) {
QL_REQUIRE(shift==0.0,"NoArbSabrInterpolation for non zero shift not implemented");
impl_ = ext::shared_ptr<Interpolation::Impl>(
new detail::XABRInterpolationImpl<I1, I2, detail::NoArbSabrSpecs>(
xBegin, xEnd, yBegin, t, forward,
{alpha, beta, nu, rho},
{alphaIsFixed, betaIsFixed, nuIsFixed, rhoIsFixed},
vegaWeighted, endCriteria, optMethod, errorAccept, useMaxError,
maxGuesses));
}
Real expiry() const { return coeffs().t_; }
Real forward() const { return coeffs().forward_; }
Real alpha() const { return coeffs().params_[0]; }
Real beta() const { return coeffs().params_[1]; }
Real nu() const { return coeffs().params_[2]; }
Real rho() const { return coeffs().params_[3]; }
Real rmsError() const { return coeffs().error_; }
Real maxError() const { return coeffs().maxError_; }
const std::vector<Real> &interpolationWeights() const {
return coeffs().weights_;
}
EndCriteria::Type endCriteria() { return coeffs().XABREndCriteria_; }
private:
const detail::XABRCoeffHolder<detail::NoArbSabrSpecs>& coeffs() const {
return *dynamic_cast<detail::XABRCoeffHolder<detail::NoArbSabrSpecs>*>(impl_.get());
}
};
//! no arbtrage sabr interpolation factory and traits
class NoArbSabr {
public:
NoArbSabr(Time t,
Real forward,
Real alpha,
Real beta,
Real nu,
Real rho,
bool alphaIsFixed,
bool betaIsFixed,
bool nuIsFixed,
bool rhoIsFixed,
bool vegaWeighted = false,
ext::shared_ptr<EndCriteria> endCriteria = ext::shared_ptr<EndCriteria>(),
ext::shared_ptr<OptimizationMethod> optMethod = ext::shared_ptr<OptimizationMethod>(),
const Real errorAccept = 0.0020,
const bool useMaxError = false,
const Size maxGuesses = 50)
: t_(t), forward_(forward), alpha_(alpha), beta_(beta), nu_(nu), rho_(rho),
alphaIsFixed_(alphaIsFixed), betaIsFixed_(betaIsFixed), nuIsFixed_(nuIsFixed),
rhoIsFixed_(rhoIsFixed), vegaWeighted_(vegaWeighted), endCriteria_(std::move(endCriteria)),
optMethod_(std::move(optMethod)), errorAccept_(errorAccept), useMaxError_(useMaxError),
maxGuesses_(maxGuesses) {}
template <class I1, class I2>
Interpolation interpolate(const I1 &xBegin, const I1 &xEnd,
const I2 &yBegin) const {
return NoArbSabrInterpolation(
xBegin, xEnd, yBegin, t_, forward_, alpha_, beta_, nu_, rho_,
alphaIsFixed_, betaIsFixed_, nuIsFixed_, rhoIsFixed_, vegaWeighted_,
endCriteria_, optMethod_, errorAccept_, useMaxError_, maxGuesses_);
}
static const bool global = true;
private:
Time t_;
Real forward_;
Real alpha_, beta_, nu_, rho_;
bool alphaIsFixed_, betaIsFixed_, nuIsFixed_, rhoIsFixed_;
bool vegaWeighted_;
const ext::shared_ptr<EndCriteria> endCriteria_;
const ext::shared_ptr<OptimizationMethod> optMethod_;
const Real errorAccept_;
const bool useMaxError_;
const Size maxGuesses_;
};
}
#endif
| 43.861592 | 100 | 0.545598 | elay00 |
a16a77af3ebe7b7ab1f826c9abd98bdc77afaf98 | 2,736 | cpp | C++ | rstbx/simage/ext.cpp | rimmartin/cctbx_project | 644090f9432d9afc22cfb542fc3ab78ca8e15e5d | [
"BSD-3-Clause-LBNL"
] | 155 | 2016-11-23T12:52:16.000Z | 2022-03-31T15:35:44.000Z | rstbx/simage/ext.cpp | rimmartin/cctbx_project | 644090f9432d9afc22cfb542fc3ab78ca8e15e5d | [
"BSD-3-Clause-LBNL"
] | 590 | 2016-12-10T11:31:18.000Z | 2022-03-30T23:10:09.000Z | rstbx/simage/ext.cpp | rimmartin/cctbx_project | 644090f9432d9afc22cfb542fc3ab78ca8e15e5d | [
"BSD-3-Clause-LBNL"
] | 115 | 2016-11-15T08:17:28.000Z | 2022-02-09T15:30:14.000Z | #include <boost/python.hpp>
#include <rstbx/simage/image_simple.hpp>
namespace rstbx { namespace simage { namespace ext {
struct image_simple_wrappers
{
typedef image_simple wt;
static void
wrap()
{
using namespace boost::python;
typedef return_value_policy<return_by_value> rbv;
typedef return_internal_reference<> rir;
class_<wt>("image_simple", no_init)
.def(init<bool, bool, bool, bool, bool, bool, bool>((
arg("apply_proximity_filter")=true,
arg("apply_detector_clipping")=true,
arg("apply_proximity_factor")=true,
arg("store_miller_index_i_seqs")=false,
arg("store_spots")=false,
arg("store_signals")=false,
arg("set_pixels")=false)))
.def("compute", &wt::compute, (
arg("unit_cell"),
arg("miller_indices"),
arg("spot_intensity_factors"),
arg("crystal_rotation_matrix"),
arg("ewald_radius"),
arg("ewald_proximity"),
arg("signal_max"),
arg("detector_distance"),
arg("detector_size"),
arg("detector_pixels"),
arg("point_spread"),
arg("gaussian_falloff_scale")), rir())
.add_property("miller_index_i_seqs",
make_getter(&wt::miller_index_i_seqs, rbv()))
.add_property("spots", make_getter(&wt::spots, rbv()))
.add_property("signals", make_getter(&wt::signals, rbv()))
.def_readonly("pixels", &wt::pixels)
;
}
};
std::string
combine_rgb_images(
boost::python::list const& rgb_images)
{
namespace bp = boost::python;
TBXX_ASSERT(bp::len(rgb_images) > 0);
std::size_t img_size = static_cast<std::size_t>(bp::len(rgb_images[0]));
std::string result(img_size, '\0');
std::size_t n_imgs = static_cast<std::size_t>(bp::len(rgb_images));
boost::scoped_array<const char*> img_ptrs(new const char*[n_imgs]);
for(std::size_t j=0;j!=n_imgs;j++) {
TBXX_ASSERT(bp::len(rgb_images[j]) == img_size);
img_ptrs[j] = bp::extract<const char*>(rgb_images[j])();
}
for(std::size_t i=0;i!=img_size;i++) {
unsigned sum = 0;
for(std::size_t j=0;j!=n_imgs;j++) {
sum += static_cast<unsigned>(img_ptrs[j][i]);
}
unsigned c = static_cast<unsigned>(
static_cast<double>(sum) / n_imgs + 0.5);
if (c > 255) c = 255;
result[i] = static_cast<char>(c);
}
return result;
}
void init_module()
{
using namespace boost::python;
image_simple_wrappers::wrap();
def("combine_rgb_images", combine_rgb_images);
}
}}} // namespace rstbx::simage::ext
BOOST_PYTHON_MODULE(rstbx_simage_ext)
{
rstbx::simage::ext::init_module();
}
| 31.448276 | 76 | 0.611842 | rimmartin |
a16ab633fcddacd1bd5fa8e422a2f09c8445aea1 | 4,967 | cpp | C++ | Src/lunaui/launcher/elements/static/textbox.cpp | ericblade/luna-sysmgr | 82d5d7ced4ba21d3802eb2c8ae063236b6562331 | [
"Apache-2.0"
] | 3 | 2018-11-16T14:51:17.000Z | 2019-11-21T10:55:24.000Z | Src/lunaui/launcher/elements/static/textbox.cpp | penk/luna-sysmgr | 60c7056a734cdb55a718507f3a739839c9d74edf | [
"Apache-2.0"
] | 1 | 2021-02-20T13:12:15.000Z | 2021-02-20T13:12:15.000Z | Src/lunaui/launcher/elements/static/textbox.cpp | ericblade/luna-sysmgr | 82d5d7ced4ba21d3802eb2c8ae063236b6562331 | [
"Apache-2.0"
] | null | null | null | /* @@@LICENSE
*
* Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P.
*
* 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.
*
* LICENSE@@@ */
#include "textbox.h"
#include "dimensionsglobal.h"
#include "debugglobal.h"
#include "pixmapobject.h"
#include "iconlayoutsettings.h"
#include <QPainter>
#include <QFont>
#include <QString>
#include <QDebug>
#include "Settings.h"
const char * TextBox::InnerTextPropertyName = "innertext";
QFont TextBox::s_textFont = QFont();
QFont TextBox::staticLabelFontForTextBox()
{
//TODO: specify a proper font
static bool fontInitalized = false;
if (!fontInitalized)
{
//TODO: TEMP: don't hiijack
s_textFont = QFont(QString::fromStdString(Settings::LunaSettings()->fontQuicklaunch));
}
return s_textFont;
}
TextBox::TextBox(PixmapObject * p_backgroundPmo,const QRectF& geom)
: ThingPaintable(geom)
, m_qp_background(p_backgroundPmo)
, m_qp_prerenderedInnerTextPixmap(0)
{
}
TextBox::TextBox(PixmapObject * p_backgroundPmo,const QRectF& geom,const QString& inner_text)
: ThingPaintable(geom)
, m_qp_background(p_backgroundPmo)
, m_qp_prerenderedInnerTextPixmap(0)
{
setInnerText(inner_text);
}
//virtual
TextBox::~TextBox()
{
}
//virtual
void TextBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget)
{
//DimensionsDebugGlobal::dbgPaintBoundingRect(painter,m_geom,4);
QPen savePen = painter->pen();
painter->setPen(IconLayoutSettings::settings()->reorderablelayout_emptyPageTextFontColor);
m_textLayoutObject.draw(painter,m_innerTextPosICS+m_innerTextGeom.topLeft());
painter->setPen(savePen);
}
//virtual
void TextBox::paintOffscreen(QPainter *painter)
{
}
//virtual
QString TextBox::innerText() const
{
return m_innerText;
}
//virtual
void TextBox::setInnerText(const QString& v)
{
m_innerText = v;
recalculateMaxTextGeomForCurrentGeom();
redoInnerTextLayout();
recalculateInnerTextPosition();
update();
}
//virtual
void TextBox::resetInnerText()
{
//TODO: LOCALIZE:
m_innerText = QString();
m_textLayoutObject.clearLayout();
update();
}
///protected:
//virtual
void TextBox::recalculateMaxTextGeomForCurrentGeom()
{
qint32 width = DimensionsGlobal::roundDown(m_geom.width());
qint32 height = DimensionsGlobal::roundDown(m_geom.height());
width = qMax(2,width - 2 - (width % 2));
height = qMax(2,height - 2 - (height % 2));
m_innerTextMaxGeom = DimensionsGlobal::realRectAroundRealPoint(QSize(width,height)).toRect();
}
//virtual
void TextBox::redoInnerTextLayout()
{
//TODO: somewhat wasteful. If there is no label, should just exit early and leave a layout that will be left unrendered by paint()
m_textLayoutObject.clearLayout();
m_textLayoutObject.setText(m_innerText);
QFont f = staticLabelFontForTextBox();
f.setBold(IconLayoutSettings::settings()->reorderablelayout_emptyPageTextFontEmbolden);
f.setPixelSize(qMax((quint32)4,IconLayoutSettings::settings()->reorderablelayout_emptyPageTextFontSizePx));
m_textLayoutObject.setFont(f);
QTextOption textOpts;
textOpts.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
textOpts.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
m_textLayoutObject.setTextOption(textOpts);
QFontMetrics fm(staticLabelFontForTextBox());
int leading = fm.leading();
int rise = fm.ascent();
qreal height = 0;
m_textLayoutObject.beginLayout();
while (height < m_innerTextMaxGeom.height()) {
QTextLine line = m_textLayoutObject.createLine();
if (!line.isValid())
break;
line.setLineWidth(m_innerTextMaxGeom.width());
if (m_textLayoutObject.lineCount() > 1)
{
// height += leading;
}
line.setPosition(QPointF(0, height));
height += line.height();
}
height = qMin((quint32)DimensionsGlobal::roundUp(height),(quint32)m_innerTextMaxGeom.height());
height = DimensionsGlobal::roundDown(height) - (DimensionsGlobal::roundDown(height) % 2); //force to an even #
m_textLayoutObject.endLayout();
//TODO: PIXEL-ALIGN
m_innerTextGeom = DimensionsGlobal::realRectAroundRealPoint(QSizeF(m_textLayoutObject.boundingRect().width(),height)).toAlignedRect();
}
//virtual
void TextBox::recalculateInnerTextPosition()
{
m_innerTextPosICS = QPointF(m_geom.center().x(),m_geom.top() - (qreal)m_innerTextGeom.top());
QPointF offset = m_innerTextPosICS + m_innerTextGeom.topLeft() - m_geom.topLeft();
offset += QPointF(DimensionsGlobal::centerRectInRectPixelAlign(m_innerTextMaxGeom,m_innerTextGeom));
m_innerTextPosPntCS = DimensionsGlobal::realPointAsPixelPosition(offset);
}
| 28.877907 | 135 | 0.765855 | ericblade |
a16d4485534a013929a9ee2e64f04644f1ce6de2 | 2,377 | cpp | C++ | src/shape.cpp | WeichenLiu/lajolla_public | daf1a095feb9b8a4a8c727a012f9d6d9a422ac69 | [
"MIT"
] | 31 | 2021-12-27T00:45:29.000Z | 2022-03-21T11:12:24.000Z | src/shape.cpp | WeichenLiu/lajolla_public | daf1a095feb9b8a4a8c727a012f9d6d9a422ac69 | [
"MIT"
] | 7 | 2022-01-04T03:08:28.000Z | 2022-03-02T23:26:20.000Z | src/shape.cpp | WeichenLiu/lajolla_public | daf1a095feb9b8a4a8c727a012f9d6d9a422ac69 | [
"MIT"
] | 14 | 2022-01-02T19:43:18.000Z | 2022-03-21T06:07:39.000Z | #include "shape.h"
#include "intersection.h"
#include "point_and_normal.h"
#include "ray.h"
#include <embree3/rtcore.h>
struct register_embree_op {
uint32_t operator()(const Sphere &sphere) const;
uint32_t operator()(const TriangleMesh &mesh) const;
const RTCDevice &device;
const RTCScene &scene;
};
struct sample_point_on_shape_op {
PointAndNormal operator()(const Sphere &sphere) const;
PointAndNormal operator()(const TriangleMesh &mesh) const;
const Vector3 &ref_point;
const Vector2 &uv; // for selecting a point on a 2D surface
const Real &w; // for selecting triangles
};
struct surface_area_op {
Real operator()(const Sphere &sphere) const;
Real operator()(const TriangleMesh &mesh) const;
};
struct pdf_point_on_shape_op {
Real operator()(const Sphere &sphere) const;
Real operator()(const TriangleMesh &mesh) const;
const PointAndNormal &point_on_shape;
const Vector3 &ref_point;
};
struct init_sampling_dist_op {
void operator()(Sphere &sphere) const;
void operator()(TriangleMesh &mesh) const;
};
struct compute_shading_info_op {
ShadingInfo operator()(const Sphere &sphere) const;
ShadingInfo operator()(const TriangleMesh &mesh) const;
const PathVertex &vertex;
};
#include "shapes/sphere.inl"
#include "shapes/triangle_mesh.inl"
uint32_t register_embree(const Shape &shape, const RTCDevice &device, const RTCScene &scene) {
return std::visit(register_embree_op{device, scene}, shape);
}
PointAndNormal sample_point_on_shape(const Shape &shape,
const Vector3 &ref_point,
const Vector2 &uv,
Real w) {
return std::visit(sample_point_on_shape_op{ref_point, uv, w}, shape);
}
Real pdf_point_on_shape(const Shape &shape,
const PointAndNormal &point_on_shape,
const Vector3 &ref_point) {
return std::visit(pdf_point_on_shape_op{point_on_shape, ref_point}, shape);
}
Real surface_area(const Shape &shape) {
return std::visit(surface_area_op{}, shape);
}
void init_sampling_dist(Shape &shape) {
return std::visit(init_sampling_dist_op{}, shape);
}
ShadingInfo compute_shading_info(const Shape &shape, const PathVertex &vertex) {
return std::visit(compute_shading_info_op{vertex}, shape);
}
| 29.7125 | 94 | 0.692469 | WeichenLiu |
a17518b87616b37d16e0dfdd69e12dfad95a016e | 4,497 | cpp | C++ | arangod/RestHandler/RestExplainHandler.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | 1 | 2020-10-27T12:19:33.000Z | 2020-10-27T12:19:33.000Z | arangod/RestHandler/RestExplainHandler.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | null | null | null | arangod/RestHandler/RestExplainHandler.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | 1 | 2020-10-01T08:49:12.000Z | 2020-10-01T08:49:12.000Z | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "RestExplainHandler.h"
#include "Aql/Query.h"
#include "Aql/QueryString.h"
#include "Logger/Logger.h"
#include "Transaction/StandaloneContext.h"
#include <velocypack/Builder.h>
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
RestExplainHandler::RestExplainHandler(application_features::ApplicationServer& server,
GeneralRequest* request, GeneralResponse* response)
: RestVocbaseBaseHandler(server, request, response) {}
RestStatus RestExplainHandler::execute() {
// extract the sub-request type
auto const type = _request->requestType();
// execute one of the CRUD methods
switch (type) {
case rest::RequestType::POST:
explainQuery();
break;
default: { generateNotImplemented("Unsupported method"); }
}
// this handler is done
return RestStatus::DONE;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief was docuBlock REST_DOCUMENT_CREATE
////////////////////////////////////////////////////////////////////////////////
void RestExplainHandler::explainQuery() {
std::vector<std::string> const& suffixes = _request->suffixes();
if (suffixes.size() != 0) {
generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_HTTP_NOT_FOUND);
return;
}
bool parseSuccess = false;
VPackSlice body = this->parseVPackBody(parseSuccess);
if (!parseSuccess) {
return;
}
auto badParamError = [&](std::string const& msg) -> void {
generateError(rest::ResponseCode::BAD, TRI_ERROR_BAD_PARAMETER, msg);
};
if (!body.isObject()) {
badParamError(
"expected usage: AQL_EXPLAIN(<queryString>, <bindVars>, "
"<options>)");
return;
}
VPackSlice const querySlice = body.get("query");
if (!querySlice.isString()) {
badParamError("expecting string for <queryString>");
return;
}
std::string const queryString(querySlice.copyString());
VPackSlice const bindSlice = body.get("bindVars");
if (!bindSlice.isNone() && !bindSlice.isObject()) {
badParamError("expecting object for <bindVars>");
return;
}
VPackSlice const optionsSlice = body.get("options");
if (!optionsSlice.isNone() && !optionsSlice.isObject()) {
badParamError("expecting object for <options>");
return;
}
auto bindBuilder = std::make_shared<VPackBuilder>(bindSlice);
auto optionsBuilder = std::make_shared<VPackBuilder>(optionsSlice);
arangodb::aql::Query query(transaction::StandaloneContext::Create(_vocbase), aql::QueryString(queryString),
bindBuilder, optionsBuilder);
auto queryResult = query.explain();
if (queryResult.result.fail()) {
generateError(queryResult.result);
return;
}
VPackBuilder result;
result.openObject();
if (query.queryOptions().allPlans) {
result.add("plans", queryResult.data->slice());
} else {
result.add("plan", queryResult.data->slice());
result.add("cacheable", VPackValue(queryResult.cached));
}
VPackSlice extras = queryResult.extra->slice();
if (extras.hasKey("warnings")) {
result.add("warnings", extras.get("warnings"));
} else {
result.add("warnings", VPackSlice::emptyArraySlice());
}
if (extras.hasKey("stats")) {
result.add("stats", extras.get("stats"));
}
result.add(StaticStrings::Error, VPackValue(false));
result.add(StaticStrings::Code, VPackValue(static_cast<int>(ResponseCode::OK)));
result.close();
generateResult(rest::ResponseCode::OK, result.slice());
}
| 31.447552 | 109 | 0.644207 | Korov |
a17532fa4518dff2cdc826d26861a6b3c800aeed | 768 | cpp | C++ | COOK82B.cpp | ss6364/CodeForces-contests | 40a2ea7fd75d754d9c42c596c5bbfccf8b3ebdc1 | [
"Unlicense"
] | 2 | 2019-05-06T04:29:05.000Z | 2019-05-06T09:19:03.000Z | COOK82B.cpp | ss6364/CodeForces-contests | 40a2ea7fd75d754d9c42c596c5bbfccf8b3ebdc1 | [
"Unlicense"
] | null | null | null | COOK82B.cpp | ss6364/CodeForces-contests | 40a2ea7fd75d754d9c42c596c5bbfccf8b3ebdc1 | [
"Unlicense"
] | null | null | null | // https://www.codechef.com/problems/COOK82B
#include<bits/stdc++.h>
using namespace std ;
#define Fors(n) for(int i=1;i<=n;i++)
#define For(n) for(i=0;i<n;i++)
#define ll long long
#define vint(s) vector<int> s
#define pb(x) push_back(x)
#define mpair(x,y) make_pair(x,y)
#define MOD 1000000007
#define mod 100000
ll x=0,y=0,s=0,n=0,i=0;
vint(v);
bool prime[mod] ;
void seive(){
int t ;
For(mod){
prime[i] = 1 ;
}
prime[1]=0 ;
prime[0]=0 ;
for(i=2;i<100000;i++){
if(prime[i]=1){
v.pb(i);
for(j=i*i;j<100000;j+=i){
prime[i] = 0 ;
}
}
}
}
int main(){
cin>>n ;
int a[n];
For(n){
cin>>a[i];
}
For(n){
}
return 0;
}
| 15.058824 | 49 | 0.486979 | ss6364 |
a1777b8e35519526623c3ff122e3095d0e211873 | 3,519 | cpp | C++ | ubiprovider/plocation/ubip_plocation.cpp | alexgarzao/UOP | 12460841ff2b9991d2f7f461635b1f551413823f | [
"MIT"
] | null | null | null | ubiprovider/plocation/ubip_plocation.cpp | alexgarzao/UOP | 12460841ff2b9991d2f7f461635b1f551413823f | [
"MIT"
] | null | null | null | ubiprovider/plocation/ubip_plocation.cpp | alexgarzao/UOP | 12460841ff2b9991d2f7f461635b1f551413823f | [
"MIT"
] | null | null | null | #include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <boost/thread.hpp>
#include<boost/tokenizer.hpp>
#include "Provider.hpp"
#include "Literal.hpp"
#include "Tools.hpp"
struct sphysical_location {
int latitude, longitude, altitude;
sphysical_location() {
latitude = longitude = altitude = -1;
}
sphysical_location(int x, int y, int z) {
latitude = x;
longitude = y;
altitude = z;
}
};
static boost::thread* _thread;
static std::map<std::string, CLiteral>* _contextsInfo;
static std::map<std::string, sphysical_location> _users_locations;
static int _current_time;
extern "C" {
static sphysical_location _get_symbolic_location();
static void _run();
static bool ubip_read_conf_file(std::string filename)
{
std::ifstream in(filename.c_str());
if (in.is_open() == false) {
std::cout << "Error reading " << filename << std::endl;
return false;
}
std::string line;
while(getline(in, line)) {
std::string::size_type i = line.find_first_not_of ( " \t\n\v" );
if (i != std::string::npos && line[i] == '#')
continue;
// Process non-comment line
boost::tokenizer<> token_list(line);
/* for(boost::tokenizer<>::iterator beg=token_list.begin(); beg!=token_list.end();++beg) {
std::cout << *beg << "\n";
}*/
boost::tokenizer<>::iterator token=token_list.begin();
std::string step = *token++;
std::string identity = *token++;
std::string latitude = *token++;
std::string longitude = *token++;
std::string altitude = *token++;
_users_locations[step + ":" + identity] = sphysical_location(atoi(latitude.c_str()),atoi(longitude.c_str()),atoi(altitude.c_str()));
}
return true;
}
int ubip_init(std::map<std::string, CLiteral>* contextsInfo)
{
_contextsInfo = contextsInfo;
ubip_read_conf_file("plocation.data");
// _users_locations["1:alex" ] = sphysical_location(1,2,0);
// _users_locations["2:alex" ] = sphysical_location(4,5,0);
// _users_locations["3:alex" ] = sphysical_location(10,18,0);
// _users_locations["4:alex" ] = sphysical_location(14,8,0);
_current_time = 0;
return UBIP_OK;
}
int ubip_finish()
{
return UBIP_OK;
}
int ubip_run()
{
_thread = new boost::thread(boost::bind(&_run));
return UBIP_OK;
}
static void _run()
{
// A simulacao so comeca apos termos a identificacao do usuario
while(true) {
sleep(5);
if ((*_contextsInfo)["identity.name"].getText() != "") {
// std::cout << "identity.name=" << (*_contextsInfo)["identity.name"].getText() << std::endl;
break;
}
}
while(true) {
sphysical_location location = _get_symbolic_location();
if (location.latitude != -1) {
(*_contextsInfo)["location.latitude" ] = CLiteral(location.latitude);
(*_contextsInfo)["location.longitude"] = CLiteral(location.longitude);
(*_contextsInfo)["location.altitude" ] = CLiteral(location.altitude);
// (*_contextsInfo)["location.latitude" ] = CLiteral(itoa(location.latitude));
// (*_contextsInfo)["location.longitude"] = CLiteral(itoa(location.longitude));
// (*_contextsInfo)["location.altitude" ] = CLiteral(itoa(location.altitude));
}
sleep(15);
}
}
static sphysical_location _get_symbolic_location()
{
_current_time++;
std::string key_map = std::string(itoa(_current_time)) + std::string(":") + (*_contextsInfo)["identity.name"].getText();
if (_users_locations.find(key_map) != _users_locations.end()) {
return _users_locations[key_map];
} else {
return sphysical_location(-1,-1,-1);
}
}
}
| 24.4375 | 134 | 0.669793 | alexgarzao |
a1784c0f4a6fc9fabb8ecb2cf9dd474906cb3dfd | 1,346 | hpp | C++ | apps/caffe/include/caffe/caffe_engine.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | null | null | null | apps/caffe/include/caffe/caffe_engine.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | null | null | null | apps/caffe/include/caffe/caffe_engine.hpp | daiwei89/wdai_petuum_public | 4068859897061201d0a63630a3da6011b0d0f75f | [
"BSD-3-Clause"
] | null | null | null | #ifndef CAFFE_ENGINE_HPP_
#define CAFFE_ENGINE_HPP_
#include <string>
#include <vector>
#include <map>
#include <atomic>
#include "caffe/net.hpp"
#include "leveldb/db.h"
namespace caffe {
/**
* @brief
*/
template <typename Dtype>
class CaffeEngine {
public:
explicit CaffeEngine(const SolverParameter& param);
explicit CaffeEngine(const string& param_file);
// used in network testing / feature extacting
explicit CaffeEngine(const NetParameter& net_param);
virtual ~CaffeEngine() {}
void Init(const SolverParameter& param);
void InitPS();
void InitPSForTrainNet(const int num_additional_tables);
void InitPSForTestNets(const int num_test_net_instances);
// Can be called concurrently.
void Start(); // model training
void StartExtractingFeature(); // feature extraction
protected:
void CreatePSTableForNetOutputs(shared_ptr<Net<Dtype> > net,
string name, bool display, int num_rows);
const int GetNumTestNets();
SolverParameter param_;
shared_ptr<Net<Dtype> > net_;
NetParameter net_param_;
int num_tables_;
// layer_name => vector of blobs' global indexes
map<string, vector<int> > layer_blobs_global_idx_;
//
std::atomic<int> thread_counter_;
int loss_table_staleness_;
DISABLE_COPY_AND_ASSIGN(CaffeEngine);
};
} // namespace caffe
#endif // CAFFE_ENGINE_HPP_
| 23.206897 | 63 | 0.741456 | daiwei89 |
a17caf5021af396e9934c7b5fab5ed0a2d3c86a7 | 8,826 | cpp | C++ | lib/webserver/status.cpp | mukhin/libwebserver | 04a72616c2dc6360136123acd4d9295417936102 | [
"MIT"
] | 1 | 2015-01-04T04:14:43.000Z | 2015-01-04T04:14:43.000Z | lib/webserver/status.cpp | mukhin/libwebserver | 04a72616c2dc6360136123acd4d9295417936102 | [
"MIT"
] | null | null | null | lib/webserver/status.cpp | mukhin/libwebserver | 04a72616c2dc6360136123acd4d9295417936102 | [
"MIT"
] | null | null | null | // Embedded web-server library
//
// Copyright 2010 LibWebserver Authors. All rights reserved.
#include "status.h"
#include <base/basicmacros.h>
#include <base/string_helpers.h>
#include <cmath>
#include <iomanip>
#include <numeric>
#include <sstream>
namespace webserver {
WebserverStatus::WebserverStatus() :
http_served_(webserver::HTTP_CODES_COUNT, 0),
sustained_rate_position_(0),
attained_rate_position_(0),
latency_position_(0),
sustained_rate_1_(0),
sustained_rate_5_(0),
sustained_rate_15_(0),
max_attained_rate_(0),
attained_rate_1_(0),
attained_rate_5_(0),
attained_rate_15_(0),
latency_1_(0),
latency_5_(0),
latency_15_(0),
total_served_requests_(0)
{
traffic_in_ = 0;
traffic_out_ = 0;
outgoing_rate_ = 0;
fast_latency_sum_ = 0;
fast_latency_count_ = 0;
max_latency_ = 0;
}
WebserverStatus::~WebserverStatus() {
}
void WebserverStatus::IncomingRequest(const size_t length) {
traffic_in_ += length;
}
void WebserverStatus::ServedRequest(const OutgoingHttpMessage::sptr& message) {
http_served_[message->GetResponseCode()]++;
traffic_out_ += message->GetLength();
clocks::HiResTimer* t = message->GetTimer();
if (t) {
t->Mark();
double nanoDifference = static_cast<double>(t->GetDifferenceNanoseconds());
unsigned int latency = static_cast<unsigned int>(t->GetDifferenceSeconds()) * 1000000 +
static_cast<unsigned int>(::round(nanoDifference / 1000));
fast_latency_sum_.fetch_and_add(latency);
++fast_latency_count_;
++outgoing_rate_;
if (latency > max_latency_ && max_attained_rate_ != 0) {
max_latency_ = latency;
}
}
}
uint64_t WebserverStatus::TotalServedRequests() const {
return total_served_requests_;
}
const WebserverStatus::HttpResponseTable& WebserverStatus::GetHttpServed() const {
return http_served_;
}
uint64_t WebserverStatus::GetTrafficIn() const {
return traffic_in_;
}
uint64_t WebserverStatus::GetTrafficOut() const {
return traffic_out_;
}
unsigned int WebserverStatus::SustainedRate1() const {
return sustained_rate_1_;
}
unsigned int WebserverStatus::SustainedRate5() const {
return sustained_rate_5_;
}
unsigned int WebserverStatus::SustainedRate15() const {
return sustained_rate_15_;
}
unsigned int WebserverStatus::AttainedRate1() const {
return attained_rate_1_;
}
unsigned int WebserverStatus::AttainedRate5() const {
return attained_rate_5_;
}
unsigned int WebserverStatus::AttainedRate15() const {
return attained_rate_15_;
}
unsigned int WebserverStatus::MaxAttainedRate() const {
return max_attained_rate_;
}
unsigned int WebserverStatus::MaxLatency() const {
return max_latency_;
}
unsigned int WebserverStatus::Latency1() const {
return latency_1_ > 0 ? latency_1_ : 0;
}
unsigned int WebserverStatus::Latency5() const {
return latency_5_ > 0 ? latency_5_ : 0;
}
unsigned int WebserverStatus::Latency15() const {
return latency_15_ > 0 ? latency_15_ : 0;
}
void WebserverStatus::Run() {
while (!ShouldStop()) {
const unsigned int rate = outgoing_rate_;
outgoing_rate_ -= rate;
max_attained_rate_ = max_attained_rate_ < rate ? rate : max_attained_rate_;
CalculateSustainedRate_(rate);
CalculateAttainedRate_(rate);
CalculateLatency_();
CalculateRequests_();
Wait(1000);
}
}
void WebserverStatus::CalculateSustainedRate_(const unsigned int rate) {
size_t size_1 = 60;
size_t size_5 = 300;
size_t size_15 = 900;
if (sustained_rate_1_history_.size() < 60) {
sustained_rate_1_history_.push_back(rate);
size_1 = sustained_rate_1_history_.size();
}
else {
sustained_rate_1_history_[sustained_rate_position_ % 60] = rate;
}
if (sustained_rate_5_history_.size() < 300) {
sustained_rate_5_history_.push_back(rate);
size_5 = sustained_rate_5_history_.size();
}
else {
sustained_rate_5_history_[sustained_rate_position_ % 300] = rate;
}
if (sustained_rate_15_history_.size() < 900) {
sustained_rate_15_history_.push_back(rate);
size_15 = sustained_rate_15_history_.size();
}
else {
sustained_rate_15_history_[sustained_rate_position_] = rate;
}
if (++sustained_rate_position_ >= 900) {
sustained_rate_position_ = 0;
}
const float acc_rate_1 = static_cast<float>(std::accumulate(sustained_rate_1_history_.begin(), sustained_rate_1_history_.end(), 0));
const float acc_rate_5 = static_cast<float>(std::accumulate(sustained_rate_5_history_.begin(), sustained_rate_5_history_.end(), 0));
const float acc_rate_15 = static_cast<float>(std::accumulate(sustained_rate_15_history_.begin(), sustained_rate_15_history_.end(), 0));
sustained_rate_1_ = static_cast<unsigned int>(acc_rate_1 / static_cast<float>(size_1));
sustained_rate_5_ = static_cast<unsigned int>(acc_rate_5 / static_cast<float>(size_5));
sustained_rate_15_ = static_cast<unsigned int>(acc_rate_15 / static_cast<float>(size_15));
}
void WebserverStatus::CalculateAttainedRate_(const unsigned int rate) {
if (rate == 0) {
return;
}
size_t size_1 = 60;
size_t size_5 = 300;
size_t size_15 = 900;
if (attained_rate_1_history_.size() < 60) {
attained_rate_1_history_.push_back(rate);
size_1 = attained_rate_1_history_.size();
}
else {
attained_rate_1_history_[attained_rate_position_ % 60] = rate;
}
if (attained_rate_5_history_.size() < 300) {
attained_rate_5_history_.push_back(rate);
size_5 = attained_rate_5_history_.size();
}
else {
attained_rate_5_history_[attained_rate_position_ % 300] = rate;
}
if (attained_rate_15_history_.size() < 900) {
attained_rate_15_history_.push_back(rate);
size_15 = attained_rate_15_history_.size();
}
else {
attained_rate_15_history_[attained_rate_position_] = rate;
}
if (++attained_rate_position_ >= 900) {
attained_rate_position_ = 0;
}
const float acc_rate_1 = static_cast<float>(std::accumulate(attained_rate_1_history_.begin(), attained_rate_1_history_.end(), 0));
const float acc_rate_5 = static_cast<float>(std::accumulate(attained_rate_5_history_.begin(), attained_rate_5_history_.end(), 0));
const float acc_rate_15 = static_cast<float>(std::accumulate(attained_rate_15_history_.begin(), attained_rate_15_history_.end(), 0));
attained_rate_1_ = static_cast<unsigned int>(acc_rate_1 / static_cast<float>(size_1));
attained_rate_5_ = static_cast<unsigned int>(acc_rate_5 / static_cast<float>(size_15));
attained_rate_15_ = static_cast<unsigned int>(acc_rate_15 / static_cast<float>(size_15));
}
void WebserverStatus::CalculateLatency_() {
if (fast_latency_sum_ != 0 && fast_latency_count_ != 0) {
float average = static_cast<float>(fast_latency_sum_) / static_cast<float>(fast_latency_count_);
fast_latency_sum_ = 0;
fast_latency_count_ = 0;
if (average > 0) {
size_t size_1 = 60;
size_t size_5 = 300;
size_t size_15 = 900;
if (latency_1_history_.size() < 60) {
latency_1_history_.push_back(average);
size_1 = latency_1_history_.size();
}
else {
latency_1_history_[latency_position_ % 60] = average;
}
if (latency_5_history_.size() < 300) {
latency_5_history_.push_back(average);
size_5 = latency_5_history_.size();
}
else {
latency_5_history_[latency_position_ % 300] = average;
}
if (latency_15_history_.size() < 900) {
latency_15_history_.push_back(average);
size_15 = latency_15_history_.size();
}
else {
latency_15_history_[latency_position_] = average;
}
if (++latency_position_ >= 900) {
latency_position_ = 0;
}
latency_1_ = static_cast<unsigned int>(std::accumulate(latency_1_history_.begin(), latency_1_history_.end(), 0.0) / static_cast<float>(size_1));
latency_5_ = static_cast<unsigned int>(std::accumulate(latency_5_history_.begin(), latency_5_history_.end(), 0.0) / static_cast<float>(size_5));
latency_15_ = static_cast<unsigned int>(std::accumulate(latency_15_history_.begin(), latency_15_history_.end(), 0.0) / static_cast<float>(size_15));
}
}
}
void WebserverStatus::CalculateRequests_() {
total_served_requests_ = 0;
for (HttpResponseTable::const_iterator i = http_served_.begin(); i != http_served_.end(); ++i) {
total_served_requests_ += *i;
}
}
} // namespace webserver
| 28.749186 | 156 | 0.687288 | mukhin |
a17cd01dfca1d02b1eaaf1321f8b891c8f6d4ed6 | 4,993 | tpp | C++ | GA/src/GA/Engine.tpp | Kaylier/Genetic-Algorithm | 7d14ec1558699e8dffec1f8d247cf6d25b4e1982 | [
"MIT"
] | null | null | null | GA/src/GA/Engine.tpp | Kaylier/Genetic-Algorithm | 7d14ec1558699e8dffec1f8d247cf6d25b4e1982 | [
"MIT"
] | null | null | null | GA/src/GA/Engine.tpp | Kaylier/Genetic-Algorithm | 7d14ec1558699e8dffec1f8d247cf6d25b4e1982 | [
"MIT"
] | null | null | null | #include <cassert>
#include <cmath> // sqrt
#include <GA/Engine.h>
template<class Individual>
GA::Engine<Individual>::Engine(Objective<Individual> &objective,
Crossover<Individual> &crossover,
Mutation<Individual> &mutation,
Selection<Individual> &selection) :
objective(objective),
crossover(crossover),
mutation(mutation),
selection(selection),
populationSize(1),
population() {
std::random_device rndDevice;
this->rnd.seed(rndDevice());
}
template<class Individual>
GA::Objective<Individual> &GA::Engine<Individual>::getObjective() const {
return this->objective;
}
template<class Individual>
GA::Crossover<Individual> &GA::Engine<Individual>::getCrossover() const {
return this->crossover;
}
template<class Individual>
GA::Mutation<Individual> &GA::Engine<Individual>::getMutation() const {
return this->mutation;
}
template<class Individual>
GA::Selection<Individual> &GA::Engine<Individual>::getSelection() const {
return this->selection;
}
template<class Individual>
size_t GA::Engine<Individual>::getPopulationSize() const {
return this->populationSize;
}
template<class Individual>
void GA::Engine<Individual>::setObjective(GA::Objective<Individual> &objective) {
this->objective = objective;
}
template<class Individual>
void GA::Engine<Individual>::setCrossover(GA::Crossover<Individual> &crossover) {
this->crossover = crossover;
}
template<class Individual>
void GA::Engine<Individual>::setMutation(GA::Mutation<Individual> &mutation) {
this->mutation = mutation;
}
template<class Individual>
void GA::Engine<Individual>::setSelection(GA::Selection<Individual> &selection) {
this->selection = selection;
}
template<class Individual>
void GA::Engine<Individual>::setPopulationSize(size_t populationSize) {
assert(populationSize != 0);
this->populationSize = populationSize;
}
template<class Individual>
void GA::Engine<Individual>::initialize() {
population.clear();
Individual individual;
for (size_t i = populationSize; i != 0; --i) {
individual.randomize();
population.emplace(objective(individual), individual);
}
}
template<class Individual>
void GA::Engine<Individual>::initialize(size_t populationSize) {
assert(populationSize != 0);
this->setPopulationSize(populationSize);
return this->initialize();
}
template<class Individual>
double GA::Engine<Individual>::step() {
return this->step(1);
}
template<class Individual>
double GA::Engine<Individual>::step(unsigned int numberStep) {
typename Population::iterator it1, it2;
std::uniform_int_distribution<size_t> unif_distrib(0,population.size()*(population.size()+1)/2);
Individual individual;
Population new_population;
for (unsigned int i = numberStep; i != 0; --i) {
new_population = selection(population);
while (new_population.size() < populationSize) {
it1 = population.begin();
it2 = population.begin();
/*
* We choose random parents after the following probability distribution :
* P(i) = (n-i) / (n(n+1)/2)
*/
std::advance(it1, population.size() - std::floor(std::sqrt(1+8*unif_distrib(rnd))-1.5));
std::advance(it2, population.size() - std::floor(std::sqrt(1+8*unif_distrib(rnd))-1.5));
individual = mutation(crossover(it1->second, it2->second));
new_population.emplace(objective(individual), individual);
}
std::swap(new_population, population);
}
return population.cbegin()->first;
}
template<class Individual>
double GA::Engine<Individual>::getScore() const {
return population.cbegin()->first;
}
template<class Individual>
const Individual GA::Engine<Individual>::getBest() const {
return population.cbegin()->second;
}
template<class Individual>
double GA::Engine<Individual>::getMean() const {
return this->getMean(population.size());
}
template<class Individual>
double GA::Engine<Individual>::getMean(size_t count) const {
assert(count <= population.size());
double total = 0.;
auto it = population.cbegin();
for (int i = 0; i < count; ++i) {
total += it->first;
it++;
}
return total / count;
}
template<class Individual>
double GA::Engine<Individual>::getStandardDeviation() const {
return getStandardDeviation(population.size());
}
template<class Individual>
double GA::Engine<Individual>::getStandardDeviation(size_t count) const {
assert(count <= population.size());
double mean = 0.;
double meanOfSquares = 0.;
auto it = population.cbegin();
for (size_t i = 0; i < count; ++i) {
meanOfSquares += it->first * it->first;
mean += it->first;
it++;
}
meanOfSquares /= count;
mean /= count;
return std::sqrt(meanOfSquares - mean*mean);
}
| 29.02907 | 100 | 0.667134 | Kaylier |
a1819445da06e968d3cc2ed37345369c644bd4ae | 24 | cpp | C++ | tools/databuffer.cpp | mihajlo2003petkovic/MeteorDemod | d7cbd842d1b31b0985ebb0581689afc7435d0684 | [
"MIT"
] | 15 | 2020-12-17T17:14:37.000Z | 2022-03-24T11:09:18.000Z | tools/databuffer.cpp | mihajlo2003petkovic/MeteorDemod | d7cbd842d1b31b0985ebb0581689afc7435d0684 | [
"MIT"
] | 11 | 2021-01-17T00:40:12.000Z | 2022-02-02T17:21:07.000Z | tools/databuffer.cpp | mihajlo2003petkovic/MeteorDemod | d7cbd842d1b31b0985ebb0581689afc7435d0684 | [
"MIT"
] | 5 | 2021-02-08T12:37:57.000Z | 2022-01-23T09:39:59.000Z | #include "databuffer.h"
| 12 | 23 | 0.75 | mihajlo2003petkovic |
a181e82d68699a1c3766372fb698e6746f748744 | 12,600 | cc | C++ | 3rdParty/s2geometry/0e7b146/src/s2/s2cap.cc | LLcat1217/arangodb | 67c51272915699e0a489e1f8d9da786f4226221a | [
"Apache-2.0"
] | 5 | 2015-11-25T14:24:13.000Z | 2017-07-17T21:53:58.000Z | src/s2/s2cap.cc | google/s2-geometry-library | ae470b730441ebe7b0bf630527038acc219b2eb9 | [
"Apache-2.0"
] | null | null | null | src/s2/s2cap.cc | google/s2-geometry-library | ae470b730441ebe7b0bf630527038acc219b2eb9 | [
"Apache-2.0"
] | null | null | null | // Copyright 2005 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.
//
// Author: ericv@google.com (Eric Veach)
#include "s2/s2cap.h"
#include <cfloat>
#include <cmath>
#include <iosfwd>
#include <vector>
#include "s2/base/integral_types.h"
#include "s2/base/logging.h"
#include "absl/flags/flag.h"
#include "s2/r1interval.h"
#include "s2/s1interval.h"
#include "s2/s2cell.h"
#include "s2/s2debug.h"
#include "s2/s2edge_distances.h"
#include "s2/s2latlng.h"
#include "s2/s2latlng_rect.h"
#include "s2/s2metrics.h"
#include "s2/s2pointutil.h"
#include "s2/util/math/vector.h"
using std::fabs;
using std::max;
using std::vector;
double S2Cap::GetArea() const {
return 2 * M_PI * max(0.0, height());
}
S2Point S2Cap::GetCentroid() const {
// From symmetry, the centroid of the cap must be somewhere on the line
// from the origin to the center of the cap on the surface of the sphere.
// When a sphere is divided into slices of constant thickness by a set of
// parallel planes, all slices have the same surface area. This implies
// that the radial component of the centroid is simply the midpoint of the
// range of radial distances spanned by the cap. That is easily computed
// from the cap height.
if (is_empty()) return S2Point();
double r = 1.0 - 0.5 * height();
return r * GetArea() * center_;
}
S2Cap S2Cap::Complement() const {
// The complement of a full cap is an empty cap, not a singleton.
// Also make sure that the complement of an empty cap is full.
if (is_full()) return Empty();
if (is_empty()) return Full();
return S2Cap(-center_, S1ChordAngle::FromLength2(4 - radius_.length2()));
}
bool S2Cap::Contains(const S2Cap& other) const {
if (is_full() || other.is_empty()) return true;
return radius_ >= S1ChordAngle(center_, other.center_) + other.radius_;
}
bool S2Cap::Intersects(const S2Cap& other) const {
if (is_empty() || other.is_empty()) return false;
return radius_ + other.radius_ >= S1ChordAngle(center_, other.center_);
}
bool S2Cap::InteriorIntersects(const S2Cap& other) const {
// Make sure this cap has an interior and the other cap is non-empty.
if (radius_.length2() <= 0 || other.is_empty()) return false;
return radius_ + other.radius_ > S1ChordAngle(center_, other.center_);
}
void S2Cap::AddPoint(const S2Point& p) {
// Compute the squared chord length, then convert it into a height.
S2_DCHECK(S2::IsUnitLength(p));
if (is_empty()) {
center_ = p;
radius_ = S1ChordAngle::Zero();
} else {
// After calling cap.AddPoint(p), cap.Contains(p) must be true. However
// we don't need to do anything special to achieve this because Contains()
// does exactly the same distance calculation that we do here.
radius_ = max(radius_, S1ChordAngle(center_, p));
}
}
void S2Cap::AddCap(const S2Cap& other) {
if (is_empty()) {
*this = other;
} else if (!other.is_empty()) {
// We round up the distance to ensure that the cap is actually contained.
// TODO(ericv): Do some error analysis in order to guarantee this.
S1ChordAngle dist = S1ChordAngle(center_, other.center_) + other.radius_;
radius_ = max(radius_, dist.PlusError(DBL_EPSILON * dist.length2()));
}
}
S2Cap S2Cap::Expanded(S1Angle distance) const {
S2_DCHECK_GE(distance.radians(), 0);
if (is_empty()) return Empty();
return S2Cap(center_, radius_ + S1ChordAngle(distance));
}
S2Cap S2Cap::Union(const S2Cap& other) const {
if (radius_ < other.radius_) {
return other.Union(*this);
}
if (is_full() || other.is_empty()) {
return *this;
}
// This calculation would be more efficient using S1ChordAngles.
S1Angle this_radius = GetRadius();
S1Angle other_radius = other.GetRadius();
S1Angle distance(center(), other.center());
if (this_radius >= distance + other_radius) {
return *this;
} else {
S1Angle result_radius = 0.5 * (distance + this_radius + other_radius);
S2Point result_center =
S2::GetPointOnLine(center(), other.center(),
0.5 * (distance - this_radius + other_radius));
return S2Cap(result_center, result_radius);
}
}
S2Cap* S2Cap::Clone() const {
return new S2Cap(*this);
}
S2Cap S2Cap::GetCapBound() const {
return *this;
}
S2LatLngRect S2Cap::GetRectBound() const {
if (is_empty()) return S2LatLngRect::Empty();
// Convert the center to a (lat,lng) pair, and compute the cap angle.
S2LatLng center_ll(center_);
double cap_angle = GetRadius().radians();
bool all_longitudes = false;
double lat[2], lng[2];
lng[0] = -M_PI;
lng[1] = M_PI;
// Check whether cap includes the south pole.
lat[0] = center_ll.lat().radians() - cap_angle;
if (lat[0] <= -M_PI_2) {
lat[0] = -M_PI_2;
all_longitudes = true;
}
// Check whether cap includes the north pole.
lat[1] = center_ll.lat().radians() + cap_angle;
if (lat[1] >= M_PI_2) {
lat[1] = M_PI_2;
all_longitudes = true;
}
if (!all_longitudes) {
// Compute the range of longitudes covered by the cap. We use the law
// of sines for spherical triangles. Consider the triangle ABC where
// A is the north pole, B is the center of the cap, and C is the point
// of tangency between the cap boundary and a line of longitude. Then
// C is a right angle, and letting a,b,c denote the sides opposite A,B,C,
// we have sin(a)/sin(A) = sin(c)/sin(C), or sin(A) = sin(a)/sin(c).
// Here "a" is the cap angle, and "c" is the colatitude (90 degrees
// minus the latitude). This formula also works for negative latitudes.
//
// The formula for sin(a) follows from the relationship h = 1 - cos(a).
double sin_a = sin(radius_);
double sin_c = cos(center_ll.lat().radians());
if (sin_a <= sin_c) {
double angle_A = asin(sin_a / sin_c);
lng[0] = remainder(center_ll.lng().radians() - angle_A, 2 * M_PI);
lng[1] = remainder(center_ll.lng().radians() + angle_A, 2 * M_PI);
}
}
return S2LatLngRect(R1Interval(lat[0], lat[1]),
S1Interval(lng[0], lng[1]));
}
// Computes a covering of the S2Cap. In general the covering consists of at
// most 4 cells except for very large caps, which may need up to 6 cells.
// The output is not sorted.
void S2Cap::GetCellUnionBound(vector<S2CellId>* cell_ids) const {
// TODO(ericv): The covering could be made quite a bit tighter by mapping
// the cap to a rectangle in (i,j)-space and finding a covering for that.
cell_ids->clear();
// Find the maximum level such that the cap contains at most one cell vertex
// and such that S2CellId::AppendVertexNeighbors() can be called.
int level = S2::kMinWidth.GetLevelForMinValue(GetRadius().radians()) - 1;
// If level < 0, then more than three face cells are required.
if (level < 0) {
cell_ids->reserve(6);
for (int face = 0; face < 6; ++face) {
cell_ids->push_back(S2CellId::FromFace(face));
}
} else {
// The covering consists of the 4 cells at the given level that share the
// cell vertex that is closest to the cap center.
cell_ids->reserve(4);
S2CellId(center_).AppendVertexNeighbors(level, cell_ids);
}
}
bool S2Cap::Intersects(const S2Cell& cell, const S2Point* vertices) const {
// Return true if this cap intersects any point of 'cell' excluding its
// vertices (which are assumed to already have been checked).
// If the cap is a hemisphere or larger, the cell and the complement of the
// cap are both convex. Therefore since no vertex of the cell is contained,
// no other interior point of the cell is contained either.
if (radius_ >= S1ChordAngle::Right()) return false;
// We need to check for empty caps due to the center check just below.
if (is_empty()) return false;
// Optimization: return true if the cell contains the cap center. (This
// allows half of the edge checks below to be skipped.)
if (cell.Contains(center_)) return true;
// At this point we know that the cell does not contain the cap center,
// and the cap does not contain any cell vertex. The only way that they
// can intersect is if the cap intersects the interior of some edge.
double sin2_angle = sin2(radius_);
for (int k = 0; k < 4; ++k) {
S2Point edge = cell.GetEdgeRaw(k);
double dot = center_.DotProd(edge);
if (dot > 0) {
// The center is in the interior half-space defined by the edge. We don't
// need to consider these edges, since if the cap intersects this edge
// then it also intersects the edge on the opposite side of the cell
// (because we know the center is not contained with the cell).
continue;
}
// The Norm2() factor is necessary because "edge" is not normalized.
if (dot * dot > sin2_angle * edge.Norm2()) {
return false; // Entire cap is on the exterior side of this edge.
}
// Otherwise, the great circle containing this edge intersects
// the interior of the cap. We just need to check whether the point
// of closest approach occurs between the two edge endpoints.
Vector3_d dir = edge.CrossProd(center_);
if (dir.DotProd(vertices[k]) < 0 && dir.DotProd(vertices[(k+1)&3]) > 0)
return true;
}
return false;
}
bool S2Cap::Contains(const S2Cell& cell) const {
// If the cap does not contain all cell vertices, return false.
// We check the vertices before taking the Complement() because we can't
// accurately represent the complement of a very small cap (a height
// of 2-epsilon is rounded off to 2).
S2Point vertices[4];
for (int k = 0; k < 4; ++k) {
vertices[k] = cell.GetVertex(k);
if (!Contains(vertices[k])) return false;
}
// Otherwise, return true if the complement of the cap does not intersect
// the cell. (This test is slightly conservative, because technically we
// want Complement().InteriorIntersects() here.)
return !Complement().Intersects(cell, vertices);
}
bool S2Cap::MayIntersect(const S2Cell& cell) const {
// If the cap contains any cell vertex, return true.
S2Point vertices[4];
for (int k = 0; k < 4; ++k) {
vertices[k] = cell.GetVertex(k);
if (Contains(vertices[k])) return true;
}
return Intersects(cell, vertices);
}
bool S2Cap::Contains(const S2Point& p) const {
S2_DCHECK(S2::IsUnitLength(p));
return S1ChordAngle(center_, p) <= radius_;
}
bool S2Cap::InteriorContains(const S2Point& p) const {
S2_DCHECK(S2::IsUnitLength(p));
return is_full() || S1ChordAngle(center_, p) < radius_;
}
bool S2Cap::operator==(const S2Cap& other) const {
return (center_ == other.center_ && radius_ == other.radius_) ||
(is_empty() && other.is_empty()) ||
(is_full() && other.is_full());
}
bool S2Cap::ApproxEquals(const S2Cap& other, S1Angle max_error_angle) const {
const double max_error = max_error_angle.radians();
const double r2 = radius_.length2();
const double other_r2 = other.radius_.length2();
return (S2::ApproxEquals(center_, other.center_, max_error_angle) &&
fabs(r2 - other_r2) <= max_error) ||
(is_empty() && other_r2 <= max_error) ||
(other.is_empty() && r2 <= max_error) ||
(is_full() && other_r2 >= 2 - max_error) ||
(other.is_full() && r2 >= 2 - max_error);
}
std::ostream& operator<<(std::ostream& os, const S2Cap& cap) {
return os << "[Center=" << cap.center()
<< ", Radius=" << cap.GetRadius() << "]";
}
void S2Cap::Encode(Encoder* encoder) const {
encoder->Ensure(4 * sizeof(double));
encoder->putdouble(center_.x());
encoder->putdouble(center_.y());
encoder->putdouble(center_.z());
encoder->putdouble(radius_.length2());
S2_DCHECK_GE(encoder->avail(), 0);
}
bool S2Cap::Decode(Decoder* decoder) {
if (decoder->avail() < 4 * sizeof(double)) return false;
double x = decoder->getdouble();
double y = decoder->getdouble();
double z = decoder->getdouble();
center_ = S2Point(x, y, z);
radius_ = S1ChordAngle::FromLength2(decoder->getdouble());
if (absl::GetFlag(FLAGS_s2debug)) {
S2_CHECK(is_valid()) << "Invalid S2Cap: " << *this;
}
return true;
}
| 36.206897 | 80 | 0.676508 | LLcat1217 |
a182e3162226097ce0bd1dfa369de8ad53ff48b2 | 16,293 | hpp | C++ | data_compression/L1/include/hw/lz4_compress.hpp | KitAway/Vitis_Libraries | 208ada169cd8ddeac0d26b2568343fab6f968331 | [
"Apache-2.0"
] | 1 | 2021-06-14T17:02:06.000Z | 2021-06-14T17:02:06.000Z | data_compression/L1/include/hw/lz4_compress.hpp | KitAway/Vitis_Libraries | 208ada169cd8ddeac0d26b2568343fab6f968331 | [
"Apache-2.0"
] | null | null | null | data_compression/L1/include/hw/lz4_compress.hpp | KitAway/Vitis_Libraries | 208ada169cd8ddeac0d26b2568343fab6f968331 | [
"Apache-2.0"
] | null | null | null | /*
* (c) Copyright 2019 Xilinx, 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 _XFCOMPRESSION_LZ4_COMPRESS_HPP_
#define _XFCOMPRESSION_LZ4_COMPRESS_HPP_
/**
* @file lz4_compress.hpp
* @brief Header for modules used in LZ4 compression kernel.
*
* This file is part of Vitis Data Compression Library.
*/
#include "hls_stream.h"
#include <ap_int.h>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "lz_compress.hpp"
#include "lz_optional.hpp"
#include "mm2s.hpp"
#include "s2mm.hpp"
#include "stream_downsizer.hpp"
#include "stream_upsizer.hpp"
typedef ap_uint<64> lz4_compressd_dt;
typedef ap_uint<32> compressd_dt;
typedef ap_uint<8> encodedData_t;
const int c_gmemBurstSize = 32;
namespace xf {
namespace compression {
namespace details {
template <int MAX_LIT_COUNT, int PARALLEL_UNITS>
static void lz4CompressPart1(hls::stream<compressd_dt>& inStream,
hls::stream<uint8_t>& lit_outStream,
hls::stream<lz4_compressd_dt>& lenOffset_Stream,
uint32_t input_size,
uint32_t max_lit_limit[PARALLEL_UNITS],
uint32_t index) {
if (input_size == 0) return;
uint8_t match_len = 0;
uint32_t lit_count = 0;
uint32_t lit_count_flag = 0;
compressd_dt nextEncodedValue = inStream.read();
lz4_divide:
for (uint32_t i = 0; i < input_size;) {
#pragma HLS PIPELINE II = 1
compressd_dt tmpEncodedValue = nextEncodedValue;
if (i < (input_size - 1)) nextEncodedValue = inStream.read();
uint8_t tCh = tmpEncodedValue.range(7, 0);
uint8_t tLen = tmpEncodedValue.range(15, 8);
uint16_t tOffset = tmpEncodedValue.range(31, 16);
uint32_t match_offset = tOffset;
if (lit_count >= MAX_LIT_COUNT) {
lit_count_flag = 1;
} else if (tLen) {
uint8_t match_len = tLen - 4; // LZ4 standard
lz4_compressd_dt tmpValue;
tmpValue.range(63, 32) = lit_count;
tmpValue.range(15, 0) = match_len;
tmpValue.range(31, 16) = match_offset;
lenOffset_Stream << tmpValue;
match_len = tLen - 1;
lit_count = 0;
} else {
lit_outStream << tCh;
lit_count++;
}
if (tLen)
i += tLen;
else
i += 1;
}
if (lit_count) {
lz4_compressd_dt tmpValue;
tmpValue.range(63, 32) = lit_count;
if (lit_count == MAX_LIT_COUNT) {
lit_count_flag = 1;
tmpValue.range(15, 0) = 777;
tmpValue.range(31, 16) = 777;
} else {
tmpValue.range(15, 0) = 0;
tmpValue.range(31, 16) = 0;
}
lenOffset_Stream << tmpValue;
}
max_lit_limit[index] = lit_count_flag;
}
static void lz4CompressPart2(hls::stream<uint8_t>& in_lit_inStream,
hls::stream<lz4_compressd_dt>& in_lenOffset_Stream,
hls::stream<ap_uint<8> >& outStream,
hls::stream<bool>& endOfStream,
hls::stream<uint32_t>& compressdSizeStream,
uint32_t input_size) {
// LZ4 Compress STATES
enum lz4CompressStates { WRITE_TOKEN, WRITE_LIT_LEN, WRITE_MATCH_LEN, WRITE_LITERAL, WRITE_OFFSET0, WRITE_OFFSET1 };
uint32_t lit_len = 0;
uint16_t outCntr = 0;
uint32_t compressedSize = 0;
enum lz4CompressStates next_state = WRITE_TOKEN;
uint16_t lit_length = 0;
uint16_t match_length = 0;
uint16_t write_lit_length = 0;
ap_uint<16> match_offset = 0;
bool lit_ending = false;
bool extra_match_len = false;
lz4_compress:
for (uint32_t inIdx = 0; (inIdx < input_size) || (next_state != WRITE_TOKEN);) {
#pragma HLS PIPELINE II = 1
ap_uint<8> outValue;
if (next_state == WRITE_TOKEN) {
lz4_compressd_dt tmpValue = in_lenOffset_Stream.read();
lit_length = tmpValue.range(63, 32);
match_length = tmpValue.range(15, 0);
match_offset = tmpValue.range(31, 16);
inIdx += match_length + lit_length + 4;
if (match_length == 777 && match_offset == 777) {
inIdx = input_size;
lit_ending = true;
}
lit_len = lit_length;
write_lit_length = lit_length;
if (match_offset == 0 && match_length == 0) {
lit_ending = true;
}
if (lit_length >= 15) {
outValue.range(7, 4) = 15;
lit_length -= 15;
next_state = WRITE_LIT_LEN;
} else if (lit_length) {
outValue.range(7, 4) = lit_length;
lit_length = 0;
next_state = WRITE_LITERAL;
} else {
outValue.range(7, 4) = 0;
next_state = WRITE_OFFSET0;
}
if (match_length >= 15) {
outValue.range(3, 0) = 15;
match_length -= 15;
extra_match_len = true;
} else {
outValue.range(3, 0) = match_length;
match_length = 0;
extra_match_len = false;
}
} else if (next_state == WRITE_LIT_LEN) {
if (lit_length >= 255) {
outValue = 255;
lit_length -= 255;
} else {
outValue = lit_length;
next_state = WRITE_LITERAL;
}
} else if (next_state == WRITE_LITERAL) {
outValue = in_lit_inStream.read();
write_lit_length--;
if (write_lit_length == 0) {
if (lit_ending) {
next_state = WRITE_TOKEN;
} else {
next_state = WRITE_OFFSET0;
}
}
} else if (next_state == WRITE_OFFSET0) {
match_offset++; // LZ4 standard
outValue = match_offset.range(7, 0);
next_state = WRITE_OFFSET1;
} else if (next_state == WRITE_OFFSET1) {
outValue = match_offset.range(15, 8);
if (extra_match_len) {
next_state = WRITE_MATCH_LEN;
} else {
next_state = WRITE_TOKEN;
}
} else if (next_state == WRITE_MATCH_LEN) {
if (match_length >= 255) {
outValue = 255;
match_length -= 255;
} else {
outValue = match_length;
next_state = WRITE_TOKEN;
}
}
if (compressedSize < input_size) {
// Limiting compression size not more than input size.
// Host code should ignore such blocks
outStream << outValue;
endOfStream << 0;
compressedSize++;
}
}
compressdSizeStream << compressedSize;
outStream << 0;
endOfStream << 1;
}
} // namespace compression
} // namespace xf
} // namespace details
namespace xf {
namespace compression {
/**
* @brief This is the core compression module which seperates the input stream into two
* output streams, one literal stream and other offset stream, then lz4 encoding is done.
*
* @param inStream Input data stream
* @param outStream Output data stream
* @param max_lit_limit Size for compressed stream
* @param input_size Size of input data
* @param endOfStream Stream indicating that all data is processed or not
* @param compressdSizeStream Gives the compressed size for each 64K block
*
*/
template <int MAX_LIT_COUNT, int PARALLEL_UNITS>
static void lz4Compress(hls::stream<compressd_dt>& inStream,
hls::stream<ap_uint<8> >& outStream,
uint32_t max_lit_limit[PARALLEL_UNITS],
uint32_t input_size,
hls::stream<bool>& endOfStream,
hls::stream<uint32_t>& compressdSizeStream,
uint32_t index) {
hls::stream<uint8_t> lit_outStream("lit_outStream");
hls::stream<lz4_compressd_dt> lenOffset_Stream("lenOffset_Stream");
#pragma HLS STREAM variable = lit_outStream depth = MAX_LIT_COUNT
#pragma HLS STREAM variable = lenOffset_Stream depth = c_gmemBurstSize
#pragma HLS RESOURCE variable = lenOffset_Stream core = FIFO_SRL
#pragma HLS dataflow
details::lz4CompressPart1<MAX_LIT_COUNT, PARALLEL_UNITS>(inStream, lit_outStream, lenOffset_Stream, input_size,
max_lit_limit, index);
details::lz4CompressPart2(lit_outStream, lenOffset_Stream, outStream, endOfStream, compressdSizeStream, input_size);
}
template <class data_t,
int DATAWIDTH = 512,
int BURST_SIZE = 16,
int NUM_BLOCK = 8,
int M_LEN = 6,
int MIN_MAT = 4,
int LZ_MAX_OFFSET_LIM = 65536,
int OFFSET_WIN = 65536,
int MAX_M_LEN = 255,
int MAX_LIT_CNT = 4096,
int MIN_B_SIZE = 128>
void hlsLz4Core(hls::stream<data_t>& inStream,
hls::stream<data_t>& outStream,
hls::stream<bool>& outStreamEos,
hls::stream<uint32_t>& compressedSize,
uint32_t max_lit_limit[NUM_BLOCK],
uint32_t input_size,
uint32_t core_idx) {
hls::stream<xf::compression::compressd_dt> compressdStream("compressdStream");
hls::stream<xf::compression::compressd_dt> bestMatchStream("bestMatchStream");
hls::stream<xf::compression::compressd_dt> boosterStream("boosterStream");
#pragma HLS STREAM variable = compressdStream depth = 8
#pragma HLS STREAM variable = bestMatchStream depth = 8
#pragma HLS STREAM variable = boosterStream depth = 8
#pragma HLS RESOURCE variable = compressdStream core = FIFO_SRL
#pragma HLS RESOURCE variable = boosterStream core = FIFO_SRL
#pragma HLS dataflow
xf::compression::lzCompress<M_LEN, MIN_MAT, LZ_MAX_OFFSET_LIM>(inStream, compressdStream, input_size);
xf::compression::lzBestMatchFilter<M_LEN, OFFSET_WIN>(compressdStream, bestMatchStream, input_size);
xf::compression::lzBooster<MAX_M_LEN>(bestMatchStream, boosterStream, input_size);
xf::compression::lz4Compress<MAX_LIT_CNT, NUM_BLOCK>(boosterStream, outStream, max_lit_limit, input_size,
outStreamEos, compressedSize, core_idx);
}
template <class data_t,
int DATAWIDTH = 512,
int BURST_SIZE = 16,
int NUM_BLOCK = 8,
int M_LEN = 6,
int MIN_MAT = 4,
int LZ_MAX_OFFSET_LIM = 65536,
int OFFSET_WIN = 65536,
int MAX_M_LEN = 255,
int MAX_LIT_CNT = 4096,
int MIN_B_SIZE = 128>
void hlsLz4(const data_t* in,
data_t* out,
const uint32_t input_idx[NUM_BLOCK],
const uint32_t output_idx[NUM_BLOCK],
const uint32_t input_size[NUM_BLOCK],
uint32_t output_size[NUM_BLOCK],
uint32_t max_lit_limit[NUM_BLOCK]) {
hls::stream<encodedData_t> inStream[NUM_BLOCK];
hls::stream<bool> outStreamEos[NUM_BLOCK];
hls::stream<encodedData_t> outStream[NUM_BLOCK];
#pragma HLS STREAM variable = outStreamEos depth = 2
#pragma HLS STREAM variable = inStream depth = c_gmemBurstSize
#pragma HLS STREAM variable = outStream depth = c_gmemBurstSize
#pragma HLS RESOURCE variable = outStreamEos core = FIFO_SRL
#pragma HLS RESOURCE variable = inStream core = FIFO_SRL
#pragma HLS RESOURCE variable = outStream core = FIFO_SRL
hls::stream<uint32_t> compressedSize[NUM_BLOCK];
#pragma HLS dataflow
xf::compression::details::mm2multStreamSize<8, NUM_BLOCK, DATAWIDTH, BURST_SIZE>(in, input_idx, inStream,
input_size);
for (uint8_t i = 0; i < NUM_BLOCK; i++) {
#pragma HLS UNROLL
// lz4Core is instantiated based on the NUM_BLOCK
hlsLz4Core<encodedData_t, DATAWIDTH, BURST_SIZE, NUM_BLOCK>(inStream[i], outStream[i], outStreamEos[i],
compressedSize[i], max_lit_limit, input_size[i], i);
}
xf::compression::details::multStream2MM<8, NUM_BLOCK, DATAWIDTH, BURST_SIZE>(
outStream, outStreamEos, compressedSize, output_idx, out, output_size);
}
template <class data_t,
int DATAWIDTH = 512,
int BURST_SIZE = 16,
int NUM_BLOCK = 8,
int M_LEN = 6,
int MIN_MAT = 4,
int LZ_MAX_OFFSET_LIM = 65536,
int OFFSET_WIN = 65536,
int MAX_M_LEN = 255,
int MAX_LIT_CNT = 4096,
int MIN_B_SIZE = 128>
void lz4CompressMM(const data_t* in, data_t* out, uint32_t* compressd_size, const uint32_t input_size) {
uint32_t block_idx = 0;
uint32_t block_length = 64 * 1024;
uint32_t no_blocks = (input_size - 1) / block_length + 1;
uint32_t max_block_size = 64 * 1024;
uint32_t readBlockSize = 0;
bool small_block[NUM_BLOCK];
uint32_t input_block_size[NUM_BLOCK];
uint32_t input_idx[NUM_BLOCK];
uint32_t output_idx[NUM_BLOCK];
uint32_t output_block_size[NUM_BLOCK];
uint32_t max_lit_limit[NUM_BLOCK];
uint32_t small_block_inSize[NUM_BLOCK];
#pragma HLS ARRAY_PARTITION variable = input_block_size dim = 0 complete
#pragma HLS ARRAY_PARTITION variable = input_idx dim = 0 complete
#pragma HLS ARRAY_PARTITION variable = output_idx dim = 0 complete
#pragma HLS ARRAY_PARTITION variable = output_block_size dim = 0 complete
#pragma HLS ARRAY_PARTITION variable = max_lit_limit dim = 0 complete
// Figure out total blocks & block sizes
for (uint32_t i = 0; i < no_blocks; i += NUM_BLOCK) {
uint32_t nblocks = NUM_BLOCK;
if ((i + NUM_BLOCK) > no_blocks) {
nblocks = no_blocks - i;
}
for (uint32_t j = 0; j < NUM_BLOCK; j++) {
if (j < nblocks) {
uint32_t inBlockSize = block_length;
if (readBlockSize + block_length > input_size) inBlockSize = input_size - readBlockSize;
if (inBlockSize < MIN_B_SIZE) {
small_block[j] = 1;
small_block_inSize[j] = inBlockSize;
input_block_size[j] = 0;
input_idx[j] = 0;
} else {
small_block[j] = 0;
input_block_size[j] = inBlockSize;
readBlockSize += inBlockSize;
input_idx[j] = (i + j) * max_block_size;
output_idx[j] = (i + j) * max_block_size;
}
} else {
input_block_size[j] = 0;
input_idx[j] = 0;
}
output_block_size[j] = 0;
max_lit_limit[j] = 0;
}
// Call for parallel compression
hlsLz4<data_t, DATAWIDTH, BURST_SIZE, NUM_BLOCK>(in, out, input_idx, output_idx, input_block_size,
output_block_size, max_lit_limit);
for (uint32_t k = 0; k < nblocks; k++) {
if (max_lit_limit[k]) {
compressd_size[block_idx] = input_block_size[k];
} else {
compressd_size[block_idx] = output_block_size[k];
}
if (small_block[k] == 1) {
compressd_size[block_idx] = small_block_inSize[k];
}
block_idx++;
}
}
}
} // namespace compression
} // namespace xf
#endif // _XFCOMPRESSION_LZ4_COMPRESS_HPP_
| 37.628176 | 120 | 0.595164 | KitAway |
a183086b4e30020642c4eba326d187db327199be | 1,490 | cpp | C++ | 王道刷题/13.cpp | CSU-FulChou/IOS_er | 4286677854c4afe61f745bfd087527e369402dc7 | [
"MIT"
] | 2 | 2020-02-10T15:20:03.000Z | 2020-02-23T07:23:57.000Z | 王道刷题/13.cpp | CSU-FulChou/IOS_er | 4286677854c4afe61f745bfd087527e369402dc7 | [
"MIT"
] | null | null | null | 王道刷题/13.cpp | CSU-FulChou/IOS_er | 4286677854c4afe61f745bfd087527e369402dc7 | [
"MIT"
] | 1 | 2020-02-24T04:46:44.000Z | 2020-02-24T04:46:44.000Z | #include<iostream>
#include<cstdio>
using namespace std;
//隐藏条件就是1年1月1日是星期一,把这个时间点设为锚点
// 字符串要用二维数组保存
char weeks[7][20]={"Sunday","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
char months[12][20]={"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
int datas[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},
{31,29,31,30,31,30,31,31,30,31,30,31}};
int isLeapYear(int year){
return (year%4==0&&year%100!=0)||year%400==0;
}
int numberOfYear(int year){
if(isLeapYear(year))
return 366;
else
return 365;
}
bool isSameArray(char x[],char y[]){
for(int i=0;i<20;i++){
if(x[i]!=y[i])
return false;
}
return true;
}
int day;
char month[20];
int year;
int main(){
while(scanf("%d%s%d",&day,&month,&year)!=EOF){
int num =0;
// 计算月份的天数
int monthNum=0;
for(int i=0;i<12;i++){
// if(months[i]==month){ // 不能直接判断字符数组,那样判断的是内存地址;
// monthNum=i;
// }
if(isSameArray(months[i],month))
monthNum=i;// no add 1;
}
for(int i=0;i<monthNum;i++){
num+=datas[isLeapYear(year)][i];
}
year--;
while(year>0){
num+=numberOfYear(year);
year--;
}
num+=day;
num=num%7;
printf("%s\n",weeks[num]);
}
return 0;
}
| 24.032258 | 95 | 0.508054 | CSU-FulChou |
a184d88664ee1c60912f5ba6f387cb6b6a3419e9 | 3,834 | cc | C++ | src/common/util/base64.cc | septicmk/v6d | 3c64e0a324adfe71feb4bfda51d0e55724bfde8d | [
"Apache-2.0"
] | null | null | null | src/common/util/base64.cc | septicmk/v6d | 3c64e0a324adfe71feb4bfda51d0e55724bfde8d | [
"Apache-2.0"
] | null | null | null | src/common/util/base64.cc | septicmk/v6d | 3c64e0a324adfe71feb4bfda51d0e55724bfde8d | [
"Apache-2.0"
] | null | null | null | /** Copyright 2020-2021 Alibaba Group Holding Limited.
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 <iostream>
#include "common/util/base64.h"
/* std::vector<unsigned char> myData;
* ...
* std::string encodedData = base64_encode(&myData[0], myData.size());
* std::vector<unsigned char> decodedData = base64_decode(encodedData);
*/
namespace vineyard {
static const char _base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(const std::string& buffer) {
const unsigned char* buf = reinterpret_cast<const unsigned char*>(&buffer[0]);
std::string base64_chars(_base64_chars);
size_t bufLen = buffer.size();
std::string ret;
int i = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (bufLen--) {
char_array_3[i++] = *(buf++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] =
((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] =
((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; (i < 4); i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i) {
for (int j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] =
((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] =
((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (int j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while ((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(const std::string& encoded_string) {
auto in_len = encoded_string.size();
std::string base64_chars(_base64_chars);
int i = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::vector<unsigned char> ret;
while (in_len-- && (encoded_string[in_] != '=') &&
is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_];
in_++;
if (i == 4) {
for (i = 0; i < 4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] =
(char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret.push_back(char_array_3[i]);
i = 0;
}
}
if (i) {
for (int j = i; j < 4; j++)
char_array_4[j] = 0;
for (int j = 0; j < 4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] =
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (int j = 0; (j < i - 1); j++)
ret.push_back(char_array_3[j]);
}
return std::string(ret.begin(), ret.end());
}
} // namespace vineyard
| 29.492308 | 80 | 0.597027 | septicmk |
a1851846bfb5782d4de2c1902ce8590d8d87fa45 | 1,078 | cpp | C++ | aws-cpp-sdk-grafana/source/model/AwsSsoAuthentication.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-grafana/source/model/AwsSsoAuthentication.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-grafana/source/model/AwsSsoAuthentication.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/grafana/model/AwsSsoAuthentication.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ManagedGrafana
{
namespace Model
{
AwsSsoAuthentication::AwsSsoAuthentication() :
m_ssoClientIdHasBeenSet(false)
{
}
AwsSsoAuthentication::AwsSsoAuthentication(JsonView jsonValue) :
m_ssoClientIdHasBeenSet(false)
{
*this = jsonValue;
}
AwsSsoAuthentication& AwsSsoAuthentication::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("ssoClientId"))
{
m_ssoClientId = jsonValue.GetString("ssoClientId");
m_ssoClientIdHasBeenSet = true;
}
return *this;
}
JsonValue AwsSsoAuthentication::Jsonize() const
{
JsonValue payload;
if(m_ssoClientIdHasBeenSet)
{
payload.WithString("ssoClientId", m_ssoClientId);
}
return payload;
}
} // namespace Model
} // namespace ManagedGrafana
} // namespace Aws
| 17.966667 | 74 | 0.74397 | perfectrecall |
a186079e4da2710a643d8e100ca6d292be8f63d9 | 492 | cpp | C++ | huemodule.std/std.cpp | HueStudios/HueLang | 3b89d6d88c6b61cc5cd94017280821d2571338e5 | [
"MIT"
] | 5 | 2020-06-26T08:54:26.000Z | 2020-06-26T16:58:17.000Z | huemodule.std/std.cpp | HueStudios/HueLang | 3b89d6d88c6b61cc5cd94017280821d2571338e5 | [
"MIT"
] | 3 | 2020-04-28T14:38:26.000Z | 2020-05-21T13:41:34.000Z | huemodule.std/std.cpp | HueStudios/HueLang | 3b89d6d88c6b61cc5cd94017280821d2571338e5 | [
"MIT"
] | null | null | null | #include "std.h"
extern "C" void ModuleEntry(Environment *env) {
cout << "Std library loaded" << endl;
Word helloword = env->definitionTable.TokToWord("hello");
env->AddPrimaryDefinition(helloword, &__hello);
}
void __hello(Environment& env) {
cout << "This word was added by the STD lib" << endl;
for (int i = 0; i < env.valueStack.size(); i++) {
cout << i << " : " << env.definitionTable.GetName(((WordValue*)env.valueStack.c[i])->contained) << endl;
}
}
| 30.75 | 112 | 0.628049 | HueStudios |
a18707911d335e2d6166b905c0e01bde5c02763e | 13,501 | cpp | C++ | benchmark/testv5.cpp | shubhamsingh91/Pinocchio_ss | 683f6d1ea445cf65e74056f2b18eb65a4151ff0f | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2021-06-30T18:01:31.000Z | 2021-06-30T21:49:06.000Z | benchmark/testv5.cpp | shubhamsingh91/Pinocchio_ss | 683f6d1ea445cf65e74056f2b18eb65a4151ff0f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | benchmark/testv5.cpp | shubhamsingh91/Pinocchio_ss | 683f6d1ea445cf65e74056f2b18eb65a4151ff0f | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | // same as testv4 but saves time values as texts and can run for all cases
// checking some boost options, ABA forward dynamics etc.
#include "pinocchio/algorithm/joint-configuration.hpp"
#include "pinocchio/algorithm/cholesky.hpp"
#include "pinocchio/parsers/urdf.hpp"
#include "pinocchio/parsers/sample-models.hpp"
#include "pinocchio/container/aligned-vector.hpp"
#include "pinocchio/algorithm/azamat.hpp"
#include "pinocchio/algorithm/azamat_v2.hpp"
#include "pinocchio/algorithm/azamat_v3.hpp"
#include "pinocchio/algorithm/azamat_v4.hpp"
#include "pinocchio/utils/timer.hpp"
#include "pinocchio/algorithm/aba-derivatives.hpp"
#include "pinocchio/algorithm/rnea-derivatives.hpp"
#include "pinocchio/algorithm/azamat_v4.hpp"
#include "pinocchio/algorithm/rnea-derivatives-faster.hpp"
#include "pinocchio/algorithm/aba_v2.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <iostream>
#include <ctime>
//-----------------Running ABA first---- //
using namespace std;
int main(int argc, const char ** argv)
{
using namespace Eigen;
using namespace pinocchio;
PinocchioTicToc timer(PinocchioTicToc::US);
#ifdef NDEBUG
int NBT= 100*1000; // 50000 initially
#else
int NBT = 1;
std::cout << "(the time score in debug mode is not relevant) " << std::endl;
#endif
// std::cout << "Enter NBT" << std::endl;
// cin >> NBT;
Model model;
string str_urdf;
string str_robotname[10];
string str_file_ext;
string robot_name="";
int str_int;
//str_int = 0; // integer to change the str_urdf
cout << "Enter the str_int here" << endl;
cin >> str_int;
str_robotname[0] = "double_pendulum"; // double pendulum
str_robotname[1] = "ur3_robot"; // UR3
str_robotname[2] = "ur5_robot"; // UR5
str_robotname[3] = "ur10_robot"; // UR10
str_robotname[4] = "kuka_peg_lwr"; // kuka
str_robotname[5] = "anymal"; // anymal
str_robotname[6] = "hyq"; // hyq
str_robotname[7] = "baxter_simple"; // baxter
str_robotname[8] = "atlas"; //atlas
str_robotname[9] = "simple_humanoid"; //simple humanoid
robot_name = str_robotname[str_int];
str_file_ext = "/home/ss86299/Desktop/test_pinocchio/pinocchio/models/";
str_urdf.append(str_file_ext);
str_urdf.append(robot_name);
str_urdf.append(".urdf");
std :: string filename = str_urdf;
if(argc>1) filename = argv[1];
bool with_ff = false; // true originally
if ((str_int >4)&&(str_int<11))
{
with_ff = true; // True for anymal and atlas
}
if (str_int==7)
{
with_ff = false; // False for Baxter
}
if(argc>2)
{
const std::string ff_option = argv[2];
if(ff_option == "-no-ff")
with_ff = false;
}
if( filename == "HS")
buildModels::humanoidRandom(model,true);
else
if(with_ff)
pinocchio::urdf::buildModel(filename,JointModelFreeFlyer(),model);
// pinocchio::urdf::buildModel(filename,JointModelRX(),model);
else
pinocchio::urdf::buildModel(filename,model);
cout << "with ff = " << with_ff << "\n \n";
std::cout << "nq = " << model.nq << std::endl;
std::cout << "nv = " << model.nv << std::endl;
cout << "Model is" << robot_name << endl;
//-- opening filename here
string filewrite="";
ofstream file1;
filewrite.append(robot_name);
filewrite.append(".txt");
file1.open(filewrite);
Data data(model);
VectorXd qmax = Eigen::VectorXd::Ones(model.nq);
PINOCCHIO_ALIGNED_STD_VECTOR(VectorXd) qs (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(VectorXd) qdots (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(VectorXd) taus (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(VectorXd) qddots (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(MatrixXd) tau_mat (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(MatrixXd) tau_mat_n2n (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(MatrixXd) tau_mat_n2n_v2 (NBT);
PINOCCHIO_ALIGNED_STD_VECTOR(MatrixXd) tau_mat_n2n_v3 (NBT);
// MatrixXd tau_mat(MatrixXd::Identity(model.nv,model.nv));
// randomizing input data here
std:: cout << "NBT variable is" << NBT << endl;
for(size_t i=0;i<NBT;++i)
{
qs[i] = randomConfiguration(model,-qmax,qmax);
qdots[i] = Eigen::VectorXd::Random(model.nv);
taus[i] = Eigen::VectorXd::Random(model.nv);
qddots[i] = Eigen::VectorXd::Random(model.nv);
tau_mat_n2n[i] = Eigen::MatrixXd::Identity(model.nv,2*model.nv);
tau_mat_n2n_v2[i] = Eigen::MatrixXd::Identity(model.nv,2*model.nv);
tau_mat_n2n_v3[i] = Eigen::MatrixXd::Identity(model.nv,2*model.nv);
}
double time_ABA[9];
//----------------------------------------------------//
// Compute RNEA derivatives here ---------------------//
//----------------------------------------------------//
PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixXd) drnea_dq(MatrixXd::Zero(model.nv,model.nv));
PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixXd) drnea_dv(MatrixXd::Zero(model.nv,model.nv));
MatrixXd drnea_da(MatrixXd::Zero(model.nv,model.nv));
timer.tic();
SMOOTH(NBT)
{
computeRNEADerivatives(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth],
drnea_dq,drnea_dv,drnea_da);
}
time_ABA[1] = timer.toc()/NBT; // RNEA timing
std::cout << "RNEA derivatives= \t\t" << time_ABA[1] << std::endl;
// for( int ll=0; ll<model.nv ; ll++)
// {
// std::cout << "tau[i] is" << data.tau[ll] <<std::endl;
// std::cout << "v[i] is" << data.v[ll] <<std::endl;
// std::cout << "a[i] is" << data.a[ll] << std::endl;
// }
//----------------------------------------------------//
// Compute RNEA derivatives faster--------------------//
//----------------------------------------------------//
PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixXd) drnea2_dq(MatrixXd::Zero(model.nv,model.nv));
PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixXd) drnea2_dv(MatrixXd::Zero(model.nv,model.nv));
MatrixXd drnea2_da(MatrixXd::Zero(model.nv,model.nv));
timer.tic();
SMOOTH(NBT)
{
computeRNEADerivativesFaster(model,data,qs[_smooth],qdots[_smooth],qddots[_smooth],
drnea2_dq,drnea2_dv,drnea2_da);
}
time_ABA[2] = timer.toc()/NBT; // RNEAF timing
std::cout << "RNEA derivativeF= \t\t" << time_ABA[2] << std::endl;
// for( int ll=0; ll<model.nv ; ll++)
// {
// std::cout << "tau[i] is" << data.tau[ll] <<std::endl;
// std::cout << "v[i] is" << data.v[ll] <<std::endl;
// std::cout << "a[i] is" << data.a[ll] << std::endl;
// }
//-- comparing the RNEA and RNEA F derivatives here
// std::cout << "----------------------------------------------" <<std::endl;
// std::cout << "comparison of RNEA derivatives here" << std::endl;
// std::cout << "difference in dtau_dq is" << (drnea2_dq-drnea_dq).squaredNorm() << std::endl;
// std::cout << "difference in dtau_dqd is" << (drnea2_dv-drnea_dv).squaredNorm() << std::endl;
// std::cout << "----------------------------------------------" <<std::endl;
//-----------------------------------------------------//
//------------- Minv_v2 with AZAmat_v4 here------------//
//-----------------------------------------------------//
tau_mat_n2n_v3[0] << -drnea_dq,-drnea_dv; // concatenating partial wrt q and qdot
timer.tic();
SMOOTH(NBT)
{
computeMinverse_v2(model,data,qs[_smooth],tau_mat_n2n_v3[_smooth]);
}
time_ABA[6] = timer.toc()/NBT; // Minv timing
std::cout << "Minv_v2 =\t\t" << time_ABA[6]<< std::endl;
//-----------------------------------------------------//
//------------- Minv here------------------------------//
//-----------------------------------------------------//
timer.tic();
SMOOTH(NBT)
{
computeMinverse(model,data,qs[_smooth]);
}
time_ABA[0] = timer.toc()/NBT; // Minv timing
std::cout << "Minv =\t\t" << time_ABA[0]<< std::endl;
// std::cout << "Minv =\t\t"; timer.toc(std::cout,NBT);
// Filling the Minv matrix here
for (int ii=0; ii < model.nv ;ii++)
{
for (int jj=0; jj<ii; jj++)
{
if (ii!=jj)
{
data.Minv.coeffRef(ii,jj) = data.Minv.coeffRef(jj,ii);
}
}
}
//-----------------------------------------------------------------//
// FD partials using AZAmat_v3/4 function here---------------------//
//-----------------------------------------------------------------//
// tau_mat_n2n_v3[0] << -drnea_dq,-drnea_dv; // concatenating partial wrt q and qdot
// // std::cout<< "tau_mat_n2n_v3 is" << tau_mat_n2n_v3[0] << std::endl;
// timer.tic();
// SMOOTH(NBT)
// azamat_v4(model,data,qs[_smooth],tau_mat_n2n_v3[_smooth]);
// time_ABA[6] = timer.toc()/NBT;
// std::cout << "IPR using AZA_mat_v4 method is = \t\t" << time_ABA[6] << std::endl;
// std::cout <<"---------------------------------------" << endl;
//----------------------------------------------------//
// Calculate ABA derivatives here
//----------------------------------------------------//
PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixXd) daba_dq(MatrixXd::Zero(model.nv,model.nv));
PINOCCHIO_EIGEN_PLAIN_ROW_MAJOR_TYPE(MatrixXd) daba_dv(MatrixXd::Zero(model.nv,model.nv));
MatrixXd daba_dtau(MatrixXd::Zero(model.nv,model.nv));
taus[0] = data.tau;
timer.tic();
SMOOTH(NBT)
{
computeABADerivatives(model,data,qs[_smooth],qdots[_smooth],taus[_smooth],
daba_dq,daba_dv,daba_dtau);
}
time_ABA[3] = timer.toc()/NBT; // ABA derivatives timing
// std::cout << "ABA derivatives= \t\t"; timer.toc(std::cout,NBT);
std::cout << "ABA derivatives= \t\t" << time_ABA[3] << endl;
//-----------------------------------------------------------------//
// FD partials using DMM here -------------------------------------//
//-----------------------------------------------------------------//
MatrixXd aba_partial_dq(MatrixXd::Zero(model.nv,model.nv));
MatrixXd aba_partial_dv(MatrixXd::Zero(model.nv,model.nv));
timer.tic();
for (int kk=0; kk<NBT; kk++)
{
aba_partial_dq = -data.Minv*drnea_dq;
aba_partial_dv = -data.Minv*drnea_dv;
}
time_ABA[7] = timer.toc()/NBT; // DMM timing
std::cout << "DMM= \t\t" << time_ABA[7] << std::endl;
//-----------------------------------------------------------------//
// FD partials using AZAmat function here--------------------------//
//-----------------------------------------------------------------//
tau_mat_n2n[0] << -drnea_dq,-drnea_dv; // concatenating partial wrt q and qdot
timer.tic();
SMOOTH(NBT)
azamat(model,data,qs[_smooth],qdots[_smooth],tau_mat_n2n[_smooth]);
time_ABA[4] = timer.toc()/NBT;
// std::cout << "IPR using AZA_mat method is = \t\t" ;timer.toc(std::cout,NBT);
std::cout << "IPR using AZA_mat method is = \t\t" << time_ABA[4] << endl;
// std::cout << "Minvmat_v1 is" << data.Minv_mat_prod << std::endl;
std::cout << "---------------------------------------" << endl;
//---------------------------------------------------//
//---------Comparison of results here----------------//
//---------------------------------------------------//
// MatrixXd diff_daba_dq2(MatrixXd::Zero(model.nv,model.nv));
// MatrixXd diff_daba_dqd2(MatrixXd::Zero(model.nv,model.nv));
// MatrixXd diff_mat1(MatrixXd::Zero(model.nv,2*model.nv));
// MatrixXd diff_daba_dq3(MatrixXd::Zero(model.nv,model.nv));
// MatrixXd diff_daba_dqd3(MatrixXd::Zero(model.nv,model.nv));
// // comparison of ABA derivs with DMM result
// diff_daba_dq3 = daba_dq-aba_partial_dq;
// diff_daba_dqd3 = daba_dv-aba_partial_dv;
// // comparison of ABA derivs with AZAMAT_v4
// diff_daba_dq2 = daba_dq-data.Minv_mat_prod_v3.middleCols(0,model.nv);
// diff_daba_dqd2 = daba_dv-data.Minv_mat_prod_v3.middleCols(model.nv,model.nv);
// diff_mat1 = data.Minv_mat_prod - data.Minv_mat_prod_v3;
// std::cout << "------------------------------" << std::endl;
// std::cout << "Norm of the difference matrix for AZAmat_v4 FD partial wrt q from orig FD partial wrt q is " << diff_daba_dq2.squaredNorm() << std::endl;
// std::cout << "Norm of the difference matrix for AZAmat_v4 FD partial wrt qd from orig FD partial wrt qd is " << diff_daba_dqd2.squaredNorm() << std::endl;
// std::cout << "\n" << endl;
// std::cout << "Norm of difference between mat_v1 and mat_v4 is" << diff_mat1.squaredNorm() << std::endl;
// std::cout << "------------------------------" << std::endl;
// std::cout << "Norm of the difference matrix for DMM FD partial wrt q from orig FD partial wrt q is " << diff_daba_dq3.squaredNorm() << std::endl;
// std::cout << "Norm of the difference matrix for DMM FD partial wrt qd from orig FD partial wrt qd is " << diff_daba_dqd3.squaredNorm() << std::endl;
// std::cout << "\n" << endl;
//--------------------------------------------------//
//----------Writing to file ------------------------//
//--------------------------------------------------//
// Writing all the timings to the file
for (int ii=0; ii<9 ; ii++)
{
file1 << time_ABA[ii] << "\n" << endl;
}
file1.close();
return 0;
} | 34.617949 | 161 | 0.545663 | shubhamsingh91 |
a1874ce6557c8a3cd0ac6f6fb84d7c1b346ef3a0 | 580 | cpp | C++ | src/GameState/status/GStartLevelProcess.cpp | isabella232/modite-adventure | 66c7779271706ec35e0a2f808afe92d7e15e0f85 | [
"MIT"
] | 5 | 2020-12-02T12:28:14.000Z | 2021-02-16T18:02:09.000Z | src/GameState/status/GStartLevelProcess.cpp | pedrohyvo/modite-adventure | 8c273803bd60747a169be3ba3f06b3419cc0ebff | [
"MIT"
] | 2 | 2021-01-22T18:51:48.000Z | 2021-01-28T18:43:43.000Z | src/GameState/status/GStartLevelProcess.cpp | pedrohyvo/modite-adventure | 8c273803bd60747a169be3ba3f06b3419cc0ebff | [
"MIT"
] | 2 | 2021-01-26T23:22:36.000Z | 2021-02-03T10:07:03.000Z | #include "Game.h"
#include "GStartLevelProcess.h"
GStartLevelProcess::GStartLevelProcess(const char *aName, TInt aLevel) : GProcess(ATTR_GONE) {
mTimer = 5 * FRAMES_PER_SECOND;
sprintf(mText, "%s level %2d", aName, aLevel);
TInt len = strlen(mText);
mX = gViewPort->mRect.Width()/2 - len*12/2;
}
GStartLevelProcess::~GStartLevelProcess() = default;
TBool GStartLevelProcess::RunAfter() {
if (--mTimer < 0) {
return EFalse;
}
gDisplay.renderBitmap->DrawString(gViewPort, mText, gFont16x16, mX, 32, COLOR_SHMOO, COLOR_TEXT_TRANSPARENT, -4);
return ETrue;
}
| 26.363636 | 115 | 0.713793 | isabella232 |
a18a1ea44b185e0ad34c81873885da5fd0f5c0fe | 4,150 | cc | C++ | base/win/wait_chain.cc | nctl144/cy-gurl | fef56d043b1f4fca22e721addc331241a8c97e46 | [
"MIT"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | base/win/wait_chain.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | base/win/wait_chain.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2016 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/win/wait_chain.h"
#include <memory>
#include "base/logging.h"
#include "base/strings/stringprintf.h"
namespace base {
namespace win {
namespace {
// Helper deleter to hold a HWCT into a unique_ptr.
struct WaitChainSessionDeleter {
using pointer = HWCT;
void operator()(HWCT session_handle) const {
::CloseThreadWaitChainSession(session_handle);
}
};
using ScopedWaitChainSessionHandle =
std::unique_ptr<HWCT, WaitChainSessionDeleter>;
const wchar_t* WctObjectTypeToString(WCT_OBJECT_TYPE type) {
switch (type) {
case WctCriticalSectionType:
return L"CriticalSection";
case WctSendMessageType:
return L"SendMessage";
case WctMutexType:
return L"Mutex";
case WctAlpcType:
return L"Alpc";
case WctComType:
return L"Com";
case WctThreadWaitType:
return L"ThreadWait";
case WctProcessWaitType:
return L"ProcessWait";
case WctThreadType:
return L"Thread";
case WctComActivationType:
return L"ComActivation";
case WctUnknownType:
return L"Unknown";
case WctSocketIoType:
return L"SocketIo";
case WctSmbIoType:
return L"SmbIo";
case WctMaxType:
break;
}
NOTREACHED();
return L"";
}
const wchar_t* WctObjectStatusToString(WCT_OBJECT_STATUS status) {
switch (status) {
case WctStatusNoAccess:
return L"NoAccess";
case WctStatusRunning:
return L"Running";
case WctStatusBlocked:
return L"Blocked";
case WctStatusPidOnly:
return L"PidOnly";
case WctStatusPidOnlyRpcss:
return L"PidOnlyRpcss";
case WctStatusOwned:
return L"Owned";
case WctStatusNotOwned:
return L"NotOwned";
case WctStatusAbandoned:
return L"Abandoned";
case WctStatusUnknown:
return L"Unknown";
case WctStatusError:
return L"Error";
case WctStatusMax:
break;
}
NOTREACHED();
return L"";
}
} // namespace
bool GetThreadWaitChain(DWORD thread_id,
WaitChainNodeVector* wait_chain,
bool* is_deadlock,
base::string16* failure_reason,
DWORD* last_error) {
DCHECK(wait_chain);
DCHECK(is_deadlock);
constexpr wchar_t kWaitChainSessionFailureReason[] =
L"OpenThreadWaitChainSession() failed.";
constexpr wchar_t kGetWaitChainFailureReason[] =
L"GetThreadWaitChain() failed.";
// Open a synchronous session.
ScopedWaitChainSessionHandle session_handle(
::OpenThreadWaitChainSession(0, nullptr));
if (!session_handle) {
if (last_error)
*last_error = ::GetLastError();
if (failure_reason)
*failure_reason = kWaitChainSessionFailureReason;
DPLOG(ERROR) << kWaitChainSessionFailureReason;
return false;
}
DWORD nb_nodes = WCT_MAX_NODE_COUNT;
wait_chain->resize(nb_nodes);
BOOL is_cycle;
if (!::GetThreadWaitChain(session_handle.get(), NULL, 0, thread_id, &nb_nodes,
wait_chain->data(), &is_cycle)) {
if (last_error)
*last_error = ::GetLastError();
if (failure_reason)
*failure_reason = kGetWaitChainFailureReason;
DPLOG(ERROR) << kGetWaitChainFailureReason;
return false;
}
*is_deadlock = is_cycle ? true : false;
wait_chain->resize(nb_nodes);
return true;
}
base::string16 WaitChainNodeToString(const WAITCHAIN_NODE_INFO& node) {
if (node.ObjectType == WctThreadType) {
return base::StringPrintf(L"Thread %d in process %d with status %ls",
node.ThreadObject.ThreadId,
node.ThreadObject.ProcessId,
WctObjectStatusToString(node.ObjectStatus));
} else {
return base::StringPrintf(L"Lock of type %ls with status %ls",
WctObjectTypeToString(node.ObjectType),
WctObjectStatusToString(node.ObjectStatus));
}
}
} // namespace win
} // namespace base
| 27.483444 | 80 | 0.661205 | nctl144 |
a18a3955ba380f57baac4cf7350d64b90aa612bd | 322 | cpp | C++ | app/app_camera/app_camera.cpp | yjf0602/PiApp | 58c34b933be77106a57e15204feb340960f7ee94 | [
"MIT"
] | null | null | null | app/app_camera/app_camera.cpp | yjf0602/PiApp | 58c34b933be77106a57e15204feb340960f7ee94 | [
"MIT"
] | null | null | null | app/app_camera/app_camera.cpp | yjf0602/PiApp | 58c34b933be77106a57e15204feb340960f7ee94 | [
"MIT"
] | null | null | null | #include "app_camera.h"
App_Camera::App_Camera()
{
icon_n = cv::imread(APP_CAMERA_ICON_N);
icon_p = cv::imread(APP_CAMERA_ICON_P);
app_name = "Camera";
printf("camera icon: %d*%d\r\n", icon_n.cols, icon_n.rows);
}
App_Camera::~App_Camera()
{
}
void App_Camera::init()
{
}
void App_Camera::run()
{
}
| 12.88 | 63 | 0.649068 | yjf0602 |
a18a801f26e67cbfdc3e26e2a50c866e66cba1b2 | 3,371 | cpp | C++ | DemoFramework/FslSimpleUI/Base/source/FslSimpleUI/Base/Control/ValueLabel.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 3 | 2019-01-19T20:21:24.000Z | 2021-08-10T02:11:32.000Z | DemoFramework/FslSimpleUI/Base/source/FslSimpleUI/Base/Control/ValueLabel.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslSimpleUI/Base/source/FslSimpleUI/Base/Control/ValueLabel.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-08-10T02:11:33.000Z | 2021-08-10T02:11:33.000Z | /****************************************************************************************************************************************************
* Copyright (c) 2015 Freescale Semiconductor, 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 the Freescale Semiconductor, 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include <FslSimpleUI/Base/Control/ValueLabel.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/Log/Log.hpp>
#include <cassert>
#include <cstdio>
namespace Fsl
{
using namespace std;
namespace UI
{
namespace
{
// -2147483648
// 2147483647
// 000000000011
// 123456789012
const int BUFFER_SIZE = 12;
}
ValueLabel::ValueLabel(const std::shared_ptr<WindowContext>& context)
: LabelBase(context)
{
}
void ValueLabel::SetContent(const int32_t value)
{
if (value != m_content)
{
m_content = value;
// convert to a string
char tmp[BUFFER_SIZE];
#ifdef _WIN32
int charsWritten = sprintf_s(tmp, BUFFER_SIZE, "%d", m_content);
#else
int charsWritten = snprintf(tmp, BUFFER_SIZE, "%d", m_content);
#endif
if (charsWritten < 0 || charsWritten >= BUFFER_SIZE)
throw std::invalid_argument("number conversion failed");
DoSetContent(tmp);
}
}
Vector2 ValueLabel::MeasureRenderedValue(const int32_t value)
{
// convert to a string
char tmp[BUFFER_SIZE];
#ifdef _WIN32
int charsWritten = sprintf_s(tmp, BUFFER_SIZE, "%d", value);
#else
int charsWritten = snprintf(tmp, BUFFER_SIZE, "%d", value);
#endif
if (charsWritten < 0 || charsWritten >= BUFFER_SIZE)
throw std::invalid_argument("number conversion failed");
return DoMeasureRenderedString(tmp);
}
}
}
| 35.114583 | 149 | 0.643726 | alejandrolozano2 |
a18be7c2cee38c65b917be2325016c45e23cc8d7 | 1,393 | cpp | C++ | source/og-core/scenegraph/i3dNodeRender.cpp | OpenWebGlobe/Application-SDK | b819ca8ccb44b70815f6c5332cfb041ea23dab61 | [
"MIT"
] | 4 | 2015-12-20T01:38:05.000Z | 2019-07-02T11:01:29.000Z | source/og-core/scenegraph/i3dNodeRender.cpp | OpenWebGlobe/Application-SDK | b819ca8ccb44b70815f6c5332cfb041ea23dab61 | [
"MIT"
] | null | null | null | source/og-core/scenegraph/i3dNodeRender.cpp | OpenWebGlobe/Application-SDK | b819ca8ccb44b70815f6c5332cfb041ea23dab61 | [
"MIT"
] | 6 | 2015-01-20T09:18:39.000Z | 2021-02-06T08:19:30.000Z | /*******************************************************************************
Project : i3D Studio
Purpose : Begin Render Node
Creation Date : 17.3.2011
Author : Martin Christen
Copyright : Copyright (c) 2011 by FHNW. All rights reserved.
*******************************************************************************/
#include "i3dNodeRender.h"
#include "scenegraph/PickResult.h"
#include <GL/glew.h>
//-----------------------------------------------------------------------------
i3dNodeRender::i3dNodeRender()
: _cbRender(0), _sceneid(-1)
{
_sNodeName = "BeginRender";
_sNodeClassName = "i3dNodeRender";
}
i3dNodeRender::~i3dNodeRender()
{
}
void i3dNodeRender::OnInit()
{
}
void i3dNodeRender::OnExit()
{
}
//------------------------------------------------------------------------------
void i3dNodeRender::OnRender(IRenderEngine* pEngine)
{
// Call Used defined Render Callback...
if (_cbRender && _sceneid != -1)
{
_cbRender(_sceneid);
}
}
//------------------------------------------------------------------------------
void i3dNodeRender::OnTraverse(TraversalState& oTrav)
{
}
//------------------------------------------------------------------------------
void i3dNodeRender::OnChangeState(IRenderEngine* pEngine)
{
}
//------------------------------------------------------------------------------
| 21.765625 | 80 | 0.401292 | OpenWebGlobe |
a190e9254ddffb21b15b34bf39da3111946d4064 | 2,060 | cpp | C++ | clients/cpp-tiny/generated/lib/Models/GithubRespositoryContainer.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/cpp-tiny/generated/lib/Models/GithubRespositoryContainer.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/cpp-tiny/generated/lib/Models/GithubRespositoryContainer.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null |
#include "GithubRespositoryContainer.h"
using namespace Tiny;
GithubRespositoryContainer::GithubRespositoryContainer()
{
_class = std::string();
_links = GithubRespositoryContainerlinks();
repositories = GithubRepositories();
}
GithubRespositoryContainer::GithubRespositoryContainer(std::string jsonString)
{
this->fromJson(jsonString);
}
GithubRespositoryContainer::~GithubRespositoryContainer()
{
}
void
GithubRespositoryContainer::fromJson(std::string jsonObj)
{
bourne::json object = bourne::json::parse(jsonObj);
const char *_classKey = "_class";
if(object.has_key(_classKey))
{
bourne::json value = object[_classKey];
jsonToValue(&_class, value, "std::string");
}
const char *_linksKey = "_links";
if(object.has_key(_linksKey))
{
bourne::json value = object[_linksKey];
GithubRespositoryContainerlinks* obj = &_links;
obj->fromJson(value.dump());
}
const char *repositoriesKey = "repositories";
if(object.has_key(repositoriesKey))
{
bourne::json value = object[repositoriesKey];
GithubRepositories* obj = &repositories;
obj->fromJson(value.dump());
}
}
bourne::json
GithubRespositoryContainer::toJson()
{
bourne::json object = bourne::json::object();
object["_class"] = getClass();
object["_links"] = getLinks().toJson();
object["repositories"] = getRepositories().toJson();
return object;
}
std::string
GithubRespositoryContainer::getClass()
{
return _class;
}
void
GithubRespositoryContainer::setClass(std::string _class)
{
this->_class = _class;
}
GithubRespositoryContainerlinks
GithubRespositoryContainer::getLinks()
{
return _links;
}
void
GithubRespositoryContainer::setLinks(GithubRespositoryContainerlinks _links)
{
this->_links = _links;
}
GithubRepositories
GithubRespositoryContainer::getRepositories()
{
return repositories;
}
void
GithubRespositoryContainer::setRepositories(GithubRepositories repositories)
{
this->repositories = repositories;
}
| 14.507042 | 78 | 0.712621 | cliffano |
a191addd7d3e0e32781fb7b435df1c346baf5f92 | 318 | cpp | C++ | main.cpp | procedural/redgpu_info | 6c2d07f1d0e418a7de983e0278e3c370954a7eed | [
"Apache-2.0"
] | null | null | null | main.cpp | procedural/redgpu_info | 6c2d07f1d0e418a7de983e0278e3c370954a7eed | [
"Apache-2.0"
] | null | null | null | main.cpp | procedural/redgpu_info | 6c2d07f1d0e418a7de983e0278e3c370954a7eed | [
"Apache-2.0"
] | null | null | null | #ifdef _WIN32
#include "C:/RedGpuSDK/redgpu.h"
#endif
#ifdef __linux__
#include "/opt/RedGpuSDK/redgpu.h"
#endif
#include <stdlib.h> // For malloc, free
int main() {
RedContext context = 0;
redCreateContext(malloc, free, 0, 0, 0, RED_SDK_VERSION_1_0_135, 0, 0, 0, 0, 0, 0, 0, &context, 0, 0, 0, 0);
} | 24.461538 | 111 | 0.650943 | procedural |
084b2481ea4f85f1b5b00829903e8eafa29fce5a | 4,438 | cc | C++ | chrome/browser/ui/webui/options/options_ui_browsertest.cc | iplo/Chain | 8bc8943d66285d5258fffc41bed7c840516c4422 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | chrome/browser/ui/webui/options/options_ui_browsertest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | chrome/browser/ui/webui/options/options_ui_browsertest.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2012 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 "chrome/browser/ui/webui/options/options_ui_browsertest.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#if !defined(OS_CHROMEOS)
#include <string>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/run_loop.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_commands.h"
#include "content/public/test/test_navigation_observer.h"
#include "ui/base/window_open_disposition.h"
#include "url/gurl.h"
#endif
namespace options {
namespace {
#if !defined(OS_CHROMEOS)
void RunClosureWhenProfileInitialized(const base::Closure& closure,
Profile* profile,
Profile::CreateStatus status) {
if (status == Profile::CREATE_STATUS_INITIALIZED)
closure.Run();
}
#endif
} // namespace
OptionsUIBrowserTest::OptionsUIBrowserTest() {
}
void OptionsUIBrowserTest::NavigateToSettings() {
const GURL& url = GURL(chrome::kChromeUISettingsURL);
ui_test_utils::NavigateToURL(browser(), url);
}
void OptionsUIBrowserTest::VerifyNavbar() {
bool navbar_exist = false;
EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
browser()->tab_strip_model()->GetActiveWebContents(),
"domAutomationController.send("
" !!document.getElementById('navigation'))",
&navbar_exist));
EXPECT_EQ(true, navbar_exist);
}
void OptionsUIBrowserTest::VerifyTitle() {
base::string16 title =
browser()->tab_strip_model()->GetActiveWebContents()->GetTitle();
base::string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
EXPECT_NE(title.find(expected_title), base::string16::npos);
}
// Flaky, see http://crbug.com/119671.
IN_PROC_BROWSER_TEST_F(OptionsUIBrowserTest, DISABLED_LoadOptionsByURL) {
NavigateToSettings();
VerifyTitle();
VerifyNavbar();
}
#if !defined(OS_CHROMEOS)
// Regression test for http://crbug.com/301436, excluded on Chrome OS because
// profile management in the settings UI exists on desktop platforms only.
IN_PROC_BROWSER_TEST_F(OptionsUIBrowserTest, NavigateBackFromOverlayDialog) {
// Navigate to the settings page.
ui_test_utils::NavigateToURL(browser(), GURL("chrome://settings-frame"));
// Click a button that opens an overlay dialog.
content::WebContents* contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(content::ExecuteScript(
contents, "$('manage-default-search-engines').click();"));
// Go back to the settings page.
content::TestNavigationObserver observer(contents);
chrome::GoBack(browser(), CURRENT_TAB);
observer.Wait();
// Verify that the settings page lists one profile.
const char javascript[] =
"domAutomationController.send("
" document.querySelectorAll('list#profiles-list > div[role=listitem]')"
" .length);";
int profiles;
ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
contents, javascript, &profiles));
EXPECT_EQ(1, profiles);
// Create a second profile.
ProfileManager* profile_manager = g_browser_process->profile_manager();
const base::FilePath profile_path =
profile_manager->GenerateNextProfileDirectoryPath();
base::RunLoop run_loop;
profile_manager->CreateProfileAsync(
profile_manager->GenerateNextProfileDirectoryPath(),
base::Bind(&RunClosureWhenProfileInitialized,
run_loop.QuitClosure()),
base::string16(),
base::string16(),
std::string());
run_loop.Run();
// Verify that the settings page has updated and lists two profiles.
ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
contents, javascript, &profiles));
EXPECT_EQ(2, profiles);
}
#endif
} // namespace options
| 33.368421 | 80 | 0.728256 | iplo |
084d60ef1459f29bc6ae251359805bcfc4549c95 | 11,448 | cpp | C++ | symengine/tests/polynomial/test_uratpoly_flint.cpp | jmig5776/symengine | 03babc5c56b047b2fe81ef6f8391d1845e6bb66c | [
"MIT"
] | 11 | 2020-02-15T23:54:19.000Z | 2020-11-28T12:45:45.000Z | symengine/tests/polynomial/test_uratpoly_flint.cpp | HQSquantumsimulations/symengine | 95d6af92dc6a759d9320d6bdadfa51d038c81218 | [
"MIT"
] | 11 | 2015-07-18T04:13:48.000Z | 2017-06-08T07:05:14.000Z | symengine/tests/polynomial/test_uratpoly_flint.cpp | HQSquantumsimulations/symengine | 95d6af92dc6a759d9320d6bdadfa51d038c81218 | [
"MIT"
] | 1 | 2020-09-10T13:08:39.000Z | 2020-09-10T13:08:39.000Z | #include "catch.hpp"
#include <chrono>
#include <symengine/polys/uintpoly_flint.h>
#include <symengine/polys/uintpoly_piranha.h>
#include <symengine/polys/uratpoly.h>
#include <symengine/polys/uintpoly.h>
#include <symengine/pow.h>
#include <symengine/symengine_exception.h>
#ifdef HAVE_SYMENGINE_PIRANHA
using SymEngine::URatPolyPiranha;
#endif
using SymEngine::SymEngineException;
using SymEngine::URatPolyFlint;
using SymEngine::URatPoly;
using SymEngine::UIntPoly;
using SymEngine::Symbol;
using SymEngine::symbol;
using SymEngine::Pow;
using SymEngine::RCP;
using SymEngine::make_rcp;
using SymEngine::print_stack_on_segfault;
using SymEngine::map_uint_mpq;
using SymEngine::Basic;
using SymEngine::one;
using SymEngine::zero;
using SymEngine::integer;
using SymEngine::rational_class;
using SymEngine::add;
using namespace SymEngine::literals;
using rc = rational_class;
TEST_CASE("Constructor of URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> P
= URatPolyFlint::from_dict(x, {{0, rc(1_z, 2_z)}, {2, rc(3_z, 2_z)}});
REQUIRE(P->__str__() == "3/2*x**2 + 1/2");
RCP<const URatPolyFlint> Q
= URatPolyFlint::from_vec(x, {0_q, rc(1_z, 2_z), rc(1_z, 2_z)});
REQUIRE(Q->__str__() == "1/2*x**2 + 1/2*x");
RCP<const URatPolyFlint> S = URatPolyFlint::from_dict(x, {{0, 2_q}});
REQUIRE(S->__str__() == "2");
RCP<const URatPolyFlint> T = URatPolyFlint::from_dict(x, map_uint_mpq{});
REQUIRE(T->__str__() == "0");
}
TEST_CASE("Adding two URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const Symbol> y = symbol("y");
RCP<const URatPolyFlint> a = URatPolyFlint::from_dict(
x, {{0, rc(1_z, 2_z)}, {1, rc(2_z, 3_z)}, {2, 1_q}});
RCP<const URatPolyFlint> b
= URatPolyFlint::from_dict(x, {{0, rc(2_z, 3_z)}, {1, 3_q}, {2, 2_q}});
RCP<const Basic> c = add_upoly(*a, *b);
REQUIRE(c->__str__() == "3*x**2 + 11/3*x + 7/6");
RCP<const URatPolyFlint> d
= URatPolyFlint::from_dict(x, {{0, rc(1_z, 2_z)}});
RCP<const Basic> e = add_upoly(*a, *d);
RCP<const Basic> f = add_upoly(*d, *a);
REQUIRE(e->__str__() == "x**2 + 2/3*x + 1");
REQUIRE(f->__str__() == "x**2 + 2/3*x + 1");
RCP<const URatPolyFlint> g = URatPolyFlint::from_dict(
y, {{0, 2_q}, {1, rc(-3_z, 2_z)}, {2, rc(1_z, 4_z)}});
CHECK_THROWS_AS(add_upoly(*a, *g), SymEngineException &);
}
TEST_CASE("Negative of a URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a
= URatPolyFlint::from_dict(x, {{0, rc(-1_z, 2_z)}, {1, 2_q}, {2, 3_q}});
RCP<const URatPolyFlint> b = neg_upoly(*a);
REQUIRE(b->__str__() == "-3*x**2 - 2*x + 1/2");
}
TEST_CASE("Subtracting two URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const Symbol> y = symbol("y");
RCP<const URatPolyFlint> a = URatPolyFlint::from_dict(
x, {{0, rc(1_z, 2_z)}, {1, rc(2_z, 3_z)}, {2, 1_q}});
RCP<const URatPolyFlint> b
= URatPolyFlint::from_dict(x, {{0, rc(2_z, 3_z)}, {1, 3_q}, {2, 2_q}});
RCP<const URatPolyFlint> c = URatPolyFlint::from_dict(
x, {{0, 2_q}, {1, rc(-3_z, 2_z)}, {2, rc(1_z, 4_z)}});
RCP<const URatPolyFlint> f = URatPolyFlint::from_dict(y, {{0, 2_q}});
RCP<const Basic> d = sub_upoly(*b, *a);
REQUIRE(d->__str__() == "x**2 + 7/3*x + 1/6");
d = sub_upoly(*c, *a);
REQUIRE(d->__str__() == "-3/4*x**2 - 13/6*x + 3/2");
d = sub_upoly(*a, *c);
REQUIRE(d->__str__() == "3/4*x**2 + 13/6*x - 3/2");
CHECK_THROWS_AS(sub_upoly(*a, *f), SymEngineException &);
}
TEST_CASE("Multiplication of two URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const Symbol> y = symbol("y");
RCP<const URatPolyFlint> a = URatPolyFlint::from_dict(
x, {{0, rc(1_z, 2_z)}, {1, rc(2_z, 3_z)}, {2, 1_q}});
RCP<const URatPolyFlint> b
= URatPolyFlint::from_dict(x, {{0, rc(2_z, 3_z)}, {1, 3_q}, {2, 2_q}});
RCP<const URatPolyFlint> e = URatPolyFlint::from_dict(
x, {{0, 2_q}, {1, rc(-3_z, 2_z)}, {2, rc(1_z, 4_z)}});
RCP<const URatPolyFlint> f
= URatPolyFlint::from_dict(x, {{0, 1_q}, {1, rc(1_z, 2_z)}});
RCP<const URatPolyFlint> c = mul_upoly(*a, *a);
RCP<const URatPolyFlint> d = mul_upoly(*a, *b);
RCP<const URatPolyFlint> g = mul_upoly(*e, *e);
RCP<const URatPolyFlint> h = mul_upoly(*e, *f);
RCP<const URatPolyFlint> i = mul_upoly(*f, *f);
REQUIRE(c->__str__() == "x**4 + 4/3*x**3 + 13/9*x**2 + 2/3*x + 1/4");
REQUIRE(d->__str__() == "2*x**4 + 13/3*x**3 + 11/3*x**2 + 35/18*x + 1/3");
REQUIRE(g->__str__() == "1/16*x**4 - 3/4*x**3 + 13/4*x**2 - 6*x + 4");
REQUIRE(h->__str__() == "1/8*x**3 - 1/2*x**2 - 1/2*x + 2");
REQUIRE(i->__str__() == "1/4*x**2 + x + 1");
c = URatPolyFlint::from_dict(x, {{0, rc(-1_z)}});
REQUIRE(mul_upoly(*a, *c)->__str__() == "-x**2 - 2/3*x - 1/2");
REQUIRE(mul_upoly(*c, *a)->__str__() == "-x**2 - 2/3*x - 1/2");
c = URatPolyFlint::from_dict(y, {{0, rc(-1_z)}});
CHECK_THROWS_AS(mul_upoly(*a, *c), SymEngineException &);
}
TEST_CASE("Comparing two URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const Symbol> y = symbol("y");
RCP<const URatPolyFlint> P
= URatPolyFlint::from_dict(x, {{0, 1_q}, {1, rc(2_z, 3_z)}});
RCP<const URatPolyFlint> Q
= URatPolyFlint::from_dict(x, {{0, 1_q}, {1, 2_q}, {2, 1_q}});
REQUIRE(P->compare(*Q) == -1);
P = URatPolyFlint::from_dict(x, {{0, 1_q}, {1, 2_q}, {2, 3_q}, {3, 2_q}});
REQUIRE(P->compare(*Q) == 1);
P = URatPolyFlint::from_dict(x, {{0, 1_q}, {1, 2_q}, {2, 1_q}});
REQUIRE(P->compare(*Q) == 0);
P = URatPolyFlint::from_dict(y, {{0, 1_q}, {1, rc(2_z, 3_z)}});
REQUIRE(P->compare(*Q) == -1);
}
TEST_CASE("URatPolyFlint as_symbolic", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a
= URatPolyFlint::from_dict(x, {{0, rc(1_z, 2_z)}, {1, 2_q}, {2, 1_q}});
REQUIRE(eq(
*a->as_symbolic(),
*add({div(one, integer(2)), mul(integer(2), x), pow(x, integer(2))})));
RCP<const URatPolyFlint> b
= URatPolyFlint::from_dict(x, {{1, rc(3_z, 2_z)}, {2, 2_q}});
REQUIRE(eq(*b->as_symbolic(), *add(mul(x, div(integer(3), integer(2))),
mul(integer(2), pow(x, integer(2))))));
RCP<const URatPolyFlint> c = URatPolyFlint::from_dict(x, map_uint_mpq{});
REQUIRE(eq(*c->as_symbolic(), *zero));
}
TEST_CASE("Evaluation of URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a
= URatPolyFlint::from_dict(x, {{0, 1_q}, {1, rc(2_z, 3_z)}});
RCP<const URatPolyFlint> b = URatPolyFlint::from_dict(
x, {{0, rc(1_z, 2_z)}, {1, rc(2_z, 5_z)}, {2, 1_q}});
REQUIRE(a->eval(2_q) == rc(7_z, 3_z));
REQUIRE(a->eval(10_q) == rc(23_z, 3_z));
REQUIRE(b->eval(-1_q) == rc(11_z, 10_z));
REQUIRE(b->eval(0_q) == rc(1_z, 2_z));
std::vector<rational_class> resa = {rc(7_z, 3_z), rc(5_z, 3_z), 1_q};
std::vector<rational_class> resb
= {rc(53_z, 10_z), rc(19_z, 10_z), rc(1_z, 2_z)};
REQUIRE(a->multieval({2_q, 1_q, 0_q}) == resa);
REQUIRE(b->multieval({2_q, 1_q, 0_q}) == resb);
}
TEST_CASE("Derivative of URatPolyFlint", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const Symbol> y = symbol("y");
RCP<const URatPolyFlint> a = URatPolyFlint::from_dict(
x, {{0, 1_q}, {1, rc(2_z, 3_z)}, {2, rc(1_z, 2_z)}});
RCP<const URatPolyFlint> b
= URatPolyFlint::from_dict(y, {{2, rc(4_z, 3_z)}});
REQUIRE(a->diff(x)->__str__() == "x + 2/3");
REQUIRE(a->diff(y)->__str__() == "0");
REQUIRE(b->diff(y)->__str__() == "8/3*y");
}
TEST_CASE("URatPolyFlint pow", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a
= URatPolyFlint::from_dict(x, {{0, rc(1_z, 2_z)}, {1, 1_q}});
RCP<const URatPolyFlint> b
= URatPolyFlint::from_dict(x, {{0, 3_q}, {2, rc(3_z, 2_z)}});
RCP<const URatPolyFlint> aaa = pow_upoly(*a, 3);
RCP<const URatPolyFlint> bb = pow_upoly(*b, 2);
REQUIRE(aaa->__str__() == "x**3 + 3/2*x**2 + 3/4*x + 1/8");
REQUIRE(bb->__str__() == "9/4*x**4 + 9*x**2 + 9");
}
TEST_CASE("URatPolyFlint divides", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a
= URatPolyFlint::from_dict(x, {{0, 1_q}, {1, 1_q}});
RCP<const URatPolyFlint> b = URatPolyFlint::from_dict(x, {{0, 4_q}});
RCP<const URatPolyFlint> c
= URatPolyFlint::from_dict(x, {{0, 8_q}, {1, 8_q}});
RCP<const URatPolyFlint> res;
REQUIRE(divides_upoly(*a, *c, outArg(res)));
REQUIRE(res->__str__() == "8");
REQUIRE(divides_upoly(*b, *c, outArg(res)));
REQUIRE(res->__str__() == "2*x + 2");
REQUIRE(divides_upoly(*b, *a, outArg(res)));
REQUIRE(res->__str__() == "1/4*x + 1/4");
REQUIRE(!divides_upoly(*a, *b, outArg(res)));
}
TEST_CASE("URatPolyFlint gcd", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a = URatPolyFlint::from_dict(x, {{2, 2_q}});
RCP<const URatPolyFlint> b = URatPolyFlint::from_dict(x, {{1, 3_q}});
RCP<const URatPolyFlint> c
= URatPolyFlint::from_dict(x, {{0, 6_q}, {1, 8_q}, {2, 2_q}});
RCP<const URatPolyFlint> d
= URatPolyFlint::from_dict(x, {{1, 4_q}, {2, 4_q}});
RCP<const URatPolyFlint> ab = gcd_upoly(*a, *b);
RCP<const URatPolyFlint> cd = gcd_upoly(*c, *d);
RCP<const URatPolyFlint> ad = gcd_upoly(*a, *d);
RCP<const URatPolyFlint> bc = gcd_upoly(*b, *c);
REQUIRE(ab->__str__() == "x");
REQUIRE(cd->__str__() == "x + 1");
REQUIRE(ad->__str__() == "x");
REQUIRE(bc->__str__() == "1");
// https://github.com/wbhart/flint2/issues/276
}
TEST_CASE("URatPolyFlint lcm", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyFlint> a = URatPolyFlint::from_dict(x, {{2, 6_q}});
RCP<const URatPolyFlint> b = URatPolyFlint::from_dict(x, {{1, 8_q}});
RCP<const URatPolyFlint> c
= URatPolyFlint::from_dict(x, {{0, 8_q}, {1, 8_q}});
RCP<const URatPolyFlint> ab = lcm_upoly(*a, *b);
RCP<const URatPolyFlint> bc = lcm_upoly(*b, *c);
RCP<const URatPolyFlint> ac = lcm_upoly(*a, *c);
REQUIRE(ab->__str__() == "x**2");
REQUIRE(bc->__str__() == "x**2 + x");
REQUIRE(ac->__str__() == "x**3 + x**2");
}
TEST_CASE("URatPolyFlint from_poly symengine", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const UIntPoly> a = UIntPoly::from_dict(x, {{0, 1_z}, {2, 1_z}});
RCP<const URatPolyFlint> b = URatPolyFlint::from_poly(*a);
RCP<const URatPoly> c
= URatPoly::from_dict(x, {{0, rc(1_z, 2_z)}, {2, rc(3_z, 2_z)}});
RCP<const URatPolyFlint> d = URatPolyFlint::from_poly(*c);
REQUIRE(b->__str__() == "x**2 + 1");
REQUIRE(d->__str__() == "3/2*x**2 + 1/2");
}
#ifdef HAVE_SYMENGINE_PIRANHA
TEST_CASE("URatPolyFlint from_poly piranha", "[URatPolyFlint]")
{
RCP<const Symbol> x = symbol("x");
RCP<const URatPolyPiranha> a
= URatPolyPiranha::from_dict(x, {{0, rc(1_z, 2_z)}, {2, rc(3_z, 2_z)}});
RCP<const URatPolyFlint> b = URatPolyFlint::from_poly(*a);
REQUIRE(b->__str__() == "3/2*x**2 + 1/2");
}
#endif | 36.342857 | 80 | 0.593117 | jmig5776 |
0853954cb326f342415182b6f9e82f3edbfa08d9 | 1,080 | cpp | C++ | runtime/helpers/dispatch_info.cpp | FelipeMLopez/compute-runtime | 3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8 | [
"MIT"
] | 3 | 2019-09-20T23:26:36.000Z | 2019-10-03T17:44:12.000Z | runtime/helpers/dispatch_info.cpp | FelipeMLopez/compute-runtime | 3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8 | [
"MIT"
] | null | null | null | runtime/helpers/dispatch_info.cpp | FelipeMLopez/compute-runtime | 3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8 | [
"MIT"
] | 3 | 2019-05-16T07:22:51.000Z | 2019-11-11T03:05:32.000Z | /*
* Copyright (C) 2017-2019 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "runtime/helpers/dispatch_info.h"
#include "runtime/kernel/kernel.h"
namespace NEO {
bool DispatchInfo::usesSlm() const {
return (kernel == nullptr) ? false : kernel->slmTotalSize > 0;
}
bool DispatchInfo::usesStatelessPrintfSurface() const {
return (kernel == nullptr) ? false : (kernel->getKernelInfo().patchInfo.pAllocateStatelessPrintfSurface != nullptr);
}
uint32_t DispatchInfo::getRequiredScratchSize() const {
return (kernel == nullptr) ? 0 : kernel->getScratchSize();
}
uint32_t DispatchInfo::getRequiredPrivateScratchSize() const {
return (kernel == nullptr) ? 0 : kernel->getPrivateScratchSize();
}
Kernel *MultiDispatchInfo::peekMainKernel() const {
if (dispatchInfos.size() == 0) {
return nullptr;
}
return mainKernel ? mainKernel : dispatchInfos.begin()->getKernel();
}
Kernel *MultiDispatchInfo::peekParentKernel() const {
return (mainKernel && mainKernel->isParentKernel) ? mainKernel : nullptr;
}
} // namespace NEO
| 27 | 120 | 0.712037 | FelipeMLopez |
085af273d77f94edc1ca0279099a1745e38223b5 | 59,217 | cpp | C++ | pegasus/src/Pegasus/Server/HTTPAuthenticatorDelegator.cpp | maciejkotSW/OpenPegasus | cda54c82ef53fd00cd6be98b1d34518b51c823a4 | [
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | pegasus/src/Pegasus/Server/HTTPAuthenticatorDelegator.cpp | maciejkotSW/OpenPegasus | cda54c82ef53fd00cd6be98b1d34518b51c823a4 | [
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | pegasus/src/Pegasus/Server/HTTPAuthenticatorDelegator.cpp | maciejkotSW/OpenPegasus | cda54c82ef53fd00cd6be98b1d34518b51c823a4 | [
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/AuditLogger.h>
#include <Pegasus/Common/Constants.h>
#include <Pegasus/Common/XmlWriter.h>
#include <Pegasus/Common/Thread.h>
#include <Pegasus/Common/MessageLoader.h>
#include <Pegasus/Common/FileSystem.h>
#include <Pegasus/Common/LanguageParser.h>
#include <Pegasus/Config/ConfigManager.h>
#include "HTTPAuthenticatorDelegator.h"
#ifdef PEGASUS_ZOS_SECURITY
// This include file will not be provided in the OpenGroup CVS for now.
// Do NOT try to include it in your compile
# include <Pegasus/Common/safCheckzOS_inline.h>
#endif
#ifdef PEGASUS_OS_ZOS
# include <sys/ps.h>
#endif
PEGASUS_USING_STD;
PEGASUS_NAMESPACE_BEGIN
static const String _HTTP_VERSION_1_0 = "HTTP/1.0";
static const String _HTTP_METHOD_MPOST = "M-POST";
static const String _HTTP_METHOD = "POST";
#ifdef PEGASUS_ENABLE_PROTOCOL_WEB
static const String _HTTP_METHOD_GET = "GET";
static const String _HTTP_METHOD_HEAD = "HEAD";
#endif /* #ifdef PEGASUS_ENABLE_PROTOCOL_WEB */
static const char* _HTTP_HEADER_CIMEXPORT = "CIMExport";
static const char* _HTTP_HEADER_CONNECTION = "Connection";
static const char* _HTTP_HEADER_CIMOPERATION = "CIMOperation";
static const char* _HTTP_HEADER_ACCEPT_LANGUAGE = "Accept-Language";
static const char* _HTTP_HEADER_CONTENT_LANGUAGE = "Content-Language";
static const char* _HTTP_HEADER_AUTHORIZATION = "Authorization";
static const char* _HTTP_HEADER_PEGASUSAUTHORIZATION = "PegasusAuthorization";
static const String _CONFIG_PARAM_ENABLEAUTHENTICATION = "enableAuthentication";
static const char _COOKIE_NAME[] = "PEGASUS_SID";
HTTPAuthenticatorDelegator::HTTPAuthenticatorDelegator(
Uint32 cimOperationMessageQueueId,
Uint32 cimExportMessageQueueId,
CIMRepository* repository)
: Base(PEGASUS_QUEUENAME_HTTPAUTHDELEGATOR),
_cimOperationMessageQueueId(cimOperationMessageQueueId),
_cimExportMessageQueueId(cimExportMessageQueueId),
_wsmanOperationMessageQueueId(PEG_NOT_FOUND),
_rsOperationMessageQueueId(PEG_NOT_FOUND),
#ifdef PEGASUS_ENABLE_PROTOCOL_WEB
_webOperationMessageQueueId(PEG_NOT_FOUND),
#endif
_repository(repository)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::HTTPAuthenticatorDelegator");
_authenticationManager.reset(new AuthenticationManager());
#ifdef PEGASUS_ENABLE_SESSION_COOKIES
_sessions.reset(new HTTPSessionList());
#endif
PEG_METHOD_EXIT();
}
HTTPAuthenticatorDelegator::~HTTPAuthenticatorDelegator()
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::~HTTPAuthenticatorDelegator");
PEG_METHOD_EXIT();
}
void HTTPAuthenticatorDelegator::enqueue(Message* message)
{
handleEnqueue(message);
}
void HTTPAuthenticatorDelegator::_sendResponse(
Uint32 queueId,
Buffer& message,
Boolean closeConnect)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::_sendResponse");
MessageQueue* queue = MessageQueue::lookup(queueId);
if (queue)
{
HTTPMessage* httpMessage = new HTTPMessage(message);
httpMessage->dest = queue->getQueueId();
httpMessage->setCloseConnect(closeConnect);
queue->enqueue(httpMessage);
}
PEG_METHOD_EXIT();
}
void HTTPAuthenticatorDelegator::_sendChallenge(
Uint32 queueId,
const String& errorDetail,
const String& authResponse,
Boolean closeConnect)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::_sendChallenge");
//
// build unauthorized (401) response message
//
Buffer message;
XmlWriter::appendUnauthorizedResponseHeader(
message,
errorDetail,
authResponse);
_sendResponse(queueId, message,closeConnect);
PEG_METHOD_EXIT();
}
void HTTPAuthenticatorDelegator::_sendHttpError(
Uint32 queueId,
const String& status,
const String& cimError,
const String& pegasusError,
Boolean closeConnect)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::_sendHttpError");
//
// build error response message
//
Buffer message;
message = XmlWriter::formatHttpErrorRspMessage(
status,
cimError,
pegasusError);
_sendResponse(queueId, message,closeConnect);
PEG_METHOD_EXIT();
}
void HTTPAuthenticatorDelegator::handleEnqueue(Message *message)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::handleEnqueue");
if (!message)
{
PEG_METHOD_EXIT();
return;
}
// Flag indicating whether the message should be deleted after handling.
// This should be set to false by handleHTTPMessage when the message is
// passed as is to another queue.
Boolean deleteMessage = true;
try
{
if (message->getType() == HTTP_MESSAGE)
{
handleHTTPMessage((HTTPMessage*)message, deleteMessage);
}
}
catch (...)
{
if (deleteMessage)
{
PEG_TRACE_CSTRING(TRC_HTTP, Tracer::LEVEL4,
"Exception caught, deleting Message in "
"HTTPAuthenticator::handleEnqueue");
delete message;
}
throw;
}
if (deleteMessage)
{
PEG_TRACE_CSTRING(TRC_HTTP, Tracer::LEVEL4,
"Deleting Message in HTTPAuthenticator::handleEnqueue");
delete message;
}
PEG_METHOD_EXIT();
}
void HTTPAuthenticatorDelegator::handleEnqueue()
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::handleEnqueue");
Message* message = dequeue();
if (message)
{
handleEnqueue(message);
}
PEG_METHOD_EXIT();
}
void HTTPAuthenticatorDelegator::handleHTTPMessage(
HTTPMessage* httpMessage,
Boolean& deleteMessage)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::handleHTTPMessage");
PEGASUS_ASSERT(httpMessage->message.size() != 0);
deleteMessage = true;
//
// Save queueId:
//
Uint32 queueId = httpMessage->queueId;
//
// Parse the HTTP message:
//
String startLine;
Array<HTTPHeader> headers;
Uint32 contentLength;
Boolean closeConnect = false;
//
// Process M-POST and POST messages:
//
PEG_TRACE_CSTRING(
TRC_HTTP,
Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - HTTP processing start");
// parse the received HTTPMessage
// parse function will return false if more than PEGASUS_MAXELEMENTS_NUM
// headers were detected in the message
if (!httpMessage->parse(startLine, headers, contentLength))
{
throw TooManyHTTPHeadersException();
}
//
// Check for Connection: Close
//
const char* connectClose;
if (HTTPMessage::lookupHeader(
headers, _HTTP_HEADER_CONNECTION, connectClose, false))
{
if (System::strcasecmp(connectClose, "Close") == 0)
{
PEG_TRACE_CSTRING(TRC_HTTP, Tracer::LEVEL3,
"Header in HTTP Message Contains a Connection: Close");
closeConnect = true;
httpMessage->setCloseConnect(closeConnect);
}
}
//
// Check and set languages
//
AcceptLanguageList acceptLanguages;
ContentLanguageList contentLanguages;
try
{
// Get and validate the Accept-Language header, if set
String acceptLanguageHeader;
if (HTTPMessage::lookupHeader(
headers,
_HTTP_HEADER_ACCEPT_LANGUAGE,
acceptLanguageHeader,
false))
{
acceptLanguages = LanguageParser::parseAcceptLanguageHeader(
acceptLanguageHeader);
httpMessage->acceptLanguagesDecoded = true;
}
// Get and validate the Content-Language header, if set
String contentLanguageHeader;
if (HTTPMessage::lookupHeader(
headers,
_HTTP_HEADER_CONTENT_LANGUAGE,
contentLanguageHeader,
false))
{
contentLanguages = LanguageParser::parseContentLanguageHeader(
contentLanguageHeader);
httpMessage->contentLanguagesDecoded = true;
}
}
catch (Exception& e)
{
// clear any existing languages to force messages to come from the
// root bundle
Thread::clearLanguages();
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator.REQUEST_NOT_VALID",
"request-not-valid");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
msg,
e.getMessage(),
closeConnect);
PEG_METHOD_EXIT();
return;
}
Thread::setLanguages(acceptLanguages);
httpMessage->acceptLanguages = acceptLanguages;
httpMessage->contentLanguages = contentLanguages;
//
// Parse the request line:
//
String methodName;
String requestUri;
String httpVersion;
HTTPMessage::parseRequestLine(
startLine, methodName, requestUri, httpVersion);
//
// Set HTTP method for the request
//
HttpMethod httpMethod = HTTP_METHOD__POST;
if (methodName == _HTTP_METHOD_MPOST)
{
httpMethod = HTTP_METHOD_M_POST;
}
#ifdef PEGASUS_ENABLE_PROTOCOL_WEB
else if (methodName == _HTTP_METHOD_GET)
{
httpMethod = HTTP_METHOD_GET;
}
else if (methodName == _HTTP_METHOD_HEAD)
{
httpMethod = HTTP_METHOD_HEAD;
}
#endif
if (httpMethod != HTTP_METHOD__POST && httpMethod != HTTP_METHOD_M_POST
#ifdef PEGASUS_ENABLE_PROTOCOL_WEB
&& httpMethod != HTTP_METHOD_GET && httpMethod != HTTP_METHOD_HEAD
#endif
)
{
//
// M-POST method is not valid with version 1.0
//
_sendHttpError(
queueId,
HTTP_STATUS_NOTIMPLEMENTED,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
}
if ((httpMethod == HTTP_METHOD_M_POST) &&
(httpVersion == _HTTP_VERSION_1_0))
{
//
// M-POST method is not valid with version 1.0
//
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
}
PEG_TRACE_CSTRING(
TRC_AUTHENTICATION,
Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - Authentication processing start");
//
// Handle authentication:
//
ConfigManager* configManager = ConfigManager::getInstance();
Boolean enableAuthentication =
ConfigManager::parseBooleanValue(configManager->getCurrentValue(
_CONFIG_PARAM_ENABLEAUTHENTICATION));
AuthenticationStatus authStatus(AUTHSC_UNAUTHORIZED);
if (httpMessage->authInfo->isConnectionAuthenticated())
{
authStatus = AuthenticationStatus(AUTHSC_SUCCESS);
}
if (enableAuthentication)
{
#ifdef PEGASUS_ENABLE_SESSION_COOKIES
// Find cookie and check if we know it
String cookieHdr;
if (!authStatus.isSuccess() && _sessions->cookiesEnabled()
&& httpMessage->lookupHeader(headers, "Cookie", cookieHdr))
{
String userName;
String cookie;
if (httpMessage->parseCookieHeader(cookieHdr, _COOKIE_NAME, cookie)
&& _sessions->isAuthenticated(cookie,
httpMessage->ipAddress, userName))
{
authStatus = AuthenticationStatus(AUTHSC_SUCCESS);
httpMessage->authInfo->setAuthenticatedUser(userName);
httpMessage->authInfo->setAuthType(
AuthenticationInfoRep::AUTH_TYPE_COOKIE);
}
}
#endif
if (authStatus.isSuccess())
{
if (httpMessage->authInfo->getAuthType()==
AuthenticationInfoRep::AUTH_TYPE_SSL)
{
// Get the user name associated with the certificate (using the
// certificate chain, if necessary).
String certUserName;
String issuerName;
String subjectName;
char serialNumber[32];
PEG_TRACE_CSTRING(TRC_HTTP, Tracer::LEVEL3,
"Client was authenticated via trusted SSL certificate.");
String trustStore =
configManager->getCurrentValue("sslTrustStore");
if (FileSystem::isDirectory(
ConfigManager::getHomedPath(trustStore)))
{
PEG_TRACE_CSTRING(TRC_HTTP, Tracer::LEVEL4,
"Truststore is a directory, lookup username");
// Get the client certificate chain to determine the
// correct username mapping. Starting with the peer
// certificate, work your way up the chain towards the
// root certificate until a match is found in the
// repository.
Array<SSLCertificateInfo*> clientCertificateChain =
httpMessage->authInfo->getClientCertificateChain();
SSLCertificateInfo* clientCertificate = NULL;
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"Client certificate chain length: %d.",
clientCertificateChain.size()));
Uint32 loopCount = clientCertificateChain.size() - 1;
for (Uint32 i = 0; i <= loopCount ; i++)
{
clientCertificate = clientCertificateChain[i];
if (clientCertificate == NULL)
{
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"BAD_CERTIFICATE",
"The certificate used for authentication is "
"not valid.");
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
MessageLoader::getMessage(msgParms),
closeConnect);
PEG_METHOD_EXIT();
return;
}
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"Certificate toString %s",
(const char*)
clientCertificate->toString().getCString()));
// Get certificate properties
issuerName = clientCertificate->getIssuerName();
sprintf(serialNumber, "%lu",
(unsigned long)
clientCertificate->getSerialNumber());
subjectName = clientCertificate->getSubjectName();
//
// The truststore type key property is deprecated. To
// retain backward compatibility, add the truststore
// type property to the key bindings and set it to
// cimserver truststore.
//
// Construct the corresponding PG_SSLCertificate
// instance
Array<CIMKeyBinding> keyBindings;
keyBindings.append(CIMKeyBinding(
"IssuerName", issuerName, CIMKeyBinding::STRING));
keyBindings.append(CIMKeyBinding(
"SerialNumber",
serialNumber,
CIMKeyBinding::STRING));
keyBindings.append(CIMKeyBinding("TruststoreType",
PG_SSLCERTIFICATE_TSTYPE_VALUE_SERVER));
CIMObjectPath cimObjectPath(
"localhost",
PEGASUS_NAMESPACENAME_CERTIFICATE,
PEGASUS_CLASSNAME_CERTIFICATE,
keyBindings);
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"Client Certificate COP: %s",
(const char*)
cimObjectPath.toString().getCString()));
CIMInstance cimInstance;
CIMValue value;
Uint32 pos;
String userName;
// Attempt to get the username registered to the
// certificate
try
{
cimInstance = _repository->getInstance(
PEGASUS_NAMESPACENAME_CERTIFICATE,
cimObjectPath);
pos =
cimInstance.findProperty("RegisteredUserName");
if (pos != PEG_NOT_FOUND &&
!(value = cimInstance.getProperty(pos).
getValue()).isNull())
{
value.get(userName);
//
// If a user name is specified, our search is
// complete
//
if (userName.size())
{
PEG_TRACE((TRC_HTTP, Tracer::LEVEL3,
"User name for certificate is %s",
(const char*)userName.getCString()));
certUserName = userName;
break;
}
// No user name is specified; continue up the
// chain
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"The certificate at level %u has no "
"associated username; moving up the "
"chain",
i));
}
else
{
PEG_TRACE_CSTRING(
TRC_HTTP,
Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - Bailing, no "
"username is registered to this "
"certificate.");
}
}
catch (CIMException& e)
{
// this certificate did not have a registration
// associated with it; continue up the chain
if (e.getCode() == CIM_ERR_NOT_FOUND)
{
PEG_TRACE_CSTRING(TRC_HTTP, Tracer::LEVEL4,
"No registration for this certificate; "
"try next certificate in chain");
continue;
}
else
{
PEG_TRACE((TRC_HTTP,Tracer::LEVEL1,
"HTTPAuthenticatorDelegator- Bailing,the "
"certificate used for authentication "
"is not valid for client IP address "
"%s.",
(const char*)
httpMessage->ipAddress.getCString())
);
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"BAD_CERTIFICATE",
"The certificate used for authentication "
"is not valid.");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
msg,
closeConnect);
PEG_METHOD_EXIT();
return;
}
}
catch (...)
{
// This scenario can occur if a certificate cached
// on the server was deleted openssl would not pick
// up the deletion but we would pick it up here
// when we went to look it up in the repository
PEG_TRACE((TRC_HTTP,Tracer::LEVEL1,
"HTTPAuthenticatorDelegator- Bailing,the "
"certificate used for authentication is "
"not valid for client IP address %s.",
(const char*)
httpMessage->ipAddress.getCString()));
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"BAD_CERTIFICATE",
"The certificate used for authentication is "
"not valid.");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
msg,
closeConnect);
PEG_METHOD_EXIT();
return;
}
} //end for clientcertificatechain
} //end sslTrustStore directory
else
{
// trustStore is a single CA file, lookup username
// user was already verified as a valid system user during
// server startup
certUserName =
configManager->getCurrentValue("sslTrustStoreUserName");
}
//
// Validate user information
//
if (certUserName == String::EMPTY)
{
PEG_TRACE((TRC_HTTP,Tracer::LEVEL1,
"HTTPAuthenticatorDelegator-No username is registered "
"to this certificate for client IP address %s.",
(const char*)httpMessage->ipAddress.getCString()));
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"BAD_CERTIFICATE_USERNAME",
"No username is registered to this certificate.");
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
MessageLoader::getMessage(msgParms),
closeConnect);
PEG_METHOD_EXIT();
return;
}
authStatus =
_authenticationManager->validateUserForHttpAuth(
certUserName,
httpMessage->authInfo);
if (!authStatus.isSuccess())
{
PEG_AUDIT_LOG(logCertificateBasedUserValidation(
certUserName,
issuerName,
subjectName,
serialNumber,
httpMessage->ipAddress,
false));
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"CERTIFICATE_USER_NOT_VALID",
"User '$0' registered to this certificate is not a "
"valid user.",
certUserName);
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
MessageLoader::getMessage(msgParms),
closeConnect);
PEG_METHOD_EXIT();
return;
}
PEG_AUDIT_LOG(logCertificateBasedUserValidation(
certUserName,
issuerName,
subjectName,
serialNumber,
httpMessage->ipAddress,
true));
httpMessage->authInfo->setAuthenticatedUser(certUserName);
PEG_TRACE((
TRC_HTTP,
Tracer::LEVEL4,
"HTTPAuthenticatorDelegator - The trusted client "
"certificate is registered to %s.",
(const char*) certUserName.getCString()));
} // end AuthenticationInfoRep::AUTH_TYPE_SSL
#ifdef PEGASUS_OS_ZOS
if (httpMessage->authInfo->getAuthType()==
AuthenticationInfoRep::AUTH_TYPE_ZOS_ATTLS)
{
String connectionUserName =
httpMessage->authInfo->getConnectionUser();
// If authenticated user not the connected user
// then check CIMSERV profile.
if (!String::equalNoCase(connectionUserName,
httpMessage->authInfo->getAuthenticatedUser()))
{
#ifdef PEGASUS_ZOS_SECURITY
if ( !CheckProfileCIMSERVclassWBEM(connectionUserName,
__READ_RESOURCE))
{
Logger::put_l(Logger::STANDARD_LOG, ZOS_SECURITY_NAME,
Logger::WARNING,
MessageLoaderParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"ATTLS_NOREAD_CIMSERV_ACCESS.PEGASUS_OS_ZOS",
"Request UserID $0 doesn't have READ permission"
" to profile CIMSERV CL(WBEM).",
connectionUserName));
PEG_AUDIT_LOG(logCertificateBasedUserValidation(
connectionUserName,
String::EMPTY,
String::EMPTY,
String::EMPTY,
httpMessage->ipAddress,
false));
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
}
#endif
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"Client UserID '%s' was authenticated via AT-TLS.",
(const char*)connectionUserName.getCString()));
httpMessage->authInfo->setAuthenticatedUser(
connectionUserName);
// For audit loging, only the mapping of the client IP to
// the resolved user ID is from interest.
// The SAF facility logs the certificate validation and
// the mapping of certificate subject to a local userID.
PEG_AUDIT_LOG(logCertificateBasedUserValidation(
connectionUserName,
String::EMPTY,
String::EMPTY,
String::EMPTY,
httpMessage->ipAddress,
true));
}// end is authenticated ?
} // end AuthenticationInfoRep::AUTH_TYPE_ZOS_ATTLS
if (httpMessage->authInfo->getAuthType()==
AuthenticationInfoRep::AUTH_TYPE_ZOS_LOCAL_DOMIAN_SOCKET)
{
String connectionUserName =
httpMessage->authInfo->getConnectionUser();
String requestUserName;
String authHeader;
String authHttpType;
String cookie;
// if lookupHeader() is not successfull parseLocalAuthHeader()
// must not be called !!
if ( HTTPMessage::lookupHeader(headers,
_HTTP_HEADER_PEGASUSAUTHORIZATION, authHeader, false)&&
HTTPMessage::parseLocalAuthHeader(authHeader,
authHttpType, requestUserName, cookie))
{
String cimServerUserName = System::getEffectiveUserName();
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"CIM server UserID = '%s', "
"Request UserID = '%s', "
"Local authenticated UserID = '%s'.",
(const char*) cimServerUserName.getCString(),
(const char*) requestUserName.getCString(),
(const char*) connectionUserName.getCString()
));
// if the request name and the user connected to the socket
// are the same, or if the currnet user running the
// cim server and the connected user are the same then
// assign the request user id as authenticated user id.
if( String::equalNoCase(
requestUserName,connectionUserName) ||
String::equalNoCase(
cimServerUserName,connectionUserName))
{
// If the designate new authenticated user, the user of
// the request, is not already the authenticated user
// then set the authenticated user and check CIMSERV.
if (!String::equalNoCase(requestUserName,
httpMessage->authInfo->getAuthenticatedUser()))
{
#ifdef PEGASUS_ZOS_SECURITY
if ( !CheckProfileCIMSERVclassWBEM(requestUserName,
__READ_RESOURCE))
{
Logger::put_l(Logger::STANDARD_LOG,
ZOS_SECURITY_NAME,
Logger::WARNING,
MessageLoaderParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"UNIXSOCKET_NOREAD_CIMSERV_ACCESS."
"PEGASUS_OS_ZOS",
"Request UserID $0 doesn't have READ "
"permission to profile "
"CIMSERV CL(WBEM).",
requestUserName));
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
}
#endif
// It is not necessary to check remote privileged
// user access for local connections;
// set the flag to "check done"
httpMessage->authInfo->
setRemotePrivilegedUserAccessChecked();
httpMessage->authInfo->setAuthenticatedUser(
requestUserName);
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"New authenticated User = '%s'.",
(const char*)requestUserName.getCString()
));
} // end changed authenticated user
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"User authenticated for request = '%s'.",
(const char*)httpMessage->authInfo->
getAuthenticatedUser().getCString()
));
// Write local authentication audit record.
PEG_AUDIT_LOG(logLocalAuthentication(
requestUserName,true));
} // end select authenticated user
else
{
PEG_AUDIT_LOG(logLocalAuthentication(
requestUserName,false));
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"User '%s' not authorized for request",
(const char*)requestUserName.getCString()));
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
}
} // end lookup header
else
{
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"AUTHORIZATION_HEADER_ERROR",
"Authorization header error");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
String::EMPTY,
msg,
closeConnect);
PEG_METHOD_EXIT();
return;
}
} // end AuthenticationInfoRep::AUTH_TYPE_ZOS_LOCAL_DOMIAN_SOCKET
#endif
} // end isRequestAuthenticated
else
{ // !isRequestAuthenticated
String authorization;
//
// do Local/Pegasus authentication
//
if (HTTPMessage::lookupHeader(headers,
_HTTP_HEADER_PEGASUSAUTHORIZATION, authorization, false))
{
try
{
//
// Do pegasus/local authentication
//
authStatus =
_authenticationManager->performPegasusAuthentication(
authorization,
httpMessage->authInfo);
if (authStatus.isSuccess())
{
#ifdef PEGASUS_ENABLE_SESSION_COOKIES
_createCookie(httpMessage);
#endif
}
else
{
String authResp;
authResp = _authenticationManager->
getPegasusAuthResponseHeader(
authorization,
httpMessage->authInfo);
if (authResp.size() > 0)
{
if (authStatus.doChallenge())
{
_sendChallenge(
queueId,
authStatus.getErrorDetail(),
authResp,
closeConnect);
}
else
{
_sendHttpError(
queueId,
authStatus.getHttpStatus(),
String::EMPTY,
authStatus.getErrorDetail(),
closeConnect);
}
}
else
{
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"AUTHORIZATION_HEADER_ERROR",
"Authorization header error");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
String::EMPTY,
msg,
closeConnect);
}
PEG_METHOD_EXIT();
return;
}
}
catch (const CannotOpenFile&)
{
_sendHttpError(
queueId,
HTTP_STATUS_INTERNALSERVERERROR,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
}
} // end PEGASUS/LOCAL authentication
//
// do HTTP authentication
//
if (HTTPMessage::lookupHeader(
headers, _HTTP_HEADER_AUTHORIZATION,
authorization, false))
{
authStatus =
_authenticationManager->performHttpAuthentication(
authorization,
httpMessage->authInfo);
#ifdef PEGASUS_PAM_SESSION_SECURITY
if (authStatus.isPasswordExpired())
{
// if this is CIM-XML and Password Expired treat as success
// expired password state is already stored in
// AuthenticationInfo
const char* cimOperation;
if (HTTPMessage::lookupHeader(
headers,
_HTTP_HEADER_CIMOPERATION,
cimOperation,
true))
{
authStatus = AuthenticationStatus(true);
}
}
#endif
if (authStatus.isSuccess())
{
#ifdef PEGASUS_ENABLE_SESSION_COOKIES
_createCookie(httpMessage);
#endif
}
else
{
//ATTN: the number of challenges get sent for a
// request on a connection can be pre-set.
#ifdef PEGASUS_NEGOTIATE_AUTHENTICATION
// Kerberos authentication needs access to the
// AuthenticationInfo object for this session in
// order to set up the reference to the
// CIMKerberosSecurityAssociation object for this
// session.
String authResp =
_authenticationManager->getHttpAuthResponseHeader(
httpMessage->authInfo);
#else
String authResp =
_authenticationManager->getHttpAuthResponseHeader();
#endif
if (authResp.size() > 0)
{
if (authStatus.doChallenge())
{
_sendChallenge(
queueId,
authStatus.getErrorDetail(),
authResp,
closeConnect);
}
else
{
_sendHttpError(
queueId,
authStatus.getHttpStatus(),
String::EMPTY,
authStatus.getErrorDetail(),
closeConnect);
}
}
else
{
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"AUTHORIZATION_HEADER_ERROR",
"Authorization header error");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
String::EMPTY,
msg,
closeConnect);
}
PEG_METHOD_EXIT();
return;
}
} // End if HTTP Authorization
} //end if (!isRequestAuthenticated)
} //end enableAuthentication
PEG_TRACE_CSTRING(
TRC_AUTHENTICATION,
Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - Authentication processing ended");
if (authStatus.isSuccess() || !enableAuthentication)
{
// Final bastion to ensure the remote privileged user access
// check is done as it should be
// check for remote privileged User Access
if (!httpMessage->authInfo->getRemotePrivilegedUserAccessChecked())
{
// the AuthenticationHandler did not process the
// enableRemotePrivilegedUserAccess check
// time to do it ourselves
String userName = httpMessage->authInfo->getAuthenticatedUser();
if (!AuthenticationManager::isRemotePrivilegedUserAccessAllowed(
userName))
{
// Send client a message that we can't proceed to talk
// to him
// HTTP 401 ?
MessageLoaderParms msgParms(
"Server.CIMOperationRequestAuthorizer."
"REMOTE_NOT_ENABLED",
"Remote privileged user access is not enabled.");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_UNAUTHORIZED,
String::EMPTY,
msg,
closeConnect);
PEG_METHOD_EXIT();
return;
}
httpMessage->authInfo->setRemotePrivilegedUserAccessChecked();
}
//
// Determine the type of this request:
//
// - A "CIMOperation" header indicates a CIM operation request
// - A "CIMExport" header indicates a CIM export request
// - A "/wsman" path in the start message indicates a WS-Man request
// - The requestUri starting with "/cimrs" indicates a CIM-RS request
CString uri = requestUri.getCString();
const char* cimOperation;
if (HTTPMessage::lookupHeader(
headers, _HTTP_HEADER_CIMOPERATION, cimOperation, true))
{
PEG_TRACE((
TRC_HTTP,
Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - CIMOperation: %s",
cimOperation));
MessageQueue* queue =
MessageQueue::lookup(_cimOperationMessageQueueId);
if (queue)
{
httpMessage->dest = queue->getQueueId();
try
{
queue->enqueue(httpMessage);
}
catch (const bad_alloc&)
{
delete httpMessage;
HTTPConnection *httpQueue =
dynamic_cast<HTTPConnection*>(
MessageQueue::lookup(queueId));
if (httpQueue)
{
httpQueue->handleInternalServerError(0, true);
}
PEG_METHOD_EXIT();
deleteMessage = false;
return;
}
deleteMessage = false;
}
}
else if (HTTPMessage::lookupHeader(
headers, _HTTP_HEADER_CIMEXPORT, cimOperation, true))
{
PEG_TRACE((
TRC_AUTHENTICATION,
Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - CIMExport: %s",
cimOperation));
MessageQueue* queue =
MessageQueue::lookup(_cimExportMessageQueueId);
if (queue)
{
httpMessage->dest = queue->getQueueId();
queue->enqueue(httpMessage);
deleteMessage = false;
}
}
else if ((_wsmanOperationMessageQueueId != PEG_NOT_FOUND) &&
((requestUri == "/wsman") ||
((requestUri == "/wsman-anon") && !enableAuthentication)))
{
// Note: DSP0226 R5.3-1 specifies if /wsman is used,
// unauthenticated access should not be allowed. This "should"
// requirement is not implemented here, because it is difficult
// for a client to determine whether enableAuthentication=true.
// DSP0226 R5.3-2 specifies if /wsman-anon is used, authenticated
// access shall not be required. Unauthenticated access is
// currently not allowed if enableAuthentication=true. When
// support for wsmid:Identify is added, it will be necessary to
// respond to that request without requiring authentication,
// regardless of the CIM Server configuration.
MessageQueue* queue =
MessageQueue::lookup(_wsmanOperationMessageQueueId);
if (queue)
{
httpMessage->dest = queue->getQueueId();
try
{
queue->enqueue(httpMessage);
}
catch (const bad_alloc&)
{
delete httpMessage;
HTTPConnection *httpQueue =
dynamic_cast<HTTPConnection*>(
MessageQueue::lookup(queueId));
if (httpQueue)
{
httpQueue->handleInternalServerError(0, true);
}
PEG_METHOD_EXIT();
deleteMessage = false;
return;
}
deleteMessage = false;
}
}
else if (
(_rsOperationMessageQueueId != PEG_NOT_FOUND) &&
(strncmp((const char*)uri, "/cimrs", 6) == 0))
{
MessageQueue* queue = MessageQueue::lookup(
_rsOperationMessageQueueId);
if (queue)
{
httpMessage->dest = queue->getQueueId();
try
{
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"HTTPAuthenticatorDelegator - "
"CIM-RS request enqueued [%d]",
queue->getQueueId()));
queue->enqueue(httpMessage);
}
catch (const bad_alloc&)
{
delete httpMessage;
_sendHttpError(
queueId,
HTTP_STATUS_REQUEST_TOO_LARGE,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
deleteMessage = false;
return;
}
deleteMessage = false;
}
else
{
PEG_TRACE((TRC_HTTP, Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - "
"Queue not found for URI: %s\n",
(const char*)uri));
}
}
#ifdef PEGASUS_ENABLE_PROTOCOL_WEB
//Unlike Other protocol, Web server is an pegasus extension
//and uses method name to identify it as it we don't have any
//like /cimrs and /wsman yet
//Instead, We deduce operation request to Webserver through it's
//method name GET and HEAD which is HACKISH.
else if ((_webOperationMessageQueueId != PEG_NOT_FOUND) &&
(httpMethod == HTTP_METHOD_GET || httpMethod == HTTP_METHOD_HEAD ))
{
MessageQueue* queue = MessageQueue::lookup(
_webOperationMessageQueueId);
if (queue)
{
httpMessage->dest = queue->getQueueId();
try
{
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"HTTPAuthenticatorDelegator - "
"WebServer request enqueued [%d]",
queue->getQueueId()));
queue->enqueue(httpMessage);
}
catch (const bad_alloc&)
{
delete httpMessage;
HTTPConnection *httpQueue =
dynamic_cast<HTTPConnection*>(
MessageQueue::lookup(queueId));
if (httpQueue)
{
httpQueue->handleInternalServerError(0, true);
}
PEG_METHOD_EXIT();
deleteMessage = false;
return;
}
catch (Exception& e)
{
PEG_TRACE((TRC_HTTP, Tracer::LEVEL4,
"HTTPAuthenticatorDelegator - "
"WebServer has thrown an exception: %s",
(const char*)e.getMessage().getCString()));
delete httpMessage;
_sendHttpError(
queueId,
HTTP_STATUS_INTERNALSERVERERROR,
String::EMPTY,
String::EMPTY,
true);
PEG_METHOD_EXIT();
deleteMessage = false;
return;
}
catch (...)
{
delete httpMessage;
HTTPConnection *httpQueue =
dynamic_cast<HTTPConnection*>(
MessageQueue::lookup(queueId));
if (httpQueue)
{
httpQueue->handleInternalServerError(0, true);
}
PEG_METHOD_EXIT();
deleteMessage = false;
return;
}
deleteMessage = false;
}
else
{
PEG_TRACE((TRC_HTTP, Tracer::LEVEL3,
"HTTPAuthenticatorDelegator - "
"Queue not found for URI: %s\n",
(const char*)requestUri.getCString()));
}
}
#endif /* PEGAUS_ENABLE_PROTOCOL_WEB */
else
{
// We don't recognize this request message type
// The Specification for CIM Operations over HTTP reads:
//
// 3.3.4. CIMOperation
//
// If a CIM Server receives a CIM Operation request without
// this [CIMOperation] header, it MUST NOT process it as if
// it were a CIM Operation Request. The status code
// returned by the CIM Server in response to such a request
// is outside of the scope of this specification.
//
// 3.3.5. CIMExport
//
// If a CIM Listener receives a CIM Export request without
// this [CIMExport] header, it MUST NOT process it. The
// status code returned by the CIM Listener in response to
// such a request is outside of the scope of this
// specification.
//
// The author has chosen to send a 400 Bad Request error, but
// without the CIMError header since this request must not be
// processed as a CIM request.
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
String::EMPTY,
String::EMPTY,
closeConnect);
PEG_METHOD_EXIT();
return;
} // bad request
} // isRequestAuthenticated and enableAuthentication check
else
{ // client not authenticated; send challenge
#ifdef PEGASUS_NEGOTIATE_AUTHENTICATION
String authResp =
_authenticationManager->getHttpAuthResponseHeader(
httpMessage->authInfo);
#else
String authResp =
_authenticationManager->getHttpAuthResponseHeader();
#endif
if (authResp.size() > 0)
{
if (authStatus.doChallenge())
{
_sendChallenge(
queueId,
authStatus.getErrorDetail(),
authResp,
closeConnect);
}
else
{
_sendHttpError(
queueId,
authStatus.getHttpStatus(),
String::EMPTY,
authStatus.getErrorDetail(),
closeConnect);
}
}
else
{
MessageLoaderParms msgParms(
"Pegasus.Server.HTTPAuthenticatorDelegator."
"AUTHORIZATION_HEADER_ERROR",
"Authorization header error");
String msg(MessageLoader::getMessage(msgParms));
_sendHttpError(
queueId,
HTTP_STATUS_BADREQUEST,
String::EMPTY,
msg,
closeConnect);
}
}
PEG_METHOD_EXIT();
}
#ifdef PEGASUS_ENABLE_SESSION_COOKIES
void HTTPAuthenticatorDelegator::_createCookie(
HTTPMessage *httpMessage)
{
PEG_METHOD_ENTER(TRC_HTTP,
"HTTPAuthenticatorDelegator::_createCookie");
if (!_sessions->cookiesEnabled())
{
PEG_METHOD_EXIT();
return;
}
// The client passed authentication, give it a cookie
String sessionID = _sessions->addNewSession(
httpMessage->authInfo->getAuthenticatedUser(),
httpMessage->ipAddress);
const char attributes[] = ";secure;httpOnly;maxAge=";
ConfigManager *configManager = ConfigManager::getInstance();
String strTimeout = configManager->getCurrentValue("httpSessionTimeout");
String cookie;
cookie.reserveCapacity(sizeof(_COOKIE_NAME) + 1 + sessionID.size()
+ sizeof(attributes) + strTimeout.size() + 1);
cookie.append(_COOKIE_NAME);
cookie.append("=");
cookie.append(sessionID);
cookie.append(attributes);
cookie.append(strTimeout);
// Schedule the cookie to be added in the next response
httpMessage->authInfo->setCookie(cookie);
PEG_METHOD_EXIT();
}
#endif
void HTTPAuthenticatorDelegator::idleTimeCleanup()
{
PEG_METHOD_ENTER(TRC_HTTP, "HTTPAuthenticatorDelegator::idleTimeCleanup");
#ifdef PEGASUS_ENABLE_SESSION_COOKIES
_sessions->clearExpired();
#endif
PEG_METHOD_EXIT();
}
PEGASUS_NAMESPACE_END
| 37.741874 | 80 | 0.480217 | maciejkotSW |
085b95c6db0127bdcc6d076a74ff463e2c2245b8 | 4,002 | hpp | C++ | lib/inc/libral/resource.hpp | puppetlabs/libral | 8f18f1022ef3676a3df6d13d6b483d2100c5bc97 | [
"Apache-2.0"
] | 68 | 2017-01-06T18:32:02.000Z | 2019-03-16T01:56:41.000Z | lib/inc/libral/resource.hpp | puppetlabs-toy-chest/libral | 8f18f1022ef3676a3df6d13d6b483d2100c5bc97 | [
"Apache-2.0"
] | 41 | 2017-01-19T19:42:23.000Z | 2017-11-08T21:38:03.000Z | lib/inc/libral/resource.hpp | puppetlabs-toy-chest/libral | 8f18f1022ef3676a3df6d13d6b483d2100c5bc97 | [
"Apache-2.0"
] | 15 | 2017-01-08T02:45:56.000Z | 2021-03-24T11:18:09.000Z | #pragma once
#include <map>
#include <libral/value.hpp>
namespace libral {
/** An individual thing that we manage
The resource only has one set of attributes, whether this resource
represents 'is' or 'should' state is therefore depending on the
context in which the resource is used.
A resource is little more than a map from attribute name to their
value. The only difference with an ordinary map is that it also has a
name.
*/
class resource {
protected:
friend class provider;
/**
* Constructs a resource with a name and no attributes set.
*/
resource(const std::string& name) : _name(name) { }
public:
/**
* A unique pointer to a resource
*/
using uptr = std::unique_ptr<resource>;
/**
* A map of attribute names to values
*/
using attributes = std::map<std::string, value>;
/**
* Retrieves the name of this resource
*/
const std::string& name() const { return _name; }
/**
* Returns the current state of attribute ATTR
*/
const value& operator[](const std::string& key) const;
/**
* Returns the current state of attribute ATTR
*/
value& operator[](const std::string& attr);
/**
* Erases the value of attribute ATTR
*/
void erase(const std::string attr) { _attrs.erase(attr); }
/**
* Returns an iterator to the beginning of the attributes
*/
attributes::iterator attr_begin() { return _attrs.begin(); }
/**
* Returns an iterator to the end of the attributes
*/
attributes::iterator attr_end() { return _attrs.end(); }
const attributes& attrs() const { return _attrs; }
/**
* Returns the value associated with KEY if it is of type T, and DEFLT
* otherwise
*/
template<typename T>
const T& lookup(const std::string& key, const T& deflt) const;
/**
* Returns a pointer to the value associated with KEY if it is of type
* T, and NULLPTR otherwise.
*/
template<typename T>
const T* lookup(const std::string& key) const;
private:
bool is_name(const std::string& key) const;
std::string _name;
attributes _attrs;
};
/**
* Represents a desired update to one resource and bundles the is and the
* should state of the resource, together with some convenience methods
* to access various aspects of the is/should pair of resources.
*
* Attributes for the should resource will only be set if a change to
* them has been requested (though it is entirely possible that the is
* and should value of the attribute are identical) If an attribute is
* not set in the should resource, it is certain that no change to it is
* being requested.
*/
struct update {
/** The current "is" state of the resource */
resource is;
/** The desired "should" state of the resource */
resource should;
/**
* Returns the name of the underlying resource.
*/
const std::string& name() const { return is.name(); }
/**
* Return true if this update contains a change for the attribute
* attr, i.e., if the should value for this attribute is set and
* differs from the is value.
*/
bool changed(const std::string& attr) const {
return (should[attr] && is[attr] != should[attr]);
}
/**
* Returns the should value for the attribute attr if it is set, and
* returns the is value for that attribute otherwise. If neither is
* set, returns a none value.
*/
const value& operator[](const std::string& attr) const {
if (should[attr])
return should[attr];
return is[attr];
}
/**
* Returns true if the is value for 'ensure' is anything but "absent"
*/
bool present() const {
// This makes 'ensure' and the value 'absent' very special
return is.lookup<std::string>("ensure", "absent") != "absent";
}
};
using updates = std::vector<update>;
}
| 27.791667 | 75 | 0.631184 | puppetlabs |
085bd25c5b4ba881982d18bab38a30c4b80db522 | 375 | cc | C++ | src/ui/lib/key_util/key_util_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/ui/lib/key_util/key_util_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/ui/lib/key_util/key_util_unittest.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2019 The Fuchsia 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 "src/ui/lib/key_util/key_util.h"
#include <gtest/gtest.h>
#include "hid-parser/usages.h"
#include "hid/usages.h"
namespace root_presenter {
namespace {} // namespace
} // namespace root_presenter
| 25 | 73 | 0.741333 | allansrc |
08608f158017d3b26380dd413f6fecaf39b22612 | 10,623 | cxx | C++ | main/oox/source/shape/ShapeContextHandler.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/oox/source/shape/ShapeContextHandler.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/oox/source/shape/ShapeContextHandler.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
#include "ShapeContextHandler.hxx"
#include "oox/vml/vmldrawingfragment.hxx"
#include "oox/vml/vmlshape.hxx"
#include "oox/vml/vmlshapecontainer.hxx"
namespace oox { namespace shape {
using namespace ::com::sun::star;
using namespace core;
using namespace drawingml;
::rtl::OUString SAL_CALL ShapeContextHandler_getImplementationName()
{
return CREATE_OUSTRING( "com.sun.star.comp.oox.ShapeContextHandler" );
}
uno::Sequence< ::rtl::OUString > SAL_CALL
ShapeContextHandler_getSupportedServiceNames()
{
uno::Sequence< ::rtl::OUString > s(1);
s[0] = CREATE_OUSTRING( "com.sun.star.xml.sax.FastShapeContextHandler" );
return s;
}
uno::Reference< uno::XInterface > SAL_CALL
ShapeContextHandler_createInstance( const uno::Reference< uno::XComponentContext > & context)
SAL_THROW((uno::Exception))
{
return static_cast< ::cppu::OWeakObject* >( new ShapeContextHandler(context) );
}
ShapeContextHandler::ShapeContextHandler
(uno::Reference< uno::XComponentContext > const & context) :
mnStartToken(0), m_xContext(context)
{
try
{
mxFilterBase.set( new ShapeFilterBase(context) );
}
catch( uno::Exception& )
{
}
}
ShapeContextHandler::~ShapeContextHandler()
{
}
uno::Reference<xml::sax::XFastContextHandler>
ShapeContextHandler::getGraphicShapeContext(::sal_Int32 Element )
{
if (! mxGraphicShapeContext.is())
{
FragmentHandlerRef rFragmentHandler
(new ShapeFragmentHandler(*mxFilterBase, msRelationFragmentPath));
ShapePtr pMasterShape;
switch (Element & 0xffff)
{
case XML_graphic:
mpShape.reset(new Shape("com.sun.star.drawing.GraphicObjectShape" ));
mxGraphicShapeContext.set
(new GraphicalObjectFrameContext(*rFragmentHandler, pMasterShape, mpShape, true));
break;
case XML_pic:
mpShape.reset(new Shape("com.sun.star.drawing.GraphicObjectShape" ));
mxGraphicShapeContext.set
(new GraphicShapeContext(*rFragmentHandler, pMasterShape, mpShape));
break;
default:
break;
}
}
return mxGraphicShapeContext;
}
uno::Reference<xml::sax::XFastContextHandler>
ShapeContextHandler::getDrawingShapeContext()
{
if (!mxDrawingFragmentHandler.is())
{
mpDrawing.reset( new oox::vml::Drawing( *mxFilterBase, mxDrawPage, oox::vml::VMLDRAWING_WORD ) );
mxDrawingFragmentHandler.set
(dynamic_cast<ContextHandler *>
(new oox::vml::DrawingFragment
( *mxFilterBase, msRelationFragmentPath, *mpDrawing )));
}
return mxDrawingFragmentHandler;
}
uno::Reference<xml::sax::XFastContextHandler>
ShapeContextHandler::getContextHandler()
{
uno::Reference<xml::sax::XFastContextHandler> xResult;
switch (getNamespace( mnStartToken ))
{
case NMSP_doc:
case NMSP_vml:
xResult.set(getDrawingShapeContext());
break;
default:
xResult.set(getGraphicShapeContext(mnStartToken));
break;
}
return xResult;
}
// ::com::sun::star::xml::sax::XFastContextHandler:
void SAL_CALL ShapeContextHandler::startFastElement
(::sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException)
{
static const ::rtl::OUString sInputStream
(RTL_CONSTASCII_USTRINGPARAM ("InputStream"));
uno::Sequence<beans::PropertyValue> aSeq(1);
aSeq[0].Name = sInputStream;
aSeq[0].Value <<= mxInputStream;
mxFilterBase->filter(aSeq);
mpThemePtr.reset(new Theme());
uno::Reference<XFastContextHandler> xContextHandler(getContextHandler());
if (xContextHandler.is())
xContextHandler->startFastElement(Element, Attribs);
}
void SAL_CALL ShapeContextHandler::startUnknownElement
(const ::rtl::OUString & Namespace, const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException)
{
uno::Reference<XFastContextHandler> xContextHandler(getContextHandler());
if (xContextHandler.is())
xContextHandler->startUnknownElement(Namespace, Name, Attribs);
}
void SAL_CALL ShapeContextHandler::endFastElement(::sal_Int32 Element)
throw (uno::RuntimeException, xml::sax::SAXException)
{
uno::Reference<XFastContextHandler> xContextHandler(getContextHandler());
if (xContextHandler.is())
xContextHandler->endFastElement(Element);
}
void SAL_CALL ShapeContextHandler::endUnknownElement
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name)
throw (uno::RuntimeException, xml::sax::SAXException)
{
uno::Reference<XFastContextHandler> xContextHandler(getContextHandler());
if (xContextHandler.is())
xContextHandler->endUnknownElement(Namespace, Name);
}
uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
ShapeContextHandler::createFastChildContext
(::sal_Int32 Element,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException)
{
uno::Reference< xml::sax::XFastContextHandler > xResult;
uno::Reference< xml::sax::XFastContextHandler > xContextHandler(getContextHandler());
if (xContextHandler.is())
xResult.set(xContextHandler->createFastChildContext
(Element, Attribs));
return xResult;
}
uno::Reference< xml::sax::XFastContextHandler > SAL_CALL
ShapeContextHandler::createUnknownChildContext
(const ::rtl::OUString & Namespace,
const ::rtl::OUString & Name,
const uno::Reference< xml::sax::XFastAttributeList > & Attribs)
throw (uno::RuntimeException, xml::sax::SAXException)
{
uno::Reference<XFastContextHandler> xContextHandler(getContextHandler());
if (xContextHandler.is())
return xContextHandler->createUnknownChildContext
(Namespace, Name, Attribs);
return uno::Reference< xml::sax::XFastContextHandler >();
}
void SAL_CALL ShapeContextHandler::characters(const ::rtl::OUString & aChars)
throw (uno::RuntimeException, xml::sax::SAXException)
{
uno::Reference<XFastContextHandler> xContextHandler(getContextHandler());
if (xContextHandler.is())
xContextHandler->characters(aChars);
}
// ::com::sun::star::xml::sax::XFastShapeContextHandler:
uno::Reference< drawing::XShape > SAL_CALL
ShapeContextHandler::getShape() throw (uno::RuntimeException)
{
uno::Reference< drawing::XShape > xResult;
uno::Reference< drawing::XShapes > xShapes( mxDrawPage, uno::UNO_QUERY );
if (mxFilterBase.is() && xShapes.is())
{
if (mpDrawing.get() != NULL)
{
mpDrawing->finalizeFragmentImport();
if( const ::oox::vml::ShapeBase* pShape = mpDrawing->getShapes().getFirstShape() )
xResult = pShape->convertAndInsert( xShapes );
}
else if (mpShape.get() != NULL)
{
mpShape->addShape(*mxFilterBase, mpThemePtr.get(), xShapes);
xResult.set(mpShape->getXShape());
mxGraphicShapeContext.clear( );
}
}
return xResult;
}
css::uno::Reference< css::drawing::XDrawPage > SAL_CALL
ShapeContextHandler::getDrawPage() throw (css::uno::RuntimeException)
{
return mxDrawPage;
}
void SAL_CALL ShapeContextHandler::setDrawPage
(const css::uno::Reference< css::drawing::XDrawPage > & the_value)
throw (css::uno::RuntimeException)
{
mxDrawPage = the_value;
}
css::uno::Reference< css::frame::XModel > SAL_CALL
ShapeContextHandler::getModel() throw (css::uno::RuntimeException)
{
if( !mxFilterBase.is() )
throw uno::RuntimeException();
return mxFilterBase->getModel();
}
void SAL_CALL ShapeContextHandler::setModel
(const css::uno::Reference< css::frame::XModel > & the_value)
throw (css::uno::RuntimeException)
{
if( !mxFilterBase.is() )
throw uno::RuntimeException();
uno::Reference<lang::XComponent> xComp(the_value, uno::UNO_QUERY_THROW);
mxFilterBase->setTargetDocument(xComp);
}
uno::Reference< io::XInputStream > SAL_CALL
ShapeContextHandler::getInputStream() throw (uno::RuntimeException)
{
return mxInputStream;
}
void SAL_CALL ShapeContextHandler::setInputStream
(const uno::Reference< io::XInputStream > & the_value)
throw (uno::RuntimeException)
{
mxInputStream = the_value;
}
::rtl::OUString SAL_CALL ShapeContextHandler::getRelationFragmentPath()
throw (uno::RuntimeException)
{
return msRelationFragmentPath;
}
void SAL_CALL ShapeContextHandler::setRelationFragmentPath
(const ::rtl::OUString & the_value)
throw (uno::RuntimeException)
{
msRelationFragmentPath = the_value;
}
::sal_Int32 SAL_CALL ShapeContextHandler::getStartToken() throw (::com::sun::star::uno::RuntimeException)
{
return mnStartToken;
}
void SAL_CALL ShapeContextHandler::setStartToken( ::sal_Int32 _starttoken ) throw (::com::sun::star::uno::RuntimeException)
{
mnStartToken = _starttoken;
}
::rtl::OUString ShapeContextHandler::getImplementationName()
throw (css::uno::RuntimeException)
{
return ShapeContextHandler_getImplementationName();
}
uno::Sequence< ::rtl::OUString > ShapeContextHandler::getSupportedServiceNames()
throw (css::uno::RuntimeException)
{
return ShapeContextHandler_getSupportedServiceNames();
}
::sal_Bool SAL_CALL ShapeContextHandler::supportsService
(const ::rtl::OUString & ServiceName) throw (css::uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSeq = getSupportedServiceNames();
if (aSeq[0].equals(ServiceName))
return sal_True;
return sal_False;
}
}}
| 30.438395 | 123 | 0.696884 | Grosskopf |
0861c31cba7a3998f40a562c80b4904013d06899 | 3,939 | cpp | C++ | Eudora71/Eudora/QCImageList.cpp | ivanagui2/hermesmail-code | 34387722d5364163c71b577fc508b567de56c5f6 | [
"BSD-3-Clause-Clear"
] | 1 | 2019-06-15T17:46:11.000Z | 2019-06-15T17:46:11.000Z | Eudora71/Eudora/QCImageList.cpp | ivanagui2/hermesmail-code | 34387722d5364163c71b577fc508b567de56c5f6 | [
"BSD-3-Clause-Clear"
] | null | null | null | Eudora71/Eudora/QCImageList.cpp | ivanagui2/hermesmail-code | 34387722d5364163c71b577fc508b567de56c5f6 | [
"BSD-3-Clause-Clear"
] | null | null | null |
#include "stdafx.h"
#include "windowsx.h"
#include "QCGraphics.h"
#include "QCImageList.h"
#include "SafetyPal.h"
#include "resource.h"
#include "DebugNewHelpers.h"
class QCCommon16ImageList g_theCommon16ImageList;
class QCCommon32ImageList g_theCommon32ImageList;
class QCMailboxImageList g_theMailboxImageList;
class QCTocImageList g_theTocImageList;
class QCMoodImageList g_theMoodImageList;
void LoadImageLists(void)
{
g_theCommon16ImageList.Load();
g_theCommon32ImageList.Load();
g_theMailboxImageList.Load();
g_theTocImageList.Load();
g_theMoodImageList.Load();
}
bool QCCommon16ImageList::Load(void)
{
return QCImageList::Load(16, 16, 40, MAKEINTRESOURCE(IDB_IL_COMMON16), RGB(192, 192, 192));
}
bool QCCommon32ImageList::Load(void)
{
return QCImageList::Load(32, 32, 0, MAKEINTRESOURCE(IDB_IL_COMMON32), RGB(192, 192, 192));
}
bool QCMailboxImageList::Load(void)
{
return QCImageList::Load(16, 16, 50, MAKEINTRESOURCE(IDB_IL_MAILTREE), RGB(192, 192, 192));
}
QCTocImageList::QCTocImageList()
{
}
bool QCTocImageList::Load(void)
{
bool rc;
rc = m_ImageListColor.Load(16, 16, 0, MAKEINTRESOURCE(IDB_IL_STATUS), RGB(192, 192, 192));
if (!rc)
{
ASSERT(0);
return false;
}
rc = m_ImageListMonochrome.Load(16, 16, 0, MAKEINTRESOURCE(IDB_IL_STATUSM), RGB(0, 0, 0));
if (!rc)
{
ASSERT(0);
return false;
}
return true;
}
void QCTocImageList::Draw(int Index, int x, int y, CDC* pdc, COLORREF color)
{
if (!pdc)
{
ASSERT(0);
return;
}
COLORREF ptcolor = pdc->GetPixel(x+2, y+2);
short r = GetRValue(ptcolor);
short g = GetGValue(ptcolor);
short b = GetBValue(ptcolor);
if (r < 150 || g < 150 || b < 150)
m_ImageListMonochrome.Draw(Index, x, y, pdc);
else
m_ImageListColor.Draw(Index, x, y, pdc);
}
void QCTocImageList::Free(void)
{
m_ImageListColor.Free();
m_ImageListMonochrome.Free();
}
QCMoodImageList::QCMoodImageList()
{
}
bool QCMoodImageList::Load(void)
{
bool rc;
rc = m_ImageListColor.Load(16, 16, 0, MAKEINTRESOURCE(IDB_IL_MOOD_MAIL), RGB(192, 192, 192));
if (!rc)
{
ASSERT(0);
return false;
}
rc = m_ImageListMonochrome.Load(16, 16, 0, MAKEINTRESOURCE(IDB_IL_MOOD_MAILM), RGB(0, 0, 0));
if (!rc)
{
ASSERT(0);
return false;
}
return true;
}
void QCMoodImageList::Draw(int Index, int x, int y, CDC* pdc, COLORREF color)
{
if (!pdc)
{
ASSERT(0);
return;
}
COLORREF ptcolor = pdc->GetPixel(x+2, y+2);
short r = GetRValue(ptcolor);
short g = GetGValue(ptcolor);
short b = GetBValue(ptcolor);
if (r < 150 || g < 150 || b < 150)
m_ImageListMonochrome.Draw(Index, x, y, pdc);
else
m_ImageListColor.Draw(Index, x, y, pdc);
}
void QCMoodImageList::Free(void)
{
m_ImageListColor.Free();
m_ImageListMonochrome.Free();
}
QCImageList::~QCImageList()
{
Free();
}
void QCImageList::Free(void)
{
DeleteImageList();
}
bool QCImageList::LoadEmpty(int cx, int cy, int nGrow)
{
// Safety checks
if (cx < 0 || cy < 0 || cx > 50 || cy > 50) return false;
// Create new area to hold images in image list
if (!Create(cx, cy, ILC_COLORDDB | ILC_MASK, 0, nGrow)) return false;
return true;
}
bool QCImageList::Load(int cx, int cy, int nGrow, LPCTSTR BmpResource, COLORREF xcolor)
{
// Load image list with no bitmaps
if (!LoadEmpty(cx, cy, nGrow)) return false;
// Load bitmap resource
if (!BmpResource) return false;
CBitmap bm1;
if ( !bm1.LoadBitmap(BmpResource) )
{
ASSERT( !"LoadBitmap failed in QCImageList::Load" );
return false;
}
// Check bitmap size compared to expected size
BITMAP bm;
bm1.GetObject(sizeof(bm), &bm);
if (bm.bmHeight != cy)
{
// bitmap for image list is sized wrong
// fix either the art or the calling code
ASSERT(0);
return false;
}
Add(&bm1, xcolor);
// Return success if we made it this far
return true;
}
void QCImageList::Draw(int Index, int x, int y, CDC* pdc)
{
if (!pdc) return;
POINT pt;
pt.x = x;
pt.y = y;
CImageList::Draw(pdc, Index, pt, ILD_NORMAL);
}
| 19.403941 | 94 | 0.694846 | ivanagui2 |
0862bd901dbd34f2e4fb66fef66af446cac11af1 | 1,279 | hpp | C++ | Support/Modules/UDLib/UDItemInfoTagContentCreator.hpp | graphisoft-python/TextEngine | 20c2ff53877b20fdfe2cd51ce7abdab1ff676a70 | [
"Apache-2.0"
] | 3 | 2019-07-15T10:54:54.000Z | 2020-01-25T08:24:51.000Z | Support/Modules/UDLib/UDItemInfoTagContentCreator.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | null | null | null | Support/Modules/UDLib/UDItemInfoTagContentCreator.hpp | graphisoft-python/GSRoot | 008fac2c6bf601ca96e7096705e25b10ba4d3e75 | [
"Apache-2.0"
] | 1 | 2020-09-26T03:17:22.000Z | 2020-09-26T03:17:22.000Z | #ifndef UDITEMINFOTAGCONTENTCREATOR_HPP
#define UDITEMINFOTAGCONTENTCREATOR_HPP
#pragma once
#include "UDDefinitions.hpp"
#include "FloatingMenu.hpp"
namespace UD {
namespace ItemInfoTag {
class UD_DLL_EXPORT InfoTagContentCreator
{
public:
enum class EntryLayoutMethod {
OneColumn,
TwoColumns
};
class UD_DLL_EXPORT InfoTagItem : public FloatingWindow::FloatingMenuItem {
public:
InfoTagItem ();
virtual ~InfoTagItem ();
};
typedef FloatingWindow::FloatingMenu::MenuItemRowArray MenuItemRowArray;
protected:
class UD_DLL_EXPORT ContentEntryCreator
{
public:
virtual ~ContentEntryCreator ();
virtual MenuItemRowArray GetContent () const = 0;
protected:
MenuItemRowArray CreateMenuItemEntry (const GS::UniString& contentType,
const GS::UniString& text,
const DG::Font::Style style = DG::Font::Plain,
GS::Ref<Gfx::Color> color = nullptr,
EntryLayoutMethod layoutMethod = EntryLayoutMethod::OneColumn) const;
};
private:
GS::Array<GS::Ref<ContentEntryCreator>> entryCreators;
protected:
void AddContentEntryCreator (GS::Ref<ContentEntryCreator> rowCreator);
public:
MenuItemRowArray GetContent () const;
virtual ~InfoTagContentCreator ();
};
}
}
#endif //UDITEMINFOTAGCONTENTCREATOR_HPP
| 21.677966 | 82 | 0.751368 | graphisoft-python |
08633ec8b6270d7720e1e366a6018814ef834aab | 423 | cpp | C++ | ADCore/ADApp/pluginSrc/test_forward_reference.cpp | jerryjiahaha/areaDetector | a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231 | [
"MIT"
] | 20 | 2015-01-07T09:02:42.000Z | 2021-07-27T14:35:19.000Z | ADCore/ADApp/pluginSrc/test_forward_reference.cpp | jerryjiahaha/areaDetector | a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231 | [
"MIT"
] | 400 | 2015-01-06T14:44:30.000Z | 2022-02-07T17:45:32.000Z | ADCore/ADApp/pluginSrc/test_forward_reference.cpp | jerryjiahaha/areaDetector | a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231 | [
"MIT"
] | 72 | 2015-01-23T23:23:02.000Z | 2022-02-07T15:14:35.000Z | #include <NDPluginStats.h>
void test_forward_reference()
{
// Creating the object as an automatic variable causes a compilation error on Linux but compiles fine on Windows
NDPluginStats stats = NDPluginStats("STATS1", 20, 0, "SIM1", 0, 0, 0, 0, 0, 1);
// Creating the object as a heap variable works fine on Linux and on Windows
NDPluginStats *pStats = new NDPluginStats("STATS1", 20, 0, "SIM1", 0, 0, 0, 0, 0, 1);
}
| 38.454545 | 112 | 0.716312 | jerryjiahaha |
0868d450facd44e942b5a8894b8151b4ee39fd12 | 3,169 | cpp | C++ | src/Player.cpp | gabrielahavranova/bomberman-game | bf50bbec8d1eb9dd4dfa59873ed50c06f6d7d592 | [
"MIT"
] | null | null | null | src/Player.cpp | gabrielahavranova/bomberman-game | bf50bbec8d1eb9dd4dfa59873ed50c06f6d7d592 | [
"MIT"
] | null | null | null | src/Player.cpp | gabrielahavranova/bomberman-game | bf50bbec8d1eb9dd4dfa59873ed50c06f6d7d592 | [
"MIT"
] | null | null | null | #include "./include/Player.h"
class Bomb;
Player::Player() {
player_src_rect = {0, 0, TILE_DIM, TILE_DIM };
player_dest_rect = {0, 0, TILE_DIM, TILE_DIM};
}
void Player::render() {
player_dest_rect.x = pos_coords2D.x;
player_dest_rect.y = pos_coords2D.y;
renderScore();
TextureManager::draw(player_texture, player_src_rect, player_dest_rect);
}
Vector2D Player::getTile2D(const int &x_pos, const int &y_pos) {
Vector2D result;
if (x_pos % 50 < 15) result.x = x_pos / 50;
else result.x = x_pos / 50 + 1;
if (y_pos % 50 < 15) result.y = y_pos / 50;
else result.y = y_pos / 50 + 1;
return result;
}
void Player::plantBomb(Map & map) {
if (bombs_active >= max_bombs ) return;
Vector2D my_tile = getTile2D(pos_coords2D.x, pos_coords2D.y);
//in the case that player wants to plant 2 bombs at the same place
if (!map.isSteppable(my_tile.x, my_tile.y)) return;
bombs_active++;
bomb_queue.emplace(SDL_GetTicks() + 3000);
Bomb(my_tile.y, my_tile.x, bomb_size, map);
}
void Player::update() {
if (!bomb_queue.empty() && bomb_queue.front() <= SDL_GetTicks()) {
bombs_active--;
bomb_queue.pop();
}
}
void Player::death() {
player_texture = dead_player_texture;
score /= 100;
updateScoreLength();
updateScoreTexture();
alive = false;
}
void Player::claimBoost(const char & boost_type) {
int old_score = score;
switch (boost_type) {
case 's':
if (speed < MAX_SPEED) speed++;
else score += 50;
break;
case 'b':
if (bomb_size < MAX_BOMB_SIZE) bomb_size++;
else score += 50;
break;
case 'c':
if (max_bombs < MAX_BOMB_CNT) max_bombs++;
else score += 50;
break;
case 'm':
score += 200;
break;
default:
break;
}
if (old_score != score) updateScoreTexture();
}
void Player::updateScoreLength() {
score_length = static_cast<int>(log10(score)) + 1;
}
void Player::renderScore() {
TextureManager::draw(name_texture, TEXT_SRC_RECT, name_dest_rect);
TextureManager::draw(score_texture, TEXT_SRC_RECT, score_dest_rect);
}
void Player::setNameTexture() {
SDL_Surface * surface = TTF_RenderText_Solid(TextureManager::font, player_name.c_str(), TextureManager::text_color);
name_texture = SDL_CreateTextureFromSurface(TextureManager::renderer, surface);
TextureManager::textures.push_back(name_texture);
SDL_FreeSurface(surface);
updateScoreTexture();
}
void Player::updateScoreTexture() {
updateScoreLength();
std::string str_score = std::to_string(score);
const char * chars_score = str_score.c_str();
SDL_Surface * surface = TTF_RenderText_Solid(TextureManager::font, chars_score, TextureManager::text_color);
score_texture = SDL_CreateTextureFromSurface(TextureManager::renderer, surface);
TextureManager::textures.push_back(score_texture);
score_dest_rect.x = name_dest_rect.x + name_dest_rect.w + TILE_DIM;
score_dest_rect.w = score_length * 30;
SDL_FreeSurface(surface);
}
| 25.97541 | 121 | 0.650363 | gabrielahavranova |
086e11a11f63a7e233f43322e35aaa3c8935f6b7 | 1,612 | cpp | C++ | interpreter/interpreter.cpp | wangyouming/DesignPatterns | ae3b3934480306bdce4bcbdec92553a688338fc3 | [
"MIT"
] | 1 | 2019-11-12T09:03:17.000Z | 2019-11-12T09:03:17.000Z | interpreter/interpreter.cpp | wangyouming/design_patterns | ae3b3934480306bdce4bcbdec92553a688338fc3 | [
"MIT"
] | null | null | null | interpreter/interpreter.cpp | wangyouming/design_patterns | ae3b3934480306bdce4bcbdec92553a688338fc3 | [
"MIT"
] | null | null | null |
#include <iostream> // std::cout std::endl
#include <map> // std::map
using std::cout;
using std::endl;
using std::string;
class Context {
public:
void set(const string& key, bool value)
{
map_.insert({key, value});
}
bool get(const string& key)
{
return map_[key];
}
private:
std::map<string, bool> map_;
};
class Expression {
public:
virtual ~Expression() = default;
virtual bool interpret(Context*) = 0;
};
class TerminalExpression : public Expression {
public:
explicit TerminalExpression(const string& value)
: value_{value}
{
}
bool interpret(Context* context)
{
return context->get(value_);
}
private:
string value_;
};
class NonterminalExpression : public Expression {
public:
NonterminalExpression(Expression* lhs, Expression* rhs)
: lhs_{lhs}
, rhs_{rhs}
{
}
bool interpret(Context* ctx)
{
return lhs_->interpret(ctx) && rhs_->interpret(ctx);
}
private:
Expression* lhs_;
Expression* rhs_;
};
int main()
{
TerminalExpression ternimal_expression_a{"A"};
TerminalExpression ternimal_expression_b{"B"};
NonterminalExpression nonterminal_expression{&ternimal_expression_a,
&ternimal_expression_b};
Context context;
context.set("A", true);
context.set("B", false);
cout << ternimal_expression_a.interpret(&context) << " "
<< ternimal_expression_b.interpret(&context) << " "
<< nonterminal_expression.interpret(&context) << endl;
}
| 19.901235 | 73 | 0.614764 | wangyouming |
0870392dd41da1af2a9cec0cdaad73ac3171f0d6 | 4,605 | cc | C++ | contrib/language/filters/http/test/language_integration_test.cc | naveensrinivasan/envoy | 6931f18c3bacb0e41a64d2107b2c0d0cd683ad80 | [
"Apache-2.0"
] | 1 | 2022-03-02T14:23:12.000Z | 2022-03-02T14:23:12.000Z | contrib/language/filters/http/test/language_integration_test.cc | naveensrinivasan/envoy | 6931f18c3bacb0e41a64d2107b2c0d0cd683ad80 | [
"Apache-2.0"
] | 153 | 2021-10-04T04:32:48.000Z | 2022-03-31T04:22:40.000Z | contrib/language/filters/http/test/language_integration_test.cc | naveensrinivasan/envoy | 6931f18c3bacb0e41a64d2107b2c0d0cd683ad80 | [
"Apache-2.0"
] | 1 | 2021-12-14T02:39:44.000Z | 2021-12-14T02:39:44.000Z | #include "test/integration/http_integration.h"
namespace Envoy {
class HttpFilterLanguageIntegrationTest
: public testing::TestWithParam<Network::Address::IpVersion>,
public HttpIntegrationTest {
public:
HttpFilterLanguageIntegrationTest()
: HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {}
void TearDown() override {
fake_upstream_connection_.reset();
fake_upstreams_.clear();
}
void initializeConfig(std::string default_language, std::string supported_languages) {
const std::string yaml = R"EOF(
name: envoy.filters.http.language
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.language.v3alpha.Language
default_language: {}
supported_languages: {}
)EOF";
config_helper_.prependFilter(fmt::format(yaml, default_language, supported_languages));
}
};
INSTANTIATE_TEST_SUITE_P(IpVersions, HttpFilterLanguageIntegrationTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
TEST_P(HttpFilterLanguageIntegrationTest, DefaultLanguageFallback) {
initializeConfig("en", "[fr]");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{
{":method", "GET"}, {":path", "/"}, {":scheme", "http"}, {":authority", "host"}});
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));
EXPECT_FALSE(
upstream_request_->headers().get(Envoy::Http::LowerCaseString{"x-language"}).empty());
EXPECT_EQ("en", upstream_request_->headers()
.get(Http::LowerCaseString{"x-language"})[0]
->value()
.getStringView());
codec_client_->close();
ASSERT_TRUE(fake_upstream_connection_->close());
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
}
TEST_P(HttpFilterLanguageIntegrationTest, AcceptLanguageHeader) {
initializeConfig("en", "[en, en-uk, de, dk, es, fr, zh, zh-tw]");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{
{":method", "GET"},
{":path", "/"},
{":scheme", "http"},
{":authority", "host"},
{"accept-language", "fr-CH,fr;q=0.9,en;q=0.8,de;q=0.7,*;q=0.5"}});
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));
EXPECT_FALSE(
upstream_request_->headers().get(Envoy::Http::LowerCaseString{"x-language"}).empty());
EXPECT_EQ("fr", upstream_request_->headers()
.get(Http::LowerCaseString{"x-language"})[0]
->value()
.getStringView());
codec_client_->close();
ASSERT_TRUE(fake_upstream_connection_->close());
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
}
TEST_P(HttpFilterLanguageIntegrationTest, InvalidAcceptLanguageHeader) {
initializeConfig("en", "[en, en-uk, de, dk, es, fr, zh, zh-tw]");
initialize();
codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(
Http::TestRequestHeaderMapImpl{{":method", "GET"},
{":path", "/"},
{":scheme", "http"},
{":authority", "host"},
{"accept-language", "foobar;;;;0000.20;0-"}});
ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_));
ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_));
ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_));
EXPECT_FALSE(
upstream_request_->headers().get(Envoy::Http::LowerCaseString{"x-language"}).empty());
EXPECT_EQ("en", upstream_request_->headers()
.get(Http::LowerCaseString{"x-language"})[0]
->value()
.getStringView());
codec_client_->close();
ASSERT_TRUE(fake_upstream_connection_->close());
ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect());
}
} // namespace Envoy
| 39.025424 | 98 | 0.67861 | naveensrinivasan |
0871b734b5f57f2f78f75119b7d254e79de3bbeb | 132 | cpp | C++ | daemon/yettad.cpp | dingjingmaster/yetta | 86977d0a670cfd7c3a9a511290e52b03abb44cef | [
"MIT"
] | null | null | null | daemon/yettad.cpp | dingjingmaster/yetta | 86977d0a670cfd7c3a9a511290e52b03abb44cef | [
"MIT"
] | null | null | null | daemon/yettad.cpp | dingjingmaster/yetta | 86977d0a670cfd7c3a9a511290e52b03abb44cef | [
"MIT"
] | null | null | null | #include <yetta-daemon.h>
int main(int argc, char *argv[])
{
YettaDaemon app (argc, argv, "yettad");
return app.exec();
}
| 14.666667 | 43 | 0.621212 | dingjingmaster |
08724aa8f4440172d96f1b637c1cb0c124c845f8 | 8,799 | cc | C++ | src/ui/scenic/lib/gfx/tests/image_pipe_render_unittest.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/ui/scenic/lib/gfx/tests/image_pipe_render_unittest.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | src/ui/scenic/lib/gfx/tests/image_pipe_render_unittest.cc | opensource-assist/fuschia | 66646c55b3d0b36aae90a4b6706b87f1a6261935 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia 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 <lib/ui/scenic/cpp/commands.h>
#include <gtest/gtest.h>
#include "src/ui/lib/escher/flib/fence.h"
#include "src/ui/lib/escher/test/gtest_vulkan.h"
#include "src/ui/lib/escher/util/image_utils.h"
#include "src/ui/lib/escher/vk/image_layout_updater.h"
#include "src/ui/scenic/lib/gfx/engine/engine_renderer_visitor.h"
#include "src/ui/scenic/lib/gfx/resources/image_pipe.h"
#include "src/ui/scenic/lib/gfx/resources/image_pipe2.h"
#include "src/ui/scenic/lib/gfx/resources/material.h"
#include "src/ui/scenic/lib/gfx/tests/image_pipe_unittest_common.h"
#include "src/ui/scenic/lib/gfx/tests/mocks/util.h"
#include "src/ui/scenic/lib/gfx/tests/vk_session_handler_test.h"
namespace scenic_impl {
namespace gfx {
namespace test {
class ImagePipeRenderTest : public VkSessionHandlerTest {
public:
// Create a one-time EngineRendererVisitor and GpuUploader to visit the material node /
// scene node to upload ImagePipe images.
template <typename T>
void Visit(T* t) {
auto gpu_uploader = escher::BatchGpuUploader(escher()->GetWeakPtr(), 0);
auto image_layout_updater = escher::ImageLayoutUpdater(escher()->GetWeakPtr());
EngineRendererVisitor visitor(/* paper_renderer */ nullptr, &gpu_uploader,
&image_layout_updater,
/* hide_protected_memory */ false,
/* replacement_material */ escher::MaterialPtr());
visitor.Visit(t);
image_layout_updater.Submit();
gpu_uploader.Submit();
}
};
// Present two frames on the ImagePipe, making sure that image is
// updated only after Visit().
VK_TEST_F(ImagePipeRenderTest, ImageUpdatedOnlyAfterVisit) {
ResourceId next_id = 1;
auto image_pipe_updater = CreateImagePipeUpdater(session());
ImagePipePtr image_pipe = fxl::MakeRefCounted<ImagePipe>(
session(), next_id++, std::move(image_pipe_updater), shared_error_reporter());
MaterialPtr pipe_material = fxl::MakeRefCounted<Material>(session(), next_id++);
pipe_material->SetTexture(image_pipe);
constexpr uint32_t kImage1Id = 1;
constexpr size_t kImage1Dim = 50;
// Create a checkerboard image and copy it into a vmo.
{
auto checkerboard = CreateVmoWithCheckerboardPixels(kImage1Dim, kImage1Dim);
auto image_info = CreateImageInfoForBgra8Image(kImage1Dim, kImage1Dim);
// Add the image to the image pipe with ImagePipe.AddImage().
image_pipe->AddImage(kImage1Id, std::move(image_info), CopyVmo(checkerboard->vmo()), 0,
GetVmoSize(checkerboard->vmo()), fuchsia::images::MemoryType::HOST_MEMORY);
}
constexpr uint32_t kImage2Id = 2;
constexpr size_t kImage2Dim = 100;
// Create a new Image with a gradient.
{
auto gradient = CreateVmoWithGradientPixels(kImage2Dim, kImage2Dim);
auto image_info = CreateImageInfoForBgra8Image(kImage2Dim, kImage2Dim);
// Add the image to the image pipe.
image_pipe->AddImage(kImage2Id, std::move(image_info), CopyVmo(gradient->vmo()), 0,
GetVmoSize(gradient->vmo()), fuchsia::images::MemoryType::HOST_MEMORY);
}
// We present Image 2 at time (0) and Image 1 at time (1).
// Only Image 1 should be updated and uploaded.
image_pipe->PresentImage(kImage2Id, zx::time(0), {}, {}, nullptr);
image_pipe->PresentImage(kImage1Id, zx::time(1), {}, {}, nullptr);
// After ImagePipeUpdater updates the ImagePipe, the current_image() should be set
// but Escher image is not created.
ASSERT_TRUE(RunLoopFor(zx::sec(1)));
ASSERT_TRUE(image_pipe->current_image());
ASSERT_FALSE(image_pipe->GetEscherImage());
auto image1 = image_pipe->current_image();
// Escher image is not created until EngineRendererVisitor visits the material.
Visit(pipe_material.get());
auto escher_image1 = image_pipe->GetEscherImage();
ASSERT_TRUE(escher_image1);
ASSERT_EQ(escher_image1->width(), kImage1Dim);
// We present Image 1 (already rendered) at time (0) and Image 2 (not rendered yet)
// at time (1). Only Image 2 should be updated and uploaded.
image_pipe->PresentImage(kImage1Id, zx::time(0), {}, {}, nullptr);
image_pipe->PresentImage(kImage2Id, zx::time(1), {}, {}, nullptr);
// After ImagePipeUpdater updates the ImagePipe, the current_image() should be set
// but Escher image is not created.
ASSERT_TRUE(RunLoopFor(zx::sec(1)));
ASSERT_TRUE(image_pipe->current_image());
ASSERT_NE(image_pipe->current_image(), image1);
ASSERT_FALSE(image_pipe->GetEscherImage());
// Escher image is not created until EngineRendererVisitor visits the material.
Visit(pipe_material.get());
auto escher_image2 = image_pipe->GetEscherImage();
ASSERT_TRUE(escher_image2);
ASSERT_NE(escher_image2, escher_image1);
ASSERT_EQ(escher_image2->width(), kImage2Dim);
}
// Present two frames on the ImagePipe, making sure that acquire fence is
// being listened to and release fences are signalled.
VK_TEST_F(ImagePipeRenderTest, ImagePipePresentTwoFrames) {
ResourceId next_id = 1;
auto image_pipe_updater = CreateImagePipeUpdater(session());
ImagePipePtr image_pipe = fxl::MakeRefCounted<ImagePipe>(
session(), next_id++, std::move(image_pipe_updater), shared_error_reporter());
MaterialPtr pipe_material = fxl::MakeRefCounted<Material>(session(), next_id++);
pipe_material->SetTexture(image_pipe);
uint32_t image1_id = 1;
// Create a checkerboard image and copy it into a vmo.
{
size_t image_dim = 100;
auto checkerboard = CreateVmoWithCheckerboardPixels(image_dim, image_dim);
auto image_info = CreateImageInfoForBgra8Image(image_dim, image_dim);
// Add the image to the image pipe with ImagePipe.AddImage().
image_pipe->AddImage(image1_id, std::move(image_info), CopyVmo(checkerboard->vmo()), 0,
GetVmoSize(checkerboard->vmo()), fuchsia::images::MemoryType::HOST_MEMORY);
}
// Make checkerboard the currently displayed image.
zx::event acquire_fence1 = CreateEvent();
zx::event release_fence1 = CreateEvent();
image_pipe->PresentImage(image1_id, zx::time(0), CopyEventIntoFidlArray(acquire_fence1),
CopyEventIntoFidlArray(release_fence1), nullptr);
// Current presented image should be null, since we haven't signalled
// acquire fence yet.
ASSERT_FALSE(RunLoopFor(zx::sec(1)));
Visit(pipe_material.get());
ASSERT_FALSE(image_pipe->current_image());
ASSERT_FALSE(image_pipe->GetEscherImage());
// Signal on the acquire fence.
acquire_fence1.signal(0u, escher::kFenceSignalled);
// Run until image1 is presented, but not rendered due to lack of engine renderer visitor.
ASSERT_TRUE(RunLoopFor(zx::sec(1)));
Visit(pipe_material.get());
// Image should now be presented.
escher::ImagePtr image1 = image_pipe->GetEscherImage();
ASSERT_TRUE(image1);
uint32_t image2_id = 2;
// Create a new Image with a gradient.
{
size_t image_dim = 100;
auto gradient = CreateVmoWithGradientPixels(image_dim, image_dim);
auto image_info = CreateImageInfoForBgra8Image(image_dim, image_dim);
// Add the image to the image pipe.
image_pipe->AddImage(image2_id, std::move(image_info), CopyVmo(gradient->vmo()), 0,
GetVmoSize(gradient->vmo()), fuchsia::images::MemoryType::HOST_MEMORY);
}
// The first image should not have been released.
ASSERT_FALSE(RunLoopFor(zx::sec(1)));
Visit(pipe_material.get());
ASSERT_FALSE(IsEventSignalled(release_fence1, escher::kFenceSignalled));
// Make gradient the currently displayed image.
zx::event acquire_fence2 = CreateEvent();
zx::event release_fence2 = CreateEvent();
image_pipe->PresentImage(image2_id, zx::time(0), CopyEventIntoFidlArray(acquire_fence2),
CopyEventIntoFidlArray(release_fence2), nullptr);
// Verify that the currently display image hasn't changed yet, since we
// haven't signalled the acquire fence.
ASSERT_FALSE(RunLoopUntilIdle());
Visit(pipe_material.get());
ASSERT_TRUE(image_pipe->GetEscherImage());
ASSERT_EQ(image_pipe->GetEscherImage(), image1);
// Signal on the acquire fence.
acquire_fence2.signal(0u, escher::kFenceSignalled);
// There should be a new image presented.
ASSERT_TRUE(RunLoopFor(zx::sec(1)));
Visit(pipe_material.get());
escher::ImagePtr image2 = image_pipe->GetEscherImage();
ASSERT_TRUE(image2);
ASSERT_NE(image1, image2);
// The first image should have been released.
ASSERT_TRUE(IsEventSignalled(release_fence1, escher::kFenceSignalled));
ASSERT_FALSE(IsEventSignalled(release_fence2, escher::kFenceSignalled));
}
} // namespace test
} // namespace gfx
} // namespace scenic_impl
| 41.701422 | 100 | 0.726105 | opensource-assist |
0874e429c80093215cb31ed8dac5a23ca3858a6e | 1,522 | cpp | C++ | code/tst/engine/gui/visibility.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 3 | 2020-04-29T14:55:58.000Z | 2020-08-20T08:43:24.000Z | code/tst/engine/gui/visibility.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | 1 | 2022-03-12T11:37:46.000Z | 2022-03-12T20:17:38.000Z | code/tst/engine/gui/visibility.cpp | shossjer/fimbulwinter | d894e4bddb5d2e6dc31a8112d245c6a1828604e3 | [
"0BSD"
] | null | null | null | #include "gui_access.hpp"
#include "engine/gui/view_refresh.hpp"
#include "engine/gui/update.hpp"
#include <catch2/catch.hpp>
SCENARIO("Adding view (show) to already updated group.", "[gui][Visibility]")
{
// this test verified a bug when working with tabs.
View group1 = ViewAccess::create_group(
Layout::RELATIVE,
Size{ { Size::FIXED, height_t{ 200 } },{ Size::FIXED, width_t{ 400 } } });
View group2 = ViewAccess::create_group(
Layout::RELATIVE,
Size{ { Size::PARENT },{ Size::PARENT } },
&group1);
ViewUpdater::update(group1, ViewUpdater::content<View::Group>(group1));
ViewUpdater::update(group2, ViewUpdater::content<View::Group>(group2));
ViewUpdater::content<View::Group>(group1).adopt(&group2);
ViewRefresh::refresh(group1);
REQUIRE(!group1.change.any());
REQUIRE(!group2.change.any());
GIVEN("a PARENT size 'child', which is added to the prev. calculated parent.")
{
View child = ViewAccess::create_child(
View::Content{ utility::in_place_type<View::Color> },
Size{ { Size::PARENT },{ Size::PARENT } },
&group2);
// child is "added" to the views.
ViewUpdater::show(child);
REQUIRE(group1.change.any());
REQUIRE(group2.change.any());
REQUIRE(child.size.height == height_t{ 0 });
REQUIRE(child.size.width == width_t{ 0 });
WHEN("the views are refreshed.")
{
ViewRefresh::refresh(group1);
THEN("the child's size should be updated")
{
REQUIRE(child.size.height == height_t{ 200 });
REQUIRE(child.size.width == width_t{ 400 });
}
}
}
}
| 28.185185 | 79 | 0.676741 | shossjer |
087508ef1969baea4c597ca48c0715b9050b4d45 | 3,129 | cpp | C++ | src/pal/src/misc/strutil.cpp | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 277 | 2015-01-04T20:42:36.000Z | 2022-03-21T06:52:03.000Z | src/pal/src/misc/strutil.cpp | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 31 | 2015-01-05T08:00:38.000Z | 2016-01-05T01:18:59.000Z | src/pal/src/misc/strutil.cpp | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 46 | 2015-01-21T00:41:59.000Z | 2021-03-23T07:00:01.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*++
Module Name:
strutil.cpp
Abstract:
Various string-related utility functions
--*/
#include "pal/corunix.hpp"
#include "pal/thread.hpp"
#include "pal/malloc.hpp"
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(PAL);
using namespace CorUnix;
/*++
Function:
CPalString::CopyString
Copies a CPalString into a new (empty) instance, allocating buffer space
as necessary
Parameters:
pthr -- thread data for calling thread
psSource -- the string to copy from
--*/
PAL_ERROR
CPalString::CopyString(
CPalThread *pthr,
CPalString *psSource
)
{
PAL_ERROR palError = NO_ERROR;
_ASSERTE(NULL != psSource);
_ASSERTE(NULL == m_pwsz);
_ASSERTE(0 == m_dwStringLength);
_ASSERTE(0 == m_dwMaxLength);
if (0 != psSource->GetStringLength())
{
_ASSERTE(psSource->GetMaxLength() > psSource->GetStringLength());
WCHAR *pwsz = reinterpret_cast<WCHAR*>(
InternalMalloc(pthr, psSource->GetMaxLength() * sizeof(WCHAR))
);
if (NULL != pwsz)
{
_ASSERTE(NULL != psSource->GetString());
CopyMemory(
pwsz,
psSource->GetString(),
psSource->GetMaxLength() * sizeof(WCHAR)
);
m_pwsz = pwsz;
m_dwStringLength = psSource->GetStringLength();
m_dwMaxLength = psSource->GetMaxLength();
}
else
{
palError = ERROR_OUTOFMEMORY;
}
}
return palError;
}
/*++
Function:
CPalString::FreeBuffer
Frees the contained string buffer
Parameters:
pthr -- thread data for calling thread
--*/
void
CPalString::FreeBuffer(
CPalThread *pthr
)
{
_ASSERTE(NULL != m_pwsz);
InternalFree(pthr, const_cast<WCHAR*>(m_pwsz));
}
/*++
Function:
InternalWszNameFromSzName
Helper function to convert an ANSI string object name parameter to a
unicode string
Parameters:
pthr -- thread data for calling thread
pszName -- the ANSI string name
pwszName -- on success, receives the converted unicode string
cch -- the size of pwszName, in characters
--*/
PAL_ERROR
CorUnix::InternalWszNameFromSzName(
CPalThread *pthr,
LPCSTR pszName,
LPWSTR pwszName,
DWORD cch
)
{
PAL_ERROR palError = NO_ERROR;
_ASSERTE(NULL != pthr);
_ASSERTE(NULL != pszName);
_ASSERTE(NULL != pwszName);
_ASSERTE(0 < cch);
if (MultiByteToWideChar(CP_ACP, 0, pszName, -1, pwszName, cch) == 0)
{
palError = pthr->GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == palError)
{
ERROR("pszName is larger than cch (%d)!\n", palError);
palError = ERROR_FILENAME_EXCED_RANGE;
}
else
{
ERROR("MultiByteToWideChar failure! (error=%d)\n", palError);
palError = ERROR_INVALID_PARAMETER;
}
}
return palError;
}
| 20.45098 | 102 | 0.612656 | CyberSys |
0875d3ef0f5b8da850ca2e01ab5de311d9e958ea | 22,124 | cpp | C++ | DdsJs/DomainParticipantWrap.cpp | rjnieves/DdsJs | 90939e43b2f62d908b1f43dc61dc4fa54ba4c1e4 | [
"Apache-2.0"
] | null | null | null | DdsJs/DomainParticipantWrap.cpp | rjnieves/DdsJs | 90939e43b2f62d908b1f43dc61dc4fa54ba4c1e4 | [
"Apache-2.0"
] | null | null | null | DdsJs/DomainParticipantWrap.cpp | rjnieves/DdsJs | 90939e43b2f62d908b1f43dc61dc4fa54ba4c1e4 | [
"Apache-2.0"
] | null | null | null | /**
* \file DomainParticipantWrap.cpp
* \brief Contains the implementation for the \c DomainParticipantWrap class.
* \author Rolando J. Nieves
* \date 2014-07-28 16:06:08
*/
#include <arpa/inet.h>
#include <cstring>
#include <sstream>
#include "ddsjs_base.hh"
#include "DomainParticipantWrap.hh"
#include "PublisherWrap.hh"
#include "SubscriberWrap.hh"
using std::stringstream;
using v8::Object;
using v8::Local;
using v8::FunctionTemplate;
using v8::String;
using v8::Persistent;
using v8::Function;
using v8::Value;
using v8::Exception;
using v8::Number;
using v8::HandleScope;
using v8::Undefined;
using v8::Null;
using v8::Isolate;
using v8::FunctionCallbackInfo;
using v8::Primitive;
using v8::PropertyCallbackInfo;
using v8::MaybeLocal;
using v8::Context;
using v8::Maybe;
using node::ObjectWrap;
using DDS::DomainParticipantFactory;
using DDS::DomainId_t;
using DDS::DomainParticipantQos;
using DDS::ReturnCode_t;
using DDS::InstanceHandleSeq;
using DDS::ParticipantBuiltinTopicData;
using DDS::InstanceHandle_t;
namespace DdsJs {
Persistent<Function> DomainParticipantWrap::constructor;
void DomainParticipantWrap::Init(Local<Object> exports)
{
Isolate *isolate = Isolate::GetCurrent();
Local<FunctionTemplate> ctorTmpl = FunctionTemplate::New(
isolate,
DomainParticipantWrap::New
);
ctorTmpl->SetClassName(String::NewFromUtf8(isolate, "DomainParticipant"));
ctorTmpl->InstanceTemplate()->SetInternalFieldCount(2);
/**
* The list of methods included in the JavaScript object prototype are
* derived, for the most part, from an appropriate counterpart in
* \c DDS::DomainParticipant:
* - \c createPublisher() - \c DDS::DomainParticipant::create_publisher()
* - \c createSubscriber() - \c DDS::DomainParticipant::create_subscriber()
* - \c createTopic() - \c DDS::DomainParticipant::create_topic()
* - \c getDiscoveredParticipants() - \c DDS::DomainParticipant::get_discovered_participants()
* - \c getDiscoveredParticipantData() - \c DDS::DomainParticipant::get_discovered_participant_data()
* - \c deleteContainedEntities() - \c DDS::DomainParticipant::delete_contained_entities()
* - \c addTransport() - \c DDS::DomainParticipant::add_transport()
* - \c enable() - \c DDS::DomainParticipant::enable()
* - \c getInstanceHandle() - \c DDS::DomainParticipant::get_instance_handle()
* - \c ignoreParticipant() - \c DDS::DomainParticipant::ignore_participant()
*/
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "createPublisher", DomainParticipantWrap::CreatePublisher);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "createSubscriber", DomainParticipantWrap::CreateSubscriber);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "createTopic", DomainParticipantWrap::CreateTopic);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "getDiscoveredParticipants", DomainParticipantWrap::GetDiscoveredParticipants);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "getDiscoveredParticipantData", DomainParticipantWrap::GetDiscoveredParticipantData);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "getDiscoveredParticipantNameAndIp", DomainParticipantWrap::GetDiscoveredParticipantNameAndIp);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "deleteContainedEntities", DomainParticipantWrap::DeleteContainedEntities);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "enable", DomainParticipantWrap::Enable);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "getInstanceHandle", DomainParticipantWrap::GetInstanceHandle);
NODE_SET_PROTOTYPE_METHOD(ctorTmpl, "ignoreParticipant", DomainParticipantWrap::IgnoreParticipant);
auto ctorFun = ctorTmpl->GetFunction(isolate->GetCurrentContext()).ToLocalChecked();
DomainParticipantWrap::constructor.Reset(isolate, ctorFun);
exports->Set(
isolate->GetCurrentContext(),
String::NewFromUtf8(isolate, "DomainParticipant"),
ctorFun
).Check();
}
DomainParticipantWrap::DomainParticipantWrap()
: m_theParticipant(NULL)
{
}
DomainParticipantWrap::~DomainParticipantWrap()
{
if (m_theParticipant != NULL)
{
/**
* In addition to resetting internal fields, the destructor for
* \c DomainParticipantWrap attempts to clean up the underlying
* C++ object tree created by the CoreDX library.
*/
m_theParticipant->delete_contained_entities();
DomainParticipantFactory::get_instance()->delete_participant(m_theParticipant);
m_theParticipant = NULL;
}
}
void DomainParticipantWrap::New(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
Local< Context > ctx = isolate->GetCurrentContext();
HandleScope scope(isolate);
if (nullptr == isolate)
{
return;
}
if (args.Length() < 1)
{
isolate->ThrowException(
Exception::TypeError(
String::NewFromUtf8(
isolate,
"Not enough arguments in DomainParticipant constructor."
)
)
);
return;
}
if (!args[0]->IsNumber())
{
isolate->ThrowException(
Exception::TypeError(
String::NewFromUtf8(
isolate,
"Domain ID must be a number."
)
)
);
return;
}
if (args.IsConstructCall())
{
DomainParticipantWrap *obj = new DomainParticipantWrap();
DomainParticipantQos dpQos;
DomainParticipantFactory::get_instance()->get_default_participant_qos(&dpQos);
if ((args.Length() > 1) && !args[1]->IsNull())
{
// -----------------------------------------------------------------------------
// At the moment, the only arguments supported on DomainParticipant construction
// are the domain ID and optionally a Quality of Service (QoS) specification.
// -----------------------------------------------------------------------------
if (!::DDS::DomainParticipantQosField::FromJsValueToCpp(args[1], dpQos))
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Invalid QoS object passed to DomainParticipant constructor."
)
)
);
delete obj;
obj = NULL;
return;
}
}
auto domainIdMaybe = args[0]->NumberValue(ctx);
if (domainIdMaybe.IsNothing())
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Could not create participant instance."
)
)
);
return;
}
DomainId_t domainIdVal = static_cast< DomainId_t >(domainIdMaybe.FromJust());
obj->m_theParticipant = DomainParticipantFactory::get_instance()->create_participant(
domainIdVal,
dpQos,
NULL,
0
);
obj->Wrap(args.This());
args.This()->SetAlignedPointerInInternalField(1, obj->m_theParticipant);
Maybe< bool > defineResult = args.This()->DefineOwnProperty(
ctx,
String::NewFromUtf8(
isolate,
"domainId"
),
Number::New(
isolate,
domainIdVal
),
::v8::ReadOnly
);
if (!defineResult.FromMaybe(false))
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Could not create participant instance."
)
)
);
return;
}
args.GetReturnValue().Set(args.This());
}
else
{
unsigned argc = 3u;
Local<Value> argv[] = {
args[0],
Undefined(isolate),
Undefined(isolate)
};
if (args.Length() > 2)
{
argv[2] = args[2];
}
else
{
argc--;
}
if (args.Length() > 1)
{
argv[1] = args[1];
}
else
{
argc--;
}
Local<Function> cons = Local<Function>::New(isolate, constructor);
MaybeLocal< Object > resultMaybe = cons->NewInstance(
isolate->GetCurrentContext(),
argc,
argv
);
if (resultMaybe.IsEmpty())
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Could not create participant instance."
)
)
);
return;
}
args.GetReturnValue().Set(resultMaybe.ToLocalChecked());
}
}
void DomainParticipantWrap::CreatePublisher(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
unsigned argc = 3u;
Local<Value> argv[] = {
args.This(),
Undefined(isolate),
Undefined(isolate)
};
if (args.Length() > 1)
{
argv[2] = args[1];
}
else
{
argc--;
}
if (args.Length() > 0)
{
argv[1] = args[0];
}
else
{
argc--;
}
/**
* Instead of calling the \c DDS::DomainParticipant::create_publisher()
* method directly, \c CreatePublisher() relies on the constructor object
* created by the \c PublisherWrap class, thereby reconciling the differences
* that exist between the object wrapping pattern of Node.js and API
* mechanisms of DDS.
*/
Local<Function> pubCons = Local<Function>::New(
isolate,
PublisherWrap::constructor
);
MaybeLocal< Object > resultMaybe = pubCons->NewInstance(
isolate->GetCurrentContext(),
argc,
argv
);
if (resultMaybe.IsEmpty())
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Could not create publisher instance."
)
)
);
return;
}
args.GetReturnValue().Set(resultMaybe.FromMaybe(Local< Object >()));
}
void DomainParticipantWrap::CreateSubscriber(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
unsigned argc = 3u;
Local<Value> argv[] = {
args.This(),
Undefined(isolate),
Undefined(isolate)
};
if (args.Length() > 1)
{
argv[2] = args[1];
}
else
{
argc--;
}
if (args.Length() > 0)
{
argv[1] = args[0];
}
else
{
argc--;
}
/**
* Instead of calling the \c DDS::DomainParticipant::create_subscriber()
* method directly, \c CreateSubscriber() relies on the constructor object
* created by the \c SubscriberWrap class, thereby reconciling the differences
* that exist between the object wrapping pattern of Node.js and API
* mechanisms of DDS.
*/
Local<Function> subCons = Local<Function>::New(
isolate,
SubscriberWrap::constructor
);
MaybeLocal< Object > resultMaybe = subCons->NewInstance(
isolate->GetCurrentContext(),
argc,
argv
);
if (resultMaybe.IsEmpty())
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Could not create subscriber instance."
)
)
);
return;
}
args.GetReturnValue().Set(resultMaybe.FromMaybe(Local< Object >()));
}
void DomainParticipantWrap::CreateTopic(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
unsigned argc = 3u;
if (args.Length() < 1)
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Not enough arguments to createTopic() method call."
)
)
);
return;
}
if (!args[0]->IsFunction())
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"First argument to createTopic() must be the topic class."
)
)
);
return;
}
Local<Value> argv[] = {
args.This(),
Undefined(isolate),
Undefined(isolate)
};
if (args.Length() > 2)
{
argv[2] = args[2];
}
else
{
argc--;
}
if (args.Length() > 1)
{
argv[1] = args[1];
}
else
{
argc--;
}
/**
* Instead of calling the \c DDS::DomainParticipant::create_topic() method
* directly, \c CreateTopic() relies on a factory object passed in to the
* \c createTopic() call. This factory object is generated by the IDL
* compiler and is available to the JavaScript script. Doing this reconciles
* the difference that exists between the object wrapping pattern of Node.js
* and the DDS API mechanics.
*/
Local<Function> topicFactory = Local<Function>::New(
isolate,
Local<Function>::Cast(args[0])
);
MaybeLocal< Object > resultMaybe = topicFactory->NewInstance(
isolate->GetCurrentContext(),
argc,
argv
);
if (resultMaybe.IsEmpty())
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Could not create topic instance."
)
)
);
return;
}
args.GetReturnValue().Set(resultMaybe.FromMaybe(Local< Object >()));
}
void DomainParticipantWrap::GetDiscoveredParticipants(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
InstanceHandleSeq dpHandles;
ReturnCode_t ddsRetCode;
DomainParticipantWrap *me = ObjectWrap::Unwrap<DomainParticipantWrap>(args.This());
ddsRetCode = me->m_theParticipant->get_discovered_participants(&dpHandles);
if (DDS::RETCODE_OK == ddsRetCode)
{
args.GetReturnValue().Set(
UnboundedSeqField< ::DdsJs::InstanceHandleField >::FromCppToJsValue(
dpHandles
)
);
}
else
{
args.GetReturnValue().Set(Null(isolate));
}
}
void DomainParticipantWrap::GetDiscoveredParticipantData(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
ParticipantBuiltinTopicData dpInfo;
ReturnCode_t ddsRetCode;
InstanceHandle_t dpHandle;
if ((args.Length() < 1) || !InstanceHandleField::FromJsValueToCpp(args[0], dpHandle))
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"DomainParticipant instance handle must be specified "
"when calling getDiscoveredParticipantData()."
)
)
);
return;
}
DomainParticipantWrap *me = ObjectWrap::Unwrap<DomainParticipantWrap>(args.This());
ddsRetCode = me->m_theParticipant->get_discovered_participant_data(
&dpInfo,
dpHandle
);
if (DDS::RETCODE_OK == ddsRetCode)
{
args.GetReturnValue().Set(
::DDS::ParticipantBuiltinTopicDataField::FromCppToJsValue(
dpInfo
)
);
}
else
{
args.GetReturnValue().Set(Null(isolate));
}
}
void DomainParticipantWrap::GetDiscoveredParticipantNameAndIp(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
ParticipantBuiltinTopicData dpInfo;
ReturnCode_t ddsRetCode;
InstanceHandle_t dpHandle;
Local<Object> result(Object::New(isolate));
char ipAddrText[20];
Maybe< bool > setResult = ::v8::Nothing< bool >();
memset(ipAddrText, 0x00, sizeof(ipAddrText));
if ((args.Length() < 1) || !InstanceHandleField::FromJsValueToCpp(args[0], dpHandle))
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"DomainParticipant instance handle must be specified "
"when calling getDiscoveredParticipantData()."
)
)
);
return;
}
DomainParticipantWrap *me = ObjectWrap::Unwrap<DomainParticipantWrap>(args.This());
ddsRetCode = me->m_theParticipant->get_discovered_participant_data(&dpInfo, dpHandle);
if ((DDS::RETCODE_OK == ddsRetCode) && (dpInfo.entity_name != NULL))
{
/**
* CoreDX embeds a participant name, and its corresponding address
* information, in the participant data object retrieved using
* \c DDS::DomainParticipant::get_discovered_participant_data() method.
* This class method takes advantage of this CoreDX-exclusive feature
* and parses out the information for JavaScript scripts.
*/
setResult = result->Set(
isolate->GetCurrentContext(),
String::NewFromUtf8(isolate, "name"),
String::NewFromUtf8(isolate, dpInfo.entity_name)
);
if (!setResult.FromMaybe(false))
{
// TODO: Throw exception.
}
struct in_addr theAddr;
theAddr.s_addr = dpInfo.key.value[0];
if (inet_ntop(AF_INET, &theAddr, ipAddrText, sizeof(ipAddrText)) == NULL)
{
strcpy(ipAddrText, "Unknown");
}
setResult = result->Set(
isolate->GetCurrentContext(),
String::NewFromUtf8(isolate, "ipAddress"),
String::NewFromUtf8(isolate, ipAddrText)
);
if (!setResult.FromMaybe(false))
{
// TODO: Throw exception.
}
args.GetReturnValue().Set(result);
}
else
{
args.GetReturnValue().Set(Null(isolate));
}
}
void DomainParticipantWrap::DeleteContainedEntities(FunctionCallbackInfo<Value> const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
ReturnCode_t ddsRetCode = DDS::RETCODE_OK;
DomainParticipantWrap *me = ObjectWrap::Unwrap<DomainParticipantWrap>(args.This());
ddsRetCode = me->m_theParticipant->delete_contained_entities();
if (ddsRetCode != DDS::RETCODE_OK)
{
stringstream errorMsg;
errorMsg << "Could not delete contained entities: " << DDS_error(ddsRetCode);
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
errorMsg.str().c_str()
)
)
);
}
}
void DomainParticipantWrap::Enable(FunctionCallbackInfo< Value > const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
DomainParticipantWrap *obj = ObjectWrap::Unwrap< DomainParticipantWrap >(args.This());
DDS::ReturnCode_t ddsRetCode = ::DDS::RETCODE_OK;
ddsRetCode = obj->m_theParticipant->enable();
if (ddsRetCode != ::DDS::RETCODE_OK)
{
stringstream errorMsg;
errorMsg << "Could not enable DomainParticipant:" << DDS_error(ddsRetCode);
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
errorMsg.str().c_str()
)
)
);
}
}
void DomainParticipantWrap::GetInstanceHandle(FunctionCallbackInfo< Value > const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
DomainParticipantWrap *obj = ObjectWrap::Unwrap< DomainParticipantWrap >(args.This());
InstanceHandle_t dpHandle;
dpHandle = obj->m_theParticipant->get_instance_handle();
args.GetReturnValue().Set(InstanceHandleField::FromCppToJsValue(dpHandle));
}
void DomainParticipantWrap::IgnoreParticipant(FunctionCallbackInfo< Value > const& args)
{
Isolate *isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
DomainParticipantWrap *obj = ObjectWrap::Unwrap< DomainParticipantWrap >(args.This());
InstanceHandle_t dpHandle;
ReturnCode_t ddsRetCode = ::DDS::RETCODE_OK;
if (args.Length() < 1)
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Not enough arguments passed to ignoreParticipant()."
)
)
);
return;
}
if (InstanceHandleField::FromJsValueToCpp(args[0], dpHandle) != true)
{
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
"Invalid argument passed to ignoreParticipant()."
)
)
);
return;
}
ddsRetCode = obj->m_theParticipant->ignore_participant(dpHandle);
if (ddsRetCode != ::DDS::RETCODE_OK)
{
stringstream errorMsg;
errorMsg << "Could not ignore participant:" << DDS_error(ddsRetCode);
isolate->ThrowException(
Exception::Error(
String::NewFromUtf8(
isolate,
errorMsg.str().c_str()
)
)
);
}
}
} // end namespace DdsJs
| 29.696644 | 135 | 0.579054 | rjnieves |
0876b21d67c4098018aa913f8ca45d32be2b96e2 | 11,174 | cc | C++ | src/openvslam/match/bow_tree.cc | Ling-Bao/openvslam | 8e891482c1950be3bbf1c0565299bc8c6e5d9910 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 2 | 2019-06-15T15:25:54.000Z | 2021-09-22T07:40:12.000Z | src/openvslam/match/bow_tree.cc | Ling-Bao/openvslam | 8e891482c1950be3bbf1c0565299bc8c6e5d9910 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | null | null | null | src/openvslam/match/bow_tree.cc | Ling-Bao/openvslam | 8e891482c1950be3bbf1c0565299bc8c6e5d9910 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | 1 | 2019-10-24T08:42:22.000Z | 2019-10-24T08:42:22.000Z | #include "openvslam/match/bow_tree.h"
#include "openvslam/data/frame.h"
#include "openvslam/data/keyframe.h"
#include "openvslam/data/landmark.h"
#ifdef USE_DBOW2
#include <DBoW2/FeatureVector.h>
#else
#include <fbow/fbow.h>
#endif
namespace openvslam {
namespace match {
unsigned int bow_tree::match_frame_and_keyframe(data::keyframe* keyfrm, data::frame& frm, std::vector<data::landmark*>& matched_lms_in_frm) const {
unsigned int num_matches = 0;
std::array<std::vector<int>, HISTOGRAM_LENGTH> orientation_histogram;
for (auto& bin : orientation_histogram) {
bin.reserve(500);
}
matched_lms_in_frm = std::vector<data::landmark*>(frm.num_keypts_, nullptr);
const auto keyfrm_lms = keyfrm->get_landmarks();
#ifdef USE_DBOW2
DBoW2::FeatureVector::const_iterator keyfrm_itr = keyfrm->bow_feat_vec_.begin();
DBoW2::FeatureVector::const_iterator frm_itr = frm.bow_feat_vec_.begin();
const DBoW2::FeatureVector::const_iterator kryfrm_end = keyfrm->bow_feat_vec_.end();
const DBoW2::FeatureVector::const_iterator frm_end = frm.bow_feat_vec_.end();
#else
fbow::BoWFeatVector::const_iterator keyfrm_itr = keyfrm->bow_feat_vec_.begin();
fbow::BoWFeatVector::const_iterator frm_itr = frm.bow_feat_vec_.begin();
const fbow::BoWFeatVector::const_iterator kryfrm_end = keyfrm->bow_feat_vec_.end();
const fbow::BoWFeatVector::const_iterator frm_end = frm.bow_feat_vec_.end();
#endif
while (keyfrm_itr != kryfrm_end && frm_itr != frm_end) {
// BoW treeのノード番号(first)が一致しているか確認する
if (keyfrm_itr->first == frm_itr->first) {
// BoW treeのノード番号(first)が一致していれば,
// 実際に特徴点index(second)を持ってきて対応しているか確認する
const auto& keyfrm_indices = keyfrm_itr->second;
const auto& frm_indices = frm_itr->second;
for (const auto keyfrm_idx : keyfrm_indices) {
// keyfrm_idxの特徴点と3次元点が対応していない場合はスルーする
auto* lm = keyfrm_lms.at(keyfrm_idx);
if (!lm) {
continue;
}
if (lm->will_be_erased()) {
continue;
}
const auto& keyfrm_desc = keyfrm->descriptors_.row(keyfrm_idx);
unsigned int best_hamm_dist = MAX_HAMMING_DIST;
int best_frm_idx = -1;
unsigned int second_best_hamm_dist = MAX_HAMMING_DIST;
for (const auto frm_idx : frm_indices) {
if (matched_lms_in_frm.at(frm_idx)) {
continue;
}
const auto& frm_desc = frm.descriptors_.row(frm_idx);
const auto hamm_dist = compute_descriptor_distance_32(keyfrm_desc, frm_desc);
if (hamm_dist < best_hamm_dist) {
second_best_hamm_dist = best_hamm_dist;
best_hamm_dist = hamm_dist;
best_frm_idx = frm_idx;
}
else if (hamm_dist < second_best_hamm_dist) {
second_best_hamm_dist = hamm_dist;
}
}
if (HAMMING_DIST_THR_LOW < best_hamm_dist) {
continue;
}
// ratio test
if (lowe_ratio_ * second_best_hamm_dist < static_cast<float>(best_hamm_dist)) {
continue;
}
matched_lms_in_frm.at(best_frm_idx) = lm;
if (check_orientation_) {
const auto& keypt = keyfrm->keypts_.at(keyfrm_idx);
auto delta_angle = keypt.angle - frm.keypts_.at(best_frm_idx).angle;
if (delta_angle < 0.0) {
delta_angle += 360.0;
}
if (360.0 <= delta_angle) {
delta_angle -= 360.0;
}
const auto bin = static_cast<unsigned int>(cvRound(delta_angle * INV_HISTOGRAM_LENGTH));
assert(bin < HISTOGRAM_LENGTH);
orientation_histogram.at(bin).push_back(best_frm_idx);
}
++num_matches;
}
++keyfrm_itr;
++frm_itr;
}
else if (keyfrm_itr->first < frm_itr->first) {
// keyfrm_itrのノード番号のほうが小さいので,ノード番号が合うところまでイテレータkeyfrm_itrをすすめる
keyfrm_itr = keyfrm->bow_feat_vec_.lower_bound(frm_itr->first);
}
else {
// frm_itrのノード番号のほうが小さいので,ノード番号が合うところまでイテレータfrm_itrをすすめる
frm_itr = frm.bow_feat_vec_.lower_bound(keyfrm_itr->first);
}
}
if (check_orientation_) {
const auto bins = index_sort_by_size(orientation_histogram);
// ヒストグラムのbinのうち,ヒストグラムの上位n個に入っているもののみを有効にする
for (unsigned int bin = 0; bin < HISTOGRAM_LENGTH; ++bin) {
const bool is_valid_match = std::any_of(bins.begin(), bins.begin() + NUM_BINS_THR,
[bin](const unsigned int i){ return bin == i; });
if (is_valid_match) {
continue;
}
for (const auto invalid_idx : orientation_histogram.at(bin)) {
matched_lms_in_frm.at(invalid_idx) = nullptr;
--num_matches;
}
}
}
return num_matches;
}
unsigned int bow_tree::match_keyframes(data::keyframe* keyfrm_1, data::keyframe* keyfrm_2, std::vector<data::landmark*>& matched_lms_in_keyfrm_1) const {
unsigned int num_matches = 0;
std::array<std::vector<int>, HISTOGRAM_LENGTH> orientation_histogram;
for (auto& bin : orientation_histogram) {
bin.reserve(500);
}
const auto keyfrm_1_lms = keyfrm_1->get_landmarks();
const auto keyfrm_2_lms = keyfrm_2->get_landmarks();
matched_lms_in_keyfrm_1 = std::vector<data::landmark*>(keyfrm_1_lms.size(), nullptr);
// keyframe2の特徴点のうち,keyfram1の特徴点と対応が取れているものはtrueにする
// NOTE: sizeはkeyframe2の特徴点に一致
std::vector<bool> is_already_matched_in_keyfrm_2(keyfrm_2_lms.size(), false);
#ifdef USE_DBOW2
DBoW2::FeatureVector::const_iterator itr_1 = keyfrm_1->bow_feat_vec_.begin();
DBoW2::FeatureVector::const_iterator itr_2 = keyfrm_2->bow_feat_vec_.begin();
const DBoW2::FeatureVector::const_iterator itr_1_end = keyfrm_1->bow_feat_vec_.end();
const DBoW2::FeatureVector::const_iterator itr_2_end = keyfrm_2->bow_feat_vec_.end();
#else
fbow::BoWFeatVector::const_iterator itr_1 = keyfrm_1->bow_feat_vec_.begin();
fbow::BoWFeatVector::const_iterator itr_2 = keyfrm_2->bow_feat_vec_.begin();
const fbow::BoWFeatVector::const_iterator itr_1_end = keyfrm_1->bow_feat_vec_.end();
const fbow::BoWFeatVector::const_iterator itr_2_end = keyfrm_2->bow_feat_vec_.end();
#endif
while (itr_1 != itr_1_end && itr_2 != itr_2_end) {
// BoW treeのノード番号(first)が一致しているか確認する
if (itr_1->first == itr_2->first) {
// BoW treeのノード番号(first)が一致していれば,
// 実際に特徴点index(second)を持ってきて対応しているか確認する
const auto& keyfrm_1_indices = itr_1->second;
const auto& keyfrm_2_indices = itr_2->second;
for (const auto idx_1 : keyfrm_1_indices) {
// keyfrm_1の特徴点と3次元点が対応していない場合はスルーする
auto* lm_1 = keyfrm_1_lms.at(idx_1);
if (!lm_1) {
continue;
}
if (lm_1->will_be_erased()) {
continue;
}
const auto& desc_1 = keyfrm_1->descriptors_.row(idx_1);
unsigned int best_hamm_dist = MAX_HAMMING_DIST;
int best_idx_2 = -1;
unsigned int second_best_hamm_dist = MAX_HAMMING_DIST;
for (const auto idx_2 : keyfrm_2_indices) {
// keyfrm_2の特徴点と3次元点が対応していない場合はスルーする
auto* lm_2 = keyfrm_2_lms.at(idx_2);
if (!lm_2) {
continue;
}
if (lm_2->will_be_erased()) {
continue;
}
if (is_already_matched_in_keyfrm_2.at(idx_2)) {
continue;
}
const auto& desc_2 = keyfrm_2->descriptors_.row(idx_2);
const auto hamm_dist = compute_descriptor_distance_32(desc_1, desc_2);
if (hamm_dist < best_hamm_dist) {
second_best_hamm_dist = best_hamm_dist;
best_hamm_dist = hamm_dist;
best_idx_2 = idx_2;
}
else if (hamm_dist < second_best_hamm_dist) {
second_best_hamm_dist = hamm_dist;
}
}
if (HAMMING_DIST_THR_LOW < best_hamm_dist) {
continue;
}
// ratio test
if (lowe_ratio_ * second_best_hamm_dist < static_cast<float>(best_hamm_dist)) {
continue;
}
// 対応情報を記録する
// keyframe1のidx_1とkeyframe2のbest_idx_2が対応している
matched_lms_in_keyfrm_1.at(idx_1) = keyfrm_2_lms.at(best_idx_2);
// keyframe2のbest_idx_2はすでにkeyframe1の特徴点と対応している
is_already_matched_in_keyfrm_2.at(best_idx_2) = true;
if (check_orientation_) {
auto delta_angle = keyfrm_1->keypts_.at(idx_1).angle - keyfrm_2->keypts_.at(best_idx_2).angle;
if (delta_angle < 0.0) {
delta_angle += 360.0;
}
if (360.0 <= delta_angle) {
delta_angle -= 360.0;
}
const auto bin = static_cast<unsigned int>(cvRound(delta_angle * INV_HISTOGRAM_LENGTH));
assert(bin < HISTOGRAM_LENGTH);
orientation_histogram.at(bin).push_back(idx_1);
}
num_matches++;
}
++itr_1;
++itr_2;
}
else if (itr_1->first < itr_2->first) {
itr_1 = keyfrm_1->bow_feat_vec_.lower_bound(itr_2->first);
}
else {
itr_2 = keyfrm_2->bow_feat_vec_.lower_bound(itr_1->first);
}
}
if (check_orientation_) {
const auto bins = index_sort_by_size(orientation_histogram);
// ヒストグラムのbinのうち,ヒストグラムの上位n個に入っているもののみを有効にする
for (unsigned int bin = 0; bin < HISTOGRAM_LENGTH; ++bin) {
const bool is_valid_match = std::any_of(bins.begin(), bins.begin() + NUM_BINS_THR,
[bin](const unsigned int i){ return bin == i; });
if (is_valid_match) {
continue;
}
for (const auto invalid_idx : orientation_histogram.at(bin)) {
matched_lms_in_keyfrm_1.at(invalid_idx) = nullptr;
--num_matches;
}
}
}
return num_matches;
}
} // namespace match
} // namespace openvslam
| 38.136519 | 153 | 0.563809 | Ling-Bao |
08772ee8d1714875946cd401bc3af2f58a414ec8 | 38,861 | cpp | C++ | src/protocols/mqtt5/Mqtt5Serialization.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | src/protocols/mqtt5/Mqtt5Serialization.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | src/protocols/mqtt5/Mqtt5Serialization.cpp | mnaveedb/finalmq | 3c3b2b213fa07bb5427a1364796b19d732890ed2 | [
"MIT"
] | null | null | null | //MIT License
//Copyright (c) 2020 bexoft GmbH (mail@bexoft.de)
//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.
#include "finalmq/protocols/mqtt5/Mqtt5Serialization.h"
#include "finalmq/protocols/mqtt5/Mqtt5Properties.h"
#include "finalmq/variant/VariantValues.h"
namespace finalmq {
static const ssize_t HEADERSIZE = 1;
#define HEADER_Low4bits(header) (((header) >> 0) & 0x0f)
#define HEADER_Dup(header) (((header) >> 3) & 0x01)
#define HEADER_QoS(header) (((header) >> 1) & 0x03)
#define HEADER_Retain(header) (((header) >> 0) & 0x01)
#define HEADER_SetCommand(value) ((static_cast<unsigned int>(value) & 0x0f) << 4)
#define HEADER_SetLow4bits(value) (((value) & 0x0f) << 0)
#define HEADER_SetDup(value) (((value) & 0x01) << 3)
#define HEADER_SetQoS(value) (((value) & 0x03) << 1)
#define HEADER_SetRetain(value) (((value) & 0x01) << 0)
#define CF_UserName(flags) (((flags) >> 7) & 0x01)
#define CF_Password(flags) (((flags) >> 6) & 0x01)
#define CF_WillRetain(flags) (((flags) >> 5) & 0x01)
#define CF_WillQoS(flags) (((flags) >> 3) & 0x03)
#define CF_WillFlag(flags) (((flags) >> 2) & 0x01)
#define CF_CleanStart(flags) (((flags) >> 1) & 0x01)
#define CF_SetUserName(value) (((value) & 0x01) << 7)
#define CF_SetPassword(value) (((value) & 0x01) << 6)
#define CF_SetWillRetain(value) (((value) & 0x01) << 5)
#define CF_SetWillQoS(value) (((value) & 0x03) << 3)
#define CF_SetWillFlag(value) (((value) & 0x01) << 2)
#define CF_SetCleanStart(value) (((value) & 0x01) << 1)
Mqtt5Serialization::Mqtt5Serialization(char* buffer, unsigned int sizeBuffer, unsigned int indexBuffer)
: m_buffer(reinterpret_cast<std::uint8_t*>(buffer))
, m_sizeBuffer(sizeBuffer)
, m_indexBuffer(indexBuffer)
{
}
unsigned int Mqtt5Serialization::getReadIndex() const
{
return m_indexBuffer;
}
bool Mqtt5Serialization::deserializeConnect(Mqtt5ConnectData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0)
{
return false;
}
// protocol
bool ok = readString(data.protocol);
if (!ok || data.protocol != "MQTT")
{
return false;
}
// version
ok = read1ByteNumber(data.version);
if (!ok || data.version != 5)
{
return false;
}
// connect flags
unsigned int connectFlags = 0;
ok = read1ByteNumber(connectFlags);
if (!ok)
{
return false;
}
// keep alive
ok = read2ByteNumber(data.keepAlive);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
// client ID
ok = readString(data.clientId);
if (!ok)
{
return false;
}
// will message
if (CF_WillFlag(connectFlags))
{
data.willMessage = std::make_unique<Mqtt5WillMessage>();
// will properties
ok = readProperties(data.willMessage->properties, data.willMessage->metainfo);
if (!ok)
{
return false;
}
// will topic
ok = readString(data.willMessage->topic);
if (!ok)
{
return false;
}
// will payload
ok = readBinary(data.willMessage->payload);
if (!ok)
{
return false;
}
data.willMessage->retain = CF_WillRetain(connectFlags);
data.willMessage->qos = CF_WillQoS(connectFlags);
}
// username
if (CF_UserName(connectFlags))
{
ok = readString(data.username);
if (!ok)
{
return false;
}
}
// password
if (CF_Password(connectFlags))
{
ok = readString(data.password);
if (!ok)
{
return false;
}
}
data.cleanStart = CF_CleanStart(connectFlags);
return ok;
}
unsigned int Mqtt5Serialization::sizeConnect(const Mqtt5ConnectData& data, unsigned int& sizePropPayload, unsigned int& sizePropWillMessage)
{
unsigned int size = 0;
// protocol
size += sizeString("MQTT");
// version (1), connect flags (1), keep alive (2)
size += 1 + 1 + 2;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
// client ID
size += sizeString(data.clientId);
// will message
sizePropWillMessage = 0;
if (data.willMessage)
{
// will properties
size += sizeProperties(data.willMessage->properties, data.willMessage->metainfo, sizePropWillMessage);
// will topic
size += sizeString(data.willMessage->topic);
// will payload
size += sizeBinary(data.willMessage->payload);
}
// username
if (!data.username.empty())
{
size += sizeString(data.username);
}
// password
if (!data.password.empty())
{
size += sizeString(data.password);
}
return size;
}
void Mqtt5Serialization::serializeConnect(const Mqtt5ConnectData& data, unsigned int sizePayload, unsigned int sizePropPayload, unsigned int sizePropWillMessage)
{
unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_CONNECT);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// protocol
writeString("MQTT");
// version
write1ByteNumber(5);
// connect flags
unsigned int connectFlags = 0;
if (data.willMessage)
{
connectFlags |= CF_SetWillFlag(1);
connectFlags |= CF_SetWillRetain(data.willMessage->retain ? 1 : 0);
connectFlags |= CF_SetWillQoS(data.willMessage->qos);
}
if (!data.username.empty())
{
connectFlags |= CF_SetUserName(1);
}
if (!data.password.empty())
{
connectFlags |= CF_SetPassword(1);
}
connectFlags |= CF_SetCleanStart(data.cleanStart ? 1 : 0);
write1ByteNumber(connectFlags);
// keep alive
write2ByteNumber(data.keepAlive);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
// client ID
writeString(data.clientId);
// will message
if (data.willMessage)
{
// will properties
writeProperties(data.willMessage->properties, data.willMessage->metainfo, sizePropWillMessage);
// will topic
writeString(data.willMessage->topic);
// will payload
writeBinary(data.willMessage->payload);
}
// username
if (!data.username.empty())
{
writeString(data.username);
}
// password
if (!data.password.empty())
{
writeString(data.password);
}
assert(m_indexBuffer == m_sizeBuffer);
}
#define CAF_SessionPresent(flags) (((flags) & 0x01) >> 0)
#define CAF_SetSessionPresent(value) (((value) & 0x01) << 1)
bool Mqtt5Serialization::deserializeConnAck(Mqtt5ConnAckData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0)
{
return false;
}
// connect ack flags
unsigned int connackflags = 0;
bool ok = read1ByteNumber(connackflags);
if (!ok)
{
return false;
}
data.sessionPresent = CAF_SessionPresent(connackflags);
// reason code
ok = read1ByteNumber(data.reasoncode);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
return ok;
}
unsigned int Mqtt5Serialization::sizeConnAck(const Mqtt5ConnAckData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
// connect ack flags (1), reason code (1)
size += 1 + 1;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
return size;
}
void Mqtt5Serialization::serializeConnAck(const Mqtt5ConnAckData& data, unsigned int sizePayload, unsigned int sizePropPayload)
{
unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_CONNACK);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// connect ack flags
unsigned int connackflags = 0;
connackflags |= CAF_SetSessionPresent(data.sessionPresent);
write1ByteNumber(connackflags);
// reason code
write1ByteNumber(data.reasoncode);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::deserializePublish(Mqtt5PublishData& data)
{
data.qos = HEADER_QoS(m_buffer[0]);
data.dup = HEADER_Dup(m_buffer[0]);
data.retain = HEADER_Retain(m_buffer[0]);
// topic name
bool ok = readString(data.topic);
if (!ok)
{
return false;
}
// packet identifier
if (data.qos > 0)
{
ok = read2ByteNumber(data.packetId);
if (!ok)
{
return false;
}
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
return ok;
}
unsigned int Mqtt5Serialization::sizePublish(const Mqtt5PublishData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
// topic name
size += sizeString(data.topic);
// packet identifier
if (data.qos > 0)
{
size += 2;
}
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
return size;
}
void Mqtt5Serialization::serializePublish(const Mqtt5PublishData& data, unsigned int sizePayload, unsigned int sizePropPayload, std::uint8_t*& bufferPacketId)
{
bufferPacketId = nullptr;
unsigned int header = 0;
header |= HEADER_SetCommand(Mqtt5Command::COMMAND_PUBLISH);
header |= HEADER_SetQoS(data.qos);
header |= HEADER_SetDup(data.dup);
header |= HEADER_SetRetain(data.retain);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// topic name
writeString(data.topic);
// packet identifier
if (data.qos > 0)
{
bufferPacketId = &m_buffer[m_indexBuffer];
write2ByteNumber(data.packetId);
}
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::deserializePubAck(Mqtt5PubAckData& data, Mqtt5Command command)
{
if (command == Mqtt5Command::COMMAND_PUBREL)
{
if (HEADER_Low4bits(m_buffer[0]) != 0x02)
{
return false;
}
}
else
{
if (HEADER_Low4bits(m_buffer[0]) != 0x00)
{
return false;
}
}
// packet identifier
bool ok = read2ByteNumber(data.packetId);
if (!ok)
{
return false;
}
if (doesFit(1))
{
// reason code
ok = read1ByteNumber(data.reasoncode);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
}
return ok;
}
unsigned int Mqtt5Serialization::sizePubAck(const Mqtt5PubAckData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
// packet identifier
size += 2;
if (data.reasoncode != 0 || !data.properties.empty() || !data.metainfo.empty())
{
// reason code
size += 1;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
}
return size;
}
void Mqtt5Serialization::serializePubAck(const Mqtt5PubAckData& data, Mqtt5Command command, unsigned int sizePayload, unsigned int sizePropPayload)
{
unsigned int header = 0;
header |= HEADER_SetCommand(command);
if (command == Mqtt5Command::COMMAND_PUBREL)
{
header |= HEADER_SetLow4bits(0x02);
}
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// packet identifier
write2ByteNumber(data.packetId);
if (data.reasoncode != 0 || !data.properties.empty() || !data.metainfo.empty())
{
// reason code
write1ByteNumber(data.reasoncode);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
}
assert(m_indexBuffer == m_sizeBuffer);
}
#define SO_RetainHandling(flags) (((flags) >> 4) & 0x03)
#define SO_RetainAsPublished(flags) (((flags) >> 3) & 0x01)
#define SO_NoLocal(flags) (((flags) >> 2) & 0x01)
#define SO_QoS(flags) (((flags) >> 0) & 0x03)
#define SO_SetRetainHandling(value) (((value) & 0x03) << 4)
#define SO_SetRetainAsPublished(value) (((value) & 0x01) << 3)
#define SO_SetNoLocal(value) (((value) & 0x01) << 2)
#define SO_SetQoS(value) (((value) & 0x03) << 0)
bool Mqtt5Serialization::deserializeSubscribe(Mqtt5SubscribeData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0x02)
{
return false;
}
// packet identifier
bool ok = read2ByteNumber(data.packetId);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
// at least one subscription must be available
if (!doesFit(1))
{
return false;
}
while (doesFit(1))
{
Mqtt5SubscribeEntry entry;
ok = readString(entry.topic);
if (!ok)
{
return false;
}
unsigned int option = 0;
ok = read1ByteNumber(option);
if (!ok)
{
return false;
}
entry.retainHandling = SO_RetainHandling(option);
entry.retainAsPublished = SO_RetainAsPublished(option);
entry.noLocal = SO_NoLocal(option);
entry.qos = SO_QoS(option);
data.subscriptions.emplace_back(std::move(entry));
}
return ok;
}
unsigned int Mqtt5Serialization::sizeSubscribe(const Mqtt5SubscribeData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
// packet identifier
size += 2;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
// at least one subscription must be available
assert(!data.subscriptions.empty());
for (size_t i = 0; i < data.subscriptions.size(); ++i)
{
const Mqtt5SubscribeEntry& entry = data.subscriptions[i];
size += sizeString(entry.topic);
}
// options
size += static_cast<unsigned int>(data.subscriptions.size());
return size;
}
void Mqtt5Serialization::serializeSubscribe(const Mqtt5SubscribeData& data, unsigned int sizePayload, unsigned int sizePropPayload, std::uint8_t*& bufferPacketId)
{
unsigned int header = 0;
header |= HEADER_SetCommand(Mqtt5Command::COMMAND_SUBSCRIBE);
header |= HEADER_SetLow4bits(0x02);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// packet identifier
bufferPacketId = &m_buffer[m_indexBuffer];
write2ByteNumber(data.packetId);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
// at least one subscription must be available
assert(!data.subscriptions.empty());
for (size_t i = 0; i < data.subscriptions.size(); ++i)
{
const Mqtt5SubscribeEntry& entry = data.subscriptions[i];
writeString(entry.topic);
unsigned int option = 0;
option |= SO_SetRetainHandling(entry.retainHandling);
option |= SO_SetRetainAsPublished(entry.retainAsPublished);
option |= SO_SetNoLocal(entry.noLocal);
option |= SO_SetQoS(entry.qos);
write1ByteNumber(option);
}
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::deserializeSubAck(Mqtt5SubAckData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0x00)
{
return false;
}
// packet identifier
bool ok = read2ByteNumber(data.packetId);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
// at least one ack must be available
if (!doesFit(1))
{
return false;
}
while (doesFit(1))
{
unsigned int reasoncode = 0x80;
ok = read1ByteNumber(reasoncode);
if (!ok)
{
return false;
}
data.reasoncodes.push_back(reasoncode);
}
return ok;
}
unsigned int Mqtt5Serialization::sizeSubAck(const Mqtt5SubAckData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
// packet identifier
size += 2;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
// at least one ack must be available
assert(!data.reasoncodes.empty());
size += static_cast<unsigned int>(data.reasoncodes.size());
return size;
}
void Mqtt5Serialization::serializeSubAck(const Mqtt5SubAckData& data, Mqtt5Command command, unsigned int sizePayload, unsigned int sizePropPayload)
{
unsigned int header = HEADER_SetCommand(command);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// packet identifier
write2ByteNumber(data.packetId);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
// at least one ack must be available
assert(!data.reasoncodes.empty());
for (size_t i = 0; i < data.reasoncodes.size(); ++i)
{
unsigned int reasoncode = data.reasoncodes[i];
write1ByteNumber(reasoncode);
}
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::deserializeUnsubscribe(Mqtt5UnsubscribeData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0x02)
{
return false;
}
// packet identifier
bool ok = read2ByteNumber(data.packetId);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
// at least one unsubscription must be available
if (!doesFit(1))
{
return false;
}
while (doesFit(1))
{
std::string topic;
ok = readString(topic);
if (!ok)
{
return false;
}
data.topics.emplace_back(std::move(topic));
}
return ok;
}
unsigned int Mqtt5Serialization::sizeUnsubscribe(const Mqtt5UnsubscribeData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
// packet identifier
size += 2;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
// at least one unsubscription must be available
assert(!data.topics.empty());
for (size_t i = 0; i < data.topics.size(); ++i)
{
const std::string& topic = data.topics[i];
size += sizeString(topic);
}
return size;
}
void Mqtt5Serialization::serializeUnsubscribe(const Mqtt5UnsubscribeData& data, unsigned int sizePayload, unsigned int sizePropPayload, std::uint8_t*& bufferPacketId)
{
unsigned int header = 0;
header |= HEADER_SetCommand(Mqtt5Command::COMMAND_UNSUBSCRIBE);
header |= HEADER_SetLow4bits(0x02);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
// packet identifier
bufferPacketId = &m_buffer[m_indexBuffer];
write2ByteNumber(data.packetId);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
// at least one unsubscription must be available
assert(!data.topics.empty());
for (size_t i = 0; i < data.topics.size(); ++i)
{
const std::string& topic = data.topics[i];
writeString(topic);
}
assert(m_indexBuffer == m_sizeBuffer);
}
void Mqtt5Serialization::serializePingReq()
{
unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_PINGREQ);
write1ByteNumber(header);
writeVarByteNumber(0);
assert(m_indexBuffer == m_sizeBuffer);
}
void Mqtt5Serialization::serializePingResp()
{
unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_PINGRESP);
write1ByteNumber(header);
writeVarByteNumber(0);
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::deserializeDisconnect(Mqtt5DisconnectData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0x00)
{
return false;
}
bool ok = true;
if (doesFit(1))
{
// reason code
ok = read1ByteNumber(data.reasoncode);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
}
return ok;
}
unsigned int Mqtt5Serialization::sizeDisconnect(const Mqtt5DisconnectData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
if (data.reasoncode != 0 || !data.properties.empty() || !data.metainfo.empty())
{
// reason code
size += 1;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
}
return size;
}
void Mqtt5Serialization::serializeDisconnect(const Mqtt5DisconnectData& data, unsigned int sizePayload, unsigned int sizePropPayload)
{
unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_DISCONNECT);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
if (data.reasoncode != 0 || !data.properties.empty() || !data.metainfo.empty())
{
// reason code
write1ByteNumber(data.reasoncode);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
}
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::deserializeAuth(Mqtt5AuthData& data)
{
if (HEADER_Low4bits(m_buffer[0]) != 0x00)
{
return false;
}
bool ok = true;
if (doesFit(1))
{
// reason code
ok = read1ByteNumber(data.reasoncode);
if (!ok)
{
return false;
}
// properties
ok = readProperties(data.properties, data.metainfo);
if (!ok)
{
return false;
}
}
return ok;
}
unsigned int Mqtt5Serialization::sizeAuth(const Mqtt5AuthData& data, unsigned int& sizePropPayload)
{
unsigned int size = 0;
if (data.reasoncode != 0 || !data.properties.empty() || !data.metainfo.empty())
{
// reason code
size += 1;
// properties
size += sizeProperties(data.properties, data.metainfo, sizePropPayload);
}
return size;
}
void Mqtt5Serialization::serializeAuth(const Mqtt5AuthData& data, unsigned int sizePayload, unsigned int sizePropPayload)
{
unsigned int header = HEADER_SetCommand(Mqtt5Command::COMMAND_AUTH);
write1ByteNumber(header);
writeVarByteNumber(sizePayload);
if (data.reasoncode != 0 || !data.properties.empty() || !data.metainfo.empty())
{
// reason code
write1ByteNumber(data.reasoncode);
// properties
writeProperties(data.properties, data.metainfo, sizePropPayload);
}
assert(m_indexBuffer == m_sizeBuffer);
}
bool Mqtt5Serialization::doesFit(int size) const
{
bool ok = (m_indexBuffer + size <= m_sizeBuffer);
return ok;
}
bool Mqtt5Serialization::read1ByteNumber(unsigned int& number)
{
if (doesFit(1))
{
unsigned int byte1 = m_buffer[m_indexBuffer];
++m_indexBuffer;
number = byte1;
return true;
}
number = 0;
return false;
}
void Mqtt5Serialization::write1ByteNumber(unsigned int number)
{
assert(m_indexBuffer + 1 <= m_sizeBuffer);
m_buffer[m_indexBuffer] = number & 0xff;
++m_indexBuffer;
}
bool Mqtt5Serialization::read2ByteNumber(unsigned int& number)
{
if (doesFit(2))
{
unsigned int byte1 = m_buffer[m_indexBuffer];
++m_indexBuffer;
unsigned int byte2 = m_buffer[m_indexBuffer];
++m_indexBuffer;
number = (byte1 << 8) | byte2;
return true;
}
number = 0;
return false;
}
void Mqtt5Serialization::write2ByteNumber(unsigned int number)
{
assert(m_indexBuffer + 2 <= m_sizeBuffer);
m_buffer[m_indexBuffer] = (number >> 8) & 0xff;
++m_indexBuffer;
m_buffer[m_indexBuffer] = (number >> 0) & 0xff;
++m_indexBuffer;
}
bool Mqtt5Serialization::read4ByteNumber(unsigned int& number)
{
if (doesFit(4))
{
unsigned int byte1 = m_buffer[m_indexBuffer];
++m_indexBuffer;
unsigned int byte2 = m_buffer[m_indexBuffer];
++m_indexBuffer;
unsigned int byte3 = m_buffer[m_indexBuffer];
++m_indexBuffer;
unsigned int byte4 = m_buffer[m_indexBuffer];
++m_indexBuffer;
number = (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4;
return true;
}
number = 0;
return false;
}
void Mqtt5Serialization::write4ByteNumber(unsigned int number)
{
assert(m_indexBuffer + 4 <= m_sizeBuffer);
m_buffer[m_indexBuffer] = (number >> 24) & 0xff;
++m_indexBuffer;
m_buffer[m_indexBuffer] = (number >> 16) & 0xff;
++m_indexBuffer;
m_buffer[m_indexBuffer] = (number >> 8) & 0xff;
++m_indexBuffer;
m_buffer[m_indexBuffer] = (number >> 0) & 0xff;
++m_indexBuffer;
}
bool Mqtt5Serialization::readVarByteNumber(unsigned int& number)
{
bool ok = true;
bool done = false;
int shift = 0;
while (!done && ok)
{
ok = false;
if (m_indexBuffer < m_sizeBuffer && shift <= 21)
{
ok = true;
char data = m_buffer[m_indexBuffer];
++m_indexBuffer;
number |= (data & 0x7f) << shift;
if ((data & 0x80) == 0)
{
done = true;
}
shift += 7;
}
}
return ok;
}
void Mqtt5Serialization::writeVarByteNumber(unsigned int number)
{
assert(number <= 268435455);
do
{
assert(m_indexBuffer + 1 <= m_sizeBuffer);
m_buffer[m_indexBuffer] = number & 0x7f;
number >>= 7;
if (number > 0)
{
m_buffer[m_indexBuffer] |= 0x80;
}
++m_indexBuffer;
} while (number > 0);
}
bool Mqtt5Serialization::readString(std::string& str)
{
unsigned int size = 0;
bool ok = read2ByteNumber(size);
if (ok && doesFit(size))
{
str.insert(0, reinterpret_cast<char*>(&m_buffer[m_indexBuffer]), size);
m_indexBuffer += size;
}
else
{
str.clear();
}
return ok;
}
unsigned int Mqtt5Serialization::sizeString(const std::string& str)
{
assert(str.size() <= 0xffff);
return static_cast<unsigned int>(2 + str.size());
}
void Mqtt5Serialization::writeString(const std::string& str)
{
unsigned int size = static_cast<unsigned int>(str.size());
write2ByteNumber(size);
assert(m_indexBuffer + size <= m_sizeBuffer);
memcpy(&m_buffer[m_indexBuffer], str.data(), str.size());
m_indexBuffer += size;
}
bool Mqtt5Serialization::readStringPair(std::string& key, std::string& value)
{
bool ok = readString(key);
if (!ok)
{
return false;
}
ok = readString(value);
return ok;
}
unsigned int Mqtt5Serialization::sizeStringPair(const std::string& key, const std::string& value)
{
assert(key.size() <= 0xffff);
assert(value.size() <= 0xffff);
return static_cast<unsigned int>(4 + key.size() + value.size());
}
void Mqtt5Serialization::writeStringPair(const std::string& key, const std::string& value)
{
writeString(key);
writeString(value);
}
bool Mqtt5Serialization::readBinary(Bytes& value)
{
unsigned int size = 0;
bool ok = read2ByteNumber(size);
if (ok && doesFit(size))
{
value.insert(value.end(), &m_buffer[m_indexBuffer], &m_buffer[m_indexBuffer + size]);
m_indexBuffer += size;
}
else
{
value.clear();
}
return ok;
}
unsigned int Mqtt5Serialization::sizeBinary(const Bytes& value)
{
assert(value.size() <= 0xffff);
return static_cast<unsigned int>(2 + value.size());
}
void Mqtt5Serialization::writeBinary(const Bytes& value)
{
unsigned int size = static_cast<unsigned int>(value.size());
write2ByteNumber(size);
assert(m_indexBuffer + size <= m_sizeBuffer);
memcpy(&m_buffer[m_indexBuffer], value.data(), size);
m_indexBuffer += size;
}
bool Mqtt5Serialization::readProperties(std::unordered_map<unsigned int, Variant>& properties, std::unordered_map<std::string, std::string>& metainfo)
{
if (!doesFit(1))
{
return true;
}
unsigned int size = 0;
bool ok = readVarByteNumber(size);
if (!ok || !doesFit(size))
{
return false;
}
unsigned int indexEndProperties = m_indexBuffer + size;
bool done = (size == 0);
while (!done && ok)
{
ok = false;
if (m_indexBuffer < indexEndProperties)
{
ok = true;
unsigned int id = 0;
ok = readVarByteNumber(id);
if (!ok)
{
return false;
}
Mqtt5PropertyId propertyId(static_cast<Mqtt5PropertyId::Enum>(id));
if (propertyId == Mqtt5PropertyId::Invalid)
{
return false;
}
Mqtt5Type type = propertyId.getPropertyType();
switch (type)
{
case Mqtt5Type::TypeNone:
ok = false;
break;
case Mqtt5Type::TypeByte:
{
unsigned int value;
ok = read1ByteNumber(value);
if (ok)
{
properties[propertyId] = value;
}
}
break;
case Mqtt5Type::TypeTwoByteInteger:
{
unsigned int value;
ok = read2ByteNumber(value);
if (ok)
{
properties[propertyId] = value;
}
}
break;
case Mqtt5Type::TypeFourByteInteger:
{
unsigned int value;
ok = read4ByteNumber(value);
if (ok)
{
properties[propertyId] = value;
}
}
break;
case Mqtt5Type::TypeVariableByteInteger:
{
unsigned int value = 0;
ok = readVarByteNumber(value);
if (ok)
{
properties[propertyId] = value;
}
}
break;
case Mqtt5Type::TypeUTF8String:
{
std::string value;
ok = readString(value);
if (ok)
{
properties[propertyId] = value;
}
}
break;
case Mqtt5Type::TypeUTF8StringPair:
{
std::string key;
std::string value;
ok = readStringPair(key, value);
if (ok)
{
if (propertyId == Mqtt5PropertyId::UserProperty)
{
metainfo[std::move(key)] = std::move(value);
}
}
}
break;
case Mqtt5Type::TypeBinaryData:
{
Bytes value;
ok = readBinary(value);
if (ok)
{
properties[propertyId] = value;
}
}
break;
case Mqtt5Type::TypeArrayVariableByteInteger:
{
unsigned int value = 0;
ok = readVarByteNumber(value);
if (ok)
{
Variant& property = properties[propertyId];
std::vector<std::uint32_t>* arr = property;
if (arr == nullptr)
{
property = std::vector<std::uint32_t>();
}
arr = property;
assert(arr != nullptr);
arr->push_back(value);
}
}
break;
default:
assert(false);
ok = false;
break;
}
if (m_indexBuffer == indexEndProperties)
{
done = true;
}
}
}
return ok;
}
unsigned int Mqtt5Serialization::sizeProperties(const std::unordered_map<unsigned int, Variant>& properties, const std::unordered_map<std::string, std::string>& metainfo, unsigned int& sizePropertyPayload)
{
sizePropertyPayload = 0;
for (auto it = properties.begin(); it != properties.end(); ++it)
{
unsigned int id = it->first;
const Variant& value = it->second;
Mqtt5PropertyId propertyId(static_cast<Mqtt5PropertyId::Enum>(id));
assert(propertyId != Mqtt5PropertyId::Invalid);
Mqtt5Type type = propertyId.getPropertyType();
switch (type)
{
case Mqtt5Type::TypeNone:
assert(false);
break;
case Mqtt5Type::TypeByte:
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += 1;
break;
case Mqtt5Type::TypeTwoByteInteger:
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += 2;
break;
case Mqtt5Type::TypeFourByteInteger:
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += 4;
break;
case Mqtt5Type::TypeVariableByteInteger:
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += sizeVarByteNumber(value);
break;
case Mqtt5Type::TypeUTF8String:
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += sizeString(value);
break;
case Mqtt5Type::TypeUTF8StringPair:
assert(false);
break;
case Mqtt5Type::TypeBinaryData:
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += sizeBinary(value);
break;
case Mqtt5Type::TypeArrayVariableByteInteger:
{
const std::vector<std::uint32_t>* arr = value;
if (arr != nullptr)
{
for (size_t i = 0; i < arr->size(); ++i)
{
sizePropertyPayload += sizeVarByteNumber(id);
sizePropertyPayload += sizeVarByteNumber(arr->at(i));
}
}
}
break;
default:
assert(false);
break;
}
}
for (auto it = metainfo.begin(); it != metainfo.end(); ++it)
{
const std::string& key = it->first;
const std::string& value = it->second;
sizePropertyPayload += sizeVarByteNumber(Mqtt5PropertyId::UserProperty);
sizePropertyPayload += sizeStringPair(key, value);
}
return (sizeVarByteNumber(sizePropertyPayload) + sizePropertyPayload);
}
void Mqtt5Serialization::writeProperties(const std::unordered_map<unsigned int, Variant>& properties, const std::unordered_map<std::string, std::string>& metainfo, unsigned int sizePropertyPayload)
{
writeVarByteNumber(sizePropertyPayload);
for (auto it = properties.begin(); it != properties.end(); ++it)
{
unsigned int id = it->first;
const Variant& value = it->second;
Mqtt5PropertyId propertyId(static_cast<Mqtt5PropertyId::Enum>(id));
assert(propertyId != Mqtt5PropertyId::Invalid);
Mqtt5Type type = propertyId.getPropertyType();
switch (type)
{
case Mqtt5Type::TypeNone:
assert(false);
break;
case Mqtt5Type::TypeByte:
writeVarByteNumber(id);
write1ByteNumber(value);
break;
case Mqtt5Type::TypeTwoByteInteger:
writeVarByteNumber(id);
write2ByteNumber(value);
break;
case Mqtt5Type::TypeFourByteInteger:
writeVarByteNumber(id);
write4ByteNumber(value);
break;
case Mqtt5Type::TypeVariableByteInteger:
writeVarByteNumber(id);
writeVarByteNumber(value);
break;
case Mqtt5Type::TypeUTF8String:
writeVarByteNumber(id);
writeString(value);
break;
case Mqtt5Type::TypeUTF8StringPair:
assert(false);
break;
case Mqtt5Type::TypeBinaryData:
writeVarByteNumber(id);
writeBinary(value);
break;
case Mqtt5Type::TypeArrayVariableByteInteger:
{
const std::vector<std::uint32_t>* arr = value;
if (arr != nullptr)
{
for (size_t i = 0; i < arr->size(); ++i)
{
writeVarByteNumber(id);
writeVarByteNumber(arr->at(i));
}
}
}
break;
default:
assert(false);
break;
}
}
for (auto it = metainfo.begin(); it != metainfo.end(); ++it)
{
const std::string& key = it->first;
const std::string& value = it->second;
writeVarByteNumber(Mqtt5PropertyId::UserProperty);
writeStringPair(key, value);
}
}
} // namespace finalmq
| 26.204316 | 205 | 0.591158 | mnaveedb |
08775931b8cde79d768ba6aada16e089b0127451 | 1,208 | hpp | C++ | include/Utils.hpp | qqwertyui/zipper | fa57b23971988fa39cbbf142837bb55458c54e46 | [
"Apache-2.0"
] | 1 | 2021-05-21T16:20:15.000Z | 2021-05-21T16:20:15.000Z | include/Utils.hpp | qqwertyui/zipper | fa57b23971988fa39cbbf142837bb55458c54e46 | [
"Apache-2.0"
] | null | null | null | include/Utils.hpp | qqwertyui/zipper | fa57b23971988fa39cbbf142837bb55458c54e46 | [
"Apache-2.0"
] | null | null | null | #ifndef UTILS_HPP
#define UTILS_HPP
#include <cstdint>
#include <string>
#include <vector>
#include <memory>
#include <fstream>
#include <cstddef>
class DosTime {
public:
DosTime(uint16_t time, uint16_t date);
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t day;
uint8_t month;
uint16_t year;
};
class Data {
public:
std::byte *data;
unsigned int data_size;
Data(std::byte *data, unsigned int data_size);
Data();
};
typedef std::vector<Data *> Data_vector;
class Chunk_manager {
public:
unsigned int elements;
unsigned int total_bytes;
Data_vector entry;
Chunk_manager();
~Chunk_manager();
void add(std::byte *data, unsigned int datasz);
std::byte *to_bytearray();
};
namespace Utils {
/* Returns address of the last occurence of given character in string, alters
* input string */
char *find_last_of(const char *text, const char *delimiter);
std::vector<std::byte> zlib_inflate(Data *input);
std::vector<std::byte> read_file(std::string &filename, std::ifstream::openmode flags = std::ifstream::in);
void write_file(std::string &filename, std::vector<std::byte> &data, std::ofstream::openmode flags = std::ofstream::out);
} // namespace Utils
#endif | 20.133333 | 121 | 0.716887 | qqwertyui |
087888b4613453adf2c32912ba0b7d7f2c71cf43 | 430 | cpp | C++ | projects/example/my-api-repo/do_stuff_fuzzer.cpp | rbehjati/oss-fuzz | a31e58fb5c9984915fdc79610660b326df20b937 | [
"Apache-2.0"
] | 7,629 | 2016-07-25T20:21:54.000Z | 2022-03-30T15:55:51.000Z | projects/example/my-api-repo/do_stuff_fuzzer.cpp | rbehjati/oss-fuzz | a31e58fb5c9984915fdc79610660b326df20b937 | [
"Apache-2.0"
] | 4,786 | 2016-09-13T15:00:30.000Z | 2022-03-31T23:57:39.000Z | projects/example/my-api-repo/do_stuff_fuzzer.cpp | rbehjati/oss-fuzz | a31e58fb5c9984915fdc79610660b326df20b937 | [
"Apache-2.0"
] | 1,825 | 2016-08-30T16:48:19.000Z | 2022-03-31T08:58:09.000Z | // Copyright 2017 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
#include "my_api.h"
#include <string>
// Simple fuzz target for DoStuff().
// See http://libfuzzer.info for details.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
std::string str(reinterpret_cast<const char *>(data), size);
DoStuff(str); // Disregard the output.
return 0;
}
| 30.714286 | 73 | 0.716279 | rbehjati |
087e0b5b86587a14bdd714f18829f00733d498e9 | 20,881 | hpp | C++ | configuration/configurator/schemas/SchemaCommon.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | null | null | null | configuration/configurator/schemas/SchemaCommon.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | null | null | null | configuration/configurator/schemas/SchemaCommon.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2015 HPCC Systems®.
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 _SCHEMA_COMMON_HPP_
#define _SCHEMA_COMMON_HPP_
#include <iostream>
#include "jiface.hpp"
#include "jstring.hpp"
#include "jlib.hpp"
#include "jlog.hpp"
#include "jarray.hpp"
#include "XMLTags.h"
#include "ExceptionStrings.hpp"
#include "build-config.h"
namespace CONFIGURATOR
{
#define MINIMUM_STRICTNESS 0
#define DEFAULT_STRICTNESS 5
#define MAXIMUM_STRICTNESS 10
#define STRICTNESS_LEVEL MINIMUM_STRICTNESS
#define QUICK_OUT(X,Y,Z) quickOut(X,#Y,get##Y(),Z);
#define QUICK_OUT_2(Y) quickOut(cout, #Y, get##Y(), offset);
#define QUICK_OUT_3(X) if (m_p##X != nullptr) m_p##X->dump(cout, offset);
#define QUICK_OUT_ARRAY(X,Z) for (int idx=0; idx < this->length(); idx++) \
{ \
quickOutPad(X,Z+STANDARD_OFFSET_1); \
X << idx+1 << "]" << ::std::endl; \
(this->item(idx)).dump(cout,Z); \
}
#define QUICK_DOC_ARRAY(X) for (int idx=0; idx < this->length(); idx++) \
{ \
(this->item(idx)).getDocumentation(X); \
}
#define LAST_ONLY -1
#define LAST_AND_FIRST -2
#define QUICK_ENV_XPATH(X) for (int idx=0; idx < this->length(); idx++) \
{ \
(this->item(idx)).populateEnvXPath(X.str(), idx+1); \
}
#define QUICK_ENV_XPATH_WITH_INDEX(X,Y) for (int idx=0; idx < this->length(); idx++) \
{ \
(this->item(idx)).populateEnvXPath(X.str(), Y); \
}
#define QUICK_LOAD_ENV_XML(X) assert(X != nullptr); \
for (int idx=0; idx < this->length(); idx++) \
{ \
(this->item(idx)).loadXMLFromEnvXml(X); \
}
#define GETTER(X) virtual const char* get##X() const { return m_str##X.str(); }
#define SETTER(X) virtual void set##X(const char* p) { m_str##X.clear().append(p); }
#define GETTERSETTER(X) protected: StringBuffer m_str##X; public: GETTER(X) SETTER(X) public:
//#define GETTER2(X) virtual const char* get##X() const { return m_str##X.str(); }
//#define SETTER2(X) virtual void set##X(const char* p) { m_str##X.clear().append(p); m_str##X.replace('/','_');}
//#define GETTERSETTER2(X) protected: StringBuffer m_str##X; public: GETTER(X) SETTER2(X) public:
#define GETTERINT(X) virtual const long get##X() const { return m_n##X; }
#define SETTERINT(X) virtual void set##X(long p) { m_n##X = p; } virtual void set##X(const char *p) { assert(p != nullptr); if (p != 0 && *p != 0) m_n##X = atol(p); }
#define GETTERSETTERINT(X) protected: long m_n##X; public: GETTERINT(X) SETTERINT(X) private:
#define SETPARENTNODE(X, Y) if (X!= nullptr && Y != nullptr) X->setParentNode(Y);
//#define DEBUG_MARK_STRDOC strDoc.append(__FILE__).append(":").append(__LINE__).append("\n");
#define DEBUG_MARK_STRDOC
#define DEBUG_MARK_COMMENT(X) X.append("// ").append(__FILE__).append(":").append(__LINE__).append("\n");
#define DEBUG_MARK_COMMENT2(X,Y) X.append("// UIType=").append(Y->getUIType()).append(" ").append(__FILE__).append(":").append(__LINE__).append("\n");
#define DEBUG_MARK_COMMENT_3 quickOutPad(strJSON, offset); strJSON.append("{ \"").append(__FILE__).append("\" : \"").append(__LINE__).append("\"},\n"); QuickOutPad(strJSON, offset);
#define DEBUG_MARK_COMMENT_4 quickOutPad(strJSON, offset); strJSON.append(",{ \"").append(__FILE__).append("\" : \"").append(__LINE__).append("\"},\n"); QuickOutPad(strJSON, offset);
#define DEBUG_MARK_STRJS DEBUG_MARK_COMMENT(strJS)
#define DEBUG_MARK_JSON_1 //DEBUG_MARK_COMMENT_4// DEBUG_MARK_COMMENT(strJSON)
#define DEBUG_MARK_JSON_2 //DEBUG_MARK_COMMENT_3// DEBUG_MARK_COMMENT(strJSON)
#define GETTERTYPE(X) C##X* get##X() const { return m_p##X; }
#define SETTERTYPE(X) void set##X( C##X *p ) { assert(p != nullptr); if (p != nullptr) m_p##X = p; }
#define GETTERSETTERTYPE(X) public: C##X *m_p##X; GETTERTYPE(X) SETTERTYPE(X) private:
#define CHECK_EXCLUSION(X) if(CConfigSchemaHelper::getInstance()->getSchemaMapManager()->isNodeExcluded(X)) return nullptr;
#define IS_EXCLUDED(X) (CConfigSchemaHelper::getInstance()->getSchemaMapManager()->isNodeExcluded(X) ? true : false)
enum NODE_TYPES
{
XSD_ANNOTATION = 0x0,
XSD_APP_INFO,
XSD_ATTRIBUTE,
XSD_ATTRIBUTE_ARRAY,
XSD_ATTRIBUTE_GROUP,
XSD_ATTRIBUTE_GROUP_ARRAY,
XSD_CHOICE,
XSD_COMPLEX_CONTENT,
XSD_COMPLEX_TYPE,
XSD_COMPLEX_TYPE_ARRAY,
XSD_DOCUMENTATION,
XSD_ELEMENT,
XSD_ELEMENT_ARRAY,
XSD_ARRAY_OF_ELEMENT_ARRAYS,
XSD_EXTENSION,
XSD_FIELD,
XSD_FIELD_ARRAY,
XSD_KEY,
XSD_KEY_ARRAY,
XSD_KEYREF,
XSD_KEYREF_ARRAY,
XSD_INCLUDE,
XSD_INCLUDE_ARRAY,
XSD_RESTRICTION,
XSD_SCHEMA,
XSD_SEQUENCE,
XSD_SIMPLE_TYPE,
XSD_SIMPLE_TYPE_ARRAY,
XSD_ENUMERATION,
XSD_ENUMERATION_ARRAY,
XSD_LENGTH,
XSD_FRACTION_DIGITS,
XSD_MAX_EXCLUSIVE,
XSD_MAX_INCLUSIVE,
XSD_MIN_EXCLUSIVE,
XSD_MIN_INCLUSIVE,
XSD_MIN_LENGTH,
XSD_MAX_LENGTH,
XSD_PATTERN,
XSD_SELECTOR,
XSD_SIMPLE_CONTENT,
XSD_TOTAL_DIGITS,
XSD_UNIQUE,
XSD_UNIQUE_ARRAY,
XSD_WHITE_SPACE,
XSD_DT_NORMALIZED_STRING, // keep this as the first DT type for array index purposes
XSD_DT_STRING,
XSD_DT_TOKEN,
XSD_DT_DATE,
XSD_DT_TIME,
XSD_DT_DATE_TIME,
XSD_DT_DECIMAL,
XSD_DT_INT,
XSD_DT_INTEGER,
XSD_DT_LONG,
XSD_DT_NON_NEG_INTEGER,
XSD_DT_NON_POS_INTEGER,
XSD_DT_NEG_INTEGER,
XSD_DT_POS_INTEGER,
XSD_DT_BOOLEAN,
XSD_ERROR
};
static const char* DEFAULT_SCHEMA_DIRECTORY(COMPONENTFILES_DIR "/configxml/");
static const char* XSD_ANNOTATION_STR("Annotation");
static const char* XSD_APP_INFO_STR("AppInfo");
static const char* XSD_ATTRIBUTE_STR("Attribute");
static const char* XSD_ATTRIBUTE_ARRAY_STR("AttributeArray");
static const char* XSD_ATTRIBUTE_GROUP_STR("AttributeGroup");
static const char* XSD_ATTRIBUTE_GROUP_ARRAY_STR("AttributeGroupArray");
static const char* XSD_CHOICE_STR("Choice");
static const char* XSD_COMPLEX_CONTENT_STR("ComplexContent");
static const char* XSD_COMPLEX_TYPE_STR("ComplexType");
static const char* XSD_COMPLEX_TYPE_ARRAY_STR("ComplexTypeArray");
static const char* XSD_DOCUMENTATION_STR("Documentation");
static const char* XSD_ELEMENT_STR("Element");
static const char* XSD_ELEMENT_ARRAY_STR("ElementArray");
static const char* XSD_ARRAY_ELEMENT_ARRAY_STR("ArrayOfElementArrays");
static const char* XSD_ERROR_STR("ERROR");
static const char* XSD_ENUMERATION_STR("Enumeration");
static const char* XSD_ENUMERATION_ARRAY_STR("EnumerationArray");
static const char* XSD_EXTENSION_STR("Extension");
static const char* XSD_FIELD_STR("Field");
static const char* XSD_FIELD_ARRAY_STR("FieldArray");
static const char* XSD_FRACTION_DIGITS_STR("FractionDigits");
static const char* XSD_INCLUDE_STR("Include");
static const char* XSD_INCLUDE_ARRAY_STR("IncludeArray");
static const char* XSD_KEY_STR("Key");
static const char* XSD_KEY_ARRAY_STR("KeyArray");
static const char* XSD_KEYREF_STR("KeyRef");
static const char* XSD_KEYREF_ARRAY_STR("KeyRefArray");
static const char* XSD_LENGTH_STR("Length");
static const char* XSD_MIN_INCLUSIVE_STR("MinInclusive");
static const char* XSD_MAX_INCLUSIVE_STR("MaxInclusive");
static const char* XSD_MIN_EXCLUSIVE_STR("MinExclusive");
static const char* XSD_MAX_EXCLUSIVE_STR("MaxExclusive");
static const char* XSD_MIN_LENGTH_STR("MinLength");
static const char* XSD_MAX_LENGTH_STR("MaxLength");
static const char* XSD_PATTERN_STR("Pattern");
static const char* XSD_RESTRICTION_STR("Restriction");
static const char* XSD_SCHEMA_STR("Schema");
static const char* XSD_SELECTOR_STR("Selector");
static const char* XSD_SEQUENCE_STR("Sequence");
static const char* XSD_SIMPLE_CONTENT_STR("SimpleContent");
static const char* XSD_SIMPLE_TYPE_STR("SimpleType");
static const char* XSD_SIMPLE_TYPE_ARRAY_STR("SimpleTypeArray");
static const char* XSD_TOTAL_DIGITS_STR("TotalDigits");
static const char* XSD_UNIQUE_STR("Unique");
static const char* XSD_UNIQUE_ARRAY_STR("UniqueArray");
static const char* XSD_WHITE_SPACE_STR("WhiteSpace");
static const char* XSD_DT_NORMALIZED_STRING_STR("NormalizedString");
static const char* XSD_DT_STRING_STR("String");
static const char* XSD_DT_TOKEN_STR("Token");
static const char* XSD_DT_DATE_STR("Date");
static const char* XSD_DT_TIME_STR("Time");
static const char* XSD_DT_DATE_TIME_STR("DateTime");
static const char* XSD_DT_DECIMAL_STR("Decimal");
static const char* XSD_DT_INTEGER_STR("Integer");
static const char* XSD_DT_INT_STR("Int");
static const char* XSD_DT_LONG_STR("Long");
static const char* XSD_DT_NON_NEG_INTEGER_STR("NonNegativeInteger");
static const char* XSD_DT_NON_POS_INTEGER_STR("NonPositiveInteger");
static const char* XSD_DT_POS_INTEGER_STR("PositiveInteger");
static const char* XSD_DT_NEG_INTEGER_STR("NegativeInteger");
static const char* XSD_DT_BOOLEAN_STR("Boolean");
static const char* XML_ENV_VALUE_OPTIONAL("optional");
static const char* XML_ENV_VALUE_REQUIRED("required");
static const char* XML_ATTR_DEFAULT("@default");
static const char* XML_ATTR_USE("@use");
static const char* XML_ATTR_MINOCCURS("@minOccurs");
static const char* XML_ATTR_BASE("@base");
static const char* XML_ATTR_XPATH("@xpath");
static const char* XML_ATTR_REFER("@refer");
static const char* TAG_VIEWCHILDNODES("viewChildNodes");
static const char* TAG_VIEWTYPE("viewType");
static const char* TAG_TOOLTIP("tooltip");
static const char* TAG_COLINDEX("colIndex");
static const char* TAG_TITLE("title");
static const char* TAG_WIDTH("width");
static const char* TAG_AUTOGENWIZARD("autogenforwizard");
static const char* TAG_AUTOGENDEFAULTVALUE("autogendefaultvalue");
static const char* TAG_AUTOGENDEFAULTVALUEFORMULTINODE("autogendefaultformultinode");
static const char* TAG_XPATH("xpath");
static const char* TAG_DOC_ID("docid");
static const char* TAG_DOC_USE_LINE_BREAK("docuselinebreak");
static const char* TAG_REQUIRED("required");
static const char* TAG_UNBOUNDED("unbounded");
#define TAG_OPTIONAL "optional"
#define TAG_REQUIRED "required"
#define XML_ATTR_ATTRIBUTEFORMDEFAULT "@attributeFormDefault"
#define XML_ATTR_ELEMENTFORMDEFAULT "@elementFormDefault"
#define XML_ATTR_ID "@id"
#define XML_ATTR_REF "@ref"
#define XML_ATTR_XMLNS_XS "@xmlns:xs"
#define XML_ATTR_SCHEMA_LOCATION "@schemaLocation"
#define XML_ATTR_VALUE "@value"
#define XML_ATTR_OVERRIDE "@overide" // intentionally misspelled
#define XML_ATTR_DEPLOYABLE "@deployable"
static unsigned int STANDARD_OFFSET_1 = 3;
static unsigned int STANDARD_OFFSET_2 = 6;
static unsigned int STANDARD_OFFSET_3 = 9;
static void quickOutPad(::std::ostream& cout, unsigned int offset)
{
while(offset > 0)
{
cout << " ";
offset--;
}
}
static void quickOutPad(::StringBuffer &str, unsigned int offset)
{
while(offset > 0)
{
str.append(" ");
offset--;
}
}
static void quickOutHeader(::std::ostream &cout, const char* pLabel, unsigned int offset = 0)
{
quickOutPad(cout,offset);
cout << "\033[32m-- " << pLabel << " START" << " --" << "\033[0m" << ::std::endl;
}
static void quickOutFooter(::std::ostream &cout, const char* pLabel, unsigned int offset = 0)
{
quickOutPad(cout,offset);
//cout << "<--- FINISH " << pLabel << ::std::endl;
cout << "\033[31m" << "-- " << pLabel << " FINISH" << " --" << "\033[0m" << ::std::endl;
}
static void quickOut(::std::ostream &cout, const char* pLabel, const char* pValue, unsigned int offset = 0)
{
if (pLabel && strlen(pValue) > 0)
{
quickOutPad(cout,offset+STANDARD_OFFSET_2);
cout << "\033[34m" << pLabel << ":\t\033[0m" << "\033[34m'\033[0m" << pValue << "\033[34m'" << "\033[0m" << ::std::endl;
}
}
static void quickOut(::std::ostream &cout, const char* pLabel, int value, unsigned int offset = 0)
{
quickOutPad(cout,offset);
cout << pLabel << ": " << value << ::std::endl;
}
static const char* stripTrailingIndex(StringBuffer& strXPath) // should this replace int CConfigSchemaHelper::stripXPathIndex(StringBuffer &strXPath)?
{
if (strXPath.length() == 0 || strXPath[strXPath.length()-1] != ']')
return strXPath.str();
while (1)
{
if (strXPath[strXPath.length()-1] == '[')
{
strXPath.setLength(strXPath.length()-1);
break;
}
strXPath.setLength(strXPath.length()-1);
}
return strXPath.str();
}
class CXSDNodeBase
{
public:
CXSDNodeBase(CXSDNodeBase* pParentNode = nullptr, NODE_TYPES eNodeType = XSD_ERROR);
virtual ~CXSDNodeBase();
GETTERSETTER(XSDXPath)
GETTERSETTER(EnvXPath)
//GETTERSETTER(EnvValueFromXML)
virtual const char* getEnvValueFromXML() const
{
return m_strEnvValueFromXML;
}
virtual bool setEnvValueFromXML(const char* p)
{
if (p != nullptr)
{
m_strEnvValueFromXML.set(p);
return true;
}
return false;
}
void dumpStdOut() const;
virtual CXSDNodeBase* getParentNode() const
{
return m_pParentNode;
}
virtual const CXSDNodeBase* getConstAncestorNode(unsigned iLevel) const;
virtual const CXSDNodeBase* getConstParentNode() const
{
return m_pParentNode;
}
virtual const CXSDNodeBase* getParentNodeByType(NODE_TYPES eNodeType[], const CXSDNodeBase *pParent = nullptr, int length = 1) const;
virtual const CXSDNodeBase* getParentNodeByType(NODE_TYPES eNodeType, const CXSDNodeBase *pParent = nullptr) const;
virtual const CXSDNodeBase* getNodeByTypeAndNameAscending(NODE_TYPES eNodeType[], const char *pName, int length = 1) const;
virtual const CXSDNodeBase* getNodeByTypeAndNameAscending(NODE_TYPES eNodeType, const char *pName) const
{
if (this->getNodeType() == eNodeType)
return this;
else
return this->getConstParentNode()->getNodeByTypeAndNameAscending(eNodeType, pName);
}
virtual const CXSDNodeBase* getNodeByTypeAndNameDescending(NODE_TYPES eNodeType[], const char *pName, int length = 1) const;
virtual const CXSDNodeBase* getNodeByTypeAndNameDescending(NODE_TYPES eNodeType, const char *pName) const
{
return getNodeByTypeAndNameDescending(&eNodeType, pName);
}
void setParentNode(CXSDNodeBase *pParentNode)
{
if (m_pParentNode == nullptr) // Should only be set once, otherwise it's an external schema and should have parent set
{
m_pParentNode = pParentNode;
}
}
const char* getNodeTypeStr() const
{
return m_pNodeType;
}
virtual NODE_TYPES getNodeType() const
{
return m_eNodeType;
}
virtual void dump(::std::ostream& cout, unsigned int offset = 0) const = 0;
virtual const char* getXML(const char* /*pComponent*/)
{
return nullptr;
}
virtual void getDocumentation(::StringBuffer &strDoc) const = 0;
virtual void populateEnvXPath(::StringBuffer strXPath, unsigned int index = 1)
{
}
virtual void loadXMLFromEnvXml(const ::IPropertyTree *pEnvTree)
{
}
protected:
CXSDNodeBase* m_pParentNode;
::StringBuffer m_strXML;
NODE_TYPES m_eNodeType;
char m_pNodeType[1024];
StringBuffer m_strEnvValueFromXML;
private:
};
class CXSDNode : public CInterface, public CXSDNodeBase
{
public:
IMPLEMENT_IINTERFACE
CXSDNode(CXSDNodeBase *pParentNode, NODE_TYPES pNodeType = XSD_ERROR );
virtual bool checkSelf(NODE_TYPES eNodeType, const char *pName, const char* pCompName) const;
virtual const CXSDNodeBase* getParentNodeByType(NODE_TYPES eNodeType) const;
private:
};
template<class T>
class CXSDNodeWithRestrictions : public CXSDNode
{
public:
CXSDNodeWithRestrictions(CXSDNodeBase* pParentNode, enum NODE_TYPES eNodeType) : CXSDNode::CXSDNode(pParentNode)
{
}
static T* load(CXSDNodeBase* pParentNode, const ::IPropertyTree *pSchemaRoot, const char* xpath)
{
assert(pSchemaRoot != nullptr);
if (pSchemaRoot == nullptr)
return nullptr;
T *pT = nullptr;
if (xpath != nullptr && *xpath != 0)
{
::IPropertyTree* pTree = pSchemaRoot->queryPropTree(xpath);
if (pTree == nullptr)
return nullptr;
pT = new T(pParentNode);
const char* pValue = pTree->queryProp(XML_ATTR_VALUE);
if (pValue != nullptr && *pValue != 0)
pT->setValue(pValue);
else
{
assert(!"No Value set");
//TODO: throw? and delete?
}
pT->setXSDXPath(xpath);
}
return pT;
}
void dump(::std::ostream& cout, unsigned int offset) const
{
offset += STANDARD_OFFSET_1;
quickOutHeader(cout, XSD_MIN_INCLUSIVE_STR, offset);
QUICK_OUT(cout, Value, offset);
quickOutFooter(cout, XSD_MIN_INCLUSIVE_STR, offset);
}
virtual void getDocumentation(::StringBuffer &strDoc) const
{
UNIMPLEMENTED;
}
virtual const char* getXML(const char* /*pComponent*/)
{
UNIMPLEMENTED;
return nullptr;
}
virtual void populateEnvXPath(::StringBuffer strXPath, unsigned int index = 1)
{
UNIMPLEMENTED;
}
virtual void loadXMLFromEnvXml(const ::IPropertyTree *pEnvTree)
{
UNIMPLEMENTED;
}
GETTERSETTER(Value)
};
class CXSDNodeWithType : public CXSDNode
{
GETTERSETTER(Type)
public:
CXSDNodeWithType(CXSDNodeBase* pParentNode, enum NODE_TYPES eNodeType) : CXSDNode::CXSDNode(pParentNode, eNodeType), m_pXSDNode(nullptr)
{
}
virtual void loadXMLFromEnvXml(const ::IPropertyTree *pEnvTree)
{
UNIMPLEMENTED_X("Should be implemented in the derived class");
}
void setTypeNode(CXSDNode* pCXSDNode)
{
m_pXSDNode = pCXSDNode;
}
const CXSDNode* getTypeNode() const
{
return m_pXSDNode;
}
protected:
CXSDNode *m_pXSDNode;
};
class CXSDNodeWithBase : public CXSDNode
{
GETTERSETTER(Base)
public:
CXSDNodeWithBase(CXSDNodeBase* pParentNode, enum NODE_TYPES eNodeType) : CXSDNode::CXSDNode(pParentNode, eNodeType), m_pXSDNode(nullptr)
{
}
void setBaseNode(CXSDNodeBase* pCXSDNode)
{
m_pXSDNode = pCXSDNode;
}
const CXSDNodeBase* getBaseNode() const
{
return m_pXSDNode;
}
protected:
CXSDNodeBase *m_pXSDNode;
};
class CXSDBuiltInDataType : public CXSDNode
{
public:
static CXSDBuiltInDataType* create(CXSDNodeBase* pParentNode, const char* pNodeType);
virtual ~CXSDBuiltInDataType();
virtual void loadXMLFromEnvXml(const ::IPropertyTree *pEnvTree);
virtual void dump(::std::ostream& cout, unsigned int offset = 0) const;
virtual void getDocumentation(::StringBuffer &strDoc) const;
virtual bool checkConstraint(const char *pValue) const;
private:
CXSDBuiltInDataType(CXSDNodeBase* pParentNode = nullptr, NODE_TYPES eNodeType = XSD_ERROR);
CXSDBuiltInDataType(CXSDNodeBase* pParentNode, const char* pNodeType);
};
}
#endif // _SCHEMA_COMMON_HPP_
| 34.976549 | 182 | 0.658829 | miguelvazq |
08808679455df51fa25983a062e062f79a3e0c71 | 505 | cpp | C++ | huawei/TwoStackForQueue/TwoStackForQueue/main.cpp | RainChang/My_ACM_Exercises | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | [
"Apache-2.0"
] | 1 | 2017-03-16T09:38:48.000Z | 2017-03-16T09:38:48.000Z | huawei/TwoStackForQueue/TwoStackForQueue/main.cpp | RainChang/My_ACM_Exercises | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | [
"Apache-2.0"
] | null | null | null | huawei/TwoStackForQueue/TwoStackForQueue/main.cpp | RainChang/My_ACM_Exercises | 36872bdcb49cbb3eebde4bb9c7d154d057775b72 | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// TwoStackForQueue
//
// Created by Rain on 08/03/2017.
// Copyright © 2017 Rain. All rights reserved.
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
stack<int> s1;
for(int i=0;i<10;i++)
{
s1.push(i);
}
cout<<"input over!"<<endl;
while(!s1.empty())
{
cout<<s1.top()<<" ";
s1.pop();
}
return 0;
}
| 16.290323 | 47 | 0.540594 | RainChang |
0881b5a2456dff821383d4a6a098a3575ca109af | 2,005 | cpp | C++ | src/core/vertex_buffer.cpp | fentacoder/PenEngine | 6f9bf8527ff3fe194737238361bc8db504de877e | [
"Apache-2.0"
] | null | null | null | src/core/vertex_buffer.cpp | fentacoder/PenEngine | 6f9bf8527ff3fe194737238361bc8db504de877e | [
"Apache-2.0"
] | null | null | null | src/core/vertex_buffer.cpp | fentacoder/PenEngine | 6f9bf8527ff3fe194737238361bc8db504de877e | [
"Apache-2.0"
] | null | null | null | /*************************************************************************************************
Copyright 2021 Jamar Phillip
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.
*************************************************************************************************/
#include "vertex_buffer.h"
VertexBuffer::VertexBuffer() {
/*This constructor is used for declaring a VertexBuffer variable as a member variable of another class*/
}
VertexBuffer::VertexBuffer(const void* data, unsigned int size) {
/*For static rendering*/
glGenBuffers(1, &rendererId);
glBindBuffer(GL_ARRAY_BUFFER, rendererId);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
}
VertexBuffer::VertexBuffer(unsigned int size) {
/*For dynamic rendering*/
glGenBuffers(1, &rendererId);
glBindBuffer(GL_ARRAY_BUFFER, rendererId);
glBufferData(GL_ARRAY_BUFFER, size, NULL, GL_DYNAMIC_DRAW);
}
VertexBuffer::~VertexBuffer() {
}
void VertexBuffer::Bind() const {
/*Binds the vertex buffer for the layer that it is a part of*/
glBindBuffer(GL_ARRAY_BUFFER, rendererId);
}
void VertexBuffer::Unbind() const {
/*Unbinds the vertex buffer*/
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexBuffer::Destroy() {
/*Removes the vertex buffer from memory on the GPU*/
glDeleteBuffers(1, &rendererId);
} | 33.416667 | 105 | 0.701746 | fentacoder |
0881fa228fb52003ebcc87e84457362b52f977fb | 665 | hpp | C++ | include/zasm/program/label.hpp | clayne/zasm | b7c1d8c529acb5dfc9f8574307d5cd6685f9c8ac | [
"MIT"
] | 59 | 2021-11-23T18:15:10.000Z | 2022-03-31T08:02:04.000Z | include/zasm/program/label.hpp | clayne/zasm | b7c1d8c529acb5dfc9f8574307d5cd6685f9c8ac | [
"MIT"
] | 8 | 2021-12-28T10:01:29.000Z | 2022-03-06T12:20:49.000Z | include/zasm/program/label.hpp | clayne/zasm | b7c1d8c529acb5dfc9f8574307d5cd6685f9c8ac | [
"MIT"
] | 7 | 2021-11-25T08:39:45.000Z | 2022-02-19T08:15:27.000Z | #pragma once
#include <cstdint>
namespace zasm
{
class Label
{
public:
enum class Id : int32_t
{
Invalid = -1,
};
private:
Id _id{ Id::Invalid };
public:
constexpr Label() noexcept = default;
constexpr explicit Label(const Id id) noexcept
: _id{ id }
{
}
constexpr Id getId() const noexcept
{
return _id;
}
constexpr bool isValid() const noexcept
{
return _id != Id::Invalid;
}
};
namespace operands
{
using Label = ::zasm::Label;
}
} // namespace zasm | 15.833333 | 54 | 0.476692 | clayne |
088339e3d661afdbe838c1cf3419784d83baf0fe | 6,752 | cc | C++ | chrome/browser/policy/profile_policy_connector.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/policy/profile_policy_connector.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/policy/profile_policy_connector.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 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 "chrome/browser/policy/profile_policy_connector.h"
#include <vector>
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/configuration_policy_provider.h"
#include "chrome/browser/policy/policy_service_impl.h"
#if defined(ENABLE_MANAGED_USERS)
#include "chrome/browser/policy/managed_mode_policy_provider.h"
#endif
#if defined(OS_CHROMEOS)
#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/chromeos/login/user.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/policy/device_local_account_policy_provider.h"
#include "chrome/browser/chromeos/policy/login_profile_policy_provider.h"
#include "chrome/browser/chromeos/policy/network_configuration_updater.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
#include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/policy/policy_service.h"
#include "chrome/common/pref_names.h"
#include "chromeos/dbus/cryptohome_client.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#else
#include "chrome/browser/policy/cloud/user_cloud_policy_manager.h"
#include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h"
#endif
namespace policy {
ProfilePolicyConnector::ProfilePolicyConnector(Profile* profile)
: profile_(profile),
#if defined(OS_CHROMEOS)
is_primary_user_(false),
#endif
weak_ptr_factory_(this) {}
ProfilePolicyConnector::~ProfilePolicyConnector() {}
void ProfilePolicyConnector::Init(
bool force_immediate_load,
base::SequencedTaskRunner* sequenced_task_runner) {
BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
// |providers| contains a list of the policy providers available for the
// PolicyService of this connector.
std::vector<ConfigurationPolicyProvider*> providers;
#if defined(OS_CHROMEOS)
UserCloudPolicyManagerChromeOS* cloud_policy_manager =
UserCloudPolicyManagerFactoryChromeOS::GetForProfile(profile_);
if (cloud_policy_manager)
providers.push_back(cloud_policy_manager);
bool is_managed = false;
std::string username;
if (chromeos::ProfileHelper::IsSigninProfile(profile_)) {
special_user_policy_provider_.reset(new LoginProfilePolicyProvider(
connector->GetPolicyService()));
special_user_policy_provider_->Init();
} else {
// |user| should never be NULL except for the signin profile.
// TODO(joaodasilva): get the |user| that corresponds to the |profile_|
// from the ProfileHelper, once that's ready.
chromeos::UserManager* user_manager = chromeos::UserManager::Get();
chromeos::User* user = user_manager->GetActiveUser();
CHECK(user);
// Check if |user| is managed, and if it's a public account.
username = user->email();
is_managed =
connector->GetUserAffiliation(username) == USER_AFFILIATION_MANAGED;
is_primary_user_ =
chromeos::UserManager::Get()->GetLoggedInUsers().size() == 1;
if (user->GetType() == chromeos::User::USER_TYPE_PUBLIC_ACCOUNT)
InitializeDeviceLocalAccountPolicyProvider(username);
}
if (special_user_policy_provider_)
providers.push_back(special_user_policy_provider_.get());
#else
UserCloudPolicyManager* cloud_policy_manager =
UserCloudPolicyManagerFactory::GetForProfile(profile_);
if (cloud_policy_manager)
providers.push_back(cloud_policy_manager);
#endif
#if defined(ENABLE_MANAGED_USERS)
managed_mode_policy_provider_ = ManagedModePolicyProvider::Create(
profile_, sequenced_task_runner, force_immediate_load);
managed_mode_policy_provider_->Init();
providers.push_back(managed_mode_policy_provider_.get());
#endif
policy_service_ = connector->CreatePolicyService(providers);
#if defined(OS_CHROMEOS)
if (is_primary_user_) {
if (cloud_policy_manager)
connector->SetUserPolicyDelegate(cloud_policy_manager);
else if (special_user_policy_provider_)
connector->SetUserPolicyDelegate(special_user_policy_provider_.get());
chromeos::CryptohomeClient* cryptohome_client =
chromeos::DBusThreadManager::Get()->GetCryptohomeClient();
cryptohome_client->GetSanitizedUsername(
username,
base::Bind(
&ProfilePolicyConnector::InitializeNetworkConfigurationUpdater,
weak_ptr_factory_.GetWeakPtr(),
is_managed));
}
#endif
}
void ProfilePolicyConnector::InitForTesting(scoped_ptr<PolicyService> service) {
policy_service_ = service.Pass();
}
void ProfilePolicyConnector::Shutdown() {
#if defined(OS_CHROMEOS)
if (is_primary_user_) {
BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
connector->SetUserPolicyDelegate(NULL);
connector->network_configuration_updater()->UnsetUserPolicyService();
}
if (special_user_policy_provider_)
special_user_policy_provider_->Shutdown();
#endif
#if defined(ENABLE_MANAGED_USERS)
if (managed_mode_policy_provider_)
managed_mode_policy_provider_->Shutdown();
#endif
}
bool ProfilePolicyConnector::UsedPolicyCertificates() {
#if defined(OS_CHROMEOS)
return profile_->GetPrefs()->GetBoolean(prefs::kUsedPolicyCertificatesOnce);
#else
return false;
#endif
}
#if defined(OS_CHROMEOS)
void ProfilePolicyConnector::InitializeDeviceLocalAccountPolicyProvider(
const std::string& username) {
BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
DeviceLocalAccountPolicyService* device_local_account_policy_service =
connector->GetDeviceLocalAccountPolicyService();
if (!device_local_account_policy_service)
return;
special_user_policy_provider_.reset(new DeviceLocalAccountPolicyProvider(
username, device_local_account_policy_service));
special_user_policy_provider_->Init();
}
void ProfilePolicyConnector::InitializeNetworkConfigurationUpdater(
bool is_managed,
chromeos::DBusMethodCallStatus status,
const std::string& hashed_username) {
// TODO(joaodasilva): create the NetworkConfigurationUpdater for user ONC
// here, after splitting that class into an instance for device policy and
// another per profile for user policy.
g_browser_process->browser_policy_connector()->
network_configuration_updater()->SetUserPolicyService(
is_managed, hashed_username, policy_service());
}
#endif
} // namespace policy
| 36.896175 | 86 | 0.781102 | pozdnyakov |
08882e1f43f71d258698d6b669c262e35a54d049 | 735 | cpp | C++ | src/bq-r.cpp | sarahkittyy/bq-r | 5aa4b4c05542d423009bb1362cab07f9871df9a1 | [
"MIT"
] | null | null | null | src/bq-r.cpp | sarahkittyy/bq-r | 5aa4b4c05542d423009bb1362cab07f9871df9a1 | [
"MIT"
] | 8 | 2021-01-06T00:08:08.000Z | 2021-01-16T19:32:34.000Z | src/bq-r.cpp | sarahkittyy/bq-r | 5aa4b4c05542d423009bb1362cab07f9871df9a1 | [
"MIT"
] | null | null | null | #include "bq-r.hpp"
#include <iostream>
#include <imgui-SFML.h>
#include <imgui.h>
app::app()
: m_window(sf::VideoMode(800, 600), "bq-r") {
ImGui::SFML::Init(m_window);
}
int app::run() {
// clock for measuring deltas between frames
sf::Clock imgui_clock;
while (m_window.isOpen()) {
// event handling
sf::Event e;
while (m_window.pollEvent(e)) {
ImGui::SFML::ProcessEvent(e);
switch (e.type) {
case sf::Event::Closed:
m_window.close();
break;
default:
break;
}
}
ImGui::SFML::Update(m_window, imgui_clock.restart());
// render imgui here
ImGui::EndFrame();
m_window.clear(sf::Color::White);
// draw here
ImGui::SFML::Render(m_window);
m_window.display();
}
return 0;
}
| 16.704545 | 55 | 0.634014 | sarahkittyy |
08898e952d967a66dd06b9b34feb5174261cfeef | 456 | cpp | C++ | slicing/src/slicingMethods/SlicingMethod.cpp | mattulbrich/llreve | 68cb958c1c02177fa0db1965a8afd879a97c2fc4 | [
"BSD-3-Clause"
] | 20 | 2016-08-11T19:51:13.000Z | 2021-09-02T13:10:58.000Z | slicing/src/slicingMethods/SlicingMethod.cpp | mattulbrich/llreve | 68cb958c1c02177fa0db1965a8afd879a97c2fc4 | [
"BSD-3-Clause"
] | 9 | 2016-08-11T11:59:24.000Z | 2021-07-16T09:44:28.000Z | slicing/src/slicingMethods/SlicingMethod.cpp | mattulbrich/llreve | 68cb958c1c02177fa0db1965a8afd879a97c2fc4 | [
"BSD-3-Clause"
] | 7 | 2017-08-19T14:42:27.000Z | 2020-05-20T16:14:13.000Z | /*
* This file is part of
* llreve - Automatic regression verification for LLVM programs
*
* Copyright (C) 2016 Karlsruhe Institute of Technology
*
* The system is published under a BSD license.
* See LICENSE (distributed with this file) for details.
*/
#include "SlicingMethod.h"
using namespace std;
using namespace llvm;
SlicingMethod::~SlicingMethod() = default;
shared_ptr<Module> SlicingMethod::getProgram(){
return this->program;
}
| 20.727273 | 66 | 0.736842 | mattulbrich |
088f3836c8218a6b0529fad653f40bd9a22ef215 | 7,664 | cpp | C++ | Server/src/modules/SD3/scripts/northrend/obsidian_sanctum/instance_obsidian_sanctum.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | null | null | null | Server/src/modules/SD3/scripts/northrend/obsidian_sanctum/instance_obsidian_sanctum.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | null | null | null | Server/src/modules/SD3/scripts/northrend/obsidian_sanctum/instance_obsidian_sanctum.cpp | ZON3DEV/wow-vanilla | 7b6f03c3e1e7d8dd29a92ba77ed021e5913e5e9f | [
"OpenSSL"
] | null | null | null | /* Copyright (C) 2006 - 2013 ScriptDev2 <http://www.scriptdev2.com/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/* ScriptData
SDName: Instance_Obsidian_Sanctum
SD%Complete: 80%
SDComment:
SDCategory: Obsidian Sanctum
EndScriptData */
#include "precompiled.h"
#include "obsidian_sanctum.h"
/* Obsidian Sanctum encounters:
0 - Sartharion
*/
struct is_obsidian_sanctum : public InstanceScript
{
is_obsidian_sanctum() : InstanceScript("instance_obsidian_sanctum") {}
class instance_obsidian_sanctum : public ScriptedInstance
{
public:
instance_obsidian_sanctum(Map* pMap) : ScriptedInstance(pMap),
m_uiAliveDragons(0)
{
Initialize();
}
void Initialize() override
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
for (uint8 i = 0; i < MAX_TWILIGHT_DRAGONS; ++i)
{
m_bPortalActive[i] = false;
}
}
void OnCreatureCreate(Creature* pCreature) override
{
switch (pCreature->GetEntry())
{
// The three dragons below set to active state once created.
// We must expect bigger raid to encounter main boss, and then three dragons must be active due to grid differences
case NPC_TENEBRON:
case NPC_SHADRON:
case NPC_VESPERON:
pCreature->SetActiveObjectState(true);
case NPC_SARTHARION:
m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid();
break;
case NPC_FIRE_CYCLONE:
m_lFireCycloneGuidList.push_back(pCreature->GetObjectGuid());
break;
}
}
void SetData(uint32 uiType, uint32 uiData) override
{
switch (uiType)
{
case TYPE_SARTHARION_EVENT:
m_auiEncounter[0] = uiData;
if (uiData == IN_PROGRESS)
{
m_sVolcanoBlowFailPlayers.clear();
}
break;
case TYPE_ALIVE_DRAGONS:
m_uiAliveDragons = uiData;
break;
case TYPE_VOLCANO_BLOW_FAILED:
// Insert the players who fail the achiev and haven't been already inserted in the set
if (m_sVolcanoBlowFailPlayers.find(uiData) == m_sVolcanoBlowFailPlayers.end())
{
m_sVolcanoBlowFailPlayers.insert(uiData);
}
break;
case TYPE_DATA_PORTAL_OFF:
case TYPE_DATA_PORTAL_ON:
SetPortalStatus(uint8(uiData), uiType == TYPE_DATA_PORTAL_ON);
return;
default:
break;
}
// No need to save anything here
}
uint32 GetData(uint32 uiType) const override
{
if (uiType == TYPE_SARTHARION_EVENT)
{
return m_auiEncounter[0];
}
if (uiType == TYPE_DATA_PORTAL_STATUS)
{
return uint32(IsActivePortal());
}
return 0;
}
uint64 GetData64(uint32 uiType) const override
{
if (uiType == DATA64_FIRE_CYCLONE)
{
return SelectRandomFireCycloneGuid().GetRawValue();
}
return 0;
}
bool CheckAchievementCriteriaMeet(uint32 uiCriteriaId, Player const* pSource, Unit const* pTarget, uint32 uiMiscValue1 /* = 0*/) const override
{
switch (uiCriteriaId)
{
case ACHIEV_DRAGONS_ALIVE_1_N:
case ACHIEV_DRAGONS_ALIVE_1_H:
return m_uiAliveDragons >= 1;
case ACHIEV_DRAGONS_ALIVE_2_N:
case ACHIEV_DRAGONS_ALIVE_2_H:
return m_uiAliveDragons >= 2;
case ACHIEV_DRAGONS_ALIVE_3_N:
case ACHIEV_DRAGONS_ALIVE_3_H:
return m_uiAliveDragons >= 3;
case ACHIEV_CRIT_VOLCANO_BLOW_N:
case ACHIEV_CRIT_VOLCANO_BLOW_H:
// Return true if not found in the set
return m_sVolcanoBlowFailPlayers.find(pSource->GetGUIDLow()) == m_sVolcanoBlowFailPlayers.end();
default:
return false;
}
}
bool CheckConditionCriteriaMeet(Player const* pPlayer, uint32 uiInstanceConditionId, WorldObject const* pConditionSource, uint32 conditionSourceType) const override
{
switch (uiInstanceConditionId)
{
case INSTANCE_CONDITION_ID_HARD_MODE: // Exactly one dragon alive on event start
case INSTANCE_CONDITION_ID_HARD_MODE_2: // Exactly two dragons alive on event start
case INSTANCE_CONDITION_ID_HARD_MODE_3: // All three dragons alive on event start
return m_uiAliveDragons == uiInstanceConditionId;
}
script_error_log("instance_obsidian_sanctum::CheckConditionCriteriaMeet called with unsupported Id %u. Called with param plr %s, src %s, condition source type %u",
uiInstanceConditionId, pPlayer ? pPlayer->GetGuidStr().c_str() : "nullptr", pConditionSource ? pConditionSource->GetGuidStr().c_str() : "nullptr", conditionSourceType);
return false;
}
private:
void SetPortalStatus(uint8 uiType, bool bStatus) { m_bPortalActive[uiType] = bStatus; }
bool IsActivePortal() const
{
for (uint8 i = 0; i < MAX_TWILIGHT_DRAGONS; ++i)
{
if (m_bPortalActive[i])
{
return true;
}
}
return false;
}
ObjectGuid SelectRandomFireCycloneGuid() const
{
if (m_lFireCycloneGuidList.empty())
{
return ObjectGuid();
}
GuidList::const_iterator iter = m_lFireCycloneGuidList.begin();
advance(iter, urand(0, m_lFireCycloneGuidList.size() - 1));
return *iter;
}
uint32 m_auiEncounter[MAX_ENCOUNTER];
bool m_bPortalActive[MAX_TWILIGHT_DRAGONS];
uint8 m_uiAliveDragons;
std::set<uint32> m_sVolcanoBlowFailPlayers;
GuidList m_lFireCycloneGuidList;
};
InstanceData* GetInstanceData(Map* pMap) override
{
return new instance_obsidian_sanctum(pMap);
}
};
void AddSC_instance_obsidian_sanctum()
{
Script* s;
s = new is_obsidian_sanctum();
s->RegisterSelf();
//pNewScript = new Script;
//pNewScript->Name = "instance_obsidian_sanctum";
//pNewScript->GetInstanceData = GetInstanceData_instance_obsidian_sanctum;
//pNewScript->RegisterSelf();
}
| 33.911504 | 184 | 0.596294 | ZON3DEV |
08906bc31eb2e097931970bdcd5bd3f6a8f99249 | 7,645 | cpp | C++ | example-blink/src/ofApp.cpp | vohoaiviet/ofxFaceTracker | d0bc2e77c57dc598df498c9096296f1124d4ca33 | [
"MIT"
] | null | null | null | example-blink/src/ofApp.cpp | vohoaiviet/ofxFaceTracker | d0bc2e77c57dc598df498c9096296f1124d4ca33 | [
"MIT"
] | null | null | null | example-blink/src/ofApp.cpp | vohoaiviet/ofxFaceTracker | d0bc2e77c57dc598df498c9096296f1124d4ca33 | [
"MIT"
] | null | null | null | #include "ofApp.h"
//===================================================================
// Used to extract eye rectangles. from ProCamToolkit
GLdouble modelviewMatrix[16], projectionMatrix[16];
GLint viewport[4];
void updateProjectionState() {
glGetDoublev(GL_MODELVIEW_MATRIX, modelviewMatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);
glGetIntegerv(GL_VIEWPORT, viewport);
}
glm::vec3 ofWorldToScreen(glm::vec3 world) {
updateProjectionState();
glm::vec3 screen = glm::project(glm::dvec3(world),
glm::make_mat4(modelviewMatrix),
glm::make_mat4(projectionMatrix),
glm::make_vec4(viewport));
screen.y = ofGetHeight() - screen.y;
return screen;
}
ofMesh getProjectedMesh(const ofMesh& mesh) {
ofMesh projected = mesh;
for(std::size_t i = 0; i < mesh.getNumVertices(); i++) {
glm::vec3 cur = ofWorldToScreen(mesh.getVerticesPointer()[i]);
cur.z = 0;
projected.setVertex(i, cur);
}
return projected;
}
template <class T>
void addTexCoords(ofMesh& to, const std::vector<T>& from) {
for(std::size_t i = 0; i < from.size(); i++) {
to.addTexCoord(glm::vec2(from[i].x, from[i].y));
}
}
//===================================================================
using namespace ofxCv;
void ofApp::setup() {
ofSetFrameRate(60);
ofSetVerticalSync(true);
ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL_BILLBOARD);
cam.initGrabber(640, 480);
// Set up images we'll use for frame-differencing
camImage.allocate(640, 480, OF_IMAGE_COLOR);
eyeImageColor.allocate(128, 48);
eyeImageGray.allocate(128,48);
eyeImageGrayPrev.allocate(128,48);
eyeImageGrayDif.allocate(128,48);
eyeFbo.allocate(128, 48, GL_RGB);
// Initialize our images to black.
eyeImageColor.set(0);
eyeImageGray.set(0);
eyeImageGrayPrev.set(0);
eyeImageGrayDif.set(0);
// Set up other objects.
tracker.setup();
osc.setup("localhost", 8338);
// This GUI slider adjusts the sensitivity of the blink detector.
gui.setup();
gui.add(percentileThreshold.setup("Threshold", 0.92, 0.75, 1.0));
}
void ofApp::update() {
cam.update();
if(cam.isFrameNew()) {
camImage.setFromPixels(cam.getPixels());
tracker.update(toCv(cam));
position = tracker.getPosition();
scale = tracker.getScale();
rotationMatrix = tracker.getRotationMatrix();
if(tracker.getFound()) {
glm::vec2
leftOuter = tracker.getImagePoint(36),
leftInner = tracker.getImagePoint(39),
rightInner = tracker.getImagePoint(42),
rightOuter = tracker.getImagePoint(45);
ofPolyline leftEye = tracker.getImageFeature(ofxFaceTracker::LEFT_EYE);
ofPolyline rightEye = tracker.getImageFeature(ofxFaceTracker::RIGHT_EYE);
glm::vec2 leftCenter = leftEye.getBoundingBox().getCenter().xy();
glm::vec2 rightCenter = rightEye.getBoundingBox().getCenter().xy();
float leftRadius = (glm::distance(leftCenter, leftInner) + glm::distance(leftCenter, leftOuter)) / 2;
float rightRadius = (glm::distance(rightCenter, rightInner) + glm::distance(rightCenter, rightOuter)) / 2;
glm::vec3
leftOuterObj = tracker.getObjectPoint(36),
leftInnerObj = tracker.getObjectPoint(39),
rightInnerObj = tracker.getObjectPoint(42),
rightOuterObj = tracker.getObjectPoint(45);
glm::vec3 upperBorder(0, -3.5, 0), lowerBorder(0, 2.5, 0);
glm::vec3 leftDirection(-1, 0, 0), rightDirection(+1, 0, 0);
float innerBorder = 1.5, outerBorder = 2.5;
ofMesh leftRect, rightRect;
leftRect.setMode(OF_PRIMITIVE_LINE_LOOP);
leftRect.addVertex(leftOuterObj + upperBorder + leftDirection * outerBorder);
leftRect.addVertex(leftInnerObj + upperBorder + rightDirection * innerBorder);
leftRect.addVertex(leftInnerObj + lowerBorder + rightDirection * innerBorder);
leftRect.addVertex(leftOuterObj + lowerBorder + leftDirection * outerBorder);
rightRect.setMode(OF_PRIMITIVE_LINE_LOOP);
rightRect.addVertex(rightInnerObj+ upperBorder + leftDirection * innerBorder);
rightRect.addVertex(rightOuterObj + upperBorder + rightDirection * outerBorder);
rightRect.addVertex(rightOuterObj + lowerBorder + rightDirection * outerBorder);
rightRect.addVertex(rightInnerObj + lowerBorder + leftDirection * innerBorder);
ofPushMatrix();
ofSetupScreenOrtho(640, 480, -1000, 1000);
ofScale(1, 1, -1);
ofTranslate(position);
applyMatrix(rotationMatrix);
ofScale(scale, scale, scale);
leftRectImg = getProjectedMesh(leftRect);
rightRectImg = getProjectedMesh(rightRect);
ofPopMatrix();
// more effective than using object space points would be to use image space
// but translate to the center of the eye and orient the rectangle in the
// direction the face is facing.
/*
ofPushMatrix();
ofTranslate(tracker.getImageFeature(ofxFaceTracker::LEFT_EYE).getCentroid2D());
applyMatrix(rotationMatrix);
ofRect(-50, -40, 2*50, 2*40);
ofPopMatrix();
ofPushMatrix();
ofTranslate(tracker.getImageFeature(ofxFaceTracker::RIGHT_EYE).getCentroid2D());
applyMatrix(rotationMatrix);
ofRect(-50, -40, 2*50, 2*40);
ofPopMatrix();
*/
ofMesh normRect, normLeft, normRight;
normRect.addVertex(glm::vec3(0, 0, 0));
normRect.addVertex(glm::vec3(64, 0, 0));
normRect.addVertex(glm::vec3(64, 48, 0));
normRect.addVertex(glm::vec3(0, 48, 0));
normLeft.setMode(OF_PRIMITIVE_TRIANGLE_FAN);
normRight.setMode(OF_PRIMITIVE_TRIANGLE_FAN);
normLeft.addVertices(normRect.getVertices());
normRight.addVertices(normRect.getVertices());
addTexCoords(normLeft, leftRectImg.getVertices());
addTexCoords(normRight, rightRectImg.getVertices());
// Copy the extracted quadrilaterals into the eyeFbo
eyeFbo.begin();
ofSetColor(255);
ofFill();
cam.getTexture().bind();
normLeft.draw();
ofTranslate(64, 0);
normRight.draw();
cam.getTexture().unbind();
eyeFbo.end();
eyeFbo.readToPixels(eyePixels);
// Convert the combined eye-image to grayscale,
// and put its data into a frame-differencer.
eyeImageColor.setFromPixels(eyePixels);
eyeImageGrayPrev.setFromPixels(eyeImageGray.getPixels());
eyeImageGray.setFromColorImage(eyeImageColor);
eyeImageGray.contrastStretch();
eyeImageGrayDif.absDiff(eyeImageGrayPrev, eyeImageGray);
// Compute the average brightness of the difference image.
unsigned char* difPixels = eyeImageGrayDif.getPixels().getData();
int nPixels = 128*48;
float sum = 0;
for (int i=0; i<nPixels; i++){
if (difPixels[i] > 4){ // don't consider diffs less than 4 gray levels;
sum += difPixels[i]; // reduces noise
}
}
// Store the current average in the row graph
float avg = sum / (float) nPixels;
rowGraph.addSample(avg, percentileThreshold);
// Send out an OSC message,
// With the value 1 if the current average is above threshold
ofxOscMessage msg;
msg.setAddress("/gesture/blink");
int oscMsgInt = (rowGraph.getState() ? 1 : 0);
msg.addIntArg(oscMsgInt);
osc.sendMessage(msg);
// Print out a message to the console if there was a blink.
if (oscMsgInt > 0){
printf("Blink happened at frame #: %d\n", (int)ofGetFrameNum());
}
}
}
}
void ofApp::draw() {
ofSetColor(255);
camImage.draw(0, 0);
tracker.draw();
leftRectImg.draw();
rightRectImg.draw();
float y = 58;
gui.draw();
eyeImageGray.draw(10, y); y+=58;
eyeImageGrayDif.draw(10, y); y+=58;
rowGraph.draw(10, y, 48);
ofDrawBitmapString(ofToString((int) ofGetFrameRate()), 10, ofGetHeight() - 20);
}
void ofApp::keyPressed(int key) {
if(key == 'r') {
tracker.reset();
}
}
| 33.095238 | 118 | 0.687116 | vohoaiviet |
0891556f637294fd4c9bb3433a362ff39d2c8055 | 530 | cc | C++ | tests/CompileTests/ElsaTestCases/t0291.cc | maurizioabba/rose | 7597292cf14da292bdb9a4ef573001b6c5b9b6c0 | [
"BSD-3-Clause"
] | 488 | 2015-01-09T08:54:48.000Z | 2022-03-30T07:15:46.000Z | tests/CompileTests/ElsaTestCases/t0291.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 174 | 2015-01-28T18:41:32.000Z | 2022-03-31T16:51:05.000Z | tests/CompileTests/ElsaTestCases/t0291.cc | sujankh/rose-matlab | 7435d4fa1941826c784ba97296c0ec55fa7d7c7e | [
"BSD-3-Clause"
] | 146 | 2015-04-27T02:48:34.000Z | 2022-03-04T07:32:53.000Z | // t0291.cc
// friend function with definition at point of declaration
struct A {
friend int foo() { return 2; }
};
// 11.4 para 5 is (IMO) unclear about precisely what names are in
// scope in an inline friend definition; gcc likes the following
// code, so I'm putting it in my test suite too..
int I; // non-type; *not* seen
class B {
typedef int I; // type; this is what 'I' looks up to (at least in gcc)
friend int bar()
{
I i; // use of type 'I'
return i;
}
};
| 22.083333 | 79 | 0.59434 | maurizioabba |
0891ce2a90700f808ba8610410ab59eb4c38a1ab | 14,578 | cpp | C++ | Lib/src/Elements/Atom.cpp | undisputed-seraphim/TBTK | 45a0875a11da951f900b6fd5e0773ccdf8462915 | [
"Apache-2.0"
] | 96 | 2016-04-21T16:46:56.000Z | 2022-01-15T21:40:25.000Z | Lib/src/Elements/Atom.cpp | undisputed-seraphim/TBTK | 45a0875a11da951f900b6fd5e0773ccdf8462915 | [
"Apache-2.0"
] | 4 | 2016-10-19T16:56:20.000Z | 2020-04-14T01:31:40.000Z | Lib/src/Elements/Atom.cpp | undisputed-seraphim/TBTK | 45a0875a11da951f900b6fd5e0773ccdf8462915 | [
"Apache-2.0"
] | 19 | 2016-10-19T14:21:58.000Z | 2021-04-15T13:52:09.000Z | /* Copyright 2017 Kristofer Björnson
*
* 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.
*/
/** @file Atom.cpp
*
* @author Kristofer Björnson
*/
#include "TBTK/Atom.h"
using namespace std;
namespace TBTK{
string Atom::symbols[Atom::totalNumAtoms+1] = {
"None",
"H",
"He",
"Li",
"Be",
"B",
"C",
"N",
"O",
"F",
"Ne", //10
"Na",
"Mg",
"Al",
"Si",
"P",
"S",
"Cl",
"Ar",
"K",
"Ca", //20
"Sc",
"Ti",
"V",
"Cr",
"Mn",
"Fe",
"Co",
"Ni",
"Cu",
"Zn", //30
"Ga",
"Ge",
"As",
"Se",
"Br",
"Kr",
"Rb",
"Sr",
"Y",
"Zr", //40
"Nb",
"Mo",
"Tc",
"Ru",
"Rh",
"Pd",
"Ag",
"Cd",
"In",
"Sn", //50
"Sb",
"Te",
"I",
"Xe",
"Cs",
"Ba",
"La",
"Ce",
"Pr",
"Nd", //60
"Pm",
"Sm",
"Eu",
"Gd",
"Tb",
"Dy",
"Ho",
"Er",
"Tm",
"Yb", //70
"Lu",
"Hf",
"Ta",
"W",
"Re",
"Os",
"Ir",
"Pt",
"Au",
"Hg", //80
"Tl",
"Pb",
"Bi",
"Po",
"At",
"Rn",
"Fr",
"Ra",
"Ac",
"Th", //90
"Pa",
"U",
"Np",
"Pu",
"Am",
"Cm",
"Bk",
"Cf",
"Es",
"Fm", //100
"Md",
"No",
"Lr",
"Rf",
"Db",
"Sg",
"Bh",
"Hs",
"Mt",
"Ds", //110
"Rg",
"Cn",
"Nh",
"Fl",
"Mc",
"Lv",
"Ts",
"Og"
};
string Atom::names[Atom::totalNumAtoms+1] = {
"None",
"Hydrogen",
"Helium",
"Lithium",
"Beryllium",
"Boron",
"Carbon",
"Nitrogen",
"Oxygen",
"Fluorine",
"Neon", //10
"Sodium",
"Magnesium",
"Aluminium",
"Silicon",
"Phosphorus",
"Sulfur",
"Chlorine",
"Argon",
"Potassium",
"Calcium", //20
"Scandium",
"Titanium",
"Vanadium",
"Chromium",
"Manganese",
"Iron",
"Cobalt",
"Nickel",
"Copper",
"Zinc", //30
"Gallium",
"Germanium",
"Arsenic",
"Selenium",
"Bromine",
"Krypton",
"Rubidium",
"Strontium",
"Yttrium",
"Zirconium", //40
"Niobium",
"Molybdenum",
"Technetium",
"Ruthenium",
"Rhodium",
"Palladium",
"Silver",
"Cadmium",
"Indium",
"Tin", //50
"Antimony",
"Tellurium",
"Iodine",
"Xenon",
"Caesium",
"Barium",
"Lanthanum",
"Cerium",
"Praseodymium",
"Neodymium", //60
"Promethium",
"Samarium",
"Europium",
"Gadolinium",
"Terbium",
"Dysprosium",
"Holmium",
"Erbium",
"Thulium",
"Ytterbium", //70
"Lutetium",
"Hafnium",
"Tantalum",
"Tungsten",
"Rhenium",
"Osmium",
"Iridium",
"Platinum",
"Gold",
"Mercury", //80
"Thallium",
"Lead",
"Bismuth",
"Polonium",
"Astatine",
"Radon",
"Francium",
"Radium",
"Actinium",
"Thorium", //90
"Protactinium",
"Uranium",
"Neptunium",
"Plutonium",
"Americium",
"Curium",
"Berkelium",
"Californium",
"Einsteinium",
"Fermium", //100
"Mendelevium",
"Nobelium",
"Lawrencium",
"Rutherfordium",
"Dubnium",
"Seaborgium",
"Bohrium",
"Hassium",
"Meitnerium",
"Darmstadtium", //110
"Roentgenium",
"Copernicium",
"Nihonium",
"Flerovium",
"Moscovium",
"Livermorium",
"Tennessine",
"Oganesson"
};
double Atom::standardWeights[totalNumAtoms+1] = {
0,
1.008,
4.0026,
6.94,
9.0122,
10.81,
12.011,
14.007,
15.999,
18.998,
20.180, //10
22.990,
24.305,
26.982,
28.085,
30.974,
32.06,
35.45,
39.948,
39.098,
40.078, //20
44.956,
47.867,
50.942,
51.996,
54.938,
55.845,
58.933,
58.693,
63.546,
65.38, //30
69.723,
72.630,
74.922,
78.971,
79.904,
83.798,
85.468,
87.62,
88.906,
91.224, //40
92.906,
95.95,
98,
101.07,
102.91,
106.42,
107.87,
112.41,
114.82,
118.71, //50
121.76,
127.60,
126.90,
131.29,
132.91,
137.33,
138.91,
140.12,
140.91,
144.24, //60
145,
150.36,
151.96,
157.25,
158.93,
162.50,
164.93,
167.26,
168.93,
173.05, //70
174.97,
178.49,
180.95,
183.84,
186.21,
190.23,
192.22,
195.08,
196.97,
200.59, //80
204.38,
207.2,
208.98,
209,
210,
222,
223,
226,
227,
232.04, //90
231.04,
238.03,
237,
244,
243,
247,
247,
251,
252,
257, //100
258,
259,
266,
267,
268,
269,
270,
277,
278,
281, //110
282,
285,
286,
289,
290,
293,
294,
294
};
Atom Atom::atoms[Atom::totalNumAtoms+1] = {
Atom(0),
Atom(1),
Atom(2),
Atom(3),
Atom(4),
Atom(5),
Atom(6),
Atom(7),
Atom(8),
Atom(9),
Atom(10),
Atom(11),
Atom(12),
Atom(13),
Atom(14),
Atom(15),
Atom(16),
Atom(17),
Atom(18),
Atom(19),
Atom(20),
Atom(21),
Atom(22),
Atom(23),
Atom(24),
Atom(25),
Atom(26),
Atom(27),
Atom(28),
Atom(29),
Atom(30),
Atom(31),
Atom(32),
Atom(33),
Atom(34),
Atom(35),
Atom(36),
Atom(37),
Atom(38),
Atom(39),
Atom(40),
Atom(41),
Atom(42),
Atom(43),
Atom(44),
Atom(45),
Atom(46),
Atom(47),
Atom(48),
Atom(49),
Atom(50),
Atom(51),
Atom(52),
Atom(53),
Atom(54),
Atom(55),
Atom(56),
Atom(57),
Atom(58),
Atom(59),
Atom(60),
Atom(61),
Atom(62),
Atom(63),
Atom(64),
Atom(65),
Atom(66),
Atom(67),
Atom(68),
Atom(69),
Atom(70),
Atom(71),
Atom(72),
Atom(73),
Atom(74),
Atom(75),
Atom(76),
Atom(77),
Atom(78),
Atom(79),
Atom(80),
Atom(81),
Atom(82),
Atom(83),
Atom(84),
Atom(85),
Atom(86),
Atom(87),
Atom(88),
Atom(89),
Atom(90),
Atom(91),
Atom(92),
Atom(93),
Atom(94),
Atom(95),
Atom(96),
Atom(97),
Atom(98),
Atom(99),
Atom(100),
Atom(101),
Atom(102),
Atom(103),
Atom(104),
Atom(105),
Atom(106),
Atom(107),
Atom(108),
Atom(109),
Atom(110),
Atom(111),
Atom(112),
Atom(113),
Atom(114),
Atom(115),
Atom(116),
Atom(117),
Atom(118)
};
const Atom &Atom::Hydrogen = atoms[1];
const Atom &Atom::Helium = atoms[2];
const Atom &Atom::Lithium = atoms[3];
const Atom &Atom::Beryllium = atoms[4];
const Atom &Atom::Boron = atoms[5];
const Atom &Atom::Carbon = atoms[6];
const Atom &Atom::Nitrogen = atoms[7];
const Atom &Atom::Oxygen = atoms[8];
const Atom &Atom::Fluorine = atoms[9];
const Atom &Atom::Neon = atoms[10];
const Atom &Atom::Sodium = atoms[11];
const Atom &Atom::Magnesium = atoms[12];
const Atom &Atom::Aluminium = atoms[13];
const Atom &Atom::Silicon = atoms[14];
const Atom &Atom::Phosphorus = atoms[15];
const Atom &Atom::Sulfur = atoms[16];
const Atom &Atom::Chlorine = atoms[17];
const Atom &Atom::Argon = atoms[18];
const Atom &Atom::Potassium = atoms[19];
const Atom &Atom::Calcium = atoms[20];
const Atom &Atom::Scandium = atoms[21];
const Atom &Atom::Titanium = atoms[22];
const Atom &Atom::Vanadium = atoms[23];
const Atom &Atom::Chromium = atoms[24];
const Atom &Atom::Manganese = atoms[25];
const Atom &Atom::Iron = atoms[26];
const Atom &Atom::Cobalt = atoms[27];
const Atom &Atom::Nickel = atoms[28];
const Atom &Atom::Copper = atoms[29];
const Atom &Atom::Zinc = atoms[30];
const Atom &Atom::Gallium = atoms[31];
const Atom &Atom::Germanium = atoms[32];
const Atom &Atom::Arsenic = atoms[33];
const Atom &Atom::Selenium = atoms[34];
const Atom &Atom::Bromine = atoms[35];
const Atom &Atom::Krypton = atoms[36];
const Atom &Atom::Rubidium = atoms[37];
const Atom &Atom::Strontium = atoms[38];
const Atom &Atom::Yttrium = atoms[39];
const Atom &Atom::Zirconium = atoms[40];
const Atom &Atom::Niobium = atoms[41];
const Atom &Atom::Molybdenum = atoms[42];
const Atom &Atom::Technetium = atoms[43];
const Atom &Atom::Ruthenium = atoms[44];
const Atom &Atom::Rhodium = atoms[45];
const Atom &Atom::Palladium = atoms[46];
const Atom &Atom::Silver = atoms[47];
const Atom &Atom::Cadmium = atoms[48];
const Atom &Atom::Indium = atoms[49];
const Atom &Atom::Tin = atoms[50];
const Atom &Atom::Antimony = atoms[51];
const Atom &Atom::Tellurium = atoms[52];
const Atom &Atom::Iodine = atoms[53];
const Atom &Atom::Xenon = atoms[54];
const Atom &Atom::Caesium = atoms[55];
const Atom &Atom::Barium = atoms[56];
const Atom &Atom::Lanthanum = atoms[57];
const Atom &Atom::Cerium = atoms[58];
const Atom &Atom::Praseodymium = atoms[59];
const Atom &Atom::Neodymium = atoms[60];
const Atom &Atom::Promethium = atoms[61];
const Atom &Atom::Samarium = atoms[62];
const Atom &Atom::Europium = atoms[63];
const Atom &Atom::Gadolinium = atoms[64];
const Atom &Atom::Terbium = atoms[65];
const Atom &Atom::Dysprosium = atoms[66];
const Atom &Atom::Holmium = atoms[67];
const Atom &Atom::Erbium = atoms[68];
const Atom &Atom::Thulium = atoms[69];
const Atom &Atom::Ytterbium = atoms[70];
const Atom &Atom::Lutetium = atoms[71];
const Atom &Atom::Hafnium = atoms[72];
const Atom &Atom::Tantalum = atoms[73];
const Atom &Atom::Tungsten = atoms[74];
const Atom &Atom::Rhenium = atoms[75];
const Atom &Atom::Osmium = atoms[76];
const Atom &Atom::Iridium = atoms[77];
const Atom &Atom::Platinum = atoms[78];
const Atom &Atom::Gold = atoms[79];
const Atom &Atom::Mercury = atoms[80];
const Atom &Atom::Thallium = atoms[81];
const Atom &Atom::Lead = atoms[82];
const Atom &Atom::Bismuth = atoms[83];
const Atom &Atom::Polonium = atoms[84];
const Atom &Atom::Astatine = atoms[85];
const Atom &Atom::Radon = atoms[86];
const Atom &Atom::Francium = atoms[87];
const Atom &Atom::Radium = atoms[88];
const Atom &Atom::Actinium = atoms[89];
const Atom &Atom::Thorium = atoms[90];
const Atom &Atom::Protactinium = atoms[91];
const Atom &Atom::Uranium = atoms[92];
const Atom &Atom::Neptunium = atoms[93];
const Atom &Atom::Plutonium = atoms[94];
const Atom &Atom::Americium = atoms[95];
const Atom &Atom::Curium = atoms[96];
const Atom &Atom::Berkelium = atoms[97];
const Atom &Atom::Californium = atoms[98];
const Atom &Atom::Einsteinium = atoms[99];
const Atom &Atom::Fermium = atoms[100];
const Atom &Atom::Mendelevium = atoms[101];
const Atom &Atom::Nobelium = atoms[102];
const Atom &Atom::Lawrencium = atoms[103];
const Atom &Atom::Rutherfordium = atoms[104];
const Atom &Atom::Dubnium = atoms[105];
const Atom &Atom::Seaborgium = atoms[106];
const Atom &Atom::Bohrium = atoms[107];
const Atom &Atom::Hassium = atoms[108];
const Atom &Atom::Meitnerium = atoms[109];
const Atom &Atom::Darmstadtium = atoms[110];
const Atom &Atom::Roentgenium = atoms[111];
const Atom &Atom::Copernicium = atoms[112];
const Atom &Atom::Nihonium = atoms[113];
const Atom &Atom::Flerovium = atoms[114];
const Atom &Atom::Moscovium = atoms[115];
const Atom &Atom::Livermorium = atoms[116];
const Atom &Atom::Tennessine = atoms[117];
const Atom &Atom::Oganesson = atoms[118];
const Atom &Atom::H = atoms[1];
const Atom &Atom::He = atoms[2];
const Atom &Atom::Li = atoms[3];
const Atom &Atom::Be = atoms[4];
const Atom &Atom::B = atoms[5];
const Atom &Atom::C = atoms[6];
const Atom &Atom::N = atoms[7];
const Atom &Atom::O = atoms[8];
const Atom &Atom::F = atoms[9];
const Atom &Atom::Ne = atoms[10];
const Atom &Atom::Na = atoms[11];
const Atom &Atom::Mg = atoms[12];
const Atom &Atom::Al = atoms[13];
const Atom &Atom::Si = atoms[14];
const Atom &Atom::P = atoms[15];
const Atom &Atom::S = atoms[16];
const Atom &Atom::Cl = atoms[17];
const Atom &Atom::Ar = atoms[18];
const Atom &Atom::K = atoms[19];
const Atom &Atom::Ca = atoms[20];
const Atom &Atom::Sc = atoms[21];
const Atom &Atom::Ti = atoms[22];
const Atom &Atom::V = atoms[23];
const Atom &Atom::Cr = atoms[24];
const Atom &Atom::Mn = atoms[25];
const Atom &Atom::Fe = atoms[26];
const Atom &Atom::Co = atoms[27];
const Atom &Atom::Ni = atoms[28];
const Atom &Atom::Cu = atoms[29];
const Atom &Atom::Zn = atoms[30];
const Atom &Atom::Ga = atoms[31];
const Atom &Atom::Ge = atoms[32];
const Atom &Atom::As = atoms[33];
const Atom &Atom::Se = atoms[34];
const Atom &Atom::Br = atoms[35];
const Atom &Atom::Kr = atoms[36];
const Atom &Atom::Rb = atoms[37];
const Atom &Atom::Sr = atoms[38];
const Atom &Atom::Y = atoms[39];
const Atom &Atom::Zr = atoms[40];
const Atom &Atom::Nb = atoms[41];
const Atom &Atom::Mo = atoms[42];
const Atom &Atom::Tc = atoms[43];
const Atom &Atom::Ru = atoms[44];
const Atom &Atom::Rh = atoms[45];
const Atom &Atom::Pd = atoms[46];
const Atom &Atom::Ag = atoms[47];
const Atom &Atom::Cd = atoms[48];
const Atom &Atom::In = atoms[49];
const Atom &Atom::Sn = atoms[50];
const Atom &Atom::Sb = atoms[51];
const Atom &Atom::Te = atoms[52];
const Atom &Atom::I = atoms[53];
const Atom &Atom::Xe = atoms[54];
const Atom &Atom::Cs = atoms[55];
const Atom &Atom::Ba = atoms[56];
const Atom &Atom::La = atoms[57];
const Atom &Atom::Ce = atoms[58];
const Atom &Atom::Pr = atoms[59];
const Atom &Atom::Nd = atoms[60];
const Atom &Atom::Pm = atoms[61];
const Atom &Atom::Sm = atoms[62];
const Atom &Atom::Eu = atoms[63];
const Atom &Atom::Gd = atoms[64];
const Atom &Atom::Tb = atoms[65];
const Atom &Atom::Dy = atoms[66];
const Atom &Atom::Ho = atoms[67];
const Atom &Atom::Er = atoms[68];
const Atom &Atom::Tm = atoms[69];
const Atom &Atom::Yb = atoms[70];
const Atom &Atom::Lu = atoms[71];
const Atom &Atom::Hf = atoms[72];
const Atom &Atom::Ta = atoms[73];
const Atom &Atom::W = atoms[74];
const Atom &Atom::Re = atoms[75];
const Atom &Atom::Os = atoms[76];
const Atom &Atom::Ir = atoms[77];
const Atom &Atom::Pt = atoms[78];
const Atom &Atom::Au = atoms[79];
const Atom &Atom::Hg = atoms[80];
const Atom &Atom::Tl = atoms[81];
const Atom &Atom::Pb = atoms[82];
const Atom &Atom::Bi = atoms[83];
const Atom &Atom::Po = atoms[84];
const Atom &Atom::At = atoms[85];
const Atom &Atom::Rn = atoms[86];
const Atom &Atom::Fr = atoms[87];
const Atom &Atom::Ra = atoms[88];
const Atom &Atom::Ac = atoms[89];
const Atom &Atom::Th = atoms[90];
const Atom &Atom::Pa = atoms[91];
const Atom &Atom::U = atoms[92];
const Atom &Atom::Np = atoms[93];
const Atom &Atom::Pu = atoms[94];
const Atom &Atom::Am = atoms[95];
const Atom &Atom::Cm = atoms[96];
const Atom &Atom::Bk = atoms[97];
const Atom &Atom::Cf = atoms[98];
const Atom &Atom::Es = atoms[99];
const Atom &Atom::Fm = atoms[100];
const Atom &Atom::Md = atoms[101];
const Atom &Atom::No = atoms[102];
const Atom &Atom::Lr = atoms[103];
const Atom &Atom::Rf = atoms[104];
const Atom &Atom::Db = atoms[105];
const Atom &Atom::Sg = atoms[106];
const Atom &Atom::Bh = atoms[107];
const Atom &Atom::Hs = atoms[108];
const Atom &Atom::Mt = atoms[109];
const Atom &Atom::Ds = atoms[110];
const Atom &Atom::Rg = atoms[111];
const Atom &Atom::Cn = atoms[112];
const Atom &Atom::Nh = atoms[113];
const Atom &Atom::Fl = atoms[114];
const Atom &Atom::Mc = atoms[115];
const Atom &Atom::Lv = atoms[116];
const Atom &Atom::Ts = atoms[117];
const Atom &Atom::Og = atoms[118];
Atom::Atom(){
}
Atom::Atom(unsigned int atomicNumber){
this->atomicNumber = atomicNumber;
}
Atom::~Atom(){
}
}; //End of namespace TBTK
| 19.081152 | 75 | 0.624365 | undisputed-seraphim |
0892b3fc71781977b697a7a2ad44ebf9cc612489 | 1,124 | cpp | C++ | FrameRateCalculator.cpp | jambolo/Misc | 0b2779c9bb1954294a722bddd51dc2ad5e449a1c | [
"MIT"
] | null | null | null | FrameRateCalculator.cpp | jambolo/Misc | 0b2779c9bb1954294a722bddd51dc2ad5e449a1c | [
"MIT"
] | 1 | 2020-04-03T09:49:25.000Z | 2020-04-03T09:50:29.000Z | FrameRateCalculator.cpp | jambolo/Misc | 0b2779c9bb1954294a722bddd51dc2ad5e449a1c | [
"MIT"
] | null | null | null | #include "FrameRateCalculator.h"
#include <chrono>
using namespace std::chrono;
using namespace std::chrono_literals;
FrameRateCalculator::FrameRateCalculator()
: nFrames_(0)
, frameRate_(0.0f)
, averageFrameRate_(0.0f)
{
oldTime_ = oldTime2_ = high_resolution_clock::now();
}
//!
//! @param t Time of current frame
void FrameRateCalculator::update(high_resolution_clock::time_point t)
{
auto dt = t - oldTime_; // Time since previous update
// Update the frame rate value
if (dt > 0s)
frameRate_ = 1.0f / duration<float, seconds::period>(dt).count();
else
frameRate_ = 0.0f;
oldTime_ = t; // Save the current time for next time
// If 1 second has passed, compute the new average FPS value and reset the counters
++nFrames_;
auto dt2 = t - oldTime2_; // Time since previous 1 second update
if (dt2 > 1s)
{
averageFrameRate_ = (float)nFrames_ / duration<float, seconds::period>(dt2).count();
oldTime2_ = t; // Save the current time for next time
nFrames_ = 0; // Reset the frame counter
}
}
| 26.139535 | 92 | 0.647687 | jambolo |
089416b2c0c9b573aea004cbc2bde14d2ed5154a | 1,817 | cpp | C++ | src/vjudge/HYSBZ/2330/23153460_TLE_0ms_0kB.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/vjudge/HYSBZ/2330/23153460_TLE_0ms_0kB.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/vjudge/HYSBZ/2330/23153460_TLE_0ms_0kB.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cctype>
#include <queue>
#include <algorithm>
using namespace std;
struct Node{
int h, dis, cnt;
bool vis;
} nodes[233333];
struct Edge {
int to, nex, w;
} edges[2333333];
int n, k, cnt, ans;
int read() {
int ret, f = 1;
char ch;
while(!isdigit(ch = getchar())) (ch == '-') && (f = -1);
for(ret = ch - '0'; isdigit(ch = getchar()); ret *= 10, ret += ch - '0');
return ret * f;
}
void print(int x) {
if(x < 0) putchar('-'), x = -x;
if(x > 9) print(x / 10);
putchar(x % 10 + '0');
}
void addedge(int u, int v, int w) {
edges[++cnt] = (Edge){v, nodes[u].h, w};
nodes[u].h = cnt;
}
bool spfa(int st) {
queue<int > q;
nodes[st].vis = 1;
q.push(st);
while(!q.empty()) {
int u = q.front();
nodes[u].vis = 0;
q.pop();
if(nodes[u].cnt == n - 1) return 0;
++nodes[u].cnt;
for(int i = nodes[u].h; i; i = edges[i].nex) {
int v = edges[i].to;
if(nodes[v].dis < nodes[u].dis + edges[i].w) {
nodes[v].dis = nodes[u].dis + edges[i].w;
if(!nodes[v].vis) {
nodes[v].vis = 1;
q.push(v);
}
}
}
}
return 1;
}
int main() {
n = read(), k = read();
for(int i = 1; i <= k; ++i) {
int opt = read(), u = read(), v = read();
if(opt == 1) addedge(u, v, 0), addedge(v, u, 0);
else if(opt == 2) addedge(u, v, 1);
else if(opt == 3) addedge(v, u, 0);
else if(opt == 4) addedge(v, u, 1);
else addedge(u, v, 0);
}
for(int i = 1; i <= n; ++i) addedge(0, i, 1);
if(spfa(0)) {
for(int i = 1; i <= n; ++i) ans += nodes[i].dis;
print(ans);
}
else print(-1);
return 0;
} | 23.294872 | 77 | 0.438635 | lnkkerst |
089419ac9d1f21b04343038a308079c2ecdfefed | 5,017 | cpp | C++ | Other/giftwrapping/hearding.cpp | lemmingapex/UVA_Online_Judge | 4ea218fc140d12ead1ee2ed51dabce21b4dca51c | [
"MIT"
] | 1 | 2022-02-24T20:18:29.000Z | 2022-02-24T20:18:29.000Z | Other/giftwrapping/hearding.cpp | lemmingapex/UVA_Online_Judge | 4ea218fc140d12ead1ee2ed51dabce21b4dca51c | [
"MIT"
] | null | null | null | Other/giftwrapping/hearding.cpp | lemmingapex/UVA_Online_Judge | 4ea218fc140d12ead1ee2ed51dabce21b4dca51c | [
"MIT"
] | null | null | null | // Scott Wiedemann
// 04/29/2012
// hearding.cpp
#include <math.h>
#include <stdio.h>
#include <vector>
#define SIZE 10000
using namespace std;
class Point
{
public:
double x,y;
Point()
{ }
Point(const double& A, const double& B)
{
x=A;
y=B;
}
Point operator+ (const Point& a) const
{
Point result;
result.x = x+a.x;
result.y = y+a.y;
return result;
}
Point operator+ (const double& a) const
{
Point result;
result.x = x+a;
result.y = y+a;
return result;
}
Point operator- (const Point& a) const
{
Point result;
result.x = x-a.x;
result.y = y-a.y;
return result;
}
Point operator- (const double& a) const
{
Point result;
result.x = x-a;
result.y = y-a;
return result;
}
Point operator* (const Point& a) const
{
Point result;
result.x = x*a.x;
result.y = y*a.y;
return result;
}
Point operator* (const double& a) const
{
Point result;
result.x = x*a;
result.y = y*a;
return result;
}
Point operator/ (const Point& a) const
{
Point result;
result.x = x/a.x;
result.y = y/a.y;
return result;
}
Point operator/ (const double& a) const
{
Point result;
result.x = x/a;
result.y = y/a;
return result;
}
double magnitude()
{
return sqrt((x*x)+(y*y));
}
double cross(const Point& P)
{
return x*P.y - y*P.x;
}
double dist(const Point& P) {
return sqrt(((P.x-x)*(P.x-x))+((P.y-y)*(P.y-y)));
}
};
// array of all the Points
Point allPoints[SIZE];
int lenPoints, right, l;
// modified quicksort based on sin of the angle
// faster to use sin, rather than the angle.
// can use cos(x) because it is monotonically decreasing function with respect to x
void sortPointsSin(int L, int R)
{
int i = L, j = R;
Point tmp;
Point pivot = allPoints[(L+R)/2];
while(i <= j)
{
while((allPoints[i].x - allPoints[0].x)/allPoints[i].dist(allPoints[0]) > (pivot.x - allPoints[0].x)/pivot.dist(allPoints[0]))
{
i++;
}
while((allPoints[j].x - allPoints[0].x)/allPoints[j].dist(allPoints[0]) < (pivot.x - allPoints[0].x)/pivot.dist(allPoints[0]))
{
j--;
}
if(i <= j)
{
tmp = allPoints[i];
allPoints[i] = allPoints[j];
allPoints[j] = tmp;
i++;
j--;
}
};
if(L < j)
{
sortPointsSin(L, j);
}
if(i < R)
{
sortPointsSin(i, R);
}
}
//is point 3 a left turn or right turn with respect to point 1 and 2?
double ccw(Point p1, Point p2, Point p3) {
return (p1 - p2).cross(p3 - p2);
}
vector<int> findConvexHull() {
vector<int> convexHullIndices;
convexHullIndices.push_back(0);
convexHullIndices.push_back(1);
// number of points on the convex hull
int i = 2;
for(int j=2; j<lenPoints; j++) {
// while left turns or co-linear?
while(ccw(allPoints[convexHullIndices.at(i-2)], allPoints[convexHullIndices.at(i-1)], allPoints[j]) <= 0 && j<lenPoints) {
//printf("left\n");
//printf("push\n");
convexHullIndices.push_back(j);
i++;
j++;
}
// if it's a right turn
if(ccw(allPoints[convexHullIndices.at(i-2)], allPoints[convexHullIndices.at(i-1)], allPoints[j]) > 0) {
//printf("right\n");
// remove points until it's a left turn
while(ccw(allPoints[convexHullIndices.at(i-2)], allPoints[convexHullIndices.at(i-1)], allPoints[j]) > 0) {
//printf("pop\n");
convexHullIndices.pop_back();
i--;
}
// add the new point;
//printf("push\n");
convexHullIndices.push_back(j);
i++;
}
}
return convexHullIndices;
}
void solve()
{
if(lenPoints<2)
return;
}
int main() {
int readReturn;
int cases = 0;
readReturn = scanf("%d", &cases);
//printf("cases: %i\n", cases);
for(int i = 0; i < cases; i++) {
readReturn = scanf("%d", &lenPoints);
// add the phone pole at 0,0
lenPoints++;
allPoints[0] = Point(0.0, 0.0);
//printf("number of Points: %i\n", lenPoints);
for(int j=1; j<lenPoints; j++) {
readReturn = scanf("%lf", &allPoints[j].x);
readReturn = scanf("%lf", &allPoints[j].y);
}
// find min y index
int minYIndex = 0;
for(int j=1; j<lenPoints; j++) {
if(allPoints[j].y < allPoints[minYIndex].y) {
minYIndex = j;
} else if(allPoints[j].y == allPoints[minYIndex].y) {
// break ties with x-coordinate
if(allPoints[j].x < allPoints[minYIndex].x) {
minYIndex = j;
}
}
}
// swap min y index with 0 index
Point temp = allPoints[0];
allPoints[0] = allPoints[minYIndex];
allPoints[minYIndex] = temp;
// sort the Points
sortPointsSin(1, lenPoints - 1);
// find the hull
vector<int> convexHullIndices = findConvexHull();
int i = 0;
for(int j=0; j<lenPoints; j++) {
if(convexHullIndices.at(i) == j) {
printf("%.2lf, %.2lf, [%i]\n", allPoints[convexHullIndices.at(i)].x, allPoints[convexHullIndices.at(i)].y, convexHullIndices.at(i)+1);
i++;
} else {
printf("%.2lf, %.2lf, %i\n", allPoints[j].x, allPoints[j].y, j+1);
}
}
solve();
//printf("%.2lf\n", delta);
//printf("%s","INFINITY\n");
printf("\n");
}
return 0;
}
| 19.67451 | 138 | 0.598565 | lemmingapex |
0894ceb5bf675d9df94dd225bbbd7c31b102f3f2 | 105,625 | cpp | C++ | vm/CheckJni.cpp | flowcoaster/android_platform_dalvik | de43d1017cd6e987a202ac2d977a716f46d429e7 | [
"Apache-2.0"
] | null | null | null | vm/CheckJni.cpp | flowcoaster/android_platform_dalvik | de43d1017cd6e987a202ac2d977a716f46d429e7 | [
"Apache-2.0"
] | null | null | null | vm/CheckJni.cpp | flowcoaster/android_platform_dalvik | de43d1017cd6e987a202ac2d977a716f46d429e7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Support for -Xcheck:jni (the "careful" version of the JNI interfaces).
*
* We want to verify types, make sure class and field IDs are valid, and
* ensure that JNI's semantic expectations are being met. JNI seems to
* be relatively lax when it comes to requirements for permission checks,
* e.g. access to private methods is generally allowed from anywhere.
*/
#include "Dalvik.h"
#include "JniInternal.h"
#include <sys/mman.h>
#include <zlib.h>
/*
* Abort if we are configured to bail out on JNI warnings.
*/
static void abortMaybe() {
if (!gDvmJni.warnOnly) {
dvmDumpThread(dvmThreadSelf(), false);
dvmAbort();
}
}
/*
* ===========================================================================
* JNI call bridge wrapper
* ===========================================================================
*/
/*
* Check the result of a native method call that returns an object reference.
*
* The primary goal here is to verify that native code is returning the
* correct type of object. If it's declared to return a String but actually
* returns a byte array, things will fail in strange ways later on.
*
* This can be a fairly expensive operation, since we have to look up the
* return type class by name in method->clazz' class loader. We take a
* shortcut here and allow the call to succeed if the descriptor strings
* match. This will allow some false-positives when a class is redefined
* by a class loader, but that's rare enough that it doesn't seem worth
* testing for.
*
* At this point, pResult->l has already been converted to an object pointer.
*/
static void checkCallResultCommon(const u4* args, const JValue* pResult,
const Method* method, Thread* self)
{
assert(pResult->l != NULL);
const Object* resultObj = (const Object*) pResult->l;
if (resultObj == kInvalidIndirectRefObject) {
ALOGW("JNI WARNING: invalid reference returned from native code");
const Method* method = dvmGetCurrentJNIMethod();
char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
ALOGW(" in %s.%s:%s", method->clazz->descriptor, method->name, desc);
free(desc);
abortMaybe();
return;
}
ClassObject* objClazz = resultObj->clazz;
/*
* Make sure that pResult->l is an instance of the type this
* method was expected to return.
*/
const char* declType = dexProtoGetReturnType(&method->prototype);
const char* objType = objClazz->descriptor;
if (strcmp(declType, objType) == 0) {
/* names match; ignore class loader issues and allow it */
ALOGV("Check %s.%s: %s io %s (FAST-OK)",
method->clazz->descriptor, method->name, objType, declType);
} else {
/*
* Names didn't match. We need to resolve declType in the context
* of method->clazz->classLoader, and compare the class objects
* for equality.
*
* Since we're returning an instance of declType, it's safe to
* assume that it has been loaded and initialized (or, for the case
* of an array, generated). However, the current class loader may
* not be listed as an initiating loader, so we can't just look for
* it in the loaded-classes list.
*/
ClassObject* declClazz = dvmFindClassNoInit(declType, method->clazz->classLoader);
if (declClazz == NULL) {
ALOGW("JNI WARNING: method declared to return '%s' returned '%s'",
declType, objType);
ALOGW(" failed in %s.%s ('%s' not found)",
method->clazz->descriptor, method->name, declType);
abortMaybe();
return;
}
if (!dvmInstanceof(objClazz, declClazz)) {
ALOGW("JNI WARNING: method declared to return '%s' returned '%s'",
declType, objType);
ALOGW(" failed in %s.%s",
method->clazz->descriptor, method->name);
abortMaybe();
return;
} else {
ALOGV("Check %s.%s: %s io %s (SLOW-OK)",
method->clazz->descriptor, method->name, objType, declType);
}
}
}
/*
* Determine if we need to check the return type coming out of the call.
*
* (We don't simply do this at the top of checkCallResultCommon() because
* this is on the critical path for native method calls.)
*/
static inline bool callNeedsCheck(const u4* args, JValue* pResult,
const Method* method, Thread* self)
{
return (method->shorty[0] == 'L' && !dvmCheckException(self) && pResult->l != NULL);
}
/*
* Check a call into native code.
*/
void dvmCheckCallJNIMethod(u4* args, JValue* pResult,
const Method* method, Thread* self)
{
dvmCallJNIMethod(args, pResult, method, self);
if (callNeedsCheck(args, pResult, method, self)) {
checkCallResultCommon(args, pResult, method, self);
}
}
/*
* ===========================================================================
* JNI function helpers
* ===========================================================================
*/
static inline const JNINativeInterface* baseEnv(JNIEnv* env) {
return ((JNIEnvExt*) env)->baseFuncTable;
}
static inline const JNIInvokeInterface* baseVm(JavaVM* vm) {
return ((JavaVMExt*) vm)->baseFuncTable;
}
class ScopedCheckJniThreadState {
public:
explicit ScopedCheckJniThreadState(JNIEnv* env) {
dvmChangeStatus(NULL, THREAD_RUNNING);
}
~ScopedCheckJniThreadState() {
dvmChangeStatus(NULL, THREAD_NATIVE);
}
private:
// Disallow copy and assignment.
ScopedCheckJniThreadState(const ScopedCheckJniThreadState&);
void operator=(const ScopedCheckJniThreadState&);
};
/*
* Flags passed into ScopedCheck.
*/
#define kFlag_Default 0x0000
#define kFlag_CritBad 0x0000 /* calling while in critical is bad */
#define kFlag_CritOkay 0x0001 /* ...okay */
#define kFlag_CritGet 0x0002 /* this is a critical "get" */
#define kFlag_CritRelease 0x0003 /* this is a critical "release" */
#define kFlag_CritMask 0x0003 /* bit mask to get "crit" value */
#define kFlag_ExcepBad 0x0000 /* raised exceptions are bad */
#define kFlag_ExcepOkay 0x0004 /* ...okay */
#define kFlag_Release 0x0010 /* are we in a non-critical release function? */
#define kFlag_NullableUtf 0x0020 /* are our UTF parameters nullable? */
#define kFlag_Invocation 0x8000 /* Part of the invocation interface (JavaVM*) */
static const char* indirectRefKindName(IndirectRef iref)
{
return indirectRefKindToString(indirectRefKind(iref));
}
class ScopedCheck {
public:
// For JNIEnv* functions.
explicit ScopedCheck(JNIEnv* env, int flags, const char* functionName) {
init(env, flags, functionName, true);
checkThread(flags);
}
// For JavaVM* functions.
explicit ScopedCheck(bool hasMethod, const char* functionName) {
init(NULL, kFlag_Invocation, functionName, hasMethod);
}
/*
* In some circumstances the VM will screen class names, but it doesn't
* for class lookup. When things get bounced through a class loader, they
* can actually get normalized a couple of times; as a result, passing in
* a class name like "java.lang.Thread" instead of "java/lang/Thread" will
* work in some circumstances.
*
* This is incorrect and could cause strange behavior or compatibility
* problems, so we want to screen that out here.
*
* We expect "fully-qualified" class names, like "java/lang/Thread" or
* "[Ljava/lang/Object;".
*/
void checkClassName(const char* className) {
if (!dexIsValidClassName(className, false)) {
ALOGW("JNI WARNING: illegal class name '%s' (%s)", className, mFunctionName);
ALOGW(" (should be formed like 'dalvik/system/DexFile')");
ALOGW(" or '[Ldalvik/system/DexFile;' or '[[B')");
abortMaybe();
}
}
void checkFieldTypeForGet(jfieldID fid, const char* expectedSignature, bool isStatic) {
if (fid == NULL) {
ALOGW("JNI WARNING: null jfieldID");
showLocation();
abortMaybe();
}
bool printWarn = false;
Field* field = (Field*) fid;
const char* actualSignature = field->signature;
if (*expectedSignature == 'L') {
// 'actualSignature' has the exact type.
// We just know we're expecting some kind of reference.
if (*actualSignature != 'L' && *actualSignature != '[') {
printWarn = true;
}
} else if (*actualSignature != *expectedSignature) {
printWarn = true;
}
if (!printWarn && isStatic && !dvmIsStaticField(field)) {
if (isStatic) {
ALOGW("JNI WARNING: accessing non-static field %s as static", field->name);
} else {
ALOGW("JNI WARNING: accessing static field %s as non-static", field->name);
}
printWarn = true;
}
if (printWarn) {
ALOGW("JNI WARNING: %s for field '%s' of expected type %s, got %s",
mFunctionName, field->name, expectedSignature, actualSignature);
showLocation();
abortMaybe();
}
}
/*
* Verify that the field is of the appropriate type. If the field has an
* object type, "jobj" is the object we're trying to assign into it.
*
* Works for both static and instance fields.
*/
void checkFieldTypeForSet(jobject jobj, jfieldID fieldID, PrimitiveType prim, bool isStatic) {
if (fieldID == NULL) {
ALOGW("JNI WARNING: null jfieldID");
showLocation();
abortMaybe();
}
bool printWarn = false;
Field* field = (Field*) fieldID;
if ((field->signature[0] == 'L' || field->signature[0] == '[') && jobj != NULL) {
ScopedCheckJniThreadState ts(mEnv);
Object* obj = dvmDecodeIndirectRef(self(), jobj);
/*
* If jobj is a weak global ref whose referent has been cleared,
* obj will be NULL. Otherwise, obj should always be non-NULL
* and valid.
*/
if (obj != NULL && !dvmIsHeapAddress(obj)) {
ALOGW("JNI WARNING: field operation on invalid %s reference (%p)",
indirectRefKindName(jobj), jobj);
printWarn = true;
} else {
ClassObject* fieldClass = dvmFindLoadedClass(field->signature);
ClassObject* objClass = obj->clazz;
assert(fieldClass != NULL);
assert(objClass != NULL);
if (!dvmInstanceof(objClass, fieldClass)) {
ALOGW("JNI WARNING: set field '%s' expected type %s, got %s",
field->name, field->signature, objClass->descriptor);
printWarn = true;
}
}
} else if (dexGetPrimitiveTypeFromDescriptorChar(field->signature[0]) != prim) {
ALOGW("JNI WARNING: %s for field '%s' expected type %s, got %s",
mFunctionName, field->name, field->signature, primitiveTypeToName(prim));
printWarn = true;
} else if (isStatic && !dvmIsStaticField(field)) {
if (isStatic) {
ALOGW("JNI WARNING: accessing non-static field %s as static", field->name);
} else {
ALOGW("JNI WARNING: accessing static field %s as non-static", field->name);
}
printWarn = true;
}
if (printWarn) {
showLocation();
abortMaybe();
}
}
/*
* Verify that this instance field ID is valid for this object.
*
* Assumes "jobj" has already been validated.
*/
void checkInstanceFieldID(jobject jobj, jfieldID fieldID) {
ScopedCheckJniThreadState ts(mEnv);
Object* obj = dvmDecodeIndirectRef(self(), jobj);
if (!dvmIsHeapAddress(obj)) {
ALOGW("JNI ERROR: field operation on invalid reference (%p)", jobj);
dvmAbort();
}
/*
* Check this class and all of its superclasses for a matching field.
* Don't need to scan interfaces.
*/
ClassObject* clazz = obj->clazz;
while (clazz != NULL) {
if ((InstField*) fieldID >= clazz->ifields &&
(InstField*) fieldID < clazz->ifields + clazz->ifieldCount) {
return;
}
clazz = clazz->super;
}
ALOGW("JNI WARNING: instance fieldID %p not valid for class %s",
fieldID, obj->clazz->descriptor);
showLocation();
abortMaybe();
}
/*
* Verify that the pointer value is non-NULL.
*/
void checkNonNull(const void* ptr) {
if (ptr == NULL) {
ALOGW("JNI WARNING: invalid null pointer (%s)", mFunctionName);
abortMaybe();
}
}
/*
* Verify that the method's return type matches the type of call.
* 'expectedType' will be "L" for all objects, including arrays.
*/
void checkSig(jmethodID methodID, const char* expectedType, bool isStatic) {
const Method* method = (const Method*) methodID;
bool printWarn = false;
if (*expectedType != method->shorty[0]) {
ALOGW("JNI WARNING: expected return type '%s'", expectedType);
printWarn = true;
} else if (isStatic && !dvmIsStaticMethod(method)) {
if (isStatic) {
ALOGW("JNI WARNING: calling non-static method with static call");
} else {
ALOGW("JNI WARNING: calling static method with non-static call");
}
printWarn = true;
}
if (printWarn) {
char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
ALOGW(" calling %s.%s %s", method->clazz->descriptor, method->name, desc);
free(desc);
showLocation();
abortMaybe();
}
}
/*
* Verify that this static field ID is valid for this class.
*
* Assumes "jclazz" has already been validated.
*/
void checkStaticFieldID(jclass jclazz, jfieldID fieldID) {
ScopedCheckJniThreadState ts(mEnv);
ClassObject* clazz = (ClassObject*) dvmDecodeIndirectRef(self(), jclazz);
StaticField* base = &clazz->sfields[0];
int fieldCount = clazz->sfieldCount;
if ((StaticField*) fieldID < base || (StaticField*) fieldID >= base + fieldCount) {
ALOGW("JNI WARNING: static fieldID %p not valid for class %s",
fieldID, clazz->descriptor);
ALOGW(" base=%p count=%d", base, fieldCount);
showLocation();
abortMaybe();
}
}
/*
* Verify that "methodID" is appropriate for "clazz".
*
* A mismatch isn't dangerous, because the jmethodID defines the class. In
* fact, jclazz is unused in the implementation. It's best if we don't
* allow bad code in the system though.
*
* Instances of "jclazz" must be instances of the method's declaring class.
*/
void checkStaticMethod(jclass jclazz, jmethodID methodID) {
ScopedCheckJniThreadState ts(mEnv);
ClassObject* clazz = (ClassObject*) dvmDecodeIndirectRef(self(), jclazz);
const Method* method = (const Method*) methodID;
if (!dvmInstanceof(clazz, method->clazz)) {
ALOGW("JNI WARNING: can't call static %s.%s on class %s",
method->clazz->descriptor, method->name, clazz->descriptor);
showLocation();
// no abort?
}
}
/*
* Verify that "methodID" is appropriate for "jobj".
*
* Make sure the object is an instance of the method's declaring class.
* (Note the methodID might point to a declaration in an interface; this
* will be handled automatically by the instanceof check.)
*/
void checkVirtualMethod(jobject jobj, jmethodID methodID) {
ScopedCheckJniThreadState ts(mEnv);
Object* obj = dvmDecodeIndirectRef(self(), jobj);
const Method* method = (const Method*) methodID;
if (!dvmInstanceof(obj->clazz, method->clazz)) {
ALOGW("JNI WARNING: can't call %s.%s on instance of %s",
method->clazz->descriptor, method->name, obj->clazz->descriptor);
showLocation();
abortMaybe();
}
}
/**
* The format string is a sequence of the following characters,
* and must be followed by arguments of the corresponding types
* in the same order.
*
* Java primitive types:
* B - jbyte
* C - jchar
* D - jdouble
* F - jfloat
* I - jint
* J - jlong
* S - jshort
* Z - jboolean (shown as true and false)
* V - void
*
* Java reference types:
* L - jobject
* a - jarray
* c - jclass
* s - jstring
*
* JNI types:
* b - jboolean (shown as JNI_TRUE and JNI_FALSE)
* f - jfieldID
* m - jmethodID
* p - void*
* r - jint (for release mode arguments)
* t - thread args (for AttachCurrentThread)
* u - const char* (modified UTF-8)
* z - jsize (for lengths; use i if negative values are okay)
* v - JavaVM*
* E - JNIEnv*
* . - no argument; just print "..." (used for varargs JNI calls)
*
* Use the kFlag_NullableUtf flag where 'u' field(s) are nullable.
*/
void check(bool entry, const char* fmt0, ...) {
va_list ap;
bool shouldTrace = false;
const Method* method = NULL;
if ((gDvm.jniTrace || gDvmJni.logThirdPartyJni) && mHasMethod) {
// We need to guard some of the invocation interface's calls: a bad caller might
// use DetachCurrentThread or GetEnv on a thread that's not yet attached.
if ((mFlags & kFlag_Invocation) == 0 || dvmThreadSelf() != NULL) {
method = dvmGetCurrentJNIMethod();
}
}
if (method != NULL) {
// If both "-Xcheck:jni" and "-Xjnitrace:" are enabled, we print trace messages
// when a native method that matches the Xjnitrace argument calls a JNI function
// such as NewByteArray.
if (gDvm.jniTrace && strstr(method->clazz->descriptor, gDvm.jniTrace) != NULL) {
shouldTrace = true;
}
// If -Xjniopts:logThirdPartyJni is on, we want to log any JNI function calls
// made by a third-party native method.
if (gDvmJni.logThirdPartyJni) {
shouldTrace |= method->shouldTrace;
}
}
if (shouldTrace) {
va_start(ap, fmt0);
std::string msg;
for (const char* fmt = fmt0; *fmt;) {
char ch = *fmt++;
if (ch == 'B') { // jbyte
jbyte b = va_arg(ap, int);
if (b >= 0 && b < 10) {
StringAppendF(&msg, "%d", b);
} else {
StringAppendF(&msg, "%#x (%d)", b, b);
}
} else if (ch == 'C') { // jchar
jchar c = va_arg(ap, int);
if (c < 0x7f && c >= ' ') {
StringAppendF(&msg, "U+%x ('%c')", c, c);
} else {
StringAppendF(&msg, "U+%x", c);
}
} else if (ch == 'F' || ch == 'D') { // jfloat, jdouble
StringAppendF(&msg, "%g", va_arg(ap, double));
} else if (ch == 'I' || ch == 'S') { // jint, jshort
StringAppendF(&msg, "%d", va_arg(ap, int));
} else if (ch == 'J') { // jlong
StringAppendF(&msg, "%lld", va_arg(ap, jlong));
} else if (ch == 'Z') { // jboolean
StringAppendF(&msg, "%s", va_arg(ap, int) ? "true" : "false");
} else if (ch == 'V') { // void
msg += "void";
} else if (ch == 'v') { // JavaVM*
JavaVM* vm = va_arg(ap, JavaVM*);
StringAppendF(&msg, "(JavaVM*)%p", vm);
} else if (ch == 'E') { // JNIEnv*
JNIEnv* env = va_arg(ap, JNIEnv*);
StringAppendF(&msg, "(JNIEnv*)%p", env);
} else if (ch == 'L' || ch == 'a' || ch == 's') { // jobject, jarray, jstring
// For logging purposes, these are identical.
jobject o = va_arg(ap, jobject);
if (o == NULL) {
msg += "NULL";
} else {
StringAppendF(&msg, "%p", o);
}
} else if (ch == 'b') { // jboolean (JNI-style)
jboolean b = va_arg(ap, int);
msg += (b ? "JNI_TRUE" : "JNI_FALSE");
} else if (ch == 'c') { // jclass
jclass jc = va_arg(ap, jclass);
Object* c = dvmDecodeIndirectRef(self(), jc);
if (c == NULL) {
msg += "NULL";
} else if (c == kInvalidIndirectRefObject || !dvmIsHeapAddress(c)) {
StringAppendF(&msg, "%p(INVALID)", jc);
} else {
std::string className(dvmHumanReadableType(c));
StringAppendF(&msg, "%s", className.c_str());
if (!entry) {
StringAppendF(&msg, " (%p)", jc);
}
}
} else if (ch == 'f') { // jfieldID
jfieldID fid = va_arg(ap, jfieldID);
std::string name(dvmHumanReadableField((Field*) fid));
StringAppendF(&msg, "%s", name.c_str());
if (!entry) {
StringAppendF(&msg, " (%p)", fid);
}
} else if (ch == 'z') { // non-negative jsize
// You might expect jsize to be size_t, but it's not; it's the same as jint.
// We only treat this specially so we can do the non-negative check.
// TODO: maybe this wasn't worth it?
jint i = va_arg(ap, jint);
StringAppendF(&msg, "%d", i);
} else if (ch == 'm') { // jmethodID
jmethodID mid = va_arg(ap, jmethodID);
std::string name(dvmHumanReadableMethod((Method*) mid, true));
StringAppendF(&msg, "%s", name.c_str());
if (!entry) {
StringAppendF(&msg, " (%p)", mid);
}
} else if (ch == 'p' || ch == 't') { // void* ("pointer" or "thread args")
void* p = va_arg(ap, void*);
if (p == NULL) {
msg += "NULL";
} else {
StringAppendF(&msg, "(void*) %p", p);
}
} else if (ch == 'r') { // jint (release mode)
jint releaseMode = va_arg(ap, jint);
if (releaseMode == 0) {
msg += "0";
} else if (releaseMode == JNI_ABORT) {
msg += "JNI_ABORT";
} else if (releaseMode == JNI_COMMIT) {
msg += "JNI_COMMIT";
} else {
StringAppendF(&msg, "invalid release mode %d", releaseMode);
}
} else if (ch == 'u') { // const char* (modified UTF-8)
const char* utf = va_arg(ap, const char*);
if (utf == NULL) {
msg += "NULL";
} else {
StringAppendF(&msg, "\"%s\"", utf);
}
} else if (ch == '.') {
msg += "...";
} else {
ALOGE("unknown trace format specifier %c", ch);
dvmAbort();
}
if (*fmt) {
StringAppendF(&msg, ", ");
}
}
va_end(ap);
if (entry) {
if (mHasMethod) {
std::string methodName(dvmHumanReadableMethod(method, false));
ALOGI("JNI: %s -> %s(%s)", methodName.c_str(), mFunctionName, msg.c_str());
mIndent = methodName.size() + 1;
} else {
ALOGI("JNI: -> %s(%s)", mFunctionName, msg.c_str());
mIndent = 0;
}
} else {
ALOGI("JNI: %*s<- %s returned %s", mIndent, "", mFunctionName, msg.c_str());
}
}
// We always do the thorough checks on entry, and never on exit...
if (entry) {
va_start(ap, fmt0);
for (const char* fmt = fmt0; *fmt; ++fmt) {
char ch = *fmt;
if (ch == 'a') {
checkArray(va_arg(ap, jarray));
} else if (ch == 'c') {
checkClass(va_arg(ap, jclass));
} else if (ch == 'L') {
checkObject(va_arg(ap, jobject));
} else if (ch == 'r') {
checkReleaseMode(va_arg(ap, jint));
} else if (ch == 's') {
checkString(va_arg(ap, jstring));
} else if (ch == 't') {
checkThreadArgs(va_arg(ap, void*));
} else if (ch == 'u') {
if ((mFlags & kFlag_Release) != 0) {
checkNonNull(va_arg(ap, const char*));
} else {
bool nullable = ((mFlags & kFlag_NullableUtf) != 0);
checkUtfString(va_arg(ap, const char*), nullable);
}
} else if (ch == 'z') {
checkLengthPositive(va_arg(ap, jsize));
} else if (strchr("BCISZbfmpEv", ch) != NULL) {
va_arg(ap, int); // Skip this argument.
} else if (ch == 'D' || ch == 'F') {
va_arg(ap, double); // Skip this argument.
} else if (ch == 'J') {
va_arg(ap, long); // Skip this argument.
} else if (ch == '.') {
} else {
ALOGE("unknown check format specifier %c", ch);
dvmAbort();
}
}
va_end(ap);
}
}
// Only safe after checkThread returns.
Thread* self() {
return ((JNIEnvExt*) mEnv)->self;
}
private:
JNIEnv* mEnv;
const char* mFunctionName;
int mFlags;
bool mHasMethod;
size_t mIndent;
void init(JNIEnv* env, int flags, const char* functionName, bool hasMethod) {
mEnv = env;
mFlags = flags;
// Use +6 to drop the leading "Check_"...
mFunctionName = functionName + 6;
// Set "hasMethod" to true if we have a valid thread with a method pointer.
// We won't have one before attaching a thread, after detaching a thread, or
// after destroying the VM.
mHasMethod = hasMethod;
}
/*
* Verify that "array" is non-NULL and points to an Array object.
*
* Since we're dealing with objects, switch to "running" mode.
*/
void checkArray(jarray jarr) {
if (jarr == NULL) {
ALOGW("JNI WARNING: received null array");
showLocation();
abortMaybe();
return;
}
ScopedCheckJniThreadState ts(mEnv);
bool printWarn = false;
Object* obj = dvmDecodeIndirectRef(self(), jarr);
if (!dvmIsHeapAddress(obj)) {
ALOGW("JNI WARNING: jarray is an invalid %s reference (%p)",
indirectRefKindName(jarr), jarr);
printWarn = true;
} else if (obj->clazz->descriptor[0] != '[') {
ALOGW("JNI WARNING: jarray arg has wrong type (expected array, got %s)",
obj->clazz->descriptor);
printWarn = true;
}
if (printWarn) {
showLocation();
abortMaybe();
}
}
void checkClass(jclass c) {
checkInstance(c, gDvm.classJavaLangClass, "jclass");
}
void checkLengthPositive(jsize length) {
if (length < 0) {
ALOGW("JNI WARNING: negative jsize (%s)", mFunctionName);
abortMaybe();
}
}
/*
* Verify that "jobj" is a valid object, and that it's an object that JNI
* is allowed to know about. We allow NULL references.
*
* Switches to "running" mode before performing checks.
*/
void checkObject(jobject jobj) {
if (jobj == NULL) {
return;
}
ScopedCheckJniThreadState ts(mEnv);
bool printWarn = false;
if (dvmGetJNIRefType(self(), jobj) == JNIInvalidRefType) {
ALOGW("JNI WARNING: %p is not a valid JNI reference", jobj);
printWarn = true;
} else {
Object* obj = dvmDecodeIndirectRef(self(), jobj);
if (obj == kInvalidIndirectRefObject) {
ALOGW("JNI WARNING: native code passing in invalid reference %p", jobj);
printWarn = true;
} else if (obj != NULL && !dvmIsHeapAddress(obj)) {
// TODO: when we remove workAroundAppJniBugs, this should be impossible.
ALOGW("JNI WARNING: native code passing in reference to invalid object %p %p",
jobj, obj);
printWarn = true;
}
}
if (printWarn) {
showLocation();
abortMaybe();
}
}
/*
* Verify that the "mode" argument passed to a primitive array Release
* function is one of the valid values.
*/
void checkReleaseMode(jint mode) {
if (mode != 0 && mode != JNI_COMMIT && mode != JNI_ABORT) {
ALOGW("JNI WARNING: bad value for mode (%d) (%s)", mode, mFunctionName);
abortMaybe();
}
}
void checkString(jstring s) {
checkInstance(s, gDvm.classJavaLangString, "jstring");
}
void checkThreadArgs(void* thread_args) {
JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(thread_args);
if (args != NULL && args->version < JNI_VERSION_1_2) {
ALOGW("JNI WARNING: bad value for JNI version (%d) (%s)", args->version, mFunctionName);
abortMaybe();
}
}
void checkThread(int flags) {
// Get the *correct* JNIEnv by going through our TLS pointer.
JNIEnvExt* threadEnv = dvmGetJNIEnvForThread();
/*
* Verify that the current thread is (a) attached and (b) associated with
* this particular instance of JNIEnv.
*/
bool printWarn = false;
if (threadEnv == NULL) {
ALOGE("JNI ERROR: non-VM thread making JNI calls");
// don't set printWarn -- it'll try to call showLocation()
dvmAbort();
} else if ((JNIEnvExt*) mEnv != threadEnv) {
if (dvmThreadSelf()->threadId != threadEnv->envThreadId) {
ALOGE("JNI: threadEnv != thread->env?");
dvmAbort();
}
ALOGW("JNI WARNING: threadid=%d using env from threadid=%d",
threadEnv->envThreadId, ((JNIEnvExt*) mEnv)->envThreadId);
printWarn = true;
// If we're keeping broken code limping along, we need to suppress the abort...
if (gDvmJni.workAroundAppJniBugs) {
printWarn = false;
}
/* this is a bad idea -- need to throw as we exit, or abort func */
//dvmThrowRuntimeException("invalid use of JNI env ptr");
} else if (((JNIEnvExt*) mEnv)->self != dvmThreadSelf()) {
/* correct JNIEnv*; make sure the "self" pointer is correct */
ALOGE("JNI ERROR: env->self != thread-self (%p vs. %p)",
((JNIEnvExt*) mEnv)->self, dvmThreadSelf());
dvmAbort();
}
/*
* Verify that, if this thread previously made a critical "get" call, we
* do the corresponding "release" call before we try anything else.
*/
switch (flags & kFlag_CritMask) {
case kFlag_CritOkay: // okay to call this method
break;
case kFlag_CritBad: // not okay to call
if (threadEnv->critical) {
ALOGW("JNI WARNING: threadid=%d using JNI after critical get",
threadEnv->envThreadId);
printWarn = true;
}
break;
case kFlag_CritGet: // this is a "get" call
/* don't check here; we allow nested gets */
threadEnv->critical++;
break;
case kFlag_CritRelease: // this is a "release" call
threadEnv->critical--;
if (threadEnv->critical < 0) {
ALOGW("JNI WARNING: threadid=%d called too many crit releases",
threadEnv->envThreadId);
printWarn = true;
}
break;
default:
assert(false);
}
/*
* Verify that, if an exception has been raised, the native code doesn't
* make any JNI calls other than the Exception* methods.
*/
bool printException = false;
if ((flags & kFlag_ExcepOkay) == 0 && dvmCheckException(dvmThreadSelf())) {
ALOGW("JNI WARNING: JNI method called with exception pending");
printWarn = true;
printException = true;
}
if (printWarn) {
showLocation();
}
if (printException) {
ALOGW("Pending exception is:");
dvmLogExceptionStackTrace();
}
if (printWarn) {
abortMaybe();
}
}
/*
* Verify that "bytes" points to valid "modified UTF-8" data.
*/
void checkUtfString(const char* bytes, bool nullable) {
if (bytes == NULL) {
if (!nullable) {
ALOGW("JNI WARNING: non-nullable const char* was NULL");
showLocation();
abortMaybe();
}
return;
}
const char* errorKind = NULL;
u1 utf8 = checkUtfBytes(bytes, &errorKind);
if (errorKind != NULL) {
ALOGW("JNI WARNING: input is not valid Modified UTF-8: illegal %s byte %#x", errorKind, utf8);
ALOGW(" string: '%s'", bytes);
showLocation();
abortMaybe();
}
}
/*
* Verify that "jobj" is a valid non-NULL object reference, and points to
* an instance of expectedClass.
*
* Because we're looking at an object on the GC heap, we have to switch
* to "running" mode before doing the checks.
*/
void checkInstance(jobject jobj, ClassObject* expectedClass, const char* argName) {
if (jobj == NULL) {
ALOGW("JNI WARNING: received null %s", argName);
showLocation();
abortMaybe();
return;
}
ScopedCheckJniThreadState ts(mEnv);
bool printWarn = false;
Object* obj = dvmDecodeIndirectRef(self(), jobj);
if (!dvmIsHeapAddress(obj)) {
ALOGW("JNI WARNING: %s is an invalid %s reference (%p)",
argName, indirectRefKindName(jobj), jobj);
printWarn = true;
} else if (obj->clazz != expectedClass) {
ALOGW("JNI WARNING: %s arg has wrong type (expected %s, got %s)",
argName, expectedClass->descriptor, obj->clazz->descriptor);
printWarn = true;
}
if (printWarn) {
showLocation();
abortMaybe();
}
}
static u1 checkUtfBytes(const char* bytes, const char** errorKind) {
while (*bytes != '\0') {
u1 utf8 = *(bytes++);
// Switch on the high four bits.
switch (utf8 >> 4) {
case 0x00:
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
// Bit pattern 0xxx. No need for any extra bytes.
break;
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0f:
/*
* Bit pattern 10xx or 1111, which are illegal start bytes.
* Note: 1111 is valid for normal UTF-8, but not the
* modified UTF-8 used here.
*/
*errorKind = "start";
return utf8;
case 0x0e:
// Bit pattern 1110, so there are two additional bytes.
utf8 = *(bytes++);
if ((utf8 & 0xc0) != 0x80) {
*errorKind = "continuation";
return utf8;
}
// Fall through to take care of the final byte.
case 0x0c:
case 0x0d:
// Bit pattern 110x, so there is one additional byte.
utf8 = *(bytes++);
if ((utf8 & 0xc0) != 0x80) {
*errorKind = "continuation";
return utf8;
}
break;
}
}
return 0;
}
/**
* Returns a human-readable name for the given primitive type.
*/
static const char* primitiveTypeToName(PrimitiveType primType) {
switch (primType) {
case PRIM_VOID: return "void";
case PRIM_BOOLEAN: return "boolean";
case PRIM_BYTE: return "byte";
case PRIM_SHORT: return "short";
case PRIM_CHAR: return "char";
case PRIM_INT: return "int";
case PRIM_LONG: return "long";
case PRIM_FLOAT: return "float";
case PRIM_DOUBLE: return "double";
case PRIM_NOT: return "Object/array";
default: return "???";
}
}
void showLocation() {
const Method* method = dvmGetCurrentJNIMethod();
char* desc = dexProtoCopyMethodDescriptor(&method->prototype);
ALOGW(" in %s.%s:%s (%s)", method->clazz->descriptor, method->name, desc, mFunctionName);
free(desc);
}
// Disallow copy and assignment.
ScopedCheck(const ScopedCheck&);
void operator=(const ScopedCheck&);
};
/*
* ===========================================================================
* Guarded arrays
* ===========================================================================
*/
#define kGuardLen 512 /* must be multiple of 2 */
#define kGuardPattern 0xd5e3 /* uncommon values; d5e3d5e3 invalid addr */
#define kGuardMagic 0xffd5aa96
/* this gets tucked in at the start of the buffer; struct size must be even */
struct GuardedCopy {
u4 magic;
uLong adler;
size_t originalLen;
const void* originalPtr;
/* find the GuardedCopy given the pointer into the "live" data */
static inline const GuardedCopy* fromData(const void* dataBuf) {
return reinterpret_cast<const GuardedCopy*>(actualBuffer(dataBuf));
}
/*
* Create an over-sized buffer to hold the contents of "buf". Copy it in,
* filling in the area around it with guard data.
*
* We use a 16-bit pattern to make a rogue memset less likely to elude us.
*/
static void* create(const void* buf, size_t len, bool modOkay) {
size_t newLen = actualLength(len);
u1* newBuf = debugAlloc(newLen);
/* fill it in with a pattern */
u2* pat = (u2*) newBuf;
for (size_t i = 0; i < newLen / 2; i++) {
*pat++ = kGuardPattern;
}
/* copy the data in; note "len" could be zero */
memcpy(newBuf + kGuardLen / 2, buf, len);
/* if modification is not expected, grab a checksum */
uLong adler = 0;
if (!modOkay) {
adler = adler32(0L, Z_NULL, 0);
adler = adler32(adler, (const Bytef*)buf, len);
*(uLong*)newBuf = adler;
}
GuardedCopy* pExtra = reinterpret_cast<GuardedCopy*>(newBuf);
pExtra->magic = kGuardMagic;
pExtra->adler = adler;
pExtra->originalPtr = buf;
pExtra->originalLen = len;
return newBuf + kGuardLen / 2;
}
/*
* Free up the guard buffer, scrub it, and return the original pointer.
*/
static void* destroy(void* dataBuf) {
const GuardedCopy* pExtra = GuardedCopy::fromData(dataBuf);
void* originalPtr = (void*) pExtra->originalPtr;
size_t len = pExtra->originalLen;
debugFree(dataBuf, len);
return originalPtr;
}
/*
* Verify the guard area and, if "modOkay" is false, that the data itself
* has not been altered.
*
* The caller has already checked that "dataBuf" is non-NULL.
*/
static bool check(const void* dataBuf, bool modOkay) {
static const u4 kMagicCmp = kGuardMagic;
const u1* fullBuf = actualBuffer(dataBuf);
const GuardedCopy* pExtra = GuardedCopy::fromData(dataBuf);
/*
* Before we do anything with "pExtra", check the magic number. We
* do the check with memcmp rather than "==" in case the pointer is
* unaligned. If it points to completely bogus memory we're going
* to crash, but there's no easy way around that.
*/
if (memcmp(&pExtra->magic, &kMagicCmp, 4) != 0) {
u1 buf[4];
memcpy(buf, &pExtra->magic, 4);
ALOGE("JNI: guard magic does not match (found 0x%02x%02x%02x%02x) -- incorrect data pointer %p?",
buf[3], buf[2], buf[1], buf[0], dataBuf); /* assume little endian */
return false;
}
size_t len = pExtra->originalLen;
/* check bottom half of guard; skip over optional checksum storage */
const u2* pat = (u2*) fullBuf;
for (size_t i = sizeof(GuardedCopy) / 2; i < (kGuardLen / 2 - sizeof(GuardedCopy)) / 2; i++) {
if (pat[i] != kGuardPattern) {
ALOGE("JNI: guard pattern(1) disturbed at %p + %d", fullBuf, i*2);
return false;
}
}
int offset = kGuardLen / 2 + len;
if (offset & 0x01) {
/* odd byte; expected value depends on endian-ness of host */
const u2 patSample = kGuardPattern;
if (fullBuf[offset] != ((const u1*) &patSample)[1]) {
ALOGE("JNI: guard pattern disturbed in odd byte after %p (+%d) 0x%02x 0x%02x",
fullBuf, offset, fullBuf[offset], ((const u1*) &patSample)[1]);
return false;
}
offset++;
}
/* check top half of guard */
pat = (u2*) (fullBuf + offset);
for (size_t i = 0; i < kGuardLen / 4; i++) {
if (pat[i] != kGuardPattern) {
ALOGE("JNI: guard pattern(2) disturbed at %p + %d", fullBuf, offset + i*2);
return false;
}
}
/*
* If modification is not expected, verify checksum. Strictly speaking
* this is wrong: if we told the client that we made a copy, there's no
* reason they can't alter the buffer.
*/
if (!modOkay) {
uLong adler = adler32(0L, Z_NULL, 0);
adler = adler32(adler, (const Bytef*)dataBuf, len);
if (pExtra->adler != adler) {
ALOGE("JNI: buffer modified (0x%08lx vs 0x%08lx) at addr %p",
pExtra->adler, adler, dataBuf);
return false;
}
}
return true;
}
private:
static u1* debugAlloc(size_t len) {
void* result = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
if (result == MAP_FAILED) {
ALOGE("GuardedCopy::create mmap(%d) failed: %s", len, strerror(errno));
dvmAbort();
}
return reinterpret_cast<u1*>(result);
}
static void debugFree(void* dataBuf, size_t len) {
u1* fullBuf = actualBuffer(dataBuf);
size_t totalByteCount = actualLength(len);
// TODO: we could mprotect instead, and keep the allocation around for a while.
// This would be even more expensive, but it might catch more errors.
// if (mprotect(fullBuf, totalByteCount, PROT_NONE) != 0) {
// ALOGW("mprotect(PROT_NONE) failed: %s", strerror(errno));
// }
if (munmap(fullBuf, totalByteCount) != 0) {
ALOGW("munmap failed: %s", strerror(errno));
dvmAbort();
}
}
static const u1* actualBuffer(const void* dataBuf) {
return reinterpret_cast<const u1*>(dataBuf) - kGuardLen / 2;
}
static u1* actualBuffer(void* dataBuf) {
return reinterpret_cast<u1*>(dataBuf) - kGuardLen / 2;
}
// Underlying length of a user allocation of 'length' bytes.
static size_t actualLength(size_t length) {
return (length + kGuardLen + 1) & ~0x01;
}
};
/*
* Return the width, in bytes, of a primitive type.
*/
static int dvmPrimitiveTypeWidth(PrimitiveType primType) {
switch (primType) {
case PRIM_BOOLEAN: return 1;
case PRIM_BYTE: return 1;
case PRIM_SHORT: return 2;
case PRIM_CHAR: return 2;
case PRIM_INT: return 4;
case PRIM_LONG: return 8;
case PRIM_FLOAT: return 4;
case PRIM_DOUBLE: return 8;
case PRIM_VOID:
default: {
assert(false);
return -1;
}
}
}
/*
* Create a guarded copy of a primitive array. Modifications to the copied
* data are allowed. Returns a pointer to the copied data.
*/
static void* createGuardedPACopy(JNIEnv* env, const jarray jarr, jboolean* isCopy) {
ScopedCheckJniThreadState ts(env);
ArrayObject* arrObj = (ArrayObject*) dvmDecodeIndirectRef(dvmThreadSelf(), jarr);
PrimitiveType primType = arrObj->clazz->elementClass->primitiveType;
int len = arrObj->length * dvmPrimitiveTypeWidth(primType);
void* result = GuardedCopy::create(arrObj->contents, len, true);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
return result;
}
/*
* Perform the array "release" operation, which may or may not copy data
* back into the VM, and may or may not release the underlying storage.
*/
static void* releaseGuardedPACopy(JNIEnv* env, jarray jarr, void* dataBuf, int mode) {
ScopedCheckJniThreadState ts(env);
ArrayObject* arrObj = (ArrayObject*) dvmDecodeIndirectRef(dvmThreadSelf(), jarr);
if (!GuardedCopy::check(dataBuf, true)) {
ALOGE("JNI: failed guarded copy check in releaseGuardedPACopy");
abortMaybe();
return NULL;
}
if (mode != JNI_ABORT) {
size_t len = GuardedCopy::fromData(dataBuf)->originalLen;
memcpy(arrObj->contents, dataBuf, len);
}
u1* result = NULL;
if (mode != JNI_COMMIT) {
result = (u1*) GuardedCopy::destroy(dataBuf);
} else {
result = (u1*) (void*) GuardedCopy::fromData(dataBuf)->originalPtr;
}
/* pointer is to the array contents; back up to the array object */
result -= OFFSETOF_MEMBER(ArrayObject, contents);
return result;
}
/*
* ===========================================================================
* JNI functions
* ===========================================================================
*/
#define CHECK_JNI_ENTRY(flags, types, args...) \
ScopedCheck sc(env, flags, __FUNCTION__); \
sc.check(true, types, args)
#define CHECK_JNI_EXIT(type, exp) ({ \
typeof (exp) _rc = (exp); \
sc.check(false, type, _rc); \
_rc; })
#define CHECK_JNI_EXIT_VOID() \
sc.check(false, "V")
static jint Check_GetVersion(JNIEnv* env) {
CHECK_JNI_ENTRY(kFlag_Default, "E", env);
return CHECK_JNI_EXIT("I", baseEnv(env)->GetVersion(env));
}
static jclass Check_DefineClass(JNIEnv* env, const char* name, jobject loader,
const jbyte* buf, jsize bufLen)
{
CHECK_JNI_ENTRY(kFlag_Default, "EuLpz", env, name, loader, buf, bufLen);
sc.checkClassName(name);
return CHECK_JNI_EXIT("c", baseEnv(env)->DefineClass(env, name, loader, buf, bufLen));
}
static jclass Check_FindClass(JNIEnv* env, const char* name) {
CHECK_JNI_ENTRY(kFlag_Default, "Eu", env, name);
sc.checkClassName(name);
return CHECK_JNI_EXIT("c", baseEnv(env)->FindClass(env, name));
}
static jclass Check_GetSuperclass(JNIEnv* env, jclass clazz) {
CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
return CHECK_JNI_EXIT("c", baseEnv(env)->GetSuperclass(env, clazz));
}
static jboolean Check_IsAssignableFrom(JNIEnv* env, jclass clazz1, jclass clazz2) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecc", env, clazz1, clazz2);
return CHECK_JNI_EXIT("b", baseEnv(env)->IsAssignableFrom(env, clazz1, clazz2));
}
static jmethodID Check_FromReflectedMethod(JNIEnv* env, jobject method) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, method);
// TODO: check that 'field' is a java.lang.reflect.Method.
return CHECK_JNI_EXIT("m", baseEnv(env)->FromReflectedMethod(env, method));
}
static jfieldID Check_FromReflectedField(JNIEnv* env, jobject field) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, field);
// TODO: check that 'field' is a java.lang.reflect.Field.
return CHECK_JNI_EXIT("f", baseEnv(env)->FromReflectedField(env, field));
}
static jobject Check_ToReflectedMethod(JNIEnv* env, jclass cls,
jmethodID methodID, jboolean isStatic)
{
CHECK_JNI_ENTRY(kFlag_Default, "Ecmb", env, cls, methodID, isStatic);
return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedMethod(env, cls, methodID, isStatic));
}
static jobject Check_ToReflectedField(JNIEnv* env, jclass cls,
jfieldID fieldID, jboolean isStatic)
{
CHECK_JNI_ENTRY(kFlag_Default, "Ecfb", env, cls, fieldID, isStatic);
return CHECK_JNI_EXIT("L", baseEnv(env)->ToReflectedField(env, cls, fieldID, isStatic));
}
static jint Check_Throw(JNIEnv* env, jthrowable obj) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
// TODO: check that 'obj' is a java.lang.Throwable.
return CHECK_JNI_EXIT("I", baseEnv(env)->Throw(env, obj));
}
static jint Check_ThrowNew(JNIEnv* env, jclass clazz, const char* message) {
CHECK_JNI_ENTRY(kFlag_NullableUtf, "Ecu", env, clazz, message);
return CHECK_JNI_EXIT("I", baseEnv(env)->ThrowNew(env, clazz, message));
}
static jthrowable Check_ExceptionOccurred(JNIEnv* env) {
CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
return CHECK_JNI_EXIT("L", baseEnv(env)->ExceptionOccurred(env));
}
static void Check_ExceptionDescribe(JNIEnv* env) {
CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
baseEnv(env)->ExceptionDescribe(env);
CHECK_JNI_EXIT_VOID();
}
static void Check_ExceptionClear(JNIEnv* env) {
CHECK_JNI_ENTRY(kFlag_ExcepOkay, "E", env);
baseEnv(env)->ExceptionClear(env);
CHECK_JNI_EXIT_VOID();
}
static void Check_FatalError(JNIEnv* env, const char* msg) {
CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, msg);
baseEnv(env)->FatalError(env, msg);
CHECK_JNI_EXIT_VOID();
}
static jint Check_PushLocalFrame(JNIEnv* env, jint capacity) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EI", env, capacity);
return CHECK_JNI_EXIT("I", baseEnv(env)->PushLocalFrame(env, capacity));
}
static jobject Check_PopLocalFrame(JNIEnv* env, jobject res) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, res);
return CHECK_JNI_EXIT("L", baseEnv(env)->PopLocalFrame(env, res));
}
static jobject Check_NewGlobalRef(JNIEnv* env, jobject obj) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewGlobalRef(env, obj));
}
static void Check_DeleteGlobalRef(JNIEnv* env, jobject globalRef) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, globalRef);
if (globalRef != NULL && dvmGetJNIRefType(sc.self(), globalRef) != JNIGlobalRefType) {
ALOGW("JNI WARNING: DeleteGlobalRef on non-global %p (type=%d)",
globalRef, dvmGetJNIRefType(sc.self(), globalRef));
abortMaybe();
} else {
baseEnv(env)->DeleteGlobalRef(env, globalRef);
CHECK_JNI_EXIT_VOID();
}
}
static jobject Check_NewLocalRef(JNIEnv* env, jobject ref) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, ref);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewLocalRef(env, ref));
}
static void Check_DeleteLocalRef(JNIEnv* env, jobject localRef) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, localRef);
if (localRef != NULL && dvmGetJNIRefType(sc.self(), localRef) != JNILocalRefType) {
ALOGW("JNI WARNING: DeleteLocalRef on non-local %p (type=%d)",
localRef, dvmGetJNIRefType(sc.self(), localRef));
abortMaybe();
} else {
baseEnv(env)->DeleteLocalRef(env, localRef);
CHECK_JNI_EXIT_VOID();
}
}
static jint Check_EnsureLocalCapacity(JNIEnv *env, jint capacity) {
CHECK_JNI_ENTRY(kFlag_Default, "EI", env, capacity);
return CHECK_JNI_EXIT("I", baseEnv(env)->EnsureLocalCapacity(env, capacity));
}
static jboolean Check_IsSameObject(JNIEnv* env, jobject ref1, jobject ref2) {
CHECK_JNI_ENTRY(kFlag_Default, "ELL", env, ref1, ref2);
return CHECK_JNI_EXIT("b", baseEnv(env)->IsSameObject(env, ref1, ref2));
}
static jobject Check_AllocObject(JNIEnv* env, jclass clazz) {
CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
return CHECK_JNI_EXIT("L", baseEnv(env)->AllocObject(env, clazz));
}
static jobject Check_NewObject(JNIEnv* env, jclass clazz, jmethodID methodID, ...) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
va_list args;
va_start(args, methodID);
jobject result = baseEnv(env)->NewObjectV(env, clazz, methodID, args);
va_end(args);
return CHECK_JNI_EXIT("L", result);
}
static jobject Check_NewObjectV(JNIEnv* env, jclass clazz, jmethodID methodID, va_list args) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectV(env, clazz, methodID, args));
}
static jobject Check_NewObjectA(JNIEnv* env, jclass clazz, jmethodID methodID, jvalue* args) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewObjectA(env, clazz, methodID, args));
}
static jobject Check_NewTaintedObjectA(JNIEnv* env, jclass clazz, jmethodID methodID, u4 objTaint, jvalue* args, u4* taints) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewTaintedObjectA(env, clazz, methodID, objTaint, args, taints));
}
static jclass Check_GetObjectClass(JNIEnv* env, jobject obj) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
return CHECK_JNI_EXIT("c", baseEnv(env)->GetObjectClass(env, obj));
}
static jboolean Check_IsInstanceOf(JNIEnv* env, jobject obj, jclass clazz) {
CHECK_JNI_ENTRY(kFlag_Default, "ELc", env, obj, clazz);
return CHECK_JNI_EXIT("b", baseEnv(env)->IsInstanceOf(env, obj, clazz));
}
static jmethodID Check_GetMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
return CHECK_JNI_EXIT("m", baseEnv(env)->GetMethodID(env, clazz, name, sig));
}
static jfieldID Check_GetFieldID(JNIEnv* env, jclass clazz, const char* name, const char* sig) {
CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
return CHECK_JNI_EXIT("f", baseEnv(env)->GetFieldID(env, clazz, name, sig));
}
static jmethodID Check_GetStaticMethodID(JNIEnv* env, jclass clazz,
const char* name, const char* sig)
{
CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
return CHECK_JNI_EXIT("m", baseEnv(env)->GetStaticMethodID(env, clazz, name, sig));
}
static jfieldID Check_GetStaticFieldID(JNIEnv* env, jclass clazz,
const char* name, const char* sig)
{
CHECK_JNI_ENTRY(kFlag_Default, "Ecuu", env, clazz, name, sig);
return CHECK_JNI_EXIT("f", baseEnv(env)->GetStaticFieldID(env, clazz, name, sig));
}
#define FIELD_ACCESSORS(_ctype, _jname, _ftype, _type) \
static _ctype Check_GetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fieldID) { \
CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fieldID); \
sc.checkStaticFieldID(clazz, fieldID); \
sc.checkFieldTypeForGet(fieldID, _type, true); \
return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##Field(env, clazz, fieldID)); \
} \
static _ctype Check_GetStatic##_jname##TaintedField(JNIEnv* env, jclass clazz, jfieldID fieldID, u4* taint) { \
CHECK_JNI_ENTRY(kFlag_Default, "Ecf", env, clazz, fieldID); \
sc.checkStaticFieldID(clazz, fieldID); \
sc.checkFieldTypeForGet(fieldID, _type, true); \
return CHECK_JNI_EXIT(_type, baseEnv(env)->GetStatic##_jname##TaintedField(env, clazz, fieldID, taint)); \
} \
static _ctype Check_Get##_jname##Field(JNIEnv* env, jobject obj, jfieldID fieldID) { \
CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fieldID); \
sc.checkInstanceFieldID(obj, fieldID); \
sc.checkFieldTypeForGet(fieldID, _type, false); \
return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##Field(env, obj, fieldID)); \
} \
static void Check_SetStatic##_jname##TaintedField(JNIEnv* env, jclass clazz, jfieldID fieldID, _ctype value, u4 taint) { \
CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fieldID, value); \
sc.checkStaticFieldID(clazz, fieldID); \
/* "value" arg only used when type == ref */ \
sc.checkFieldTypeForSet((jobject)(u4)value, fieldID, _ftype, true); \
baseEnv(env)->SetStatic##_jname##TaintedField(env, clazz, fieldID, value, taint); \
CHECK_JNI_EXIT_VOID(); \
} \
static void Check_SetStatic##_jname##Field(JNIEnv* env, jclass clazz, jfieldID fieldID, _ctype value) { \
CHECK_JNI_ENTRY(kFlag_Default, "Ecf" _type, env, clazz, fieldID, value); \
sc.checkStaticFieldID(clazz, fieldID); \
/* "value" arg only used when type == ref */ \
sc.checkFieldTypeForSet((jobject)(u4)value, fieldID, _ftype, true); \
baseEnv(env)->SetStatic##_jname##Field(env, clazz, fieldID, value); \
CHECK_JNI_EXIT_VOID(); \
} \
static void Check_Set##_jname##Field(JNIEnv* env, jobject obj, jfieldID fieldID, _ctype value) { \
CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fieldID, value); \
sc.checkInstanceFieldID(obj, fieldID); \
/* "value" arg only used when type == ref */ \
sc.checkFieldTypeForSet((jobject)(u4) value, fieldID, _ftype, false); \
baseEnv(env)->Set##_jname##Field(env, obj, fieldID, value); \
CHECK_JNI_EXIT_VOID(); \
} \
static _ctype Check_Get##_jname##TaintedField(JNIEnv* env, jobject obj, jfieldID fieldID, u4* taint) { \
CHECK_JNI_ENTRY(kFlag_Default, "ELf", env, obj, fieldID); \
sc.checkInstanceFieldID(obj, fieldID); \
sc.checkFieldTypeForGet(fieldID, _type, false); \
return CHECK_JNI_EXIT(_type, baseEnv(env)->Get##_jname##TaintedField(env, obj, fieldID, taint)); \
} \
static void Check_Set##_jname##TaintedField(JNIEnv* env, jobject obj, jfieldID fieldID, _ctype value, u4 taint) { \
CHECK_JNI_ENTRY(kFlag_Default, "ELf" _type, env, obj, fieldID, value); \
sc.checkInstanceFieldID(obj, fieldID); \
/* "value" arg only used when type == ref */ \
sc.checkFieldTypeForSet((jobject)(u4) value, fieldID, _ftype, false); \
baseEnv(env)->Set##_jname##TaintedField(env, obj, fieldID, value, taint); \
CHECK_JNI_EXIT_VOID(); \
}
FIELD_ACCESSORS(jobject, Object, PRIM_NOT, "L");
FIELD_ACCESSORS(jboolean, Boolean, PRIM_BOOLEAN, "Z");
FIELD_ACCESSORS(jbyte, Byte, PRIM_BYTE, "B");
FIELD_ACCESSORS(jchar, Char, PRIM_CHAR, "C");
FIELD_ACCESSORS(jshort, Short, PRIM_SHORT, "S");
FIELD_ACCESSORS(jint, Int, PRIM_INT, "I");
FIELD_ACCESSORS(jlong, Long, PRIM_LONG, "J");
FIELD_ACCESSORS(jfloat, Float, PRIM_FLOAT, "F");
FIELD_ACCESSORS(jdouble, Double, PRIM_DOUBLE, "D");
#define CALL(_ctype, _jname, _retdecl, _retasgn, _retok, _retsig) \
/* Virtual... */ \
static _ctype Check_Call##_jname##Method(JNIEnv* env, jobject obj, \
jmethodID methodID, ...) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
va_list args; \
va_start(args, methodID); \
_retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, methodID, args); \
va_end(args); \
_retok; \
} \
static _ctype Check_Call##_jname##MethodV(JNIEnv* env, jobject obj, \
jmethodID methodID, va_list args) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
_retasgn baseEnv(env)->Call##_jname##MethodV(env, obj, methodID, args); \
_retok; \
} \
static _ctype Check_Call##_jname##MethodA(JNIEnv* env, jobject obj, \
jmethodID methodID, jvalue* args) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
_retasgn baseEnv(env)->Call##_jname##MethodA(env, obj, methodID, args); \
_retok; \
} \
static _ctype Check_Call##_jname##TaintedMethodA(JNIEnv* env, jobject obj, \
u4 objTaint, jmethodID methodID, u4* retTaint, jvalue* args, u4* taints) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELm.", env, obj, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
_retasgn baseEnv(env)->Call##_jname##TaintedMethodA(env, obj, objTaint, methodID, retTaint, args, taints); \
_retok; \
} \
/* Non-virtual... */ \
static _ctype Check_CallNonvirtual##_jname##Method(JNIEnv* env, \
jobject obj, jclass clazz, jmethodID methodID, ...) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
va_list args; \
va_start(args, methodID); \
_retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, methodID, args); \
va_end(args); \
_retok; \
} \
static _ctype Check_CallNonvirtual##_jname##MethodV(JNIEnv* env, \
jobject obj, jclass clazz, jmethodID methodID, va_list args) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
_retasgn baseEnv(env)->CallNonvirtual##_jname##MethodV(env, obj, clazz, methodID, args); \
_retok; \
} \
static _ctype Check_CallNonvirtual##_jname##MethodA(JNIEnv* env, \
jobject obj, jclass clazz, jmethodID methodID, jvalue* args) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
_retasgn baseEnv(env)->CallNonvirtual##_jname##MethodA(env, obj, clazz, methodID, args); \
_retok; \
} \
static _ctype Check_CallNonvirtual##_jname##TaintedMethodA(JNIEnv* env, \
jobject obj, u4 objTaint, jclass clazz, jmethodID methodID, u4* resultTaint, jvalue* args, u4* taints) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "ELcm.", env, obj, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, false); \
sc.checkVirtualMethod(obj, methodID); \
_retdecl; \
_retasgn baseEnv(env)->CallNonvirtual##_jname##TaintedMethodA(env, obj, objTaint, clazz, methodID, resultTaint, args, taints); \
_retok; \
} \
/* Static... */ \
static _ctype Check_CallStatic##_jname##Method(JNIEnv* env, \
jclass clazz, jmethodID methodID, ...) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, true); \
sc.checkStaticMethod(clazz, methodID); \
_retdecl; \
va_list args; \
va_start(args, methodID); \
_retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, methodID, args); \
va_end(args); \
_retok; \
} \
static _ctype Check_CallStatic##_jname##MethodV(JNIEnv* env, \
jclass clazz, jmethodID methodID, va_list args) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, true); \
sc.checkStaticMethod(clazz, methodID); \
_retdecl; \
_retasgn baseEnv(env)->CallStatic##_jname##MethodV(env, clazz, methodID, args); \
_retok; \
} \
static _ctype Check_CallStatic##_jname##TaintedMethodA(JNIEnv* env, \
jclass clazz, jmethodID methodID, u4* returnTaint, jvalue* args, u4* taints) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, true); \
sc.checkStaticMethod(clazz, methodID); \
_retdecl; \
_retasgn baseEnv(env)->CallStatic##_jname##TaintedMethodA(env, clazz, methodID, returnTaint, args, taints); \
_retok; \
} \
static _ctype Check_CallStatic##_jname##MethodA(JNIEnv* env, \
jclass clazz, jmethodID methodID, jvalue* args) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "Ecm.", env, clazz, methodID); /* TODO: args! */ \
sc.checkSig(methodID, _retsig, true); \
sc.checkStaticMethod(clazz, methodID); \
_retdecl; \
_retasgn baseEnv(env)->CallStatic##_jname##MethodA(env, clazz, methodID, args); \
_retok; \
}
#define NON_VOID_RETURN(_retsig, _ctype) return CHECK_JNI_EXIT(_retsig, (_ctype) result)
#define VOID_RETURN CHECK_JNI_EXIT_VOID()
CALL(jobject, Object, Object* result, result=(Object*), NON_VOID_RETURN("L", jobject), "L");
CALL(jboolean, Boolean, jboolean result, result=, NON_VOID_RETURN("Z", jboolean), "Z");
CALL(jbyte, Byte, jbyte result, result=, NON_VOID_RETURN("B", jbyte), "B");
CALL(jchar, Char, jchar result, result=, NON_VOID_RETURN("C", jchar), "C");
CALL(jshort, Short, jshort result, result=, NON_VOID_RETURN("S", jshort), "S");
CALL(jint, Int, jint result, result=, NON_VOID_RETURN("I", jint), "I");
CALL(jlong, Long, jlong result, result=, NON_VOID_RETURN("J", jlong), "J");
CALL(jfloat, Float, jfloat result, result=, NON_VOID_RETURN("F", jfloat), "F");
CALL(jdouble, Double, jdouble result, result=, NON_VOID_RETURN("D", jdouble), "D");
CALL(void, Void, , , VOID_RETURN, "V");
static jstring Check_NewString(JNIEnv* env, const jchar* unicodeChars, jsize len) {
CHECK_JNI_ENTRY(kFlag_Default, "Epz", env, unicodeChars, len);
return CHECK_JNI_EXIT("s", baseEnv(env)->NewString(env, unicodeChars, len));
}
static jsize Check_GetStringLength(JNIEnv* env, jstring string) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringLength(env, string));
}
static jsize Check_GetTaintedStringLength(JNIEnv* env, jstring string, u4* taint) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
return CHECK_JNI_EXIT("I", baseEnv(env)->GetTaintedStringLength(env, string, taint));
}
static const jchar* Check_GetStringChars(JNIEnv* env, jstring string, jboolean* isCopy) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
const jchar* result = baseEnv(env)->GetStringChars(env, string, isCopy);
if (gDvmJni.forceCopy && result != NULL) {
ScopedCheckJniThreadState ts(env);
StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(dvmThreadSelf(), string);
int byteCount = strObj->length() * 2;
result = (const jchar*) GuardedCopy::create(result, byteCount, false);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
}
return CHECK_JNI_EXIT("p", result);
}
static const jchar* Check_GetTaintedStringChars(JNIEnv* env, jstring string, jboolean* isCopy, u4* taint) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
const jchar* result = baseEnv(env)->GetTaintedStringChars(env, string, isCopy, taint);
if (gDvmJni.forceCopy && result != NULL) {
ScopedCheckJniThreadState ts(env);
StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(dvmThreadSelf(), string);
int byteCount = strObj->length() * 2;
result = (const jchar*) GuardedCopy::create(result, byteCount, false);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
}
return CHECK_JNI_EXIT("p", result);
}
static void Check_ReleaseStringChars(JNIEnv* env, jstring string, const jchar* chars) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
sc.checkNonNull(chars);
if (gDvmJni.forceCopy) {
if (!GuardedCopy::check(chars, false)) {
ALOGE("JNI: failed guarded copy check in ReleaseStringChars");
abortMaybe();
return;
}
chars = (const jchar*) GuardedCopy::destroy((jchar*)chars);
}
baseEnv(env)->ReleaseStringChars(env, string, chars);
CHECK_JNI_EXIT_VOID();
}
static void Check_ReleaseTaintedStringChars(JNIEnv* env, jstring string, u4 taint, const jchar* chars) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Esp", env, string, chars);
sc.checkNonNull(chars);
if (gDvmJni.forceCopy) {
if (!GuardedCopy::check(chars, false)) {
ALOGE("JNI: failed guarded copy check in ReleaseStringChars");
abortMaybe();
return;
}
chars = (const jchar*) GuardedCopy::destroy((jchar*)chars);
}
baseEnv(env)->ReleaseTaintedStringChars(env, string, taint, chars);
CHECK_JNI_EXIT_VOID();
}
static jstring Check_NewStringUTF(JNIEnv* env, const char* bytes) {
CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
return CHECK_JNI_EXIT("s", baseEnv(env)->NewStringUTF(env, bytes));
}
static jstring Check_NewTaintedStringUTF(JNIEnv* env, const char* bytes, u4 taint) {
CHECK_JNI_ENTRY(kFlag_NullableUtf, "Eu", env, bytes); // TODO: show pointer and truncate string.
return CHECK_JNI_EXIT("s", baseEnv(env)->NewTaintedStringUTF(env, bytes, taint));
}
static jsize Check_GetStringUTFLength(JNIEnv* env, jstring string) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Es", env, string);
return CHECK_JNI_EXIT("I", baseEnv(env)->GetStringUTFLength(env, string));
}
static const char* Check_GetTaintedStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy, u4* taint) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
const char* result = baseEnv(env)->GetTaintedStringUTFChars(env, string, isCopy, taint);
if (gDvmJni.forceCopy && result != NULL) {
result = (const char*) GuardedCopy::create(result, strlen(result) + 1, false);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
}
return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
}
static const char* Check_GetStringUTFChars(JNIEnv* env, jstring string, jboolean* isCopy) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Esp", env, string, isCopy);
const char* result = baseEnv(env)->GetStringUTFChars(env, string, isCopy);
if (gDvmJni.forceCopy && result != NULL) {
result = (const char*) GuardedCopy::create(result, strlen(result) + 1, false);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
}
return CHECK_JNI_EXIT("u", result); // TODO: show pointer and truncate string.
}
static void Check_ReleaseStringUTFChars(JNIEnv* env, jstring string, const char* utf) {
CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
if (gDvmJni.forceCopy) {
if (!GuardedCopy::check(utf, false)) {
ALOGE("JNI: failed guarded copy check in ReleaseStringUTFChars");
abortMaybe();
return;
}
utf = (const char*) GuardedCopy::destroy((char*)utf);
}
baseEnv(env)->ReleaseStringUTFChars(env, string, utf);
CHECK_JNI_EXIT_VOID();
}
static void Check_ReleaseTaintedStringUTFChars(JNIEnv* env, jstring string, u4 taint, const char* utf) {
CHECK_JNI_ENTRY(kFlag_ExcepOkay | kFlag_Release, "Esu", env, string, utf); // TODO: show pointer and truncate string.
if (gDvmJni.forceCopy) {
if (!GuardedCopy::check(utf, false)) {
ALOGE("JNI: failed guarded copy check in ReleaseStringUTFChars");
abortMaybe();
return;
}
utf = (const char*) GuardedCopy::destroy((char*)utf);
}
baseEnv(env)->ReleaseTaintedStringUTFChars(env, string, taint, utf);
CHECK_JNI_EXIT_VOID();
}
static jsize Check_GetArrayLength(JNIEnv* env, jarray array) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "Ea", env, array);
return CHECK_JNI_EXIT("I", baseEnv(env)->GetArrayLength(env, array));
}
static jobjectArray Check_NewObjectArray(JNIEnv* env, jsize length,
jclass elementClass, jobject initialElement)
{
CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
return CHECK_JNI_EXIT("a", baseEnv(env)->NewObjectArray(env, length, elementClass, initialElement));
}
static jobjectArray Check_NewTaintedObjectArray(JNIEnv* env, jsize length,
jclass elementClass, jobject initialElement, u4 taint)
{
CHECK_JNI_ENTRY(kFlag_Default, "EzcL", env, length, elementClass, initialElement);
return CHECK_JNI_EXIT("a", baseEnv(env)->NewTaintedObjectArray(env, length, elementClass, initialElement, taint));
}
static jobject Check_GetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index) {
CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
return CHECK_JNI_EXIT("L", baseEnv(env)->GetObjectArrayElement(env, array, index));
}
static void Check_SetObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value)
{
CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
baseEnv(env)->SetObjectArrayElement(env, array, index, value);
CHECK_JNI_EXIT_VOID();
}
static jobject Check_GetTaintedObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, u4* taint) {
CHECK_JNI_ENTRY(kFlag_Default, "EaI", env, array, index);
return CHECK_JNI_EXIT("L", baseEnv(env)->GetTaintedObjectArrayElement(env, array, index, taint));
}
static void Check_SetTaintedObjectArrayElement(JNIEnv* env, jobjectArray array, jsize index, jobject value, u4 taint)
{
CHECK_JNI_ENTRY(kFlag_Default, "EaIL", env, array, index, value);
baseEnv(env)->SetTaintedObjectArrayElement(env, array, index, value, taint);
CHECK_JNI_EXIT_VOID();
}
#define NEW_PRIMITIVE_ARRAY(_artype, _jname) \
static _artype Check_New##_jname##Array(JNIEnv* env, jsize length) { \
CHECK_JNI_ENTRY(kFlag_Default, "Ez", env, length); \
return CHECK_JNI_EXIT("a", baseEnv(env)->New##_jname##Array(env, length)); \
}
NEW_PRIMITIVE_ARRAY(jbooleanArray, Boolean);
NEW_PRIMITIVE_ARRAY(jbyteArray, Byte);
NEW_PRIMITIVE_ARRAY(jcharArray, Char);
NEW_PRIMITIVE_ARRAY(jshortArray, Short);
NEW_PRIMITIVE_ARRAY(jintArray, Int);
NEW_PRIMITIVE_ARRAY(jlongArray, Long);
NEW_PRIMITIVE_ARRAY(jfloatArray, Float);
NEW_PRIMITIVE_ARRAY(jdoubleArray, Double);
/*
* Hack to allow forcecopy to work with jniGetNonMovableArrayElements.
* The code deliberately uses an invalid sequence of operations, so we
* need to pass it through unmodified. Review that code before making
* any changes here.
*/
#define kNoCopyMagic 0xd5aab57f
#define GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
static _ctype* Check_Get##_jname##ArrayElements(JNIEnv* env, \
_ctype##Array array, jboolean* isCopy) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
u4 noCopy = 0; \
if (gDvmJni.forceCopy && isCopy != NULL) { \
/* capture this before the base call tramples on it */ \
noCopy = *(u4*) isCopy; \
} \
_ctype* result = baseEnv(env)->Get##_jname##ArrayElements(env, array, isCopy); \
if (gDvmJni.forceCopy && result != NULL) { \
if (noCopy == kNoCopyMagic) { \
ALOGV("FC: not copying %p %x", array, noCopy); \
} else { \
result = (_ctype*) createGuardedPACopy(env, array, isCopy); \
} \
} \
return CHECK_JNI_EXIT("p", result); \
} \
static _ctype* Check_GetTainted##_jname##ArrayElements(JNIEnv* env, \
_ctype##Array array, jboolean* isCopy, u4* taint) \
{ \
CHECK_JNI_ENTRY(kFlag_Default, "Eap", env, array, isCopy); \
u4 noCopy = 0; \
if (gDvmJni.forceCopy && isCopy != NULL) { \
/* capture this before the base call tramples on it */ \
noCopy = *(u4*) isCopy; \
} \
_ctype* result = baseEnv(env)->GetTainted##_jname##ArrayElements(env, array, isCopy, taint); \
if (gDvmJni.forceCopy && result != NULL) { \
if (noCopy == kNoCopyMagic) { \
ALOGV("FC: not copying %p %x", array, noCopy); \
} else { \
result = (_ctype*) createGuardedPACopy(env, array, isCopy); \
} \
} \
return CHECK_JNI_EXIT("p", result); \
}
#define RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname) \
static void Check_Release##_jname##ArrayElements(JNIEnv* env, \
_ctype##Array array, _ctype* elems, jint mode) \
{ \
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
sc.checkNonNull(elems); \
if (gDvmJni.forceCopy) { \
if ((uintptr_t)elems == kNoCopyMagic) { \
ALOGV("FC: not freeing %p", array); \
elems = NULL; /* base JNI call doesn't currently need */ \
} else { \
elems = (_ctype*) releaseGuardedPACopy(env, array, elems, mode); \
} \
} \
baseEnv(env)->Release##_jname##ArrayElements(env, array, elems, mode); \
CHECK_JNI_EXIT_VOID(); \
} \
static void Check_ReleaseTainted##_jname##ArrayElements(JNIEnv* env, \
_ctype##Array array, _ctype* elems, jint mode, u4 taint) \
{ \
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "Eapr", env, array, elems, mode); \
sc.checkNonNull(elems); \
if (gDvmJni.forceCopy) { \
if ((uintptr_t)elems == kNoCopyMagic) { \
ALOGV("FC: not freeing %p", array); \
elems = NULL; /* base JNI call doesn't currently need */ \
} else { \
elems = (_ctype*) releaseGuardedPACopy(env, array, elems, mode); \
} \
} \
baseEnv(env)->ReleaseTainted##_jname##ArrayElements(env, array, elems, mode, taint); \
CHECK_JNI_EXIT_VOID(); \
}
#define GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
static void Check_Get##_jname##ArrayRegion(JNIEnv* env, \
_ctype##Array array, jsize start, jsize len, _ctype* buf) { \
CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
baseEnv(env)->Get##_jname##ArrayRegion(env, array, start, len, buf); \
CHECK_JNI_EXIT_VOID(); \
} \
static void Check_GetTainted##_jname##ArrayRegion(JNIEnv* env, \
_ctype##Array array, jsize start, jsize len, _ctype* buf, u4* taint) { \
CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
baseEnv(env)->GetTainted##_jname##ArrayRegion(env, array, start, len, buf, taint); \
CHECK_JNI_EXIT_VOID(); \
}
#define SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname) \
static void Check_Set##_jname##ArrayRegion(JNIEnv* env, \
_ctype##Array array, jsize start, jsize len, const _ctype* buf) { \
CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
baseEnv(env)->Set##_jname##ArrayRegion(env, array, start, len, buf); \
CHECK_JNI_EXIT_VOID(); \
} \
static void Check_SetTainted##_jname##ArrayRegion(JNIEnv* env, \
_ctype##Array array, jsize start, jsize len, const _ctype* buf, u4 taint) { \
CHECK_JNI_ENTRY(kFlag_Default, "EaIIp", env, array, start, len, buf); \
baseEnv(env)->SetTainted##_jname##ArrayRegion(env, array, start, len, buf, taint); \
CHECK_JNI_EXIT_VOID(); \
}
#define PRIMITIVE_ARRAY_FUNCTIONS(_ctype, _jname, _typechar) \
GET_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
RELEASE_PRIMITIVE_ARRAY_ELEMENTS(_ctype, _jname); \
GET_PRIMITIVE_ARRAY_REGION(_ctype, _jname); \
SET_PRIMITIVE_ARRAY_REGION(_ctype, _jname);
/* TODO: verify primitive array type matches call type */
PRIMITIVE_ARRAY_FUNCTIONS(jboolean, Boolean, 'Z');
PRIMITIVE_ARRAY_FUNCTIONS(jbyte, Byte, 'B');
PRIMITIVE_ARRAY_FUNCTIONS(jchar, Char, 'C');
PRIMITIVE_ARRAY_FUNCTIONS(jshort, Short, 'S');
PRIMITIVE_ARRAY_FUNCTIONS(jint, Int, 'I');
PRIMITIVE_ARRAY_FUNCTIONS(jlong, Long, 'J');
PRIMITIVE_ARRAY_FUNCTIONS(jfloat, Float, 'F');
PRIMITIVE_ARRAY_FUNCTIONS(jdouble, Double, 'D');
static jint Check_RegisterNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods,
jint nMethods)
{
CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterNatives(env, clazz, methods, nMethods));
}
static jint Check_RegisterTaintedNatives(JNIEnv* env, jclass clazz, const JNINativeMethod* methods,
jint nMethods)
{
CHECK_JNI_ENTRY(kFlag_Default, "EcpI", env, clazz, methods, nMethods);
return CHECK_JNI_EXIT("I", baseEnv(env)->RegisterTaintedNatives(env, clazz, methods, nMethods));
}
static jint Check_UnregisterNatives(JNIEnv* env, jclass clazz) {
CHECK_JNI_ENTRY(kFlag_Default, "Ec", env, clazz);
return CHECK_JNI_EXIT("I", baseEnv(env)->UnregisterNatives(env, clazz));
}
static jint Check_MonitorEnter(JNIEnv* env, jobject obj) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorEnter(env, obj));
}
static jint Check_MonitorExit(JNIEnv* env, jobject obj) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
return CHECK_JNI_EXIT("I", baseEnv(env)->MonitorExit(env, obj));
}
static jint Check_GetJavaVM(JNIEnv *env, JavaVM **vm) {
CHECK_JNI_ENTRY(kFlag_Default, "Ep", env, vm);
return CHECK_JNI_EXIT("I", baseEnv(env)->GetJavaVM(env, vm));
}
static void Check_GetStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
baseEnv(env)->GetStringRegion(env, str, start, len, buf);
CHECK_JNI_EXIT_VOID();
}
static void Check_GetTaintedStringRegion(JNIEnv* env, jstring str, jsize start, jsize len, jchar* buf, u4* taint) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
baseEnv(env)->GetTaintedStringRegion(env, str, start, len, buf, taint);
CHECK_JNI_EXIT_VOID();
}
static void Check_GetStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
baseEnv(env)->GetStringUTFRegion(env, str, start, len, buf);
CHECK_JNI_EXIT_VOID();
}
static void Check_GetTaintedStringUTFRegion(JNIEnv* env, jstring str, jsize start, jsize len, char* buf, u4* taint) {
CHECK_JNI_ENTRY(kFlag_CritOkay, "EsIIp", env, str, start, len, buf);
baseEnv(env)->GetTaintedStringUTFRegion(env, str, start, len, buf, taint);
CHECK_JNI_EXIT_VOID();
}
static void* Check_GetPrimitiveArrayCritical(JNIEnv* env, jarray array, jboolean* isCopy) {
CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
void* result = baseEnv(env)->GetPrimitiveArrayCritical(env, array, isCopy);
if (gDvmJni.forceCopy && result != NULL) {
result = createGuardedPACopy(env, array, isCopy);
}
return CHECK_JNI_EXIT("p", result);
}
static void* Check_GetTaintedPrimitiveArrayCritical(JNIEnv* env, jarray array, u4* taint, jboolean* isCopy) {
CHECK_JNI_ENTRY(kFlag_CritGet, "Eap", env, array, isCopy);
void* result = baseEnv(env)->GetTaintedPrimitiveArrayCritical(env, array, taint, isCopy);
if (gDvmJni.forceCopy && result != NULL) {
result = createGuardedPACopy(env, array, isCopy);
}
return CHECK_JNI_EXIT("p", result);
}
static void Check_ReleasePrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, jint mode)
{
CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
sc.checkNonNull(carray);
if (gDvmJni.forceCopy) {
carray = releaseGuardedPACopy(env, array, carray, mode);
}
baseEnv(env)->ReleasePrimitiveArrayCritical(env, array, carray, mode);
CHECK_JNI_EXIT_VOID();
}
static void Check_ReleaseTaintedPrimitiveArrayCritical(JNIEnv* env, jarray array, void* carray, u4 taint, jint mode)
{
CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Eapr", env, array, carray, mode);
sc.checkNonNull(carray);
if (gDvmJni.forceCopy) {
carray = releaseGuardedPACopy(env, array, carray, mode);
}
baseEnv(env)->ReleaseTaintedPrimitiveArrayCritical(env, array, carray, taint, mode);
CHECK_JNI_EXIT_VOID();
}
static const jchar* Check_GetStringCritical(JNIEnv* env, jstring string, jboolean* isCopy) {
CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, string, isCopy);
const jchar* result = baseEnv(env)->GetStringCritical(env, string, isCopy);
if (gDvmJni.forceCopy && result != NULL) {
ScopedCheckJniThreadState ts(env);
StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(dvmThreadSelf(), string);
int byteCount = strObj->length() * 2;
result = (const jchar*) GuardedCopy::create(result, byteCount, false);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
}
return CHECK_JNI_EXIT("p", result);
}
static const jchar* Check_GetTaintedStringCritical(JNIEnv* env, jstring string, u4* taint, jboolean* isCopy) {
CHECK_JNI_ENTRY(kFlag_CritGet, "Esp", env, string, isCopy);
const jchar* result = baseEnv(env)->GetTaintedStringCritical(env, string, taint, isCopy);
if (gDvmJni.forceCopy && result != NULL) {
ScopedCheckJniThreadState ts(env);
StringObject* strObj = (StringObject*) dvmDecodeIndirectRef(dvmThreadSelf(), string);
int byteCount = strObj->length() * 2;
result = (const jchar*) GuardedCopy::create(result, byteCount, false);
if (isCopy != NULL) {
*isCopy = JNI_TRUE;
}
}
return CHECK_JNI_EXIT("p", result);
}
static void Check_ReleaseStringCritical(JNIEnv* env, jstring string, const jchar* carray) {
CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
sc.checkNonNull(carray);
if (gDvmJni.forceCopy) {
if (!GuardedCopy::check(carray, false)) {
ALOGE("JNI: failed guarded copy check in ReleaseStringCritical");
abortMaybe();
return;
}
carray = (const jchar*) GuardedCopy::destroy((jchar*)carray);
}
baseEnv(env)->ReleaseStringCritical(env, string, carray);
CHECK_JNI_EXIT_VOID();
}
static void Check_ReleaseTaintedStringCritical(JNIEnv* env, jstring string, u4 taint, const jchar* carray) {
CHECK_JNI_ENTRY(kFlag_CritRelease | kFlag_ExcepOkay, "Esp", env, string, carray);
sc.checkNonNull(carray);
if (gDvmJni.forceCopy) {
if (!GuardedCopy::check(carray, false)) {
ALOGE("JNI: failed guarded copy check in ReleaseStringCritical");
abortMaybe();
return;
}
carray = (const jchar*) GuardedCopy::destroy((jchar*)carray);
}
baseEnv(env)->ReleaseTaintedStringCritical(env, string, taint, carray);
CHECK_JNI_EXIT_VOID();
}
static jweak Check_NewWeakGlobalRef(JNIEnv* env, jobject obj) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewWeakGlobalRef(env, obj));
}
static void Check_DeleteWeakGlobalRef(JNIEnv* env, jweak obj) {
CHECK_JNI_ENTRY(kFlag_Default | kFlag_ExcepOkay, "EL", env, obj);
baseEnv(env)->DeleteWeakGlobalRef(env, obj);
CHECK_JNI_EXIT_VOID();
}
static jboolean Check_ExceptionCheck(JNIEnv* env) {
CHECK_JNI_ENTRY(kFlag_CritOkay | kFlag_ExcepOkay, "E", env);
return CHECK_JNI_EXIT("b", baseEnv(env)->ExceptionCheck(env));
}
static jobjectRefType Check_GetObjectRefType(JNIEnv* env, jobject obj) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, obj);
// TODO: proper decoding of jobjectRefType!
return CHECK_JNI_EXIT("I", baseEnv(env)->GetObjectRefType(env, obj));
}
static jobject Check_NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) {
CHECK_JNI_ENTRY(kFlag_Default, "EpJ", env, address, capacity);
return CHECK_JNI_EXIT("L", baseEnv(env)->NewDirectByteBuffer(env, address, capacity));
}
static void* Check_GetDirectBufferAddress(JNIEnv* env, jobject buf) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
// TODO: check that 'buf' is a java.nio.Buffer.
return CHECK_JNI_EXIT("p", baseEnv(env)->GetDirectBufferAddress(env, buf));
}
static jlong Check_GetDirectBufferCapacity(JNIEnv* env, jobject buf) {
CHECK_JNI_ENTRY(kFlag_Default, "EL", env, buf);
// TODO: check that 'buf' is a java.nio.Buffer.
return CHECK_JNI_EXIT("J", baseEnv(env)->GetDirectBufferCapacity(env, buf));
}
/*
* ===========================================================================
* JNI invocation functions
* ===========================================================================
*/
static jint Check_DestroyJavaVM(JavaVM* vm) {
ScopedCheck sc(false, __FUNCTION__);
sc.check(true, "v", vm);
return CHECK_JNI_EXIT("I", baseVm(vm)->DestroyJavaVM(vm));
}
static jint Check_AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
ScopedCheck sc(false, __FUNCTION__);
sc.check(true, "vpt", vm, p_env, thr_args);
return CHECK_JNI_EXIT("I", baseVm(vm)->AttachCurrentThread(vm, p_env, thr_args));
}
static jint Check_AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
ScopedCheck sc(false, __FUNCTION__);
sc.check(true, "vpt", vm, p_env, thr_args);
return CHECK_JNI_EXIT("I", baseVm(vm)->AttachCurrentThreadAsDaemon(vm, p_env, thr_args));
}
static jint Check_DetachCurrentThread(JavaVM* vm) {
ScopedCheck sc(true, __FUNCTION__);
sc.check(true, "v", vm);
return CHECK_JNI_EXIT("I", baseVm(vm)->DetachCurrentThread(vm));
}
static jint Check_GetEnv(JavaVM* vm, void** env, jint version) {
ScopedCheck sc(true, __FUNCTION__);
sc.check(true, "v", vm);
return CHECK_JNI_EXIT("I", baseVm(vm)->GetEnv(vm, env, version));
}
// for wrapper
static const char* Check_GetArrayType(JNIEnv* env, jarray jarr) {
const char* result = baseEnv(env)->GetArrayType(env, jarr);
return result;
}
/*
* ===========================================================================
* Function tables
* ===========================================================================
*/
static const struct JNINativeInterface gCheckNativeInterface = {
NULL,
NULL,
NULL,
NULL,
Check_GetVersion,
Check_DefineClass,
Check_FindClass,
Check_FromReflectedMethod,
Check_FromReflectedField,
Check_ToReflectedMethod,
Check_GetSuperclass,
Check_IsAssignableFrom,
Check_ToReflectedField,
Check_Throw,
Check_ThrowNew,
Check_ExceptionOccurred,
Check_ExceptionDescribe,
Check_ExceptionClear,
Check_FatalError,
Check_PushLocalFrame,
Check_PopLocalFrame,
Check_NewGlobalRef,
Check_DeleteGlobalRef,
Check_DeleteLocalRef,
Check_IsSameObject,
Check_NewLocalRef,
Check_EnsureLocalCapacity,
Check_AllocObject,
Check_NewObject,
Check_NewObjectV,
Check_NewObjectA,
Check_GetObjectClass,
Check_IsInstanceOf,
Check_GetMethodID,
Check_CallObjectMethod,
Check_CallObjectMethodV,
Check_CallObjectMethodA,
Check_CallBooleanMethod,
Check_CallBooleanMethodV,
Check_CallBooleanMethodA,
Check_CallByteMethod,
Check_CallByteMethodV,
Check_CallByteMethodA,
Check_CallCharMethod,
Check_CallCharMethodV,
Check_CallCharMethodA,
Check_CallShortMethod,
Check_CallShortMethodV,
Check_CallShortMethodA,
Check_CallIntMethod,
Check_CallIntMethodV,
Check_CallIntMethodA,
Check_CallLongMethod,
Check_CallLongMethodV,
Check_CallLongMethodA,
Check_CallFloatMethod,
Check_CallFloatMethodV,
Check_CallFloatMethodA,
Check_CallDoubleMethod,
Check_CallDoubleMethodV,
Check_CallDoubleMethodA,
Check_CallVoidMethod,
Check_CallVoidMethodV,
Check_CallVoidMethodA,
Check_CallNonvirtualObjectMethod,
Check_CallNonvirtualObjectMethodV,
Check_CallNonvirtualObjectMethodA,
Check_CallNonvirtualBooleanMethod,
Check_CallNonvirtualBooleanMethodV,
Check_CallNonvirtualBooleanMethodA,
Check_CallNonvirtualByteMethod,
Check_CallNonvirtualByteMethodV,
Check_CallNonvirtualByteMethodA,
Check_CallNonvirtualCharMethod,
Check_CallNonvirtualCharMethodV,
Check_CallNonvirtualCharMethodA,
Check_CallNonvirtualShortMethod,
Check_CallNonvirtualShortMethodV,
Check_CallNonvirtualShortMethodA,
Check_CallNonvirtualIntMethod,
Check_CallNonvirtualIntMethodV,
Check_CallNonvirtualIntMethodA,
Check_CallNonvirtualLongMethod,
Check_CallNonvirtualLongMethodV,
Check_CallNonvirtualLongMethodA,
Check_CallNonvirtualFloatMethod,
Check_CallNonvirtualFloatMethodV,
Check_CallNonvirtualFloatMethodA,
Check_CallNonvirtualDoubleMethod,
Check_CallNonvirtualDoubleMethodV,
Check_CallNonvirtualDoubleMethodA,
Check_CallNonvirtualVoidMethod,
Check_CallNonvirtualVoidMethodV,
Check_CallNonvirtualVoidMethodA,
Check_GetFieldID,
Check_GetObjectField,
Check_GetBooleanField,
Check_GetByteField,
Check_GetCharField,
Check_GetShortField,
Check_GetIntField,
Check_GetLongField,
Check_GetFloatField,
Check_GetDoubleField,
Check_SetObjectField,
Check_SetBooleanField,
Check_SetByteField,
Check_SetCharField,
Check_SetShortField,
Check_SetIntField,
Check_SetLongField,
Check_SetFloatField,
Check_SetDoubleField,
Check_GetStaticMethodID,
Check_CallStaticObjectMethod,
Check_CallStaticObjectMethodV,
Check_CallStaticObjectMethodA,
Check_CallStaticBooleanMethod,
Check_CallStaticBooleanMethodV,
Check_CallStaticBooleanMethodA,
Check_CallStaticByteMethod,
Check_CallStaticByteMethodV,
Check_CallStaticByteMethodA,
Check_CallStaticCharMethod,
Check_CallStaticCharMethodV,
Check_CallStaticCharMethodA,
Check_CallStaticShortMethod,
Check_CallStaticShortMethodV,
Check_CallStaticShortMethodA,
Check_CallStaticIntMethod,
Check_CallStaticIntMethodV,
Check_CallStaticIntMethodA,
Check_CallStaticLongMethod,
Check_CallStaticLongMethodV,
Check_CallStaticLongMethodA,
Check_CallStaticFloatMethod,
Check_CallStaticFloatMethodV,
Check_CallStaticFloatMethodA,
Check_CallStaticDoubleMethod,
Check_CallStaticDoubleMethodV,
Check_CallStaticDoubleMethodA,
Check_CallStaticVoidMethod,
Check_CallStaticVoidMethodV,
Check_CallStaticVoidMethodA,
Check_GetStaticFieldID,
Check_GetStaticObjectField,
Check_GetStaticBooleanField,
Check_GetStaticByteField,
Check_GetStaticCharField,
Check_GetStaticShortField,
Check_GetStaticIntField,
Check_GetStaticLongField,
Check_GetStaticFloatField,
Check_GetStaticDoubleField,
Check_SetStaticObjectField,
Check_SetStaticBooleanField,
Check_SetStaticByteField,
Check_SetStaticCharField,
Check_SetStaticShortField,
Check_SetStaticIntField,
Check_SetStaticLongField,
Check_SetStaticFloatField,
Check_SetStaticDoubleField,
Check_NewString,
Check_GetStringLength,
Check_GetStringChars,
Check_ReleaseStringChars,
Check_NewStringUTF,
Check_GetStringUTFLength,
Check_GetStringUTFChars,
Check_ReleaseStringUTFChars,
Check_GetArrayLength,
Check_NewObjectArray,
Check_GetObjectArrayElement,
Check_SetObjectArrayElement,
Check_NewBooleanArray,
Check_NewByteArray,
Check_NewCharArray,
Check_NewShortArray,
Check_NewIntArray,
Check_NewLongArray,
Check_NewFloatArray,
Check_NewDoubleArray,
Check_GetBooleanArrayElements,
Check_GetByteArrayElements,
Check_GetCharArrayElements,
Check_GetShortArrayElements,
Check_GetIntArrayElements,
Check_GetLongArrayElements,
Check_GetFloatArrayElements,
Check_GetDoubleArrayElements,
Check_ReleaseBooleanArrayElements,
Check_ReleaseByteArrayElements,
Check_ReleaseCharArrayElements,
Check_ReleaseShortArrayElements,
Check_ReleaseIntArrayElements,
Check_ReleaseLongArrayElements,
Check_ReleaseFloatArrayElements,
Check_ReleaseDoubleArrayElements,
Check_GetBooleanArrayRegion,
Check_GetByteArrayRegion,
Check_GetCharArrayRegion,
Check_GetShortArrayRegion,
Check_GetIntArrayRegion,
Check_GetLongArrayRegion,
Check_GetFloatArrayRegion,
Check_GetDoubleArrayRegion,
Check_SetBooleanArrayRegion,
Check_SetByteArrayRegion,
Check_SetCharArrayRegion,
Check_SetShortArrayRegion,
Check_SetIntArrayRegion,
Check_SetLongArrayRegion,
Check_SetFloatArrayRegion,
Check_SetDoubleArrayRegion,
Check_RegisterNatives,
Check_UnregisterNatives,
Check_MonitorEnter,
Check_MonitorExit,
Check_GetJavaVM,
Check_GetStringRegion,
Check_GetStringUTFRegion,
Check_GetPrimitiveArrayCritical,
Check_ReleasePrimitiveArrayCritical,
Check_GetStringCritical,
Check_ReleaseStringCritical,
Check_NewWeakGlobalRef,
Check_DeleteWeakGlobalRef,
Check_ExceptionCheck,
Check_NewDirectByteBuffer,
Check_GetDirectBufferAddress,
Check_GetDirectBufferCapacity,
Check_GetObjectRefType,
Check_GetArrayType,
Check_NewTaintedObjectA,
Check_CallObjectTaintedMethodA,
Check_CallBooleanTaintedMethodA,
Check_CallByteTaintedMethodA,
Check_CallCharTaintedMethodA,
Check_CallShortTaintedMethodA,
Check_CallIntTaintedMethodA,
Check_CallLongTaintedMethodA,
Check_CallFloatTaintedMethodA,
Check_CallDoubleTaintedMethodA,
Check_CallVoidTaintedMethodA,
Check_CallNonvirtualObjectTaintedMethodA,
Check_CallNonvirtualBooleanTaintedMethodA,
Check_CallNonvirtualByteTaintedMethodA,
Check_CallNonvirtualCharTaintedMethodA,
Check_CallNonvirtualShortTaintedMethodA,
Check_CallNonvirtualIntTaintedMethodA,
Check_CallNonvirtualLongTaintedMethodA,
Check_CallNonvirtualFloatTaintedMethodA,
Check_CallNonvirtualDoubleTaintedMethodA,
Check_CallNonvirtualVoidTaintedMethodA,
Check_GetObjectTaintedField,
Check_GetBooleanTaintedField,
Check_GetByteTaintedField,
Check_GetCharTaintedField,
Check_GetShortTaintedField,
Check_GetIntTaintedField,
Check_GetLongTaintedField,
Check_GetFloatTaintedField,
Check_GetDoubleTaintedField,
Check_SetObjectTaintedField,
Check_SetBooleanTaintedField,
Check_SetByteTaintedField,
Check_SetCharTaintedField,
Check_SetShortTaintedField,
Check_SetIntTaintedField,
Check_SetLongTaintedField,
Check_SetFloatTaintedField,
Check_SetDoubleTaintedField,
Check_CallStaticObjectTaintedMethodA,
Check_CallStaticBooleanTaintedMethodA,
Check_CallStaticByteTaintedMethodA,
Check_CallStaticCharTaintedMethodA,
Check_CallStaticShortTaintedMethodA,
Check_CallStaticIntTaintedMethodA,
Check_CallStaticLongTaintedMethodA,
Check_CallStaticFloatTaintedMethodA,
Check_CallStaticDoubleTaintedMethodA,
Check_CallStaticVoidTaintedMethodA,
Check_GetStaticObjectTaintedField,
Check_GetStaticBooleanTaintedField,
Check_GetStaticByteTaintedField,
Check_GetStaticCharTaintedField,
Check_GetStaticShortTaintedField,
Check_GetStaticIntTaintedField,
Check_GetStaticLongTaintedField,
Check_GetStaticFloatTaintedField,
Check_GetStaticDoubleTaintedField,
Check_SetStaticObjectTaintedField,
Check_SetStaticBooleanTaintedField,
Check_SetStaticByteTaintedField,
Check_SetStaticCharTaintedField,
Check_SetStaticShortTaintedField,
Check_SetStaticIntTaintedField,
Check_SetStaticLongTaintedField,
Check_SetStaticFloatTaintedField,
Check_SetStaticDoubleTaintedField,
Check_GetTaintedStringLength,
Check_GetTaintedStringChars,
Check_ReleaseTaintedStringChars,
Check_NewTaintedStringUTF,
Check_GetTaintedStringUTFChars,
Check_ReleaseTaintedStringUTFChars,
Check_NewTaintedObjectArray,
Check_GetTaintedObjectArrayElement,
Check_SetTaintedObjectArrayElement,
Check_GetTaintedBooleanArrayElements,
Check_GetTaintedByteArrayElements,
Check_GetTaintedCharArrayElements,
Check_GetTaintedShortArrayElements,
Check_GetTaintedIntArrayElements,
Check_GetTaintedLongArrayElements,
Check_GetTaintedFloatArrayElements,
Check_GetTaintedDoubleArrayElements,
Check_ReleaseTaintedBooleanArrayElements,
Check_ReleaseTaintedByteArrayElements,
Check_ReleaseTaintedCharArrayElements,
Check_ReleaseTaintedShortArrayElements,
Check_ReleaseTaintedIntArrayElements,
Check_ReleaseTaintedLongArrayElements,
Check_ReleaseTaintedFloatArrayElements,
Check_ReleaseTaintedDoubleArrayElements,
Check_GetTaintedBooleanArrayRegion,
Check_GetTaintedByteArrayRegion,
Check_GetTaintedCharArrayRegion,
Check_GetTaintedShortArrayRegion,
Check_GetTaintedIntArrayRegion,
Check_GetTaintedLongArrayRegion,
Check_GetTaintedFloatArrayRegion,
Check_GetTaintedDoubleArrayRegion,
Check_SetTaintedBooleanArrayRegion,
Check_SetTaintedByteArrayRegion,
Check_SetTaintedCharArrayRegion,
Check_SetTaintedShortArrayRegion,
Check_SetTaintedIntArrayRegion,
Check_SetTaintedLongArrayRegion,
Check_SetTaintedFloatArrayRegion,
Check_SetTaintedDoubleArrayRegion,
Check_GetTaintedStringRegion,
Check_GetTaintedStringUTFRegion,
Check_GetTaintedPrimitiveArrayCritical,
Check_ReleaseTaintedPrimitiveArrayCritical,
Check_GetTaintedStringCritical,
Check_ReleaseTaintedStringCritical,
Check_RegisterTaintedNatives
};
static const struct JNIInvokeInterface gCheckInvokeInterface = {
NULL,
NULL,
NULL,
Check_DestroyJavaVM,
Check_AttachCurrentThread,
Check_DetachCurrentThread,
Check_GetEnv,
Check_AttachCurrentThreadAsDaemon,
};
/*
* Replace the normal table with the checked table.
*/
void dvmUseCheckedJniEnv(JNIEnvExt* pEnv) {
assert(pEnv->funcTable != &gCheckNativeInterface);
pEnv->baseFuncTable = pEnv->funcTable;
pEnv->funcTable = &gCheckNativeInterface;
}
/*
* Replace the normal table with the checked table.
*/
void dvmUseCheckedJniVm(JavaVMExt* pVm) {
assert(pVm->funcTable != &gCheckInvokeInterface);
pVm->baseFuncTable = pVm->funcTable;
pVm->funcTable = &gCheckInvokeInterface;
}
| 38.14554 | 136 | 0.620507 | flowcoaster |
0895447c4d3756c74ac58c1fae6017bbf84173b3 | 2,838 | cpp | C++ | hw/Assignment2-vs2008/Word Ladder/Word Ladder/WordLadder.cpp | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | hw/Assignment2-vs2008/Word Ladder/Word Ladder/WordLadder.cpp | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | hw/Assignment2-vs2008/Word Ladder/Word Ladder/WordLadder.cpp | Liquidibrium/PAbstractions | e3cf51b5d713a181abdda87ed5205d998289f878 | [
"MIT"
] | null | null | null | /*
* File: WordLadder.cpp
* --------------------------
* Name: [TODO: enter name here]
* Section: [TODO: enter section leader here]
* This file is the starter project for the Word Ladder problem.
* [TODO: rewrite the documentation]
*/
#include <iostream>e
#include "console.h"
#include "simpio.h"
#include "lexicon.h"
#include "queue.h"
#include <vector>
using namespace std;
void inputWords(string& starting , string& ending){
cout<<"Enter the STARTING word (or 0 to quite): " ;
cin>>starting;
if(starting=="0"){
cout<<"Bye"<<endl;
return ;
}
cout<<"Enter the ENDING word : " ;
cin>>ending;
cout<<"Searching ... "<<endl;
}
bool firstCheck(string& starting,string& ending,Lexicon& english){
if(starting.length()!=ending.length()) return false;
if(!english.contains(starting))return false;
if(!english.contains(ending))return false;
return true;
}
// adds words in lexicon those are one letter different from word
void findWords(string word,Lexicon& oneLetterDiff,Lexicon& english){
int length = word.length();
for(int i = 0;i < length ; i++){
char letter = word[i];
for(char ch = 'a' ; ch<='z' ; ch++){
string tmp = word;
if(letter!=ch){
tmp[i]=ch;
if(english.contains(tmp)&& !oneLetterDiff.contains(tmp)){
oneLetterDiff.add(tmp);
}
}
}
}
}
// returns shortest ladder as vector of strings
vector<string> findLadder(string& starting,string& ending,Lexicon& english){
Lexicon usedWords;
Queue<vector<string> > ladders;
vector<string> firstLadder;
firstLadder.push_back(starting);
usedWords.add(starting);
ladders.enqueue(firstLadder);
while(!ladders.isEmpty()){
vector<string> topLadder = ladders.dequeue();
string lastWord = topLadder[topLadder.size()-1];
if(lastWord==ending){
return topLadder;
}
Lexicon oneLetterDiff;
findWords(lastWord,oneLetterDiff,english);
foreach(string word in oneLetterDiff){
if(!usedWords.contains(word)){
usedWords.add(word);
vector<string> tmp = topLadder;
tmp.push_back(word);
ladders.enqueue(tmp);
}
}
}
vector<string> empty;
return empty;
}
void printOut(vector<string>& ladder){
if(ladder.size()!=0){
cout<<"Ladder found: ";
for(int i = 0 ; i < ladder.size()-1 ; i++){
cout<< ladder[i]<< " --> " ;
}
cout<< ladder[ladder.size()-1]<< endl ;
}else {
cout<<"No word ladder could be found"<<endl;
}
}
void searchForLadder(string& starting , string& ending , Lexicon& english){
if(firstCheck(starting,ending,english)){
vector<string> ladder = findLadder(starting,ending,english);
printOut(ladder);
}else{
cout<<"No word ladder could be found"<<endl;
}
}
int main() {
Lexicon english("EnglishWords.dat");
string starting , ending ;
while(true){
inputWords(starting,ending);
if(starting=="0")return 0;
searchForLadder(starting,ending,english);
}
return 0;
}
| 25.567568 | 76 | 0.674419 | Liquidibrium |
08961aefa3d4b1ad40dd570bd6497b8cc501ba88 | 1,855 | cpp | C++ | 03_Tutorial/T02_XMCocos2D-v3/Source/ClickAndMoveTest/ClickAndMoveTest.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 03_Tutorial/T02_XMCocos2D-v3/Source/ClickAndMoveTest/ClickAndMoveTest.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 03_Tutorial/T02_XMCocos2D-v3/Source/ClickAndMoveTest/ClickAndMoveTest.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | #include "ClickAndMoveTest.h"
#include "../testResource.h"
enum
{
kTagSprite = 1,
};
void ClickAndMoveTestScene::runThisTest()
{
auto layer = new MainLayer();
layer->autorelease();
addChild(layer);
Director::getInstance()->replaceScene(this);
}
MainLayer::MainLayer()
{
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(MainLayer::onTouchBegan, this);
listener->onTouchEnded = CC_CALLBACK_2(MainLayer::onTouchEnded, this);
m_pEventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto sprite = Sprite::create(s_pathGrossini);
auto layer = LayerColor::create(Color4B(255,255,0,255));
addChild(layer, -1);
addChild(sprite, 0, kTagSprite);
sprite->setPosition( Point(20,150) );
sprite->runAction( JumpTo::create(4, Point(300,48), 100, 4) );
layer->runAction( RepeatForever::create(
Sequence::create(
FadeIn::create(1),
FadeOut::create(1),
NULL)
));
}
bool MainLayer::onTouchBegan(Touch* touch, Event *event)
{
return true;
}
void MainLayer::onTouchEnded(Touch* touch, Event *event)
{
auto location = touch->getLocation();
auto s = getChildByTag(kTagSprite);
s->stopAllActions();
s->runAction( MoveTo::create(1, Point(location.x, location.y) ) );
float o = location.x - s->getPosition().x;
float a = location.y - s->getPosition().y;
float at = (float) CC_RADIANS_TO_DEGREES( kdAtanf( o/a) );
if( a < 0 )
{
if( o < 0 )
at = 180 + kdFabsf(at);
else
at = 180 - kdFabsf(at);
}
s->runAction( RotateTo::create(1, at) );
}
| 26.884058 | 79 | 0.577898 | mcodegeeks |
089b34e456829d7729aff86f2842f6c178dd98c9 | 12,040 | cpp | C++ | src/RTL/Component/Importing/CIFXInternetReadBufferX.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 44 | 2016-05-06T00:47:11.000Z | 2022-02-11T06:51:37.000Z | src/RTL/Component/Importing/CIFXInternetReadBufferX.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 3 | 2016-06-27T12:37:31.000Z | 2021-03-24T12:39:48.000Z | src/RTL/Component/Importing/CIFXInternetReadBufferX.cpp | alemuntoni/u3d | 7907b907464a2db53dac03fdc137dcb46d447513 | [
"Apache-2.0"
] | 15 | 2016-02-28T11:08:30.000Z | 2021-06-01T03:32:01.000Z | //***************************************************************************
//
// Copyright (c) 2000 - 2006 Intel Corporation
//
// 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.
//
//***************************************************************************
/**
@file CIFXInternetReadBufferX.cpp
Implementation of the CIFXInternetReadBufferX class which implements the
IFXReadBuffer, IFXReadBufferX and IFXStdio interfaces.
*/
#include "CIFXInternetReadBufferX.h"
#include "IFXImportingCIDs.h"
#include "IFXCheckX.h"
#include "IFXMemory.h"
#include "IFXScheduler.h"
#include "IFXOSSocket.h"
const U32 BUFFER_BLOCK_SIZE = 65536;
const U32 INTERNET_READ_TASK_PRIORITY = 4;
// Factory function.
IFXRESULT IFXAPI_CALLTYPE CIFXInternetReadBufferX_Factory(
IFXREFIID interfaceId, void** ppInterface)
{
IFXRESULT rc = IFX_OK;
if (ppInterface)
{
// Create the CIFXInternetReadBufferX component.
CIFXInternetReadBufferX *pComponent = new CIFXInternetReadBufferX;
if (pComponent)
{
// Perform a temporary AddRef for our usage of the component.
pComponent->AddRef();
// Attempt to obtain a pointer to the requested interface.
rc = pComponent->QueryInterface(interfaceId, ppInterface);
// Perform a Release since our usage of the component is now
// complete. Note: If the QI fails, this will cause the
// component to be destroyed.
pComponent->Release();
}
else
{
rc = IFX_E_OUT_OF_MEMORY;
}
}
else
{
rc = IFX_E_INVALID_POINTER;
}
return rc;
}
CIFXInternetReadBufferX::CIFXInternetReadBufferX() :
IFXDEFINEMEMBER(m_pReadingCallback),
IFXDEFINEMEMBER(m_pReadBuffer)
{
m_refCount = 0;
m_readPosition = 0;
m_readTaskHandle = IFXTASK_HANDLE_INVALID;
m_pReadBuffer = NULL;
}
CIFXInternetReadBufferX::~CIFXInternetReadBufferX()
{
Close();
}
// IFXUnknown
U32 CIFXInternetReadBufferX::AddRef( void )
{
return ++m_refCount;
}
U32 CIFXInternetReadBufferX::Release( void )
{
if (1 == m_refCount) {
delete this;
return 0;
}
return --m_refCount;
}
IFXRESULT CIFXInternetReadBufferX::QueryInterface(
IFXREFIID interfaceId, void** ppInterface )
{
IFXRESULT rc = IFX_OK;
if (ppInterface)
{
if (interfaceId == IID_IFXReadBufferX)
{
*ppInterface = ( IFXReadBufferX* ) this;
}
else if ( interfaceId == IID_IFXStdio )
{
*ppInterface = ( IFXStdio* )this;
}
else if ( interfaceId == IID_IFXInet )
{
*ppInterface = ( IFXInet* )this;
}
else if ( interfaceId == IID_IFXReadBuffer )
{
*ppInterface = ( IFXReadBuffer* )this;
}
else if ( interfaceId == IID_IFXUnknown )
{
*ppInterface = ( IFXUnknown* )this;
}
else if ( interfaceId == IID_IFXTask )
{
*ppInterface = ( IFXTask* )this;
}
else
{
*ppInterface = NULL;
rc = IFX_E_UNSUPPORTED;
}
if( IFXSUCCESS( rc ) )
AddRef();
}
else
{
rc = IFX_E_INVALID_POINTER;
}
return rc;
}
// IFXReadBuffer
IFXRESULT CIFXInternetReadBufferX::Read( U8* pBytes, U64 position, U32 count )
{
IFXRESULT rc = IFX_OK;
try
{
// Check the input pointer and file pointer
if(NULL == pBytes)
{
IFXCHECKX(IFX_E_INVALID_POINTER);
}
// Note the check for the file pointer (m_hFile) is done in GetTotalSizeX
ReadX(pBytes,position,count,rc);
if(IFX_W_END_OF_FILE == rc)
{
rc = IFX_E_END_OF_FILE; // Convert end of file warning to an error
}
}
catch(IFXException& rException)
{
rc = rException.GetIFXResult();
}
return rc;
}
void CIFXInternetReadBufferX::ReadX(
U8* pBytes, U64 position, U32 count,
IFXRESULT& rWarningCode )
{
rWarningCode = IFX_OK;
U32 bytesRead = 0;
// Check the input pointer and file pointer
if (NULL == pBytes)
{
IFXCHECKX(IFX_E_INVALID_POINTER);
}
if (m_readPosition != position)
IFXCHECKX(IFX_E_IO);
// Read the data
IFXRESULT result = m_session.Read( pBytes, count, &bytesRead );
if (IFX_OK == result)
{
m_readPosition += bytesRead;
}
else
{
// Check for end of file
if (IFX_W_FINISHED == result)
{
m_readPosition += bytesRead;
rWarningCode = IFX_W_END_OF_FILE;
}
else
IFXCHECKX( result );
}
}
IFXRESULT CIFXInternetReadBufferX::GetTotalSize( U64* pCount )
{
IFXRESULT rc = IFX_OK;
try
{
// Check the input pointer
if (NULL == pCount)
{
IFXCHECKX(IFX_E_INVALID_POINTER);
}
// Note the check for the file pointer (m_hFile) is done in GetTotalSizeX
GetTotalSizeX(*pCount);
}
catch(IFXException& rException)
{
rc = rException.GetIFXResult();
}
return rc;
}
void CIFXInternetReadBufferX::GetTotalSizeX( U64& rCount )
{
GetAvailableSizeX(rCount);
}
IFXRESULT CIFXInternetReadBufferX::GetAvailableSize( U64* pCount )
{
IFXRESULT rc = IFX_OK;
try
{
// Check the input pointer and file pointer
if(NULL == pCount)
{
IFXCHECKX(IFX_E_INVALID_POINTER);
}
// Note the check for the file pointer (m_hFile) is done in GetAvailableSizeX
GetAvailableSizeX(*pCount);
}
catch (IFXException& rException)
{
rc = rException.GetIFXResult();
}
return rc;
}
void CIFXInternetReadBufferX::GetAvailableSizeX( U64& rCount )
{
// For InternetReadBufferX, available size and total size are the same.
/// @todo Get file size for CIFXInternetReadBufferX is not implemented
//IFXInternetQueryDataAvailable(m_hFile, &rCount);
}
// IFXStdio
IFXRESULT CIFXInternetReadBufferX::Open(const IFXCHAR *pUrl)
{
IFXRESULT rc = IFX_OK;
try
{
m_session.OpenX( pUrl );
m_readPosition = 0;
}
catch (IFXException& rException)
{
rc = rException.GetIFXResult();
}
return rc;
}
IFXRESULT CIFXInternetReadBufferX::Close()
{
IFXRESULT result = IFX_OK;
result = m_session.Close();
return result;
}
// IFXInet
/// @todo complete CIFXInternetReadBufferX::GetConnectTimeout
IFXRESULT CIFXInternetReadBufferX::GetConnectTimeout(U32& rConnectTimeout)
{
IFXRESULT rc = IFX_E_UNSUPPORTED;
return rc;
}
/// @todo complete CIFXInternetReadBufferX::SetConnectTimeout
IFXRESULT CIFXInternetReadBufferX::SetConnectTimeout(const U32 connectTimeout)
{
IFXRESULT rc = IFX_E_UNSUPPORTED;
return rc;
}
IFXRESULT CIFXInternetReadBufferX::GetSendTimeout(U32& rSendTimeout)
{
IFXRESULT rc = IFX_OK;
U32 buffer;
I32 buflen = sizeof(buffer);
rc = m_session.GetOptions( IFXOSSOCKET_SEND_TIMEOUT, (I8*)&buffer, &buflen );
if( IFXSUCCESS( rc ) )
rSendTimeout = buffer;
return rc;
}
IFXRESULT CIFXInternetReadBufferX::SetSendTimeout(const U32 sendTimeout)
{
IFXRESULT rc = IFX_OK;
const I8* buffer = (const I8*)&sendTimeout;
U32 buflen = sizeof(sendTimeout);
rc = m_session.SetOptions( IFXOSSOCKET_SEND_TIMEOUT, buffer, buflen );
return rc;
}
IFXRESULT CIFXInternetReadBufferX::GetReceiveTimeout(U32& rReceiveTimeout)
{
IFXRESULT rc = IFX_OK;
U32 buffer;
I32 buflen = sizeof(buffer);
rc = m_session.GetOptions( IFXOSSOCKET_RECEIVE_TIMEOUT, (I8*)&buffer, &buflen );
if( IFXSUCCESS( rc ) )
rReceiveTimeout = buffer;
return rc;
}
IFXRESULT CIFXInternetReadBufferX::SetReceiveTimeout(const U32 receiveTimeout)
{
IFXRESULT rc = IFX_OK;
const I8* pBuffer = (const I8*)&receiveTimeout;
U32 buflen = sizeof(receiveTimeout);
rc = m_session.SetOptions( IFXOSSOCKET_RECEIVE_TIMEOUT, pBuffer, buflen );
return rc;
}
IFXRESULT CIFXInternetReadBufferX::InitiateRead(
IFXCoreServices* pCoreServices,
IFXReadingCallback* pReadingCallback)
{
IFXRESULT rc = IFX_OK;
if (IFXSUCCESS(rc) && (NULL == pReadingCallback)) rc = IFX_E_INVALID_POINTER;
m_pCoreServices = pCoreServices;
IFXRELEASE(m_pReadingCallback);
m_pReadingCallback = pReadingCallback;
m_pReadingCallback->AddRef();
m_pReadingCallback->GetURLCount(m_URLs);
m_currentURL = 0;
IFXDECLARELOCAL(IFXScheduler, pScheduler);
if (IFXSUCCESS(rc))
rc = m_pCoreServices->GetScheduler(IID_IFXScheduler, (void**)&pScheduler);
IFXDECLARELOCAL(IFXSystemManager, pSysMgr);
if (IFXSUCCESS(rc))
rc = pScheduler->GetSystemManager(&pSysMgr);
IFXDECLARELOCAL(IFXTask, pReadTask);
if (IFXSUCCESS(rc))
rc = this->QueryInterface(IID_IFXTask, (void**) &pReadTask);
if (IFXSUCCESS(rc))
{
rc = pSysMgr->RegisterTask(
pReadTask, INTERNET_READ_TASK_PRIORITY,
NULL, &m_readTaskHandle);
}
return rc;
}
IFXRESULT CIFXInternetReadBufferX::Execute(IFXTaskData* pTaskData)
{
IFXRESULT rc = IFX_OK;
if (m_currentURL < m_URLs)
{
U8* pFile = NULL;
U64 totalSize = 0;
if (m_pReadBuffer == NULL)
{
IFXString sURL;
rc = m_pReadingCallback->GetURL(m_currentURL, sURL);
if(IFXSUCCESS( rc ))
{
IFXDECLARELOCAL(IFXStdio, pStdio);
U32 tmp = 0;
totalSize = 0;
if (IFXSUCCESS(sURL.FindSubstring(L"://", &tmp)))
rc = this->QueryInterface(IID_IFXReadBuffer, (void**)&m_pReadBuffer);
else
{
rc = IFXCreateComponent(
CID_IFXStdioReadBuffer,
IID_IFXReadBuffer,
(void**)&m_pReadBuffer);
totalSize = 1;
}
if (IFXSUCCESS(rc))
rc = m_pReadBuffer->QueryInterface(IID_IFXStdio, (void**)&pStdio);
if (IFXSUCCESS(rc))
rc = pStdio->Open( (IFXCHAR*)sURL.Raw() );
if (IFXFAILURE(rc))
{
// try another URL
IFXRELEASE(m_pReadBuffer);
m_currentURL++;
}
}
}
if (IFXSUCCESS(rc))
{
if (0 != totalSize) // local file
{
m_pReadBuffer->GetTotalSize(&totalSize);
pFile = (U8*)IFXAllocate( (size_t)totalSize );
if (NULL != pFile )
{
rc = m_pReadBuffer->Read( pFile, 0, (U32)totalSize );
}
else
{
rc = IFX_E_OUT_OF_MEMORY;
}
if( IFXSUCCESS( rc) )
{
rc = IFX_W_END_OF_FILE;
}
}
else
{
U64 readSize = 0;
U64 currentSize = 0;
while (IFX_OK == rc)
{
currentSize += BUFFER_BLOCK_SIZE;
readSize = m_readPosition;
pFile = (U8*)IFXReallocate( pFile, (size_t)currentSize );
if (pFile != NULL)
{
rc = m_pReadBuffer->Read(
pFile+readSize,
readSize,
BUFFER_BLOCK_SIZE );
}
else
{
rc = IFX_E_OUT_OF_MEMORY;
break;
}
}
if (rc == IFX_E_END_OF_FILE)
{
totalSize = m_readPosition;
pFile = (U8*)IFXReallocate(pFile, (size_t)totalSize);
rc = IFX_W_END_OF_FILE;
}
}
if (rc == IFX_W_END_OF_FILE)
{
IFXDECLARELOCAL(IFXStdio, pStdio);
rc = m_pReadBuffer->QueryInterface(IID_IFXStdio, (void**)&pStdio);
if (IFXSUCCESS(rc))
pStdio->Close();
IFXRELEASE(m_pReadBuffer);
/**
@todo Dangerous pass of pFile buffer allocated here. It will be
deallocated in CIFXImageTools.
*/
m_pReadingCallback->AcceptSuccess(m_currentURL, pFile, (U32)totalSize);
pFile = NULL; // deleting is left to the m_pReadingCallback
totalSize = 0;
IFXDECLARELOCAL(IFXScheduler, pScheduler);
m_pCoreServices->GetScheduler(IID_IFXScheduler, (void**)&pScheduler);
IFXDECLARELOCAL(IFXSystemManager, pSysMgr);
pScheduler->GetSystemManager(&pSysMgr);
pSysMgr->UnregisterTask(m_readTaskHandle);
m_readTaskHandle = IFXTASK_HANDLE_INVALID;
}
}
}
else
{
m_pReadingCallback->AcceptFailure(IFX_E_CANNOT_FIND);
IFXDECLARELOCAL(IFXScheduler, pScheduler);
m_pCoreServices->GetScheduler(IID_IFXScheduler, (void**)&pScheduler);
IFXDECLARELOCAL(IFXSystemManager, pSysMgr);
pScheduler->GetSystemManager(&pSysMgr);
pSysMgr->UnregisterTask(m_readTaskHandle);
m_readTaskHandle = IFXTASK_HANDLE_INVALID;
}
// If one of the URL in the URL list is not valid this is okay, try another one
if (rc == IFX_E_INVALID_FILE)
rc = IFX_OK;
return rc;
}
| 21.385435 | 81 | 0.684551 | alemuntoni |
089ba1beb32f6574bc5d3300b4fd914258f8b778 | 294 | cpp | C++ | 3_OOP/LyThuyet-T6/Bai-3/main.cpp | SummerSad/HCMUS-Lectures | b376e144e2601a73684e2ff437ab5c94a943909c | [
"MIT"
] | 8 | 2020-05-11T09:48:40.000Z | 2022-03-28T13:43:27.000Z | 3_OOP/LyThuyet-T6/Bai-3/main.cpp | SummerSad/HCMUS-Lectures | b376e144e2601a73684e2ff437ab5c94a943909c | [
"MIT"
] | null | null | null | 3_OOP/LyThuyet-T6/Bai-3/main.cpp | SummerSad/HCMUS-Lectures | b376e144e2601a73684e2ff437ab5c94a943909c | [
"MIT"
] | 4 | 2021-04-13T04:01:50.000Z | 2021-12-10T01:12:15.000Z | #include "Xe.h"
#include <iostream>
using namespace std;
int main(void)
{
XeMay a;
a.themHang(10);
a.themXang(200);
a.chay(100);
cout << a.xang() << endl;
XeTai b;
b.themHang(1000);
b.themXang(100);
b.chay(1000);
cout << b.hetXang() << endl;
cout << b.xang() << endl;
return 0;
}
| 14 | 29 | 0.608844 | SummerSad |
089bc39c3595d84a74de45116f1380f4ba67c094 | 3,340 | cpp | C++ | src/visual-scripting/processors/logical/gates/XorProcessor.cpp | inexorgame/entity-system | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 19 | 2018-10-11T09:19:48.000Z | 2020-04-19T16:36:58.000Z | src/visual-scripting/processors/logical/gates/XorProcessor.cpp | inexorgame-obsolete/entity-system-inactive | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 132 | 2018-07-28T12:30:54.000Z | 2020-04-25T23:05:33.000Z | src/visual-scripting/processors/logical/gates/XorProcessor.cpp | inexorgame-obsolete/entity-system-inactive | 230a6f116fb02caeace79bc9b32f17fe08687c36 | [
"MIT"
] | 3 | 2019-03-02T16:19:23.000Z | 2020-02-18T05:15:29.000Z | #include "XorProcessor.hpp"
#include <type-system/types/logical/gates/Xor.hpp>
#include <utility>
namespace inexor::visual_scripting {
using namespace inexor::entity_system;
using namespace inexor::entity_system::type_system;
using Xor = entity_system::type_system::Xor;
using EntityTypePtrOpt = std::optional<EntityTypePtr>;
using EntityAttributeInstancePtrOptional = std::optional<std::shared_ptr<EntityAttributeInstance>>;
XorProcessor::XorProcessor(EntityTypeManagerPtr entity_type_manager, EntityInstanceManagerPtr entity_instance_manager, LogManagerPtr log_manager)
: Processor(), LifeCycleComponent(), entity_type_manager(std::move(entity_type_manager)), entity_instance_manager(std::move(entity_instance_manager)), log_manager(std::move(log_manager))
{
}
XorProcessor::~XorProcessor() = default;
void XorProcessor::init()
{
log_manager->register_logger(LOGGER_NAME);
init_processor();
}
void XorProcessor::init_processor()
{
EntityTypePtrOpt o_ent_type = entity_type_manager->get_entity_type(Xor::TYPE_NAME);
if (o_ent_type.has_value()) {
this->entity_type = o_ent_type.value();
entity_instance_manager->register_on_created(this->entity_type->get_GUID(), shared_from_this());
entity_instance_manager->register_on_deleted(this->entity_type->get_GUID(), shared_from_this());
} else {
spdlog::get(LOGGER_NAME)->error("Failed to initialize processor {}: Entity type does not exist", Xor::TYPE_NAME);
}
}
std::string XorProcessor::get_component_name()
{
return "XorProcessor";
}
void XorProcessor::on_entity_instance_created(EntityInstancePtr entity_instance)
{
make_signals(entity_instance);
}
void XorProcessor::on_entity_instance_deleted(const xg::Guid &type_GUID, const xg::Guid &inst_GUID)
{
// Disconnect observers with execution method
// Delete observer for each input atttribute of the entity instance
// TODO: remove / clear signal
// signals[inst_GUID].clear
}
void XorProcessor::make_signals(const EntityInstancePtr &entity_instance)
{
spdlog::get(LOGGER_NAME)->debug("Initializing processor XOR for newly created entity instance {} of type {}", entity_instance->get_GUID().str(), entity_instance->get_entity_type()->get_type_name());
auto o_xor_input_1 = entity_instance->get_attribute_instance(Xor::INPUT_1);
auto o_xor_input_2 = entity_instance->get_attribute_instance(Xor::INPUT_2);
auto o_xor_result = entity_instance->get_attribute_instance(Xor::RESULT);
if (o_xor_input_1.has_value() && o_xor_input_2.has_value() && o_xor_result.has_value())
{
signals[entity_instance->get_GUID()] =
MakeSignal(With(o_xor_input_1.value()->value, o_xor_input_2.value()->value), [](DataValue xor_input_1, DataValue xor_input_2) { return DataValue(std::get<DataType::BOOL>(xor_input_1) ^ std::get<DataType::BOOL>(xor_input_2)); });
o_xor_result.value()->value = signals[entity_instance->get_GUID()];
} else
{
spdlog::get(LOGGER_NAME)
->error("Failed to initialize processor signals for entity instance {} of type {}: Missing one of these attributes: {} {} {}", entity_instance->get_GUID().str(), entity_instance->get_entity_type()->get_type_name(),
Xor::INPUT_1, Xor::INPUT_2, Xor::RESULT);
}
}
} // namespace inexor::visual_scripting
| 41.75 | 240 | 0.746108 | inexorgame |
089e0e7e7e56b1fb1d345ab36f0527b92210a877 | 287 | cpp | C++ | pointers/pointer6.cpp | manish1822510059/cpp-program | 03ec133857daf81163c621d4d54244409a94a200 | [
"Apache-2.0"
] | 1 | 2021-04-04T15:47:36.000Z | 2021-04-04T15:47:36.000Z | pointers/pointer6.cpp | manish1822510059/cpp-program | 03ec133857daf81163c621d4d54244409a94a200 | [
"Apache-2.0"
] | null | null | null | pointers/pointer6.cpp | manish1822510059/cpp-program | 03ec133857daf81163c621d4d54244409a94a200 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
int sum(int *a,int size){
int ans=0;
for(int i=0;i< size;i++)
{
ans+=a[i];
}
return ans;
}
int main(){
int a[10]={1,2,3,4,5,3,22,66,44,4};
cout<<sizeof(a)<<endl;
cout<<sum(a+2,3)<<endl;
} | 13.045455 | 36 | 0.484321 | manish1822510059 |
08a12b45156def996e2aef19400bc90cf52415e8 | 3,899 | cc | C++ | cplusplus/Tadpole5/tadpole/lex/test_token.cc | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 22 | 2015-05-18T07:04:36.000Z | 2021-08-02T03:01:43.000Z | cplusplus/Tadpole5/tadpole/lex/test_token.cc | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 1 | 2017-08-31T22:13:57.000Z | 2017-09-05T15:00:25.000Z | cplusplus/Tadpole5/tadpole/lex/test_token.cc | ASMlover/study | 5878f862573061f94c5776a351e30270dfd9966a | [
"BSD-2-Clause"
] | 6 | 2015-06-06T07:16:12.000Z | 2021-07-06T13:45:56.000Z | // Copyright (c) 2021 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "../common/harness.hh"
#include "token.hh"
TADPOLE_TEST(TadpoleToken) {
using TK = tadpole::TokenKind;
#define NEWTK2(k, s) tadpole::Token(k, s, 0)
#define NEWTK3(k, s, n) tadpole::Token(k, s, n)
#define TESTEQ(a, b) TADPOLE_CHECK_EQ(a, b)
#define TESTTK(k, s) do {\
auto t = NEWTK2(k, s);\
TESTEQ(t.kind(), k);\
TESTEQ(t.literal(), s);\
TESTEQ(t.lineno(), 0);\
} while (false)
#define TESTNUM(n) do {\
auto t = NEWTK2(TK::TK_NUMERIC, #n);\
TESTEQ(t.kind(), TK::TK_NUMERIC);\
TESTEQ(t.as_numeric(), n);\
TESTEQ(t.lineno(), 0);\
} while (false)
#define TESTSTR(s, n) do {\
auto t = NEWTK3(TK::TK_STRING, s, n);\
TESTEQ(t.kind(), TK::TK_STRING);\
TESTEQ(t.literal(), s);\
TESTEQ(t.lineno(), n);\
} while (false)
TESTTK(TK::TK_LPAREN, "(");
TESTTK(TK::TK_RPAREN, ")");
TESTTK(TK::TK_LBRACE, "{");
TESTTK(TK::TK_RBRACE, "}");
TESTTK(TK::TK_COMMA, ",");
TESTTK(TK::TK_MINUS, "-");
TESTTK(TK::TK_PLUS, "+");
TESTTK(TK::TK_SEMI, ";");
TESTTK(TK::TK_SLASH, "/");
TESTTK(TK::TK_STAR, "*");
TESTTK(TK::TK_EQ, "=");
TESTTK(TK::KW_FALSE, "false");
TESTTK(TK::KW_FN, "fn");
TESTTK(TK::KW_NIL, "nil");
TESTTK(TK::KW_TRUE, "true");
TESTTK(TK::KW_VAR, "var");
TESTTK(TK::TK_EOF, "EOF");
TESTTK(TK::TK_ERR, "ERR");
{
// test for IDENTIFIER
TESTTK(TK::TK_IDENTIFIER, "foo");
TESTTK(TK::TK_IDENTIFIER, "Foo");
TESTTK(TK::TK_IDENTIFIER, "_foo");
TESTTK(TK::TK_IDENTIFIER, "_Foo");
TESTTK(TK::TK_IDENTIFIER, "__foo");
TESTTK(TK::TK_IDENTIFIER, "__Foo");
TESTTK(TK::TK_IDENTIFIER, "foo_");
TESTTK(TK::TK_IDENTIFIER, "Foo_");
TESTTK(TK::TK_IDENTIFIER, "foo__");
TESTTK(TK::TK_IDENTIFIER, "Foo__");
TESTTK(TK::TK_IDENTIFIER, "__foo__");
TESTTK(TK::TK_IDENTIFIER, "__Foo__");
TESTTK(TK::TK_IDENTIFIER, "foo1");
TESTTK(TK::TK_IDENTIFIER, "Foo1");
}
{
// test for NUMERIC
TESTNUM(100);
TESTNUM(3.14);
TESTNUM(-100);
TESTNUM(-3.14);
}
{
// test for STRING
TESTSTR("Hello", 0);
TESTSTR("World", 1);
TESTSTR("This is String testing", 5);
TESTSTR("======================", 78);
TESTSTR("STRING testing for Token", 99);
}
#undef TESTSTR
#undef TESTNUM
#undef TESTTK
#undef TESTEQ
#undef NEWTK3
#undef NEWTK2
}
| 31.443548 | 71 | 0.630675 | ASMlover |
08a407ccc1dc7996c4ffa7e1f3bc64503b9af909 | 10,584 | cpp | C++ | src/mongo/logger/rotatable_file_writer.cpp | SunguckLee/real-mongodb | fef0e44fafc6d3709a84101327e7d2f54dd18d88 | [
"Apache-2.0"
] | 4 | 2018-02-06T01:53:12.000Z | 2018-02-20T01:47:36.000Z | src/mongo/logger/rotatable_file_writer.cpp | SunguckLee/real-mongodb | fef0e44fafc6d3709a84101327e7d2f54dd18d88 | [
"Apache-2.0"
] | null | null | null | src/mongo/logger/rotatable_file_writer.cpp | SunguckLee/real-mongodb | fef0e44fafc6d3709a84101327e7d2f54dd18d88 | [
"Apache-2.0"
] | 3 | 2018-02-06T01:53:18.000Z | 2021-07-28T09:48:15.000Z | /* Copyright 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/logger/rotatable_file_writer.h"
#include <boost/filesystem/operations.hpp>
#include <cstdio>
#include <fstream>
#include "mongo/base/string_data.h"
#include "mongo/util/mongoutils/str.h"
namespace mongo {
namespace logger {
namespace {
/**
* Renames file "oldName" to "newName".
*
* Both names are UTF-8 encoded.
*/
int renameFile(const std::string& oldName, const std::string& newName);
} // namespace
#ifdef _WIN32
namespace {
/**
* Converts UTF-8 encoded "utf8Str" to std::wstring.
*/
std::wstring utf8ToWide(StringData utf8Str) {
if (utf8Str.empty())
return std::wstring();
// A Windows wchar_t encoding of a unicode codepoint never takes more instances of wchar_t
// than the UTF-8 encoding takes instances of char.
std::unique_ptr<wchar_t[]> tempBuffer(new wchar_t[utf8Str.size()]);
tempBuffer[0] = L'\0';
int finalSize = MultiByteToWideChar(CP_UTF8, // Code page
0, // Flags
utf8Str.rawData(), // Input string
utf8Str.size(), // Count
tempBuffer.get(), // UTF-16 output buffer
utf8Str.size() // Buffer size in wide characters
);
// TODO(schwerin): fassert finalSize > 0?
return std::wstring(tempBuffer.get(), finalSize);
}
/**
* Minimal implementation of a std::streambuf for writing to Win32 files via HANDLEs.
*
* We require this implementation and the std::ostream subclass below to handle the following:
* (1) Opening files for shared-delete access, so that open file handles may be renamed.
* (2) Opening files with non-ASCII characters in their names.
*/
class Win32FileStreambuf : public std::streambuf {
MONGO_DISALLOW_COPYING(Win32FileStreambuf);
public:
Win32FileStreambuf();
virtual ~Win32FileStreambuf();
bool open(StringData fileName, bool append);
bool is_open() {
return _fileHandle != INVALID_HANDLE_VALUE;
}
private:
virtual std::streamsize xsputn(const char* s, std::streamsize count);
virtual int_type overflow(int_type ch = traits_type::eof());
HANDLE _fileHandle;
};
/**
* Minimal implementation of a stream to Win32 files.
*/
class Win32FileOStream : public std::ostream {
MONGO_DISALLOW_COPYING(Win32FileOStream);
public:
/**
* Constructs an instance, opening "fileName" in append or truncate mode according to
* "append".
*/
Win32FileOStream(const std::string& fileName, bool append) : std::ostream(&_buf), _buf() {
if (!_buf.open(fileName, append)) {
setstate(failbit);
}
}
virtual ~Win32FileOStream() {}
private:
Win32FileStreambuf _buf;
};
Win32FileStreambuf::Win32FileStreambuf() : _fileHandle(INVALID_HANDLE_VALUE) {}
Win32FileStreambuf::~Win32FileStreambuf() {
if (is_open()) {
CloseHandle(_fileHandle); // TODO(schwerin): Should we check for failure?
}
}
bool Win32FileStreambuf::open(StringData fileName, bool append) {
_fileHandle = CreateFileW(utf8ToWide(fileName).c_str(), // lpFileName
GENERIC_WRITE, // dwDesiredAccess
FILE_SHARE_DELETE | FILE_SHARE_READ, // dwShareMode
NULL, // lpSecurityAttributes
OPEN_ALWAYS, // dwCreationDisposition
FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttributes
NULL // hTemplateFile
);
if (INVALID_HANDLE_VALUE == _fileHandle)
return false;
LARGE_INTEGER zero;
zero.QuadPart = 0LL;
if (append) {
if (SetFilePointerEx(_fileHandle, zero, NULL, FILE_END)) {
return true;
}
} else {
if (SetFilePointerEx(_fileHandle, zero, NULL, FILE_BEGIN) && SetEndOfFile(_fileHandle)) {
return true;
}
}
// TODO(schwerin): Record error info?
CloseHandle(_fileHandle);
return false;
}
// Called when strings are written to ostream
std::streamsize Win32FileStreambuf::xsputn(const char* s, std::streamsize count) {
DWORD totalBytesWritten = 0;
while (count > totalBytesWritten) {
DWORD bytesWritten;
if (!WriteFile(_fileHandle, s, count - totalBytesWritten, &bytesWritten, NULL)) {
break;
}
totalBytesWritten += bytesWritten;
}
return totalBytesWritten;
}
// Overflow is called for single character writes to the ostream
Win32FileStreambuf::int_type Win32FileStreambuf::overflow(int_type ch) {
if (ch == traits_type::eof())
return ~ch; // Returning traits_type::eof() => failure, anything else => success.
char toPut = static_cast<char>(ch);
if (1 == xsputn(&toPut, 1))
return ch;
return traits_type::eof();
}
} // namespace
#endif
RotatableFileWriter::RotatableFileWriter() : _stream(nullptr) {}
RotatableFileWriter::Use::Use(RotatableFileWriter* writer)
: _writer(writer), _lock(writer->_mutex) {}
Status RotatableFileWriter::Use::setFileName(const std::string& name, bool append) {
_writer->_fileName = name;
return _openFileStream(append);
}
Status RotatableFileWriter::Use::rotate(bool renameOnRotate, const std::string& renameTarget) {
if (_writer->_stream) {
_writer->_stream->flush();
if (renameOnRotate) {
try {
if (boost::filesystem::exists(renameTarget)) {
return Status(
ErrorCodes::FileRenameFailed,
mongoutils::str::stream() << "Renaming file " << _writer->_fileName
<< " to "
<< renameTarget
<< " failed; destination already exists");
}
} catch (const std::exception& e) {
return Status(
ErrorCodes::FileRenameFailed,
mongoutils::str::stream() << "Renaming file " << _writer->_fileName << " to "
<< renameTarget
<< " failed; Cannot verify whether destination "
"already exists: "
<< e.what());
}
boost::system::error_code ec;
boost::filesystem::rename(_writer->_fileName, renameTarget, ec);
if (ec) {
return Status(ErrorCodes::FileRenameFailed,
mongoutils::str::stream() << "Failed to rename \""
<< _writer->_fileName
<< "\" to \""
<< renameTarget
<< "\": "
<< ec.message());
// TODO(schwerin): Make errnoWithDescription() available in the logger library, and
// use it here.
}
}
}
return _openFileStream(false);
}
Status RotatableFileWriter::Use::status() {
if (!_writer->_stream) {
return Status(ErrorCodes::FileNotOpen,
mongoutils::str::stream() << "File \"" << _writer->_fileName
<< "\" not open");
}
if (_writer->_stream->fail()) {
return Status(ErrorCodes::FileStreamFailed,
mongoutils::str::stream() << "File \"" << _writer->_fileName
<< "\" in failed state");
}
return Status::OK();
}
Status RotatableFileWriter::Use::_openFileStream(bool append) {
using std::swap;
#ifdef _WIN32
std::unique_ptr<std::ostream> newStream(new Win32FileOStream(_writer->_fileName, append));
#else
std::ios::openmode mode = std::ios::out;
if (append) {
mode |= std::ios::app;
} else {
mode |= std::ios::trunc;
}
std::unique_ptr<std::ostream> newStream(new std::ofstream(_writer->_fileName.c_str(), mode));
#endif
if (newStream->fail()) {
return Status(ErrorCodes::FileNotOpen, "Failed to open \"" + _writer->_fileName + "\"");
}
swap(_writer->_stream, newStream);
return status();
}
} // namespace logger
} // namespace mongo
| 37.399293 | 100 | 0.558579 | SunguckLee |
08a4e32ddc96af4c433751993c60590e552592fe | 2,682 | cc | C++ | native_client_sdk/src/libraries/nacl_io/passthroughfs/real_node.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | native_client_sdk/src/libraries/nacl_io/passthroughfs/real_node.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | native_client_sdk/src/libraries/nacl_io/passthroughfs/real_node.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2014 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 "nacl_io/passthroughfs/real_node.h"
#include <errno.h>
#include "nacl_io/kernel_handle.h"
#include "nacl_io/kernel_wrap_real.h"
namespace nacl_io {
RealNode::RealNode(Filesystem* filesystem, int real_fd, bool close_on_destroy)
: Node(filesystem),
real_fd_(real_fd),
close_on_destroy_(close_on_destroy)
{
}
void RealNode::Destroy() {
if (close_on_destroy_)
_real_close(real_fd_);
real_fd_ = -1;
}
// Normal read/write operations on a file
Error RealNode::Read(const HandleAttr& attr,
void* buf,
size_t count,
int* out_bytes) {
*out_bytes = 0;
int64_t new_offset;
int err = _real_lseek(real_fd_, attr.offs, 0, &new_offset);
if (err && err != ESPIPE)
return err;
size_t nread;
err = _real_read(real_fd_, buf, count, &nread);
if (err)
return err;
*out_bytes = static_cast<int>(nread);
return 0;
}
Error RealNode::Write(const HandleAttr& attr,
const void* buf,
size_t count,
int* out_bytes) {
//nacl_io_log("Real::Write\n");
int err;
*out_bytes = 0;
int64_t new_offset;
err = _real_lseek(real_fd_, attr.offs, 0, &new_offset);
if (err && err != ESPIPE)
return err;
size_t nwrote;
err = _real_write(real_fd_, buf, count, &nwrote);
if (err)
return err;
*out_bytes = static_cast<int>(nwrote);
return 0;
}
Error RealNode::FTruncate(off_t size) {
// TODO(binji): what to do here?
return ENOSYS;
}
Error RealNode::GetDents(size_t offs,
struct dirent* pdir,
size_t count,
int* out_bytes) {
size_t nread;
int err = _real_getdents(real_fd_, pdir, count, &nread);
if (err)
return err;
return nread;
}
Error RealNode::GetStat(struct stat* stat) {
int err = _real_fstat(real_fd_, stat);
if (err)
return err;
return 0;
}
Error RealNode::Isatty() {
#ifdef __GLIBC__
// isatty is not yet hooked up to the IRT interface under glibc.
return ENOTTY;
#else
int result = 0;
int err = _real_isatty(real_fd_, &result);
if (err)
return err;
return 0;
#endif
}
Error RealNode::MMap(void* addr,
size_t length,
int prot,
int flags,
size_t offset,
void** out_addr) {
*out_addr = addr;
int err = _real_mmap(out_addr, length, prot, flags, real_fd_, offset);
if (err)
return err;
return 0;
}
}
| 22.537815 | 78 | 0.61223 | Fusion-Rom |
08a5be3c183f278f696ea14de23bd5c64a885845 | 2,203 | hpp | C++ | src/actor/context/Context.hpp | SpeedXer/Nebula | 62f55ab2f45f7e95580b800ef351da9b3073becf | [
"MIT"
] | null | null | null | src/actor/context/Context.hpp | SpeedXer/Nebula | 62f55ab2f45f7e95580b800ef351da9b3073becf | [
"MIT"
] | 1 | 2019-12-31T01:10:26.000Z | 2019-12-31T01:10:26.000Z | src/actor/context/Context.hpp | wincsb/Nebula | 70a7baf24d17ae59a0f2788af45887fc2b1092df | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Project: Nebula
* @file Context.hpp
* @brief
* @author Bwar
* @date: 2019年2月16日
* @note
* Modify history:
******************************************************************************/
#ifndef SRC_ACTOR_CONTEXT_HPP_
#define SRC_ACTOR_CONTEXT_HPP_
#include "actor/DynamicCreator.hpp"
#include "actor/Actor.hpp"
namespace neb
{
class ActorBuilder;
/**
* @brief Actor上下文信息
* @note Actor上下文信息用于保存Actor(主要是Step,也可用于Session)运行
* 过程中的上下信息存储和数据共享。
* Context由Actor(可以是Cmd、Module、Step、Chain)创建,并由创建者
* Actor和传递使用者Actor之间共享,框架不登记和持有;当没有一个Actor持有
* Context时,std::shared_ptr<Context>引用计数为0将自动回收。
* 比如Cmd收到一个消息,后续需要若干个Step才完成全部操作,在最后一个
* Step中给请求方发送响应,那么最后一个Step需要获取Cmd当时收到的请求上下
* 文,而最后一个Step可能不是Cmd所创建的,一种实现方式是将上下文信息顺着
* Step链条赋值传递(因为前面的Step执行完毕可能会被销毁,不能用引用传递)
* 下去,这样会导致多次内存拷贝。Context的存在是为了减少这种不必要的复制,
* Context由框架管理,Step只需传递Context的引用。
* 从Context基类派生出业务自己的Context类可以用于Step间自定义数据的共
* 享(当然,Session类也可以达到同样目的,区别在于GetSession()需要传入
* SessionId才能获取到Session,GetContext()则不需要传参即可获取)。什么时
* 候用Context?建议是同一个Chain(共同完成一个操作的Step执行链)的上
* 下文信息和数据共享用Context,其他情况用Session。
*/
class Context: public Actor
{
public:
Context();
Context(std::shared_ptr<SocketChannel> pChannel);
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
virtual ~Context();
/**
* @brief 动态处理链上下文操作完成
* @note 一次客户端请求可能需要若干步骤(Step)才能完成,当处理完成时,
* 对于预定义的静态请求处理链,通常会由最后一个步骤(Step)给客户端发响
* 应,响应信息通常来自于各步骤存储于Context的数据。然而,对于通过配置
* 完成的动态请求处理链,最后一个步骤通常是未知的,如果想要由最后一个步
* 骤发送响应,那么无论处理链有多少个步骤,都需要固定最后一个步骤,这是
* 不合理的,配置动态处理链的时候也容易出错。因此,在Context中引入一个
* Done()方法,把给客户端的响应放在Done()方法里,系统在处理链调度完最后
* 一个节点处理完成时调用Done()方法将整个动态处理链的响应结果发给客户端,
* 那样动态处理链的Block节点顺序只跟链的业务逻辑相关,而无需固定最后一个
* 步骤。注意,该方法只适用于配置的动态处理链,预定义的静态处理链无需实
* 现此方法,所以该方法是实现为空的方法而非纯虚方法。
*/
virtual void Done()
{
}
std::shared_ptr<SocketChannel> GetChannel()
{
return(m_pChannel);
}
private:
std::shared_ptr<SocketChannel> m_pChannel;
friend class ActorBuilder;
};
} /* namespace neb */
#endif /* SRC_ACTOR_CONTEXT_HPP_ */
| 27.5375 | 80 | 0.679074 | SpeedXer |
08a8b25904d305e39dceace1ce1e0c6d96131f5d | 112 | hpp | C++ | FirstOrderLogic/libfol-basictypes/variable.hpp | s3ponia/FOL-parser | 5cbfc1bf02acae78104238781b9c5c4e71ffe925 | [
"MIT"
] | null | null | null | FirstOrderLogic/libfol-basictypes/variable.hpp | s3ponia/FOL-parser | 5cbfc1bf02acae78104238781b9c5c4e71ffe925 | [
"MIT"
] | null | null | null | FirstOrderLogic/libfol-basictypes/variable.hpp | s3ponia/FOL-parser | 5cbfc1bf02acae78104238781b9c5c4e71ffe925 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
namespace fol::types {
using Variable = std::string;
} // namespace fol::types
| 16 | 29 | 0.705357 | s3ponia |
08a91a5be4c4d09cf056247a5d2fc20c3c35850d | 13,908 | cpp | C++ | libOSR/src/OSRUnity.cpp | snowymo/OnlineSurfaceReconstruction | 2f44e292c69a16a9d8fe1f292a92396a652a8b06 | [
"BSD-3-Clause"
] | null | null | null | libOSR/src/OSRUnity.cpp | snowymo/OnlineSurfaceReconstruction | 2f44e292c69a16a9d8fe1f292a92396a652a8b06 | [
"BSD-3-Clause"
] | null | null | null | libOSR/src/OSRUnity.cpp | snowymo/OnlineSurfaceReconstruction | 2f44e292c69a16a9d8fe1f292a92396a652a8b06 | [
"BSD-3-Clause"
] | null | null | null | #include "dllwrapper/OSRUnity.h"
#include "osr/common.h"
#include "osr/Colors.h"
//#include "gui/ScanRenderer.h"
#include <stdio.h>
osr::Data* CreateOSRData()
{
// std::streambuf *psbuf;
// std::ofstream filestr;
// remove("test.txt");
// filestr.open("test.txt", std::ios::app);
// psbuf = filestr.rdbuf(); // get file's streambuf
// std::cout.rdbuf(psbuf);
//
// std::cout << "bf CreateOSRData\n";
osr::Data *d = new osr::Data();
//d->meshSettings.setScale(5.0);
std::cout << "CreateOSRData\n";
/* filestr.close();*/
return d;
}
osr::Scan* AddScan(osr::Data* osrData, Vector3* vertices, LABColor* colors, unsigned int* faces, float* transform, int verCnt, int faceCnt)
{
// std::streambuf *psbuf;
// std::ofstream filestr;
// filestr.open("testa.txt", std::ios::app);
// psbuf = filestr.rdbuf(); // get file's streambuf
// std::cout.rdbuf(psbuf);
std::cout << "AddScan\tresize(3," << verCnt << ")\n";
osr::Matrix3Xf V = osr::Matrix3Xf();
V.resize(3, verCnt);
memcpy_s(V.data(), 3 * verCnt * 4, vertices, 3 * verCnt * 4); // float=4
osr::Matrix3Xf N = osr::Matrix3Xf();
N.resize(3, 0);
// osr::Matrix3Xuc C = osr::Matrix3Xuc();
// C.resize(3, verCnt);
// for (int i = 0; i < verCnt; i++) {
// C(0, i) = colors[i].r;
// C(1, i) = colors[i].g;
// C(2, i) = colors[i].b;
// }
osr::Matrix3Xus C = osr::Matrix3Xus();
C.resize(3, verCnt);
// for (int i = 0; i < verCnt; i++) {
// C(0, i) = (unsigned short)(colors[i].r) * 255;
// C(1, i) = (unsigned short)(colors[i].g) * 255;
// C(2, i) = (unsigned short)(colors[i].b) * 255;
// C.col(i) = osr::RGBToLab(C.col(i));
// }
memcpy_s(C.data(), 3 * verCnt * 2, colors, 3 * verCnt * 2); // ushort=2
// int i = 0;
// std::cout << "C.cols(" << i << ")" << C.col(i) << " by " <<colors[i].r << " " << colors[i].g << " " << colors[i].b << "\n";
// i = 100;
// std::cout << "C.cols(" << i << ")" << C.col(i) << " by " << colors[i].r << " " << colors[i].g << " " << colors[i].b << "\n";
//memcpy_s(C.data(), 3 * verCnt * 2, colors, 3 * verCnt * 2); // uchar = char = 2
osr::MatrixXu F = osr::MatrixXu();
F.resize(3, faceCnt);
memcpy_s(F.data(), 3 * faceCnt * 4, faces, 3 * faceCnt * 4); // uint = int = 4
//osr::MatrixXu F(faces);
Eigen::Matrix4f transform4f(transform);
Eigen::Affine3f transformMatrix(transform4f);
Eigen::Affine3f identityMatrix = Eigen::Affine3f::Identity();
std::cout << "AddScan\tbefore new scan\n";
osr::Scan* newscan = new osr::Scan(V, N, C, F, "lala" + std::to_string(V.cols()) , transformMatrix);
newscan->initialize();
std::cout << "AddScan\tafter new scan\n";
//osr::Scan* newscan = new osr::Scan(true);
//newscan->ScanUnity(V, N, C, F, "wu", transformMatrix);
osrData->AddScan(newscan);
//newscan->renderer = std::make_shared<osr::gui::ScanRenderer>();
std::cout << "AddScan\tinitialize()\n";
//filestr.close();
return newscan;
}
void DestroyOSRData(osr::Data* osrData)
{
delete osrData;
}
void Integrate(osr::Data* osrData, osr::Scan* scan)
{
// std::streambuf *psbuf;
// std::ofstream filestr;
// filestr.open("testi.txt", std::ios::out | std::ios::app);
// psbuf = filestr.rdbuf(); // get file's streambuf
// std::cout.rdbuf(psbuf);
std::cout << "IntegrateScan\tbefore IntegrateScan(scan);\n";
osrData->IntegrateScan(scan);
// do something similar to saveFineToPly -> generateFineMesh
osrData->extractedMesh.extractFineMemoryMesh(true);
osr::MatrixX4uc myTransC = osrData->extractedMesh.fvisitor.colors.transpose();
osr::MatrixX3f myTransV = osrData->extractedMesh.fvisitor.positions.transpose();
osr::MatrixXu myTransF = osrData->extractedMesh.fvisitor.indices.transpose();
splitFineMemMesh(myTransV, myTransF, myTransC,
osrData->extractedMesh.extractedSplittedVerts,
osrData->extractedMesh.extractedSplittedFaces,
osrData->extractedMesh.extractedSplittedColors, osrData->extractedMesh.splitBound);
//osrData->extractedMesh.saveFineToPLY("D:\\Scans\\integrated.ply", true);
// now actually I have a v pointer, c pointer, and a f pointer, also assign the amount of v and f
// it is still possible to have more than 65k v or f after integration, so let's use splitmesh func to generate a list of v/c/f pairs, and retrieve them by index
//osrData->extractedMesh.splitFineMemMesh(); // now everything is saved in extractedSplittedVerts, extractedSplittedColors, extractedSplittedFaces;
//filestr.close();
std::cout << "split into " << osrData->extractedMesh.extractedSplittedVerts.size() << " pieces and save to int" + std::to_string(myTransC.rows()) + ".ply\n";
// test
osrData->extractedMesh.saveFineToPLY("int" + std::to_string(myTransC.rows()) + ".ply");
}
float* Register(osr::Data* osrData, osr::Scan* scan)
{
// std::streambuf *psbuf;
// std::ofstream filestr;
// filestr.open("testr.txt", std::ios::app);
// psbuf = filestr.rdbuf(); // get file's streambuf
// std::cout.rdbuf(psbuf);
std::cout << "start register:\n";
float* d = new float[16];
if (scan != NULL) {
if (osrData->hierarchy.vertexCount() == 0)
return d;
std::cout << "hierarchy not zero\n";
osrData->RegisterScan(scan);
// return the changed transformation
d = scan->transform().data();
std::cout << "result:\t";
for (int i = 0; i < 16; i++)
std::cout << d[i] << "\t";
}
//filestr.close();
return d;
}
Vector3* GetIntegratedVerts(osr::Data* osrData, unsigned int& count)
{
// return float pointer of extractedMesh.verts
if (osrData == NULL)
return NULL;
count = (unsigned int)osrData->extractedMesh.fvisitor.positions.cols();
float* ret = (((osrData->extractedMesh).fvisitor.positions).data());
return (Vector3*)ret;
}
Vector3* GetIntegratedVertsByIdx(osr::Data* osrData, int index, unsigned int& count)
{
if (osrData == NULL)
return NULL;
count = (unsigned int)osrData->extractedMesh.extractedSplittedVerts[index].cols();
float* ret = (((osrData->extractedMesh).extractedSplittedVerts[index]).data());
return (Vector3*)ret;
}
Color32* GetIntegratedColors(osr::Data* osrData, unsigned int& count)
{
// return float pointer of extractedMesh.verts
if (osrData == NULL)
return NULL;
count = (unsigned int)osrData->extractedMesh.fvisitor.colors.cols();
unsigned char* ret = (((osrData->extractedMesh).fvisitor.colors).data());
return (Color32*)ret;
}
Color32* GetIntegratedColorsByIdx(osr::Data* osrData, int index, unsigned int& count)
{
// return float pointer of extractedMesh.verts
if (osrData == NULL)
return NULL;
count = (unsigned int)osrData->extractedMesh.extractedSplittedColors[index].cols();
unsigned char* ret = (((osrData->extractedMesh).extractedSplittedColors[index]).data());
return (Color32*)ret;
}
unsigned int * GetIntegratedIndices(osr::Data* osrData, unsigned int& count)
{
// return float pointer of extractedMesh.verts
if (osrData == NULL)
return NULL;
count = (unsigned int)osrData->extractedMesh.fvisitor.indices.cols();
return (((osrData->extractedMesh).fvisitor.indices).data());
}
unsigned int * GetIntegratedIndicesByIdx(osr::Data* osrData, int index, unsigned int& count)
{
// return float pointer of extractedMesh.verts
if (osrData == NULL)
return NULL;
count = (unsigned int)osrData->extractedMesh.extractedSplittedFaces[index].cols();
return (((osrData->extractedMesh).extractedSplittedFaces[index]).data());
}
int GetIntegrateAmount(osr::Data* osrData)
{
return osrData->extractedMesh.extractedSplittedColors.size();
}
osr::Scan* AddOldScan(osr::Data* osrData, Vector3* vertices, Color32* colors, unsigned int* faces, float* transform, int verCnt, int faceCnt)
{
// std::streambuf *psbuf;
// std::ofstream filestr;
// filestr.open("test.txt");
// psbuf = filestr.rdbuf(); // get file's streambuf
// std::cout.rdbuf(psbuf);
std::cout << "AddScan\tresize(3," << verCnt << ")\n";
osr::Matrix3Xf V = osr::Matrix3Xf();
V.resize(3, verCnt);
memcpy_s(V.data(), 3 * verCnt * 4, vertices, 3 * verCnt * 4); // float=4
osr::Matrix3Xf N = osr::Matrix3Xf();
N.resize(3, 0);
// osr::Matrix3Xuc C = osr::Matrix3Xuc();
// C.resize(3, verCnt);
// for (int i = 0; i < verCnt; i++) {
// C(0, i) = colors[i].r;
// C(1, i) = colors[i].g;
// C(2, i) = colors[i].b;
// }
osr::Matrix3Xus C = osr::Matrix3Xus();
C.resize(3, verCnt);
for (int i = 0; i < verCnt; i++) {
C(0, i) = (unsigned short)(colors[i].r) * 255;
C(1, i) = (unsigned short)(colors[i].g) * 255;
C(2, i) = (unsigned short)(colors[i].b) * 255;
C.col(i) = osr::RGBToLab(C.col(i));
}
//memcpy_s(C.data(), 3 * verCnt * 2, colors, 3 * verCnt * 2); // ushort=2
int i = 0;
std::cout << "C.cols(" << i << ")" << C.col(i) << " by " << colors[i].r << " " << colors[i].g << " " << colors[i].b << "\n";
i = 100;
std::cout << "C.cols(" << i << ")" << C.col(i) << " by " << colors[i].r << " " << colors[i].g << " " << colors[i].b << "\n";
//memcpy_s(C.data(), 3 * verCnt * 2, colors, 3 * verCnt * 2); // uchar = char = 2
osr::MatrixXu F = osr::MatrixXu();
F.resize(3, faceCnt);
memcpy_s(F.data(), 3 * faceCnt * 4, faces, 3 * faceCnt * 4); // uint = int = 4
//osr::MatrixXu F(faces);
Eigen::Matrix4f transform4f(transform);
Eigen::Affine3f transformMatrix(transform4f);
Eigen::Affine3f identityMatrix = Eigen::Affine3f::Identity();
std::cout << "AddScan\tbefore new scan\n";
osr::Scan* newscan = new osr::Scan(V, N, C, F, "lala", transformMatrix);
newscan->initialize();
std::cout << "AddScan\tafter new scan\n";
//osr::Scan* newscan = new osr::Scan(true);
//newscan->ScanUnity(V, N, C, F, "wu", transformMatrix);
osrData->AddScan(newscan);
std::cout << "AddScan\tafter addscan()\n";
//newscan->renderer = std::make_shared<osr::gui::ScanRenderer>();
//std::cout << "AddScan\tinitialize()\n";
//filestr.close();
return newscan;
}
// std::vector<Eigen::Matrix<float, Eigen::Dynamic, 3>> subVs;
// std::vector<Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic>> subFs;
// std::vector<Eigen::Matrix<unsigned char, 4, Eigen::Dynamic>> subCs;
void splitFineMemMesh(const Eigen::Matrix<float, Eigen::Dynamic, 3> & transV,
const Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic> & transF,
const Eigen::Matrix<unsigned char, Eigen::Dynamic, 4> & transC,
std::vector<Eigen::Matrix<float, 3, Eigen::Dynamic>>& subVs,
std::vector<Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic>>& subFs,
std::vector<Eigen::Matrix<unsigned char, 4, Eigen::Dynamic>>& subCs,
int bound/*=64995*/)
{
// clear up the splitted containers at the beginning
subVs.clear();
subCs.clear();
subFs.clear();
// triangle triangle adjacency
Eigen::MatrixXi TT;
//MatrixX3f transV = fvisitor.positions.transpose();
igl::triangle_triangle_adjacency(transF, TT);
// face discover to record if the face is already into the queue
//int *FD = new int[F.cols()]{ 0 };
Eigen::VectorXi FD = Eigen::VectorXi::Zero(transF.rows());
// face queue
std::queue<int> FQ;
bool isOverSize = false;
// set of face and vertex for current submesh
std::set<int> FS;
std::set<int> VS;
// if there is still face not being discovered.
while (!FD.isOnes()) {
// find the first non-one
int curIdx = findFirstZero(FD);
if (curIdx < 0) break;
// visit it
FQ.push(curIdx);
while (!FQ.empty()) {
int curFace = FQ.front();
FD(curFace) = 1;
FQ.pop();
//std::cout << "\ndealing " << curFace << " pushing neighbours ";
FS.insert(curFace);
for (int i = 0; i < transF.cols(); i++)
VS.insert(transF(curFace, i));
// get three adjacencies and push into the queue aka visit
for (int i = 0; i < transF.cols(); i++) {
int neighbour = TT(curFace, i);
// check if already discovered
if ((neighbour != -1) && (FD(neighbour) == 0)) {
FQ.push(neighbour);
FD(neighbour) = 2;
//std::cout << neighbour << "\t";
}
//std::cout << "\n";
}
// check the size of vertices and faces
if (FS.size() > bound || VS.size() > bound) {
isOverSize = true;
break;
}
}
if (isOverSize) {
splitHelper(FS, VS, transV, transF, transC, subVs, subFs, subCs);
isOverSize = false;
}
}
if (FS.size() > 0) {
splitHelper(FS, VS, transV, transF, transC, subVs, subFs, subCs);
}
}
int findFirstZero(Eigen::VectorXi v)
{
for (int i = 0; i < v.rows(); i++)
if (v[i] == 0)
return i;
return -1;
}
void splitHelper(std::set<int> &FS, std::set<int> &VS,
const Eigen::Matrix<float, Eigen::Dynamic, 3> & transV,
const Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic> & transF,
const Eigen::Matrix<unsigned char, Eigen::Dynamic, 4> & transC,
std::vector<Eigen::Matrix<float, 3, Eigen::Dynamic>>& subVs,
std::vector<Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic>>& subFs,
std::vector<Eigen::Matrix<unsigned char, 4, Eigen::Dynamic>>& subCs)
{
// deal with current submesh, turn set of faces to MatrixXd
Eigen::Matrix<float, Eigen::Dynamic, 3> transsubV;
Eigen::Matrix<unsigned char, Eigen::Dynamic, 4> transsubC;
Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic> transsubF(FS.size(), transF.cols());
Eigen::Matrix<uint32_t, Eigen::Dynamic, Eigen::Dynamic> transresF(FS.size(), transF.cols());
int i = 0;
for (std::set<int>::iterator it = FS.begin(); it != FS.end(); ++it, i++) {
transsubF.row(i) = transF.row(*it);
}
Eigen::VectorXi UJ;
igl::remove_unreferenced(transV, transsubF, transsubV, transresF, UJ);
igl::remove_unreferenced(transC, transsubF, transsubC, transresF, UJ);
subVs.push_back(transsubV.transpose());
subCs.push_back(transsubC.transpose());
subFs.push_back(transresF.transpose());
FS.clear();
VS.clear();
}
void SetSplitBound(osr::Data* osrData, int bound)
{
osrData->extractedMesh.splitBound = bound;
}
void SetScale(osr::Data* osrData, float scale)
{
osrData->meshSettings.setScale(scale);
}
void SetMaxRegError(osr::Data* osrData, float maxError)
{
osrData->meshSettings.setMaxRegistrationError(maxError);
}
| 32.194444 | 162 | 0.649195 | snowymo |
08ab76ca3c0ca3f8ab82aa7833aa8cd8883d7e82 | 7,091 | cpp | C++ | test/rocprim/test_thread.cpp | stanleytsang-amd/rocPRIM | 1a4135dfc43f90f465c336a551bccbe359d40f11 | [
"MIT"
] | null | null | null | test/rocprim/test_thread.cpp | stanleytsang-amd/rocPRIM | 1a4135dfc43f90f465c336a551bccbe359d40f11 | [
"MIT"
] | null | null | null | test/rocprim/test_thread.cpp | stanleytsang-amd/rocPRIM | 1a4135dfc43f90f465c336a551bccbe359d40f11 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2020 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.
#include "common_test_header.hpp"
// required rocprim headers
#include <rocprim/intrinsics/thread.hpp>
#include "test_utils.hpp"
template<
unsigned int BlockSizeX,
unsigned int BlockSizeY,
unsigned int BlockSizeZ
>
struct params
{
static constexpr unsigned int block_size_x = BlockSizeX;
static constexpr unsigned int block_size_y = BlockSizeY;
static constexpr unsigned int block_size_z = BlockSizeZ;
};
template<class Params>
class RocprimThreadTests : public ::testing::Test {
public:
using params = Params;
};
typedef ::testing::Types<
params<32, 1, 1>,
params<64, 1, 1>,
params<128, 1, 1>,
params<256, 1, 1>,
params<512, 1, 1>,
params<1024, 1, 1>,
params<16, 2, 1>,
params<32, 2, 1>,
params<64, 2, 1>,
params<128, 2, 1>,
params<256, 2, 1>,
params<512, 2, 1>,
params<8, 2, 2>,
params<16, 2, 2>,
params<32, 2, 2>,
params<64, 2, 2>,
params<128, 2, 2>,
params<256, 2, 2>
> Params;
TYPED_TEST_CASE(RocprimThreadTests, Params);
template<
unsigned int BlockSizeX,
unsigned int BlockSizeY,
unsigned int BlockSizeZ
>
__global__
__launch_bounds__(1024, ROCPRIM_DEFAULT_MIN_WARPS_PER_EU)
void flat_id_kernel(unsigned int* device_output)
{
unsigned int thread_id = rocprim::flat_block_thread_id<BlockSizeX, BlockSizeY, BlockSizeZ>();
device_output[thread_id] = thread_id;
}
TYPED_TEST(RocprimThreadTests, FlatBlockThreadID)
{
using Type = unsigned int;
constexpr size_t block_size_x = TestFixture::params::block_size_x;
constexpr size_t block_size_y = TestFixture::params::block_size_y;
constexpr size_t block_size_z = TestFixture::params::block_size_z;
constexpr size_t block_size = block_size_x * block_size_y * block_size_z;
// Given block size not supported
if(block_size > test_utils::get_max_block_size() || (block_size & (block_size - 1)) != 0)
{
return;
}
for(size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++)
{
unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count];
SCOPED_TRACE(testing::Message() << "with seed= " << seed_value);
// Generate data
std::vector<Type> output(block_size, 0);
// Calculate expected results on host
std::vector<Type> expected(block_size, 0);
for(size_t i = 0; i < block_size; i++)
{
expected[i] = i;
}
// Preparing device
Type* device_output;
HIP_CHECK(hipMalloc(&device_output, block_size * sizeof(typename decltype(output)::value_type)));
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(
flat_id_kernel<
block_size_x, block_size_y, block_size_z
>
),
dim3(1), dim3(block_size_x, block_size_y, block_size_z), 0, 0,
device_output
);
// Reading results from device
HIP_CHECK(
hipMemcpy(
output.data(), device_output,
output.size() * sizeof(typename decltype(output)::value_type),
hipMemcpyDeviceToHost
)
);
// Validating results
ASSERT_NO_FATAL_FAILURE(test_utils::assert_eq(output, expected));
HIP_CHECK(hipFree(device_output));
}
}
template<
unsigned int BlockSizeX,
unsigned int BlockSizeY,
unsigned int BlockSizeZ
>
__global__
__launch_bounds__(1024, ROCPRIM_DEFAULT_MIN_WARPS_PER_EU)
void block_id_kernel(unsigned int* device_output)
{
unsigned int block_id = rocprim::flat_block_id<BlockSizeX, BlockSizeY, BlockSizeZ>();
if(hipThreadIdx_x)
{
device_output[block_id] = block_id;
}
}
TYPED_TEST(RocprimThreadTests, FlatBlockID)
{
using Type = unsigned int;
constexpr size_t block_size_x = TestFixture::params::block_size_x;
constexpr size_t block_size_y = TestFixture::params::block_size_y;
constexpr size_t block_size_z = TestFixture::params::block_size_z;
constexpr size_t block_size = block_size_x * block_size_y * block_size_z;
const size_t size = block_size * block_size;
const auto grid_size = size / block_size;
// Given block size not supported
if(block_size > test_utils::get_max_block_size() || (block_size & (block_size - 1)) != 0)
{
return;
}
for(size_t seed_index = 0; seed_index < random_seeds_count + seed_size; seed_index++)
{
unsigned int seed_value = seed_index < random_seeds_count ? rand() : seeds[seed_index - random_seeds_count];
SCOPED_TRACE(testing::Message() << "with seed= " << seed_value);
// Generate data
std::vector<Type> output(grid_size, 0);
// Calculate expected results on host
std::vector<Type> expected(grid_size, 0);
for(size_t i = 0; i < grid_size; i++)
{
expected[i] = i;
}
// Preparing device
Type* device_output;
HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(typename decltype(output)::value_type)));
// Running kernel
hipLaunchKernelGGL(
HIP_KERNEL_NAME(
block_id_kernel<
block_size_x, block_size_y, block_size_z
>
),
dim3(block_size_x, block_size_y, block_size_z), dim3(block_size_x, block_size_y, block_size_z), 0, 0,
device_output
);
// Reading results from device
HIP_CHECK(
hipMemcpy(
output.data(), device_output,
output.size() * sizeof(typename decltype(output)::value_type),
hipMemcpyDeviceToHost
)
);
// Validating results
ASSERT_NO_FATAL_FAILURE(test_utils::assert_eq(output, expected));
HIP_CHECK(hipFree(device_output));
}
}
| 32.231818 | 117 | 0.659145 | stanleytsang-amd |
08ac132da4f1f72aa169fd338d6b87a257715ef8 | 3,843 | cc | C++ | src/xpu-0.1.5/xpu/net/udp_socket.cc | qbee-eu/qx-simulator | 4e795dafd87bd226cd228437a67f2c10db4bff0b | [
"Apache-2.0"
] | null | null | null | src/xpu-0.1.5/xpu/net/udp_socket.cc | qbee-eu/qx-simulator | 4e795dafd87bd226cd228437a67f2c10db4bff0b | [
"Apache-2.0"
] | null | null | null | src/xpu-0.1.5/xpu/net/udp_socket.cc | qbee-eu/qx-simulator | 4e795dafd87bd226cd228437a67f2c10db4bff0b | [
"Apache-2.0"
] | 2 | 2021-03-10T22:03:32.000Z | 2021-04-20T09:47:29.000Z |
udp_socket::udp_socket() throw (socket_exception) : active_socket(SOCK_DGRAM, IPPROTO_UDP)
{
set_broadcast();
}
udp_socket::udp_socket(unsigned short local_port) throw (socket_exception) : active_socket(SOCK_DGRAM, IPPROTO_UDP)
{
set_local_port(local_port);
set_broadcast();
}
udp_socket::udp_socket(const std::string &local_address,
unsigned short local_port) throw (socket_exception) : active_socket(SOCK_DGRAM, IPPROTO_UDP)
{
set_local_address_and_port(local_address, local_port);
set_broadcast();
}
void udp_socket::set_broadcast()
{
// If this fails, we'll hear about it when we try to send. This will allow
// system that cannot broadcast to continue if they don't plan to broadcast
int broadcast_permission = 1;
setsockopt(sock_desc,
SOL_SOCKET,
SO_BROADCAST,
(raw_type *) &broadcast_permission,
sizeof(broadcast_permission));
}
void udp_socket::disconnect() throw (socket_exception) {
sockaddr_in null_addr;
memset(&null_addr, 0, sizeof(null_addr));
null_addr.sin_family = AF_UNSPEC;
// try to disconnect
if (::connect(sock_desc, (sockaddr *) &null_addr, sizeof(null_addr)) < 0) {
#ifdef WIN32
if (errno != WSAEAFNOSUPPORT) {
#else
if (errno != EAFNOSUPPORT) {
#endif
throw socket_exception("disconnect failed (connect())", true);
}
}
}
void udp_socket::send_to(const void *buffer,
int buffer_len,
const std::string &foreign_address, unsigned short foreign_port) throw (socket_exception)
{
sockaddr_in dest_addr;
fill_addr(foreign_address, foreign_port, dest_addr);
// Write out the whole buffer as a single message.
if (sendto(sock_desc, (raw_type *) buffer, buffer_len, 0,
(sockaddr *) &dest_addr, sizeof(dest_addr)) != buffer_len) {
throw socket_exception("send failed (sendto())", true);
}
}
int udp_socket::recv_from(void *buffer, int buffer_len, std::string &source_address,
unsigned short &source_port) throw (socket_exception) {
sockaddr_in clnt_addr;
socklen_t addr_len = sizeof(clnt_addr);
int rtn;
if ((rtn = recvfrom(sock_desc, (raw_type *) buffer, buffer_len, 0,
(sockaddr *) &clnt_addr, (socklen_t *) &addr_len)) < 0) {
throw socket_exception("receive failed (recvfrom())", true);
}
source_address = inet_ntoa(clnt_addr.sin_addr);
source_port = ntohs(clnt_addr.sin_port);
return rtn;
}
void udp_socket::set_multicast_ttl(unsigned char multicast_ttl) throw (socket_exception) {
if (setsockopt(sock_desc, IPPROTO_IP, IP_MULTICAST_TTL,
(raw_type *) &multicast_ttl, sizeof(multicast_ttl)) < 0) {
throw socket_exception("multicast TTL set failed (setsockopt())", true);
}
}
void udp_socket::join_group(const std::string &multicast_group) throw (socket_exception) {
struct ip_mreq multicast_request;
multicast_request.imr_multiaddr.s_addr = inet_addr(multicast_group.c_str());
multicast_request.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sock_desc, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(raw_type *) &multicast_request,
sizeof(multicast_request)) < 0) {
throw socket_exception("multicast group join failed (setsockopt())", true);
}
}
void udp_socket::leave_group(const std::string &multicast_group) throw (socket_exception) {
struct ip_mreq multicast_request;
multicast_request.imr_multiaddr.s_addr = inet_addr(multicast_group.c_str());
multicast_request.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(sock_desc, IPPROTO_IP, IP_DROP_MEMBERSHIP,
(raw_type *) &multicast_request,
sizeof(multicast_request)) < 0) {
throw socket_exception("multicast group leave failed (setsockopt())", true);
}
}
| 32.567797 | 117 | 0.696591 | qbee-eu |
08ad68ed8a061fe0c92070d98e01f28801f24c23 | 541 | cpp | C++ | source/365.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/365.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/365.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 365.cpp
// LeetCode
//
// Created by Narikbi on 19.04.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <numeric>
#include <unordered_map>
#include <sstream>
#include <unordered_set>
using namespace std;
bool canMeasureWater(int x, int y, int z) {
return z == 0 || (z - x <= y && z % __gcd(x, y) == 0);
}
| 17.451613 | 58 | 0.656192 | narikbi |
08b0beb7e49b3a1f844dd83191613b7b0b37a0ab | 2,111 | cpp | C++ | src/Kalem_Hash_Checker.cpp | ferhatgec/kalem | 556fc8b3cb6946c6be5654aa44f7146832c14d78 | [
"MIT"
] | 5 | 2020-12-29T19:52:53.000Z | 2021-06-11T17:36:30.000Z | src/Kalem_Hash_Checker.cpp | ferhatgec/kalem | 556fc8b3cb6946c6be5654aa44f7146832c14d78 | [
"MIT"
] | null | null | null | src/Kalem_Hash_Checker.cpp | ferhatgec/kalem | 556fc8b3cb6946c6be5654aa44f7146832c14d78 | [
"MIT"
] | null | null | null | /* MIT License
#
# Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
# Distributed under the terms of the MIT License.
#
# */
#include <string>
#include <fstream>
#include <functional>
#include <sstream>
#include "../include/Kalem_Hash_Checker.hpp"
#include "../include/libs/FileSystemPlusPlus.hpp"
bool KalemHashChecker::HashInit(std::string file) {
std::string _data = fsplusplus::ReadFileWithReturn(file);
hash.hash = std::hash<std::string>{}(_data);
_data.erase();
if(fsplusplus::IsExistFile(fsplusplus::GetCurrentWorkingDir()
+ "/"
+ file
+ ".__kalem_hash_cache__")) {
const std::string old_hash = fsplusplus::ReadFileWithReturn(file
+ ".__kalem_hash_cache__");
// TODO: Implement size_t to string converter
std::stringstream temp_stream(old_hash);
std::size_t temp_hash;
temp_stream >> temp_hash;
if(hash.hash == temp_hash) {
return true;
} else {
return false;
}
} else {
return false;
}
return false;
}
void KalemHashChecker::HashCreate(std::string file) {
std::string _data = fsplusplus::ReadFileWithReturn(file);
hash.hash = std::hash<std::string>{}(_data);
_data.erase();
if(fsplusplus::IsExistFile(fsplusplus::GetCurrentWorkingDir()
+ "/"
+ file
+ ".__kalem_hash_cache__") == false) {
fsplusplus::CreateFile(file + ".__kalem_hash_cache__", std::to_string(hash.hash));
} else {
_data = fsplusplus::ReadFileWithReturn(file
+ ".__kalem_hash_cache__");
if(std::to_string(hash.hash) != _data) {
std::ofstream output_stream;
output_stream.open(fsplusplus::GetCurrentWorkingDir()
+ "/"
+ file
+ ".__kalem_hash_cache__", std::ofstream::trunc);
output_stream << std::to_string(hash.hash);
output_stream.close();
}
}
} | 27.064103 | 90 | 0.57082 | ferhatgec |
08b3ce0e16746a951c5b63cc25ca988acd273a75 | 13,128 | hpp | C++ | include/state_saver.hpp | Neargye/yacppl | 032d8c044c84e0942607220679ca2d4da48631bd | [
"MIT"
] | 10 | 2018-12-13T06:52:13.000Z | 2022-02-21T16:39:58.000Z | include/state_saver.hpp | Neargye/yacppl | 032d8c044c84e0942607220679ca2d4da48631bd | [
"MIT"
] | null | null | null | include/state_saver.hpp | Neargye/yacppl | 032d8c044c84e0942607220679ca2d4da48631bd | [
"MIT"
] | 1 | 2020-06-02T08:05:13.000Z | 2020-06-02T08:05:13.000Z | // _____ _ _ _____ _____
// / ____| | | | / ____| / ____|_ _
// | (___ | |_ __ _| |_ ___ | (___ __ ___ _____ _ __ | | _| |_ _| |_
// \___ \| __/ _` | __/ _ \ \___ \ / _` \ \ / / _ \ '__| | | |_ _|_ _|
// ____) | || (_| | || __/ ____) | (_| |\ V / __/ | | |____|_| |_|
// |_____/ \__\__,_|\__\___| |_____/ \__,_| \_/ \___|_| \_____|
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
// SPDX-License-Identifier: MIT
// Copyright (c) 2018 - 2021 Daniil Goncharov <neargye@gmail.com>.
//
// 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.
#ifndef NEARGYE_STATE_SAVER_HPP
#define NEARGYE_STATE_SAVER_HPP
// Sometimes a certain value has to change only for a limited scope.
// This class wrapper saves a copy of the current state of some object,
// and resets the object’s state at destruction time, undoing any change the object may have gone through.
// * saver_exit - saves the original variable value and restores on scope exit.
// * saver_fail - saves the original variable value and restores on scope exit when an exception has been thrown.
// * saver_success - saves the original variable value and restores on scope exit when no exceptions have been thrown.
// Interface of state_saver:
// * constructor state_saver(T& object) - construct state_saver with saved object.
// * dismiss() - dismiss restore on scope exit.
// * restore() - resets the object’s state. Requirements copy operator =.
// Requirements to saved object:
// * Object semantic (cannot be reference, function, ...).
// * Copy constructor.
// * operator= (no-throw one preferred).
// Throwable settings:
// STATE_SAVER_NO_THROW_CONSTRUCTIBLE requires nothrow constructible action.
// STATE_SAVER_MAY_THROW_RESTORE restore may throw exceptions.
// STATE_SAVER_NO_THROW_RESTORE requires noexcept restore.
// STATE_SAVER_SUPPRESS_THROW_RESTORE exceptions during restore will be suppressed.
// STATE_SAVER_CATCH_HANDLER exceptions handler. If STATE_SAVER_SUPPRESS_THROW_RESTORE is not defined, it will do nothing.
// Assignable settings:
// STATE_SAVER_FORCE_MOVE_ASSIGNABLE restore on scope exit will be move assigned.
// STATE_SAVER_FORCE_COPY_ASSIGNABLE restore on scope exit will be copy assigned.
#include <type_traits>
#if (defined(_MSC_VER) && _MSC_VER >= 1900) || ((defined(__clang__) || defined(__GNUC__)) && __cplusplus >= 201700L)
#include <exception>
#endif
#if !defined(STATE_SAVER_MAY_THROW_RESTORE) && !defined(STATE_SAVER_NO_THROW_RESTORE) && !defined(STATE_SAVER_SUPPRESS_THROW_RESTORE)
# define STATE_SAVER_MAY_THROW_RESTORE
#elif (defined(STATE_SAVER_MAY_THROW_RESTORE) + defined(STATE_SAVER_NO_THROW_RESTORE) + defined(STATE_SAVER_SUPPRESS_THROW_RESTORE)) > 1
# error Only one of STATE_SAVER_MAY_THROW_RESTORE and STATE_SAVER_NO_THROW_RESTORE and STATE_SAVER_SUPPRESS_THROW_RESTORE may be defined.
#endif
#if (defined(STATE_SAVER_FORCE_MOVE_ASSIGNABLE) + defined(STATE_SAVER_FORCE_COPY_ASSIGNABLE)) > 1
# error Only one of STATE_SAVER_FORCE_MOVE_ASSIGNABLE and STATE_SAVER_FORCE_COPY_ASSIGNABLE may be defined.
#endif
#if !defined(STATE_SAVER_CATCH_HANDLER)
# define STATE_SAVER_CATCH_HANDLER /* Suppress exception.*/
#endif
namespace nstd {
namespace detail {
#if defined(STATE_SAVER_SUPPRESS_THROW_RESTORE) && (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND))
# define NEARGYE_NOEXCEPT(...) noexcept
# define NEARGYE_TRY try {
# define NEARGYE_CATCH } catch (...) { SCOPE_GUARD_CATCH_HANDLER }
#else
# define NEARGYE_NOEXCEPT(...) noexcept(__VA_ARGS__)
# define NEARGYE_TRY
# define NEARGYE_CATCH
#endif
#if defined(_MSC_VER) && _MSC_VER < 1900
inline int uncaught_exceptions() noexcept {
return *(reinterpret_cast<int*>(static_cast<char*>(static_cast<void*>(_getptd())) + (sizeof(void*) == 8 ? 0x100 : 0x90)));
}
#elif (defined(__clang__) || defined(__GNUC__)) && __cplusplus < 201700L
struct __cxa_eh_globals;
extern "C" __cxa_eh_globals* __cxa_get_globals() noexcept;
inline int uncaught_exceptions() noexcept {
return static_cast<int>(*(reinterpret_cast<unsigned int*>(static_cast<char*>(static_cast<void*>(__cxa_get_globals())) + sizeof(void*))));
}
#else
inline int uncaught_exceptions() noexcept {
return std::uncaught_exceptions();
}
#endif
class on_exit_policy {
bool execute_;
public:
explicit on_exit_policy(bool execute) noexcept : execute_{execute} {}
void dismiss() noexcept {
execute_ = false;
}
bool should_execute() const noexcept {
return execute_;
}
};
class on_fail_policy {
int ec_;
public:
explicit on_fail_policy(bool execute) noexcept : ec_{execute ? uncaught_exceptions() : -1} {}
void dismiss() noexcept {
ec_ = -1;
}
bool should_execute() const noexcept {
return ec_ != -1 && ec_ < uncaught_exceptions();
}
};
class on_success_policy {
int ec_;
public:
explicit on_success_policy(bool execute) noexcept : ec_{execute ? uncaught_exceptions() : -1} {}
void dismiss() noexcept {
ec_ = -1;
}
bool should_execute() const noexcept {
return ec_ != -1 && ec_ >= uncaught_exceptions();
}
};
template <typename U, typename P>
class state_saver {
using T = typename std::remove_reference<U>::type;
#if defined(STATE_SAVER_FORCE_MOVE_ASSIGNABLE)
using assignable_t = T&&;
#elif defined(STATE_SAVER_FORCE_COPY_ASSIGNABLE)
using assignable_t = T&;
#else
using assignable_t = typename std::conditional<
std::is_nothrow_assignable<T&, T&&>::value ||
!std::is_assignable<T&, T&>::value ||
(!std::is_nothrow_assignable<T&, T&>::value && std::is_assignable<T&, T&&>::value),
T&&, T&>::type;
#endif
static_assert(!std::is_const<T>::value,
"state_saver requires not const type.");
static_assert(!std::is_rvalue_reference<U>::value && (std::is_lvalue_reference<U>::value || std::is_same<T, U>::value),
"state_saver requires lvalue type.");
static_assert(!std::is_array<T>::value,
"state_saver requires not array type.");
static_assert(!std::is_pointer<T>::value,
"state_saver requires not pointer type.");
static_assert(!std::is_function<T>::value,
"state_saver requires not function type.");
static_assert(std::is_constructible<T, T&>::value,
"state_saver requires copy constructible.");
static_assert(std::is_assignable<T&, assignable_t>::value,
"state_saver requires operator=.");
static_assert(std::is_same<P, on_exit_policy>::value || std::is_same<P, on_fail_policy>::value || std::is_same<P, on_success_policy>::value,
"state_saver requires on_exit_policy, on_fail_policy or on_success_policy.");
#if defined(STATE_SAVER_NO_THROW_RESTORE)
static_assert(std::is_nothrow_assignable<T&, assignable_t>::value,
"state_saver requires noexcept operator=.");
#endif
#if defined(STATE_SAVER_NO_THROW_CONSTRUCTIBLE)
static_assert(std::is_nothrow_constructible<T, T&>::value,
"state_saver requires nothrow constructible.");
#endif
P policy_;
T& previous_ref_;
T previous_value_;
public:
state_saver() = delete;
state_saver(const state_saver&) = delete;
state_saver(state_saver&&) = delete;
state_saver& operator=(const state_saver&) = delete;
state_saver& operator=(state_saver&&) = delete;
state_saver(T&&) = delete;
state_saver(const T&) = delete;
explicit state_saver(T& object) noexcept(std::is_nothrow_constructible<T, T&>::value)
: policy_{true},
previous_ref_{object},
previous_value_{object} {}
void dismiss() noexcept {
policy_.dismiss();
}
template <typename O = T>
auto restore() NEARGYE_NOEXCEPT(std::is_nothrow_assignable<O&, O&>::value) -> typename std::enable_if<std::is_same<T, O>::value && std::is_assignable<O&, O&>::value>::type {
static_assert(std::is_assignable<O&, O&>::value, "state_saver::restore requires copy operator=.");
#if defined(STATE_SAVER_NO_THROW_RESTORE)
static_assert(std::is_nothrow_assignable<O&, O&>::value, "state_saver::restore requires noexcept copy operator=.");
#endif
NEARGYE_TRY
previous_ref_ = previous_value_;
NEARGYE_CATCH
}
~state_saver() NEARGYE_NOEXCEPT(std::is_nothrow_assignable<T&, assignable_t>::value) {
if (policy_.should_execute()) {
NEARGYE_TRY
previous_ref_ = static_cast<assignable_t>(previous_value_);
NEARGYE_CATCH
}
}
};
#undef NEARGYE_NOEXCEPT
#undef NEARGYE_TRY
#undef NEARGYE_CATCH
} // namespace nstd::detail
template <typename U>
class saver_exit : public detail::state_saver<U, detail::on_exit_policy> {
public:
using detail::state_saver<U, detail::on_exit_policy>::state_saver;
};
template <typename U>
class saver_fail : public detail::state_saver<U, detail::on_fail_policy> {
public:
using detail::state_saver<U, detail::on_fail_policy>::state_saver;
};
template <typename U>
class saver_success : public detail::state_saver<U, detail::on_success_policy> {
public:
using detail::state_saver<U, detail::on_success_policy>::state_saver;
};
#if defined(__cpp_deduction_guides) && __cpp_deduction_guides >= 201611L
template <typename U>
saver_exit(U&) -> saver_exit<U>;
template <typename U>
saver_fail(U&) -> saver_fail<U>;
template <typename U>
saver_success(U&) -> saver_success<U>;
#endif
} // namespace nstd
// NEARGYE_MAYBE_UNUSED suppresses compiler warnings on unused entities, if any.
#if !defined(NEARGYE_MAYBE_UNUSED)
# if defined(__clang__)
# if (__clang_major__ * 10 + __clang_minor__) >= 39 && __cplusplus >= 201703L
# define NEARGYE_MAYBE_UNUSED [[maybe_unused]]
# else
# define NEARGYE_MAYBE_UNUSED __attribute__((__unused__))
# endif
# elif defined(__GNUC__)
# if __GNUC__ >= 7 && __cplusplus >= 201703L
# define NEARGYE_MAYBE_UNUSED [[maybe_unused]]
# else
# define NEARGYE_MAYBE_UNUSED __attribute__((__unused__))
# endif
# elif defined(_MSC_VER)
# if _MSC_VER >= 1911 && defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
# define NEARGYE_MAYBE_UNUSED [[maybe_unused]]
# else
# define NEARGYE_MAYBE_UNUSED __pragma(warning(suppress : 4100 4101 4189))
# endif
# else
# define NEARGYE_MAYBE_UNUSED
# endif
#endif
#if !defined(NEARGYE_STR_CONCAT)
# define NEARGYE_STR_CONCAT_(s1, s2) s1##s2
# define NEARGYE_STR_CONCAT(s1, s2) NEARGYE_STR_CONCAT_(s1, s2)
#endif
#if !defined(NEARGYE_COUNTER)
# if defined(__COUNTER__)
# define NEARGYE_COUNTER __COUNTER__
# elif defined(__LINE__)
# define NEARGYE_COUNTER __LINE__
# endif
#endif
#define NEARGYE_STATE_SAVER_WITH_(s, i) for (int i = 1; i--; s)
#define NEARGYE_STATE_SAVER_WITH(s) NEARGYE_STATE_SAVER_WITH_(s, NEARGYE_STR_CONCAT(NEARGYE_INTERNAL_OBJECT_, NEARGYE_COUNTER))
// SAVER_EXIT saves the original variable value and restores on scope exit.
#define MAKE_SAVER_EXIT(name, x) ::nstd::saver_exit<decltype(x)> name{x}
#define SAVER_EXIT(x) NEARGYE_MAYBE_UNUSED const MAKE_SAVER_EXIT(NEARGYE_STR_CONCAT(SAVER_EXIT_, NEARGYE_COUNTER), x)
#define WITH_SAVER_EXIT(x) NEARGYE_STATE_SAVER_WITH(::nstd::saver_exit<decltype(x)>{x})
// SAVER_FAIL saves the original variable value and restores on scope exit when an exception has been thrown.
#define MAKE_SAVER_FAIL(name, x) ::nstd::saver_fail<decltype(x)> name{x}
#define SAVER_FAIL(x) NEARGYE_MAYBE_UNUSED const MAKE_SAVER_FAIL(NEARGYE_STR_CONCAT(SAVER_FAIL_, NEARGYE_COUNTER), x)
#define WITH_SAVER_FAIL(x) NEARGYE_STATE_SAVER_WITH(::nstd::saver_fail<decltype(x)>{x})
// SAVER_SUCCESS saves the original variable value and restores on scope exit when no exceptions have been thrown.
#define MAKE_SAVER_SUCCESS(name, x) ::nstd::saver_success<decltype(x)> name{x}
#define SAVER_SUCCESS(x) NEARGYE_MAYBE_UNUSED const MAKE_SAVER_SUCCESS(NEARGYE_STR_CONCAT(SAVER_SUCCES_, NEARGYE_COUNTER), x)
#define WITH_SAVER_SUCCESS(x) NEARGYE_STATE_SAVER_WITH(::nstd::saver_success<decltype(x)>{x})
#endif // NEARGYE_STATE_SAVER_HPP
| 39.542169 | 175 | 0.722273 | Neargye |
08b3dc2d136c62283a6a80327a3071d99406c7ec | 1,223 | hpp | C++ | Spades Game/Game/Net/ClientEventHandler.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 6 | 2017-01-04T22:40:50.000Z | 2019-11-24T15:37:46.000Z | Spades Game/Game/Net/ClientEventHandler.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 1 | 2016-09-18T19:10:01.000Z | 2017-08-04T23:53:38.000Z | Spades Game/Game/Net/ClientEventHandler.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 2 | 2015-11-21T16:42:18.000Z | 2019-04-21T20:41:39.000Z | #ifndef CGE_CLIENT_EVENT_HANDLER_HPP
#define CGE_CLIENT_EVENT_HANDLER_HPP
#include "Game/Net/ServerEventProvider.hpp"
#include "Game/Net/NetEventListener.hpp"
namespace cge
{
class ClientEventHandler : public ServerEventProvider,
public NetEventListener
{
public:
ClientEventHandler(void);
virtual void fetchServerListMS(const std::string& username, const std::vector<std::string>& names, const std::vector<std::string>& ips, const std::vector<int>& ports,
const std::vector<int>& capacities, const std::vector<int>& numUsers, const std::vector<int>& numFriends);
virtual void fetchFriendServerListMS(const std::string& username, const std::vector<std::string>& names,
const std::vector<std::string>& ips, const std::vector<int>& ports, const std::vector<int>& capacities,
const std::vector<int>& numUsers, const std::vector<std::string>& serverNames);
virtual void serverFullMS(const std::string& username, const std::string& serverName, const std::string& ip, int port, bool full);
virtual void logoutPlayerMS(const std::string& username);
virtual void lostConnectionCS();
virtual void connectionFailedCS();
virtual void isClientAliveSC();
virtual ~ClientEventHandler(void);
};
}
#endif
| 47.038462 | 168 | 0.762878 | jmasterx |
08b906f340ee58501dd0bb709eb314dc44601c53 | 10,371 | cc | C++ | google-tv-pairing-protocol/cpp/tests/polo/wire/protobuf/protobufwireadaptertest.cc | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | google-tv-pairing-protocol/cpp/tests/polo/wire/protobuf/protobufwireadaptertest.cc | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | google-tv-pairing-protocol/cpp/tests/polo/wire/protobuf/protobufwireadaptertest.cc | Keneral/ae1 | e5bbf05e3a01b449f33cca14c5ce8048df45624b | [
"Unlicense"
] | null | null | null | // Copyright 2012 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.
// Tests for ProtobufWireAdapter.
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <polo/util/poloutil.h>
#include <polo/wire/protobuf/protobufwireadapter.h>
#include "polo/wire/mocks.h"
using ::testing::InSequence;
using ::testing::Mock;
using ::testing::Return;
using ::testing::StrictMock;
namespace polo {
namespace wire {
namespace protobuf {
// A mock MessageListener.
class MockMessageListener : public pairing::message::MessageListener {
MOCK_METHOD1(OnConfigurationMessage,
void(const pairing::message::ConfigurationMessage& message));
MOCK_METHOD1(OnConfigurationAckMessage,
void(const pairing::message::ConfigurationAckMessage& message));
MOCK_METHOD1(OnOptionsMessage,
void(const pairing::message::OptionsMessage& message));
MOCK_METHOD1(OnPairingRequestMessage,
void(const pairing::message::PairingRequestMessage& message));
MOCK_METHOD1(OnPairingRequestAckMessage,
void(const pairing::message::PairingRequestAckMessage& message));
MOCK_METHOD1(OnSecretMessage,
void(const pairing::message::SecretMessage& message));
MOCK_METHOD1(OnSecretAckMessage,
void(const pairing::message::SecretAckMessage& message));
MOCK_METHOD1(OnError, void(pairing::PoloError error));
};
// Test fixture for ProtobufWireAdapter tests.
class ProtobufWireAdapterTest : public ::testing::Test {
public:
ProtobufWireAdapterTest() : interface_(), adapter_(&interface_) {}
protected:
virtual void SetUp() {
adapter_.set_listener(&listener_);
}
// Expects that a call to GetNextMessage will be made which triggers a read
// for the 4 byte preamble.
void ExpectGetPreamble() {
EXPECT_CALL(interface_, Receive(4));
adapter_.GetNextMessage();
}
// Expects that a call to GetNextMessage will be made, and the preamble will
// be read containing the given message size. This will trigger another read
// for the full message.
void ExpectReadPreamble(uint32_t message_size) {
ExpectGetPreamble();
unsigned char* size_bytes;
util::PoloUtil::IntToBigEndianBytes(message_size, size_bytes);
EXPECT_CALL(interface_, Receive(message_size));
adapter_.OnBytesReceived(
std::vector<uint8_t>(size_bytes, size_bytes + 4));
}
// Expects that the given OuterMessage will be sent over the interface.
void ExpectSend(const OuterMessage& message) {
std::string outer_string = message.SerializeAsString();
unsigned char* size_bytes;
util::PoloUtil::IntToBigEndianBytes(outer_string.length(), size_bytes);
std::vector<unsigned char> data(outer_string.length() + 4);
unsigned char* buffer = &data[0];
memcpy(buffer, size_bytes, 4);
memcpy((buffer + 4), &outer_string[0], outer_string.length());
EXPECT_CALL(interface_, Send(data));
}
StrictMock<MockWireInterface> interface_;
StrictMock<MockMessageListener> listener_;
ProtobufWireAdapter adapter_;
};
// Verifies that a call to GetNextMessage will trigger a read for the 4 byte
// preamble.
TEST_F(ProtobufWireAdapterTest, GetNextMessage) {
ExpectGetPreamble();
}
// Verifies that once the preamble is received, a read will be triggered for
// the full message.
TEST_F(ProtobufWireAdapterTest, OnBytesReceivedPreamble) {
InSequence sequence;
ExpectReadPreamble(0xAABBCCDD);
}
// Verifies that a ConfigurationMessage is successfully sent over the interface.
TEST_F(ProtobufWireAdapterTest, SendConfigurationMessage) {
InSequence sequence;
Configuration proto;
proto.set_client_role(Options_RoleType_ROLE_TYPE_OUTPUT);
proto.mutable_encoding()->set_type(
Options_Encoding_EncodingType_ENCODING_TYPE_QRCODE);
proto.mutable_encoding()->set_symbol_length(64);
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_CONFIGURATION);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::ConfigurationMessage message(
encoding::EncodingOption(encoding::EncodingOption::kQRCode, 64),
pairing::message::OptionsMessage::kDisplayDevice);
adapter_.SendConfigurationMessage(message);
}
// Verifies that a ConfigurationAckMessage is successfully sent over the
// interface.
TEST_F(ProtobufWireAdapterTest, SendConfigurationAckMessage) {
InSequence sequence;
ConfigurationAck proto;
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_CONFIGURATION_ACK);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::ConfigurationAckMessage message;
adapter_.SendConfigurationAckMessage(message);
}
// Verifies that an OptionsMessage is successfully sent over the interface.
TEST_F(ProtobufWireAdapterTest, SendOptionsMessage) {
InSequence sequence;
Options proto;
proto.set_preferred_role(Options_RoleType_ROLE_TYPE_INPUT);
Options_Encoding* encoding = proto.add_input_encodings();
encoding->set_type(Options_Encoding_EncodingType_ENCODING_TYPE_NUMERIC);
encoding->set_symbol_length(16);
encoding = proto.add_input_encodings();
encoding->set_type(Options_Encoding_EncodingType_ENCODING_TYPE_ALPHANUMERIC);
encoding->set_symbol_length(32);
encoding = proto.add_output_encodings();
encoding->set_type(Options_Encoding_EncodingType_ENCODING_TYPE_HEXADECIMAL);
encoding->set_symbol_length(128);
encoding = proto.add_output_encodings();
encoding->set_type(Options_Encoding_EncodingType_ENCODING_TYPE_QRCODE);
encoding->set_symbol_length(512);
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_OPTIONS);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::OptionsMessage message;
message.set_protocol_role_preference(
pairing::message::OptionsMessage::kInputDevice);
// Note, the input and output encoding sets are sorted by complexity, so these
// should be in the same order as the encodings added to the proto above to
// ensure the assert matches.
message.AddInputEncoding(
encoding::EncodingOption(encoding::EncodingOption::kNumeric, 16));
message.AddInputEncoding(
encoding::EncodingOption(encoding::EncodingOption::kAlphaNumeric, 32));
message.AddOutputEncoding(
encoding::EncodingOption(encoding::EncodingOption::kHexadecimal, 128));
message.AddOutputEncoding(
encoding::EncodingOption(encoding::EncodingOption::kQRCode, 512));
adapter_.SendOptionsMessage(message);
}
// Verifies that a PairingRequestMessage is successfully sent over the
// interface.
TEST_F(ProtobufWireAdapterTest, SendPairingRequestMessage) {
InSequence sequence;
PairingRequest proto;
proto.set_client_name("foo-client");
proto.set_service_name("foo-service");
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_PAIRING_REQUEST);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::PairingRequestMessage message("foo-service", "foo-client");
adapter_.SendPairingRequestMessage(message);
}
// Verifies that a SendPairingRequestAckMesssage is successfully sent over the
// interface.
TEST_F(ProtobufWireAdapterTest, SendPairingRequestAckMessage) {
InSequence sequence;
PairingRequestAck proto;
proto.set_server_name("foo-server");
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_PAIRING_REQUEST_ACK);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::PairingRequestAckMessage message("foo-server");
adapter_.SendPairingRequestAckMessage(message);
}
// Verifies that a SecretMessage is successfully sent over the interface.
TEST_F(ProtobufWireAdapterTest, SendSecretMessage) {
InSequence sequence;
std::vector<unsigned char> secret(4);
secret[0] = 0xAA;
secret[1] = 0xBB;
secret[2] = 0xCC;
secret[3] = 0xDD;
Secret proto;
proto.set_secret(&secret[0], secret.size());
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_SECRET);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::SecretMessage message(secret);
adapter_.SendSecretMessage(message);
}
// Verifies that a SecretAckMessage is successfully sent over the interface.
TEST_F(ProtobufWireAdapterTest, SendSecretAckMessage) {
InSequence sequence;
std::vector<unsigned char> secret(4);
secret[0] = 0xAA;
secret[1] = 0xBB;
secret[2] = 0xCC;
secret[3] = 0xDD;
SecretAck proto;
proto.set_secret(&secret[0], secret.size());
OuterMessage outer;
outer.set_type(OuterMessage_MessageType_MESSAGE_TYPE_SECRET_ACK);
outer.set_payload(proto.SerializeAsString());
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_OK);
ExpectSend(outer);
pairing::message::SecretAckMessage message(secret);
adapter_.SendSecretAckMessage(message);
}
// Verifies that an ErrorMessage is successfully sent over the interface.
TEST_F(ProtobufWireAdapterTest, SendErrorMessage) {
InSequence sequence;
OuterMessage outer;
outer.set_protocol_version(1);
outer.set_status(OuterMessage_Status_STATUS_BAD_SECRET);
ExpectSend(outer);
adapter_.SendErrorMessage(pairing::kErrorInvalidChallengeResponse);
}
} // namespace protobuf
} // namespace wire
} // namespace polo
| 32.208075 | 80 | 0.773696 | Keneral |
08be2b29cbe58b463019d929c190fd62ce6dd37a | 2,238 | cpp | C++ | src/mlpack/methods/gmm/gmm_probability_main.cpp | NaxAlpha/mlpack-build | 1f0c1454d4b35eb97ff115669919c205cee5bd1c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2018-05-21T11:08:36.000Z | 2022-03-12T07:52:14.000Z | src/mlpack/methods/gmm/gmm_probability_main.cpp | okmegy/Mlpack | ac9abef3c1353f483ed1af42ba5a7432f291ca1a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/gmm/gmm_probability_main.cpp | okmegy/Mlpack | ac9abef3c1353f483ed1af42ba5a7432f291ca1a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file gmm_probability_main.cpp
* @author Ryan Curtin
*
* Given a GMM, calculate the probability of points coming from it.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/prereqs.hpp>
#include "gmm.hpp"
#include <mlpack/core/data/load.hpp>
#include <mlpack/core/data/save.hpp>
using namespace std;
using namespace mlpack;
using namespace mlpack::gmm;
PROGRAM_INFO("GMM Probability Calculator",
"This program calculates the probability that given points came from a "
"given GMM (that is, P(X | gmm)). The GMM is specified with the "
"--input_model_file option, and the points are specified with the "
"--input_file option. The output probabilities are stored in the file "
"specified by the --output_file option.");
PARAM_STRING_IN_REQ("input_model_file", "File containing input GMM.", "m");
PARAM_STRING_IN_REQ("input_file", "File containing points.", "i");
PARAM_STRING_OUT("output_file", "File to save calculated probabilities to.",
"o");
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
const string inputFile = CLI::GetParam<string>("input_file");
const string inputModelFile = CLI::GetParam<string>("input_model_file");
const string outputFile = CLI::GetParam<string>("output_file");
if (!CLI::HasParam("output_file"))
Log::Warn << "--output_file (-o) is not specified;"
<< "no results will be saved!" << endl;
// Get the GMM and the points.
GMM gmm;
data::Load(inputModelFile, "gmm", gmm);
arma::mat dataset;
data::Load(inputFile, dataset);
// Now calculate the probabilities.
arma::rowvec probabilities(dataset.n_cols);
for (size_t i = 0; i < dataset.n_cols; ++i)
probabilities[i] = gmm.Probability(dataset.unsafe_col(i));
// And save the result.
if (CLI::HasParam("output_file"))
data::Save(CLI::GetParam<string>("output_file"), probabilities);
else
Log::Warn << "--output_file was not specified, so no output will be saved!"
<< endl;
}
| 34.430769 | 79 | 0.703753 | NaxAlpha |
08bec8b14d8f7c6c750f4cab4eafaed88a6db114 | 2,028 | cpp | C++ | wide-IDE/cpwin.cpp | nickmain/Amzi-Prolog | 6ce17a494fc93f3f27e02896a6a5ff7ac4b33c3e | [
"MIT"
] | 86 | 2016-04-16T06:35:44.000Z | 2021-04-14T05:46:32.000Z | wide-IDE/cpwin.cpp | nickmain/Amzi-Prolog | 6ce17a494fc93f3f27e02896a6a5ff7ac4b33c3e | [
"MIT"
] | 20 | 2021-05-09T20:54:54.000Z | 2021-05-14T13:12:05.000Z | wide-IDE/cpwin.cpp | nickmain/Amzi-Prolog | 6ce17a494fc93f3f27e02896a6a5ff7ac4b33c3e | [
"MIT"
] | 15 | 2016-04-16T19:10:45.000Z | 2020-11-04T04:07:21.000Z | //-----------------------------------------------------------
// Extended Windows Predicates, MFC version
//
#include "stdafx.h"
#include <direct.h>
#include <io.h>
#include "amzi.h"
#include "conview.h"
#include "proprog.h"
#include "cpwin.h"
/*
TF EXPFUNC p_keyb(ENGid);
PRED_INIT winPreds[] =
{
// keyboard predicates
{_T("keyb"), 1, p_keyb},
{NULL, 0, NULL}
};
TF EXPFUNC p_keyb(ENGid eid)
{
// get the ASCII value for the next key struck
// use the listener window's GetCh method
int a;
a = (int)(g_pConView->GetCh());
if (! lsUnifyParm(eid, 1, cINT, &a)) return FALSE;
return TRUE;
}
*/
///////////////////////////////////////////////////////////
// Utility Functions
//
void slashslash2(_TCHAR* sout, const _TCHAR* sin)
/* Any string of _TCHARacters sent to Prolog is read using the
Prolog reader, which interprets a backslash as an escape
_TCHARacter. So, this means if you really want a backslash,
such as in a file path, then it has to be a double
backslash. This function makes that conversion. */
{
while(*sin)
{
if (*sin == _T('\\'))
{
*sout++ = *sin;
*sout++ = *sin++;
}
else
*sout++ = *sin++;
}
*sout = *sin;
return;
}
void slashslash1(_TCHAR* s)
/* Same as slashslash2 except conversion is done in place.
Therefor, the input buffer must be large enough to handle
the expanded string. */
{
int nslash=0;
int len=0;
int i;
_TCHAR* s1;
_TCHAR* s2;
/* Count the slashes, then copy in place from right to
left so we don't write on ourself. */
s1 = s;
while(*s1)
{
len++;
if (*s1++ == _T('\\')) nslash++;
}
s2 = s + len + nslash;
s1 = s + len;
for(i=0; i<=len; i++)
{
if (*s1 == _T('\\'))
{
*s2-- = *s1;
*s2-- = *s1--;
}
else
*s2-- = *s1--;
}
return;
}
| 20.28 | 64 | 0.496055 | nickmain |
08c2f4a2a8b272af322be5139ca8ca252d73d27b | 270 | cpp | C++ | src/CountingBits.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | src/CountingBits.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | src/CountingBits.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "CountingBits.hpp"
vector<int> CountingBits::countBits(int num) {
vector<int> ret(num + 1, 0);
if (num == 0) return ret;
ret[1] = 1;
for (int i = 2; i <= num; i++)
ret[i] = (i & 0x1) ? ret[i / 2] + 1 : ret[i / 2];
return ret;
}
| 18 | 57 | 0.503704 | yanzhe-chen |
08c4acaa94e2e5a33936607e333c5e23ef529012 | 1,196 | cc | C++ | media/base/renderer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | media/base/renderer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | media/base/renderer.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2014 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/base/renderer.h"
#include "base/logging.h"
namespace media {
Renderer::Renderer() = default;
Renderer::~Renderer() = default;
void Renderer::SetCdm(CdmContext* cdm_context, CdmAttachedCB cdm_attached_cb) {
DLOG(WARNING) << "CdmContext is not supported.";
std::move(cdm_attached_cb).Run(false);
}
void Renderer::OnSelectedVideoTracksChanged(
const std::vector<DemuxerStream*>& enabled_tracks,
base::OnceClosure change_completed_cb) {
DLOG(WARNING) << "Track changes are not supported.";
std::move(change_completed_cb).Run();
}
void Renderer::OnEnabledAudioTracksChanged(
const std::vector<DemuxerStream*>& enabled_tracks,
base::OnceClosure change_completed_cb) {
DLOG(WARNING) << "Track changes are not supported.";
std::move(change_completed_cb).Run();
}
void Renderer::SetPreservesPitch(bool preserves_pitch) {
// Not supported by most renderers.
}
void Renderer::SetAutoplayInitiated(bool autoplay_initiated) {
// Not supported by most renderers.
}
} // namespace media
| 28.47619 | 79 | 0.747492 | zealoussnow |
c09311a05b90dcbe5f105bc66a448033f05f385d | 9,278 | cpp | C++ | externals/wasm-compiler/llvm/tools/llvm-lto2/llvm-lto2.cpp | JaminChan/eos_win | c03e57151cfe152d0d3120abb13226f4df74f37e | [
"MIT"
] | 427 | 2018-05-29T14:21:02.000Z | 2022-03-16T03:17:54.000Z | llvm/tools/llvm-lto2/llvm-lto2.cpp | squirrel-explorer/eagleeye-ios | 9569e1d3cf2759490557337dd940e88907517052 | [
"Apache-2.0"
] | 25 | 2018-07-23T08:34:15.000Z | 2021-11-05T07:13:36.000Z | llvm/tools/llvm-lto2/llvm-lto2.cpp | squirrel-explorer/eagleeye-ios | 9569e1d3cf2759490557337dd940e88907517052 | [
"Apache-2.0"
] | 52 | 2018-07-19T19:57:32.000Z | 2022-03-11T16:05:38.000Z | //===-- llvm-lto2: test harness for the resolution-based LTO interface ----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This program takes in a list of bitcode files, links them and performs
// link-time optimization according to the provided symbol resolutions using the
// resolution-based LTO interface, and outputs one or more object files.
//
// This program is intended to eventually replace llvm-lto which uses the legacy
// LTO interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/LTO/Caching.h"
#include "llvm/CodeGen/CommandFlags.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/Threading.h"
using namespace llvm;
using namespace lto;
using namespace object;
static cl::opt<char>
OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
"(default = '-O2')"),
cl::Prefix, cl::ZeroOrMore, cl::init('2'));
static cl::opt<char> CGOptLevel(
"cg-opt-level",
cl::desc("Codegen optimization level (0, 1, 2 or 3, default = '2')"),
cl::init('2'));
static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
cl::desc("<input bitcode files>"));
static cl::opt<std::string> OutputFilename("o", cl::Required,
cl::desc("Output filename"),
cl::value_desc("filename"));
static cl::opt<std::string> CacheDir("cache-dir", cl::desc("Cache Directory"),
cl::value_desc("directory"));
static cl::opt<std::string> OptPipeline("opt-pipeline",
cl::desc("Optimizer Pipeline"),
cl::value_desc("pipeline"));
static cl::opt<std::string> AAPipeline("aa-pipeline",
cl::desc("Alias Analysis Pipeline"),
cl::value_desc("aapipeline"));
static cl::opt<bool> SaveTemps("save-temps", cl::desc("Save temporary files"));
static cl::opt<bool>
ThinLTODistributedIndexes("thinlto-distributed-indexes", cl::init(false),
cl::desc("Write out individual index and "
"import files for the "
"distributed backend case"));
static cl::opt<int> Threads("thinlto-threads",
cl::init(llvm::heavyweight_hardware_concurrency()));
static cl::list<std::string> SymbolResolutions(
"r",
cl::desc("Specify a symbol resolution: filename,symbolname,resolution\n"
"where \"resolution\" is a sequence (which may be empty) of the\n"
"following characters:\n"
" p - prevailing: the linker has chosen this definition of the\n"
" symbol\n"
" l - local: the definition of this symbol is unpreemptable at\n"
" runtime and is known to be in this linkage unit\n"
" x - externally visible: the definition of this symbol is\n"
" visible outside of the LTO unit\n"
"A resolution for each symbol must be specified."),
cl::ZeroOrMore);
static cl::opt<std::string> OverrideTriple(
"override-triple",
cl::desc("Replace target triples in input files with this triple"));
static cl::opt<std::string> DefaultTriple(
"default-triple",
cl::desc(
"Replace unspecified target triples in input files with this triple"));
static void check(Error E, std::string Msg) {
if (!E)
return;
handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
errs() << "llvm-lto: " << Msg << ": " << EIB.message().c_str() << '\n';
});
exit(1);
}
template <typename T> static T check(Expected<T> E, std::string Msg) {
if (E)
return std::move(*E);
check(E.takeError(), Msg);
return T();
}
static void check(std::error_code EC, std::string Msg) {
check(errorCodeToError(EC), Msg);
}
template <typename T> static T check(ErrorOr<T> E, std::string Msg) {
if (E)
return std::move(*E);
check(E.getError(), Msg);
return T();
}
int main(int argc, char **argv) {
InitializeAllTargets();
InitializeAllTargetMCs();
InitializeAllAsmPrinters();
InitializeAllAsmParsers();
cl::ParseCommandLineOptions(argc, argv, "Resolution-based LTO test harness");
// FIXME: Workaround PR30396 which means that a symbol can appear
// more than once if it is defined in module-level assembly and
// has a GV declaration. We allow (file, symbol) pairs to have multiple
// resolutions and apply them in the order observed.
std::map<std::pair<std::string, std::string>, std::list<SymbolResolution>>
CommandLineResolutions;
for (std::string R : SymbolResolutions) {
StringRef Rest = R;
StringRef FileName, SymbolName;
std::tie(FileName, Rest) = Rest.split(',');
if (Rest.empty()) {
llvm::errs() << "invalid resolution: " << R << '\n';
return 1;
}
std::tie(SymbolName, Rest) = Rest.split(',');
SymbolResolution Res;
for (char C : Rest) {
if (C == 'p')
Res.Prevailing = true;
else if (C == 'l')
Res.FinalDefinitionInLinkageUnit = true;
else if (C == 'x')
Res.VisibleToRegularObj = true;
else
llvm::errs() << "invalid character " << C << " in resolution: " << R
<< '\n';
}
CommandLineResolutions[{FileName, SymbolName}].push_back(Res);
}
std::vector<std::unique_ptr<MemoryBuffer>> MBs;
Config Conf;
Conf.DiagHandler = [](const DiagnosticInfo &DI) {
DiagnosticPrinterRawOStream DP(errs());
DI.print(DP);
errs() << '\n';
exit(1);
};
Conf.CPU = MCPU;
Conf.Options = InitTargetOptionsFromCodeGenFlags();
Conf.MAttrs = MAttrs;
if (auto RM = getRelocModel())
Conf.RelocModel = *RM;
Conf.CodeModel = CMModel;
if (SaveTemps)
check(Conf.addSaveTemps(OutputFilename + "."),
"Config::addSaveTemps failed");
// Run a custom pipeline, if asked for.
Conf.OptPipeline = OptPipeline;
Conf.AAPipeline = AAPipeline;
Conf.OptLevel = OptLevel - '0';
switch (CGOptLevel) {
case '0':
Conf.CGOptLevel = CodeGenOpt::None;
break;
case '1':
Conf.CGOptLevel = CodeGenOpt::Less;
break;
case '2':
Conf.CGOptLevel = CodeGenOpt::Default;
break;
case '3':
Conf.CGOptLevel = CodeGenOpt::Aggressive;
break;
default:
llvm::errs() << "invalid cg optimization level: " << CGOptLevel << '\n';
return 1;
}
Conf.OverrideTriple = OverrideTriple;
Conf.DefaultTriple = DefaultTriple;
ThinBackend Backend;
if (ThinLTODistributedIndexes)
Backend = createWriteIndexesThinBackend("", "", true, "");
else
Backend = createInProcessThinBackend(Threads);
LTO Lto(std::move(Conf), std::move(Backend));
bool HasErrors = false;
for (std::string F : InputFilenames) {
std::unique_ptr<MemoryBuffer> MB = check(MemoryBuffer::getFile(F), F);
std::unique_ptr<InputFile> Input =
check(InputFile::create(MB->getMemBufferRef()), F);
std::vector<SymbolResolution> Res;
for (const InputFile::Symbol &Sym : Input->symbols()) {
auto I = CommandLineResolutions.find({F, Sym.getName()});
if (I == CommandLineResolutions.end()) {
llvm::errs() << argv[0] << ": missing symbol resolution for " << F
<< ',' << Sym.getName() << '\n';
HasErrors = true;
} else {
Res.push_back(I->second.front());
I->second.pop_front();
if (I->second.empty())
CommandLineResolutions.erase(I);
}
}
if (HasErrors)
continue;
MBs.push_back(std::move(MB));
check(Lto.add(std::move(Input), Res), F);
}
if (!CommandLineResolutions.empty()) {
HasErrors = true;
for (auto UnusedRes : CommandLineResolutions)
llvm::errs() << argv[0] << ": unused symbol resolution for "
<< UnusedRes.first.first << ',' << UnusedRes.first.second
<< '\n';
}
if (HasErrors)
return 1;
auto AddStream =
[&](size_t Task) -> std::unique_ptr<lto::NativeObjectStream> {
std::string Path = OutputFilename + "." + utostr(Task);
std::error_code EC;
auto S = llvm::make_unique<raw_fd_ostream>(Path, EC, sys::fs::F_None);
check(EC, Path);
return llvm::make_unique<lto::NativeObjectStream>(std::move(S));
};
auto AddFile = [&](size_t Task, StringRef Path) {
auto ReloadedBufferOrErr = MemoryBuffer::getFile(Path);
if (auto EC = ReloadedBufferOrErr.getError())
report_fatal_error(Twine("Can't reload cached file '") + Path + "': " +
EC.message() + "\n");
*AddStream(Task)->OS << (*ReloadedBufferOrErr)->getBuffer();
};
NativeObjectCache Cache;
if (!CacheDir.empty())
Cache = localCache(CacheDir, AddFile);
check(Lto.run(AddStream, Cache), "LTO::run failed");
}
| 33.738182 | 80 | 0.595279 | JaminChan |
c0934c3e35e6384d025f570650d814fc9101700a | 2,717 | hpp | C++ | ql/experimental/exoticoptions/writerextensibleoption.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 2 | 2021-12-12T01:27:45.000Z | 2022-01-25T17:44:12.000Z | ql/experimental/exoticoptions/writerextensibleoption.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 19 | 2020-11-23T08:36:10.000Z | 2022-03-28T10:06:53.000Z | ql/experimental/exoticoptions/writerextensibleoption.hpp | urgu00/QuantLib | fecce0abb0ff3d50da29c129f8f9e73176e20ab9 | [
"BSD-3-Clause"
] | 5 | 2020-06-04T15:19:22.000Z | 2020-06-18T08:24:37.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2011 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file writerextensibleoption.hpp
\brief Writer-extensible option
*/
#ifndef quantlib_writer_extensible_option_hpp
#define quantlib_writer_extensible_option_hpp
#include <ql/instruments/oneassetoption.hpp>
#include <ql/instruments/payoffs.hpp>
#include <ql/exercise.hpp>
namespace QuantLib {
//! Writer-extensible option
class WriterExtensibleOption : public OneAssetOption {
public:
class arguments;
class engine;
/*!
\param payoff1 The first payoff
\param exercise1 The first exercise date
\param payoff2 The payoff of the extended option
\param exercise2 The second exercise date
*/
WriterExtensibleOption(
const ext::shared_ptr<PlainVanillaPayoff>& payoff1,
const ext::shared_ptr<Exercise>& exercise1,
const ext::shared_ptr<PlainVanillaPayoff>& payoff2,
const ext::shared_ptr<Exercise>& exercise2);
// inspectors
ext::shared_ptr<Payoff> payoff2() { return payoff2_; }
ext::shared_ptr<Exercise> exercise2() { return exercise2_; };
// Instrument interface
bool isExpired() const;
void setupArguments(PricingEngine::arguments*) const;
private:
ext::shared_ptr<StrikedTypePayoff> payoff2_;
ext::shared_ptr<Exercise> exercise2_;
};
//! Additional arguments for writer-extensible option
class WriterExtensibleOption::arguments
: public OneAssetOption::arguments {
public:
void validate() const;
ext::shared_ptr<Payoff> payoff2;
ext::shared_ptr<Exercise> exercise2;
};
//! Base engine
class WriterExtensibleOption::engine :
public GenericEngine<WriterExtensibleOption::arguments,
WriterExtensibleOption::results> {};
}
#endif
| 35.285714 | 93 | 0.691204 | urgu00 |
c098c6c896dacd8d817ee0b9e36cc0605fc29ba7 | 3,834 | cpp | C++ | src/main/cpp/edu/rice/habanero/benchmarks/caf/caf_07_big.cpp | tud-ccc/savina | 914be6292f379a119751a8b5a38e35e6a99de69d | [
"MIT"
] | null | null | null | src/main/cpp/edu/rice/habanero/benchmarks/caf/caf_07_big.cpp | tud-ccc/savina | 914be6292f379a119751a8b5a38e35e6a99de69d | [
"MIT"
] | 1 | 2022-02-06T17:40:09.000Z | 2022-02-10T22:48:19.000Z | src/main/cpp/edu/rice/habanero/benchmarks/caf/caf_07_big.cpp | tud-ccc/savina | 914be6292f379a119751a8b5a38e35e6a99de69d | [
"MIT"
] | null | null | null | #include <iostream>
#include <random>
#include <fstream>
#include <stdlib.h>
#include "benchmark_runner.hpp"
using namespace std;
using namespace caf;
class config : public actor_system_config {
public:
int n = 20000;
int w = 120;
config() {
opt_group{custom_options_, "global"}
.add(n, "nnn,n", "number of pings")
.add(w, "www,w", "number of actors");
}
};
struct ping_msg {
int sender;
};
CAF_ALLOW_UNSAFE_MESSAGE_TYPE(ping_msg);
struct pong_msg {
int sender;
};
CAF_ALLOW_UNSAFE_MESSAGE_TYPE(pong_msg);
struct neighbor_msg {
vector<actor> neighbors;
};
CAF_ALLOW_UNSAFE_MESSAGE_TYPE(neighbor_msg);
using exit_msg_atom = atom_constant<atom("exit")>;
struct sink_actor_state {
int num_messages;
vector<actor> neighbors;
};
behavior sink_actor_fun(stateful_actor<sink_actor_state>* self,
int num_workers) {
self->state.num_messages = 0;
return {
[=](exit_msg_atom) {
auto& s = self->state;
++s.num_messages;
if (s.num_messages == num_workers) {
for (auto& loop_worker : s.neighbors) {
self->send(loop_worker, exit_msg_atom::value);
self->quit();
}
}
},
[=](neighbor_msg& nm) {
self->state.neighbors = move(nm.neighbors);
}
};
}
struct big_actor_state {
int num_pings;
int exp_pinger;
std::default_random_engine random;
vector<actor> neighbors;
ping_msg my_ping_msg;
pong_msg my_pong_msg;
};
behavior big_actor_fun(stateful_actor<big_actor_state>* self, int id,
int num_messages, actor sink_actor) {
auto& s = self->state;
s.num_pings = 0;
s.exp_pinger = -1;
s.random.seed(id);
s.my_ping_msg = ping_msg{id};
s.my_pong_msg = pong_msg{id};
auto send_ping = [=](){
auto& s = self->state;
int target = s.random() % s.neighbors.size();
auto target_actor = s.neighbors[target];
s.exp_pinger = target;
self->send(target_actor, s.my_ping_msg);
};
return {
[=](ping_msg& pm) {
auto& s = self->state;
auto& sender = s.neighbors[pm.sender];
self->send(sender, s.my_pong_msg);
},
[=](pong_msg& pm) {
auto& s = self->state;
if (pm.sender != s.exp_pinger) {
cerr << "ERROR: Expected: " << s.exp_pinger
<< ", but received ping from " << pm.sender << endl;
}
if (s.num_pings == num_messages) {
self->send(sink_actor, exit_msg_atom::value);
} else {
send_ping();
++s.num_pings;
}
},
[=](exit_msg_atom) {
self->quit();
},
[=](neighbor_msg& nm) {
self->state.neighbors = move(nm.neighbors);
}
};
}
class bench : public benchmark {
public:
void print_arg_info() const override {
printf(benchmark_runner::arg_output_format(), "N (num pings)",
to_string(cfg_.n).c_str());
printf(benchmark_runner::arg_output_format(), "W (num actors)",
to_string(cfg_.w).c_str());
}
void initialize(int argc, char** argv) override {
cfg_.parse(argc, argv);
}
void run_iteration() override {
actor_system system{cfg_};
actor sink_actor = system.spawn(sink_actor_fun, cfg_.w);
vector<actor> big_actors;
big_actors.reserve(cfg_.w);
for (int i = 0; i < cfg_.w; ++i) {
big_actors.emplace_back(
system.spawn(big_actor_fun, i, cfg_.n, sink_actor));
}
anon_send(sink_actor, neighbor_msg{big_actors});
for (auto& loop_actor : big_actors) {
anon_send(loop_actor, neighbor_msg{big_actors});
}
for (auto& loop_actor : big_actors) {
anon_send(loop_actor, pong_msg{-1});
}
}
protected:
const char* current_file() const override {
return __FILE__;
}
private:
config cfg_;
};
int main(int argc, char** argv) {
benchmark_runner br;
br.run_benchmark(argc, argv, bench{});
}
| 23.521472 | 69 | 0.624674 | tud-ccc |
c09c771b7f2613188ed139fa02a9a483ba78a391 | 15,215 | hxx | C++ | main/tools/inc/tools/errcode.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/tools/inc/tools/errcode.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/tools/inc/tools/errcode.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* 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.
*
*************************************************************/
#ifndef _ERRCODE_HXX
#define _ERRCODE_HXX
#ifndef __RSC
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#endif
/*
01234567012345670123456701234567
|| || ||| || |
Warning || || |
| || || || |
Dynamic || || |
| || || |
Subsystembereiche | |
| || |
| || |
| || |
Class |
| |
| |
| |
Code
*/
#define ERRCODE_BUTTON_OK 0x01
#define ERRCODE_BUTTON_CANCEL 0x02
#define ERRCODE_BUTTON_RETRY 0x04
#define ERRCODE_BUTTON_OK_CANCEL 0x03
#define ERRCODE_BUTTON_OK_RETRY_CANCEL 0x07
#define ERRCODE_BUTTON_NO 0x08
#define ERRCODE_BUTTON_YES 0x10
#define ERRCODE_BUTTON_YES_NO 0x18
#define ERRCODE_BUTTON_YES_NO_CANCEL 0x1a
#define ERRCODE_BUTTON_DEF_OK 0x100
#define ERRCODE_BUTTON_DEF_CANCEL 0x200
#define ERRCODE_BUTTON_DEF_YES 0x300
#define ERRCODE_BUTTON_DEF_NO 0x400
#define ERRCODE_MSG_ERROR 0x1000
#define ERRCODE_MSG_WARNING 0x2000
#define ERRCODE_MSG_INFO 0x3000
#define ERRCODE_MSG_QUERY 0x4000
#define ERRCODE_ERROR_MASK 0x3fffffffUL
#define ERRCODE_WARNING_MASK 0x80000000UL
#define ERRCODE_RES_MASK 0x7fff
#define ERRCODE_CLASS_SHIFT 8
#define ERRCODE_AREA_SHIFT 13
#define ERRCODE_DYNAMIC_SHIFT 26
#define ERRCODE_CLASS_MASK (31UL <<ERRCODE_CLASS_SHIFT)
#define ERRCODE_DYNAMIC_START (1UL <<ERRCODE_DYNAMIC_SHIFT)
#define ERRCODE_DYNAMIC_COUNT 31UL
#define ERRCODE_DYNAMIC_MASK (31UL <<ERRCODE_DYNAMIC_SHIFT)
#ifdef __RSC
#define ERRCODE_TOERRID(x) (x & ~ERRCODE_DYNAMIC_MASK)
#define ERRCODE_TOERROR(x) \
((x & ERRCODE_WARNING_MASK) ? 0 : (x & ERRCODE_ERROR_MASK))
#else
typedef sal_uIntPtr ErrCode;
inline sal_uIntPtr ERRCODE_TOERRID( sal_uIntPtr x )
{
return x & ~ERRCODE_DYNAMIC_MASK;
}
inline sal_uIntPtr ERRCODE_TOERROR( sal_uIntPtr x )
{
return ((x & ERRCODE_WARNING_MASK) ? 0 : (x & ERRCODE_ERROR_MASK));
}
#endif
#define ERRCODE_AREA_TOOLS (0UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_SV (1UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_SFX (2UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_INET (3UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_IO ERRCODE_AREA_TOOLS
#define ERRCODE_AREA_LIB1 (8UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_SVX ERRCODE_AREA_LIB1
#define ERRCODE_AREA_SVX_END (ERRCODE_AREA_SO-1)
#define ERRCODE_AREA_SO (9UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_SO_END (ERRCODE_AREA_SBX-1)
#define ERRCODE_AREA_SBX (10UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_SBX_END ((11UL << ERRCODE_AREA_SHIFT) - 1)
#define ERRCODE_AREA_DB (11UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_DB_END ((12UL << ERRCODE_AREA_SHIFT) - 1)
#define ERRCODE_AREA_JAVA (12UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_JAVA_END ((13UL << ERRCODE_AREA_SHIFT) - 1)
#define ERRCODE_AREA_UUI (13UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_UUI_END ((14UL << ERRCODE_AREA_SHIFT) - 1)
#define ERRCODE_AREA_LIB2 (14UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_LIB2_END ((15UL << ERRCODE_AREA_SHIFT) - 1)
#define ERRCODE_AREA_CHAOS (15UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_CHAOS_END ((16UL << ERRCODE_AREA_SHIFT) - 1)
#define ERRCODE_AREA_APP1 (32UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_APP2 (40UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_APP3 (48UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_APP4 (56UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_APP5 (64UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_APP6 (72UL << ERRCODE_AREA_SHIFT)
#define ERRCODE_AREA_SC ERRCODE_AREA_APP1
#define ERRCODE_AREA_SC_END (ERRCODE_AREA_APP2-1)
#define ERRCODE_AREA_SD ERRCODE_AREA_APP2
#define ERRCODE_AREA_SD_END (ERRCODE_AREA_APP3-1)
#define ERRCODE_AREA_SW ERRCODE_AREA_APP4
#define ERRCODE_AREA_SW_END (ERRCODE_AREA_APP5-1)
#define ERRCODE_AREA_OFA ERRCODE_AREA_APP5
#define ERRCODE_AREA_OFA_END (ERRCODE_AREA_APP6-1)
#define ERRCODE_CLASS_NONE (0UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_ABORT (1UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_GENERAL (2UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_NOTEXISTS (3UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_ALREADYEXISTS (4UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_ACCESS (5UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_PATH (6UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_LOCKING (7UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_PARAMETER (8UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_SPACE (9UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_NOTSUPPORTED (10UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_READ (11UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_WRITE (12UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_UNKNOWN (13UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_VERSION (14UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_FORMAT (15UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_CREATE (16UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_IMPORT (17UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_EXPORT (18UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_FILTER (19UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_SO (20UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_SBX (21UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_RUNTIME (22UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_CLASS_COMPILER (23UL << ERRCODE_CLASS_SHIFT)
#define ERRCODE_NONE (0UL)
#define ERRCODE_ABORT ERRCODE_IO_ABORT
#define ERRCODE_IO_MISPLACEDCHAR (1UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTEXISTS (2UL |ERRCODE_CLASS_NOTEXISTS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_ALREADYEXISTS (3UL |ERRCODE_CLASS_ALREADYEXISTS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTADIRECTORY (4UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTAFILE (5UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_INVALIDDEVICE (6UL |ERRCODE_CLASS_PATH|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_ACCESSDENIED (7UL |ERRCODE_CLASS_ACCESS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_LOCKVIOLATION (8UL |ERRCODE_CLASS_LOCKING|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_OUTOFSPACE (9UL |ERRCODE_CLASS_SPACE|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_ISWILDCARD (11UL|ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTSUPPORTED (12UL|ERRCODE_CLASS_NOTSUPPORTED|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_GENERAL (13UL|ERRCODE_CLASS_GENERAL|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_TOOMANYOPENFILES (14UL|ERRCODE_CLASS_SPACE|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_CANTREAD (15UL|ERRCODE_CLASS_READ|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_CANTWRITE (16UL|ERRCODE_CLASS_WRITE|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_OUTOFMEMORY (17UL|ERRCODE_CLASS_SPACE|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_CANTSEEK (18UL|ERRCODE_CLASS_GENERAL|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_CANTTELL (19UL|ERRCODE_CLASS_GENERAL|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_WRONGVERSION (20UL|ERRCODE_CLASS_VERSION|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_WRONGFORMAT (21UL|ERRCODE_CLASS_FORMAT|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_INVALIDCHAR (22UL|ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_UNKNOWN (23UL|ERRCODE_CLASS_UNKNOWN|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_INVALIDACCESS (24UL|ERRCODE_CLASS_ACCESS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_CANTCREATE (25UL|ERRCODE_CLASS_CREATE|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_INVALIDPARAMETER (26UL|ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_ABORT (27UL|ERRCODE_CLASS_ABORT|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTEXISTSPATH (28UL |ERRCODE_CLASS_NOTEXISTS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_PENDING (29UL |ERRCODE_CLASS_NOTEXISTS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_RECURSIVE (30UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NAMETOOLONG (31UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_INVALIDLENGTH (32UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_CURRENTDIR (33UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTSAMEDEVICE (34UL |ERRCODE_CLASS_PARAMETER|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_DEVICENOTREADY (35UL |ERRCODE_CLASS_READ|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_BADCRC (36UL |ERRCODE_CLASS_READ|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_WRITEPROTECTED (37UL |ERRCODE_CLASS_ACCESS|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_BROKENPACKAGE (38UL |ERRCODE_CLASS_FORMAT|\
ERRCODE_AREA_IO)
#define ERRCODE_IO_NOTSTORABLEINBINARYFORMAT (39UL |ERRCODE_CLASS_FORMAT|\
ERRCODE_AREA_IO)
// FsysErrorCodes
#define FSYS_ERR_OK ERRCODE_NONE
#define FSYS_ERR_MISPLACEDCHAR ERRCODE_IO_MISPLACEDCHAR
#define FSYS_ERR_INVALIDCHAR ERRCODE_IO_INVALIDCHAR
#define FSYS_ERR_NOTEXISTS ERRCODE_IO_NOTEXISTS
#define FSYS_ERR_ALREADYEXISTS ERRCODE_IO_ALREADYEXISTS
#define FSYS_ERR_NOTADIRECTORY ERRCODE_IO_NOTADIRECTORY
#define FSYS_ERR_NOTAFILE ERRCODE_IO_NOTAFILE
#define FSYS_ERR_INVALIDDEVICE ERRCODE_IO_INVALIDDEVICE
#define FSYS_ERR_ACCESSDENIED ERRCODE_IO_ACCESSDENIED
#define FSYS_ERR_LOCKVIOLATION ERRCODE_IO_LOCKVIOLATION
#define FSYS_ERR_VOLUMEFULL ERRCODE_IO_OUTOFSPACE
#define FSYS_ERR_ISWILDCARD ERRCODE_IO_ISWILDCARD
#define FSYS_ERR_NOTSUPPORTED ERRCODE_IO_NOTSUPPORTED
#define FSYS_ERR_UNKNOWN ERRCODE_IO_UNKNOWN
// StreamErrorCodes
#define SVSTREAM_OK ERRCODE_NONE
#define SVSTREAM_GENERALERROR ERRCODE_IO_GENERAL
#define SVSTREAM_FILE_NOT_FOUND ERRCODE_IO_NOTEXISTS
#define SVSTREAM_PATH_NOT_FOUND ERRCODE_IO_NOTEXISTSPATH
#define SVSTREAM_TOO_MANY_OPEN_FILES ERRCODE_IO_TOOMANYOPENFILES
#define SVSTREAM_ACCESS_DENIED ERRCODE_IO_ACCESSDENIED
#define SVSTREAM_SHARING_VIOLATION ERRCODE_IO_LOCKVIOLATION
#define SVSTREAM_LOCKING_VIOLATION ERRCODE_IO_LOCKVIOLATION
#define SVSTREAM_SHARE_BUFF_EXCEEDED ERRCODE_IO_LOCKVIOLATION
#define SVSTREAM_INVALID_ACCESS ERRCODE_IO_INVALIDACCESS
#define SVSTREAM_INVALID_HANDLE ERRCODE_IO_GENERAL
#define SVSTREAM_CANNOT_MAKE ERRCODE_IO_CANTCREATE
#define SVSTREAM_INVALID_PARAMETER ERRCODE_IO_INVALIDPARAMETER
#define SVSTREAM_READ_ERROR ERRCODE_IO_CANTREAD
#define SVSTREAM_WRITE_ERROR ERRCODE_IO_CANTWRITE
#define SVSTREAM_SEEK_ERROR ERRCODE_IO_CANTSEEK
#define SVSTREAM_TELL_ERROR ERRCODE_IO_CANTTELL
#define SVSTREAM_OUTOFMEMORY ERRCODE_IO_OUTOFMEMORY
#define SVSTREAM_FILEFORMAT_ERROR ERRCODE_IO_WRONGFORMAT
#define SVSTREAM_WRONGVERSION ERRCODE_IO_WRONGVERSION
#define SVSTREAM_DISK_FULL ERRCODE_IO_OUTOFSPACE
// Fuer die EditEngine:
#define SVSTREAM_ERRBASE_USER ERRCODE_AREA_LIB1
#define PRINTER_OK ERRCODE_NONE
#define PRINTER_ABORT ERRCODE_IO_ABORT
#define PRINTER_OUTOFMEMORY ERRCODE_IO_OUTOFMEMORY
#define PRINTER_GENERALERROR ERRCODE_IO_GENERAL
#define PRINTER_ACCESSDENIED ERRCODE_IO_ACCESSDENIED
#define ERRCODE_INET_NAME_RESOLVE (ERRCODE_AREA_INET | ERRCODE_CLASS_READ | 1)
#define ERRCODE_INET_CONNECT (ERRCODE_AREA_INET | ERRCODE_CLASS_READ | 2)
#define ERRCODE_INET_READ (ERRCODE_AREA_INET | ERRCODE_CLASS_READ | 3)
#define ERRCODE_INET_WRITE (ERRCODE_AREA_INET | ERRCODE_CLASS_WRITE| 4)
#define ERRCODE_INET_GENERAL (ERRCODE_AREA_INET | ERRCODE_CLASS_WRITE |5)
#define ERRCODE_INET_OFFLINE (ERRCODE_AREA_INET | ERRCODE_CLASS_READ |6)
#endif
| 47.546875 | 78 | 0.640946 | Grosskopf |
c09cf6b2b1ef0c22292a5c688253029e431c11e4 | 28,313 | cpp | C++ | llvm-3.9.0.src/tools/lld/ELF/Relocations.cpp | oscourse-tsinghua/OS2018spring-projects-g02 | 4adfd1c00096b1ff804a5874d9c400043a087d92 | [
"MIT"
] | 4 | 2018-10-14T04:17:32.000Z | 2021-08-10T04:05:39.000Z | llvm-3.9.0.src/tools/lld/ELF/Relocations.cpp | Hoblovski/OS2018spring-projects-g02 | 6a4894a1114848b064bcb847362a1f62746b3337 | [
"MIT"
] | 2 | 2018-04-12T03:53:11.000Z | 2018-04-15T12:44:28.000Z | llvm-3.9.0.src/tools/lld/ELF/Relocations.cpp | Hoblovski/OS2018spring-projects-g02 | 6a4894a1114848b064bcb847362a1f62746b3337 | [
"MIT"
] | 1 | 2018-04-11T05:05:24.000Z | 2018-04-11T05:05:24.000Z | //===- Relocations.cpp ----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains platform-independent functions to process relocations.
// I'll describe the overview of this file here.
//
// Simple relocations are easy to handle for the linker. For example,
// for R_X86_64_PC64 relocs, the linker just has to fix up locations
// with the relative offsets to the target symbols. It would just be
// reading records from relocation sections and applying them to output.
//
// But not all relocations are that easy to handle. For example, for
// R_386_GOTOFF relocs, the linker has to create new GOT entries for
// symbols if they don't exist, and fix up locations with GOT entry
// offsets from the beginning of GOT section. So there is more than
// fixing addresses in relocation processing.
//
// ELF defines a large number of complex relocations.
//
// The functions in this file analyze relocations and do whatever needs
// to be done. It includes, but not limited to, the following.
//
// - create GOT/PLT entries
// - create new relocations in .dynsym to let the dynamic linker resolve
// them at runtime (since ELF supports dynamic linking, not all
// relocations can be resolved at link-time)
// - create COPY relocs and reserve space in .bss
// - replace expensive relocs (in terms of runtime cost) with cheap ones
// - error out infeasible combinations such as PIC and non-relative relocs
//
// Note that the functions in this file don't actually apply relocations
// because it doesn't know about the output file nor the output file buffer.
// It instead stores Relocation objects to InputSection's Relocations
// vector to let it apply later in InputSection::writeTo.
//
//===----------------------------------------------------------------------===//
#include "Relocations.h"
#include "Config.h"
#include "OutputSections.h"
#include "SymbolTable.h"
#include "Target.h"
#include "Thunks.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support::endian;
namespace lld {
namespace elf {
static bool refersToGotEntry(RelExpr Expr) {
return Expr == R_GOT || Expr == R_GOT_OFF || Expr == R_MIPS_GOT_LOCAL_PAGE ||
Expr == R_MIPS_GOT_OFF || Expr == R_MIPS_TLSGD ||
Expr == R_MIPS_TLSLD || Expr == R_GOT_PAGE_PC || Expr == R_GOT_PC ||
Expr == R_GOT_FROM_END || Expr == R_TLSGD || Expr == R_TLSGD_PC ||
Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE;
}
static bool isPreemptible(const SymbolBody &Body, uint32_t Type) {
// In case of MIPS GP-relative relocations always resolve to a definition
// in a regular input file, ignoring the one-definition rule. So we,
// for example, should not attempt to create a dynamic relocation even
// if the target symbol is preemptible. There are two two MIPS GP-relative
// relocations R_MIPS_GPREL16 and R_MIPS_GPREL32. But only R_MIPS_GPREL16
// can be against a preemptible symbol.
// To get MIPS relocation type we apply 0xff mask. In case of O32 ABI all
// relocation types occupy eight bit. In case of N64 ABI we extract first
// relocation from 3-in-1 packet because only the first relocation can
// be against a real symbol.
if (Config->EMachine == EM_MIPS && (Type & 0xff) == R_MIPS_GPREL16)
return false;
return Body.isPreemptible();
}
// This function is similar to the `handleTlsRelocation`. MIPS does not support
// any relaxations for TLS relocations so by factoring out MIPS handling into
// the separate function we can simplify the code and does not pollute
// `handleTlsRelocation` by MIPS `ifs` statements.
template <class ELFT>
static unsigned
handleMipsTlsRelocation(uint32_t Type, SymbolBody &Body,
InputSectionBase<ELFT> &C, typename ELFT::uint Offset,
typename ELFT::uint Addend, RelExpr Expr) {
if (Expr == R_MIPS_TLSLD) {
if (Out<ELFT>::Got->addTlsIndex())
Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
Out<ELFT>::Got->getTlsIndexOff(), false,
nullptr, 0});
C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
return 1;
}
if (Target->isTlsGlobalDynamicRel(Type)) {
if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
typedef typename ELFT::uint uintX_t;
uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
Out<ELFT>::RelaDyn->addReloc(
{Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
Off + (uintX_t)sizeof(uintX_t), false,
&Body, 0});
}
C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
return 1;
}
return 0;
}
// Returns the number of relocations processed.
template <class ELFT>
static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
InputSectionBase<ELFT> &C,
typename ELFT::uint Offset,
typename ELFT::uint Addend, RelExpr Expr) {
if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
return 0;
if (!Body.isTls())
return 0;
typedef typename ELFT::uint uintX_t;
if (Config->EMachine == EM_MIPS)
return handleMipsTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr);
if ((Expr == R_TLSDESC || Expr == R_TLSDESC_PAGE || Expr == R_HINT) &&
Config->Shared) {
if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
Out<ELFT>::RelaDyn->addReloc(
{Target->TlsDescRel, Out<ELFT>::Got, Off, false, &Body, 0});
}
if (Expr != R_HINT)
C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
return 1;
}
if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
// Local-Dynamic relocs can be relaxed to Local-Exec.
if (!Config->Shared) {
C.Relocations.push_back(
{R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
return 2;
}
if (Out<ELFT>::Got->addTlsIndex())
Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
Out<ELFT>::Got->getTlsIndexOff(), false,
nullptr, 0});
C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
return 1;
}
// Local-Dynamic relocs can be relaxed to Local-Exec.
if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
C.Relocations.push_back(
{R_RELAX_TLS_LD_TO_LE, Type, &C, Offset, Addend, &Body});
return 1;
}
if (Expr == R_TLSDESC_PAGE || Expr == R_TLSDESC || Expr == R_HINT ||
Target->isTlsGlobalDynamicRel(Type)) {
if (Config->Shared) {
if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
Out<ELFT>::RelaDyn->addReloc(
{Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
// If the symbol is preemptible we need the dynamic linker to write
// the offset too.
if (isPreemptible(Body, Type))
Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
Off + (uintX_t)sizeof(uintX_t), false,
&Body, 0});
}
C.Relocations.push_back({Expr, Type, &C, Offset, Addend, &Body});
return 1;
}
// Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
// depending on the symbol being locally defined or not.
if (isPreemptible(Body, Type)) {
C.Relocations.push_back(
{Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_IE), Type,
&C, Offset, Addend, &Body});
if (!Body.isInGot()) {
Out<ELFT>::Got->addEntry(Body);
Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
Body.getGotOffset<ELFT>(), false, &Body,
0});
}
return Target->TlsGdRelaxSkip;
}
C.Relocations.push_back(
{Target->adjustRelaxExpr(Type, nullptr, R_RELAX_TLS_GD_TO_LE), Type, &C,
Offset, Addend, &Body});
return Target->TlsGdRelaxSkip;
}
// Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
// defined.
if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
!isPreemptible(Body, Type)) {
C.Relocations.push_back(
{R_RELAX_TLS_IE_TO_LE, Type, &C, Offset, Addend, &Body});
return 1;
}
return 0;
}
template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
return read32<E>(Loc) & 0xffff;
}
template <class RelTy>
static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
switch (Rel->getType(Config->Mips64EL)) {
case R_MIPS_HI16:
return R_MIPS_LO16;
case R_MIPS_GOT16:
return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
case R_MIPS_PCHI16:
return R_MIPS_PCLO16;
case R_MICROMIPS_HI16:
return R_MICROMIPS_LO16;
default:
return R_MIPS_NONE;
}
}
template <class ELFT, class RelTy>
static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
SymbolBody &Sym, const RelTy *Rel,
const RelTy *End) {
uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
uint32_t Type = getMipsPairType(Rel, Sym);
// Some MIPS relocations use addend calculated from addend of the relocation
// itself and addend of paired relocation. ABI requires to compute such
// combined addend in case of REL relocation record format only.
// See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
if (RelTy::IsRela || Type == R_MIPS_NONE)
return 0;
for (const RelTy *RI = Rel; RI != End; ++RI) {
if (RI->getType(Config->Mips64EL) != Type)
continue;
if (RI->getSymbol(Config->Mips64EL) != SymIndex)
continue;
const endianness E = ELFT::TargetEndianness;
return ((read32<E>(BufLoc) & 0xffff) << 16) +
readSignedLo16<E>(Buf + RI->r_offset);
}
warning("can't find matching " + getRelName(Type) + " relocation for " +
getRelName(Rel->getType(Config->Mips64EL)));
return 0;
}
// True if non-preemptable symbol always has the same value regardless of where
// the DSO is loaded.
template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
if (Body.isUndefined())
return !Body.isLocal() && Body.symbol()->isWeak();
if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
return DR->Section == nullptr; // Absolute symbol.
return false;
}
static bool needsPlt(RelExpr Expr) {
return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT ||
Expr == R_PLT_PAGE_PC || Expr == R_THUNK_PLT_PC;
}
// True if this expression is of the form Sym - X, where X is a position in the
// file (PC, or GOT for example).
static bool isRelExpr(RelExpr Expr) {
return Expr == R_PC || Expr == R_GOTREL || Expr == R_PAGE_PC ||
Expr == R_RELAX_GOT_PC || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC;
}
template <class ELFT>
static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
const SymbolBody &Body) {
// These expressions always compute a constant
if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF ||
E == R_MIPS_GOT_LOCAL_PAGE || E == R_MIPS_GOT_OFF || E == R_MIPS_TLSGD ||
E == R_GOT_PAGE_PC || E == R_GOT_PC || E == R_PLT_PC || E == R_TLSGD_PC ||
E == R_TLSGD || E == R_PPC_PLT_OPD || E == R_TLSDESC_PAGE ||
E == R_HINT || E == R_THUNK_PC || E == R_THUNK_PLT_PC)
return true;
// These never do, except if the entire file is position dependent or if
// only the low bits are used.
if (E == R_GOT || E == R_PLT || E == R_TLSDESC)
return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
if (isPreemptible(Body, Type))
return false;
if (!Config->Pic)
return true;
bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
bool RelE = isRelExpr(E);
if (AbsVal && !RelE)
return true;
if (!AbsVal && RelE)
return true;
// Relative relocation to an absolute value. This is normally unrepresentable,
// but if the relocation refers to a weak undefined symbol, we allow it to
// resolve to the image base. This is a little strange, but it allows us to
// link function calls to such symbols. Normally such a call will be guarded
// with a comparison, which will load a zero from the GOT.
if (AbsVal && RelE) {
if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
return true;
error("relocation " + getRelName(Type) +
" cannot refer to absolute symbol " + Body.getName());
return true;
}
return Target->usesOnlyLowPageBits(Type);
}
static RelExpr toPlt(RelExpr Expr) {
if (Expr == R_PPC_OPD)
return R_PPC_PLT_OPD;
if (Expr == R_PC)
return R_PLT_PC;
if (Expr == R_PAGE_PC)
return R_PLT_PAGE_PC;
if (Expr == R_ABS)
return R_PLT;
return Expr;
}
static RelExpr fromPlt(RelExpr Expr) {
// We decided not to use a plt. Optimize a reference to the plt to a
// reference to the symbol itself.
if (Expr == R_PLT_PC)
return R_PC;
if (Expr == R_PPC_PLT_OPD)
return R_PPC_OPD;
if (Expr == R_PLT)
return R_ABS;
return Expr;
}
template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
typedef typename ELFT::uint uintX_t;
uintX_t SecAlign = SS->file()->getSection(SS->Sym)->sh_addralign;
uintX_t SymValue = SS->Sym.st_value;
int TrailingZeros =
std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
return 1 << TrailingZeros;
}
// Reserve space in .bss for copy relocation.
template <class ELFT> static void addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
typedef typename ELFT::uint uintX_t;
typedef typename ELFT::Sym Elf_Sym;
// Copy relocation against zero-sized symbol doesn't make sense.
uintX_t SymSize = SS->template getSize<ELFT>();
if (SymSize == 0)
fatal("cannot create a copy relocation for " + SS->getName());
uintX_t Alignment = getAlignment(SS);
uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Alignment);
Out<ELFT>::Bss->setSize(Off + SymSize);
Out<ELFT>::Bss->updateAlignment(Alignment);
uintX_t Shndx = SS->Sym.st_shndx;
uintX_t Value = SS->Sym.st_value;
// Look through the DSO's dynamic symbol table for aliases and create a
// dynamic symbol for each one. This causes the copy relocation to correctly
// interpose any aliases.
for (const Elf_Sym &S : SS->file()->getElfSymbols(true)) {
if (S.st_shndx != Shndx || S.st_value != Value)
continue;
auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
Symtab<ELFT>::X->find(check(S.getName(SS->file()->getStringTable()))));
if (!Alias)
continue;
Alias->OffsetInBss = Off;
Alias->NeedsCopyOrPltAddr = true;
Alias->symbol()->IsUsedInRegularObj = true;
}
Out<ELFT>::RelaDyn->addReloc(
{Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
}
template <class ELFT>
static RelExpr adjustExpr(const elf::ObjectFile<ELFT> &File, SymbolBody &Body,
bool IsWrite, RelExpr Expr, uint32_t Type,
const uint8_t *Data) {
bool Preemptible = isPreemptible(Body, Type);
if (Body.isGnuIFunc()) {
Expr = toPlt(Expr);
} else if (!Preemptible) {
if (needsPlt(Expr))
Expr = fromPlt(Expr);
if (Expr == R_GOT_PC)
Expr = Target->adjustRelaxExpr(Type, Data, Expr);
}
Expr = Target->getThunkExpr(Expr, Type, File, Body);
if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
return Expr;
// This relocation would require the dynamic linker to write a value to read
// only memory. We can hack around it if we are producing an executable and
// the refered symbol can be preemepted to refer to the executable.
if (Config->Shared || (Config->Pic && !isRelExpr(Expr))) {
error("can't create dynamic relocation " + getRelName(Type) +
" against readonly segment");
return Expr;
}
if (Body.getVisibility() != STV_DEFAULT) {
error("cannot preempt symbol");
return Expr;
}
if (Body.isObject()) {
// Produce a copy relocation.
auto *B = cast<SharedSymbol<ELFT>>(&Body);
if (!B->needsCopy())
addCopyRelSymbol(B);
return Expr;
}
if (Body.isFunc()) {
// This handles a non PIC program call to function in a shared library. In
// an ideal world, we could just report an error saying the relocation can
// overflow at runtime. In the real world with glibc, crt1.o has a
// R_X86_64_PC32 pointing to libc.so.
//
// The general idea on how to handle such cases is to create a PLT entry and
// use that as the function value.
//
// For the static linking part, we just return a plt expr and everything
// else will use the the PLT entry as the address.
//
// The remaining problem is making sure pointer equality still works. We
// need the help of the dynamic linker for that. We let it know that we have
// a direct reference to a so symbol by creating an undefined symbol with a
// non zero st_value. Seeing that, the dynamic linker resolves the symbol to
// the value of the symbol we created. This is true even for got entries, so
// pointer equality is maintained. To avoid an infinite loop, the only entry
// that points to the real function is a dedicated got entry used by the
// plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
// R_386_JMP_SLOT, etc).
Body.NeedsCopyOrPltAddr = true;
return toPlt(Expr);
}
error("symbol is missing type");
return Expr;
}
template <class ELFT, class RelTy>
static typename ELFT::uint computeAddend(const elf::ObjectFile<ELFT> &File,
const uint8_t *SectionData,
const RelTy *End, const RelTy &RI,
RelExpr Expr, SymbolBody &Body) {
typedef typename ELFT::uint uintX_t;
uint32_t Type = RI.getType(Config->Mips64EL);
uintX_t Addend = getAddend<ELFT>(RI);
const uint8_t *BufLoc = SectionData + RI.r_offset;
if (!RelTy::IsRela)
Addend += Target->getImplicitAddend(BufLoc, Type);
if (Config->EMachine == EM_MIPS) {
Addend += findMipsPairedAddend<ELFT>(SectionData, BufLoc, Body, &RI, End);
if (Type == R_MIPS_LO16 && Expr == R_PC)
// R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
// symbol. In that case we should use the following formula for
// calculation "AHL + GP - P + 4". Let's add 4 right here.
// For details see p. 4-19 at
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Addend += 4;
if (Expr == R_GOTREL) {
Addend -= MipsGPOffset;
if (Body.isLocal())
Addend += File.getMipsGp0();
}
}
if (Config->Pic && Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
Addend += getPPC64TocBase();
return Addend;
}
// The reason we have to do this early scan is as follows
// * To mmap the output file, we need to know the size
// * For that, we need to know how many dynamic relocs we will have.
// It might be possible to avoid this by outputting the file with write:
// * Write the allocated output sections, computing addresses.
// * Apply relocations, recording which ones require a dynamic reloc.
// * Write the dynamic relocations.
// * Write the rest of the file.
// This would have some drawbacks. For example, we would only know if .rela.dyn
// is needed after applying relocations. If it is, it will go after rw and rx
// sections. Given that it is ro, we will need an extra PT_LOAD. This
// complicates things for the dynamic linker and means we would have to reserve
// space for the extra PT_LOAD even if we end up not using it.
template <class ELFT, class RelTy>
static void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
typedef typename ELFT::uint uintX_t;
bool IsWrite = C.getSectionHdr()->sh_flags & SHF_WRITE;
auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
Out<ELFT>::RelaDyn->addReloc(Reloc);
};
const elf::ObjectFile<ELFT> &File = *C.getFile();
ArrayRef<uint8_t> SectionData = C.getSectionData();
const uint8_t *Buf = SectionData.begin();
for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
const RelTy &RI = *I;
SymbolBody &Body = File.getRelocTargetSym(RI);
uint32_t Type = RI.getType(Config->Mips64EL);
RelExpr Expr = Target->getRelExpr(Type, Body);
bool Preemptible = isPreemptible(Body, Type);
Expr = adjustExpr(File, Body, IsWrite, Expr, Type, Buf + RI.r_offset);
if (HasError)
continue;
// Skip a relocation that points to a dead piece
// in a mergeable section.
if (C.getOffset(RI.r_offset) == (uintX_t)-1)
continue;
// This relocation does not require got entry, but it is relative to got and
// needs it to be created. Here we request for that.
if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
Out<ELFT>::Got->HasGotOffRel = true;
uintX_t Addend = computeAddend(File, Buf, E, RI, Expr, Body);
if (unsigned Processed = handleTlsRelocation<ELFT>(
Type, Body, C, RI.r_offset, Addend, Expr)) {
I += (Processed - 1);
continue;
}
// Ignore "hint" relocation because it is for optional code optimization.
if (Expr == R_HINT)
continue;
if (needsPlt(Expr) || Expr == R_THUNK_ABS || Expr == R_THUNK_PC ||
Expr == R_THUNK_PLT_PC || refersToGotEntry(Expr) ||
!isPreemptible(Body, Type)) {
// If the relocation points to something in the file, we can process it.
bool Constant = isStaticLinkTimeConstant<ELFT>(Expr, Type, Body);
// If the output being produced is position independent, the final value
// is still not known. In that case we still need some help from the
// dynamic linker. We can however do better than just copying the incoming
// relocation. We can process some of it and and just ask the dynamic
// linker to add the load address.
if (!Constant)
AddDyn({Target->RelativeRel, &C, RI.r_offset, true, &Body, Addend});
// If the produced value is a constant, we just remember to write it
// when outputting this section. We also have to do it if the format
// uses Elf_Rel, since in that case the written value is the addend.
if (Constant || !RelTy::IsRela)
C.Relocations.push_back({Expr, Type, &C, RI.r_offset, Addend, &Body});
} else {
// We don't know anything about the finaly symbol. Just ask the dynamic
// linker to handle the relocation for us.
AddDyn({Target->getDynRel(Type), &C, RI.r_offset, false, &Body, Addend});
// MIPS ABI turns using of GOT and dynamic relocations inside out.
// While regular ABI uses dynamic relocations to fill up GOT entries
// MIPS ABI requires dynamic linker to fills up GOT entries using
// specially sorted dynamic symbol table. This affects even dynamic
// relocations against symbols which do not require GOT entries
// creation explicitly, i.e. do not have any GOT-relocations. So if
// a preemptible symbol has a dynamic relocation we anyway have
// to create a GOT entry for it.
// If a non-preemptible symbol has a dynamic relocation against it,
// dynamic linker takes it st_value, adds offset and writes down
// result of the dynamic relocation. In case of preemptible symbol
// dynamic linker performs symbol resolution, writes the symbol value
// to the GOT entry and reads the GOT entry when it needs to perform
// a dynamic relocation.
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
if (Config->EMachine == EM_MIPS)
Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
continue;
}
// Some targets might require creation of thunks for relocations.
// Now we support only MIPS which requires LA25 thunk to call PIC
// code from non-PIC one, and ARM which requires interworking.
if (Expr == R_THUNK_ABS || Expr == R_THUNK_PC || Expr == R_THUNK_PLT_PC) {
auto *Sec = cast<InputSection<ELFT>>(&C);
addThunk<ELFT>(Type, Body, *Sec);
}
// At this point we are done with the relocated position. Some relocations
// also require us to create a got or plt entry.
// If a relocation needs PLT, we create a PLT and a GOT slot for the symbol.
if (needsPlt(Expr)) {
if (Body.isInPlt())
continue;
Out<ELFT>::Plt->addEntry(Body);
uint32_t Rel;
if (Body.isGnuIFunc() && !Preemptible)
Rel = Target->IRelativeRel;
else
Rel = Target->PltRel;
Out<ELFT>::GotPlt->addEntry(Body);
Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
Body.getGotPltOffset<ELFT>(), !Preemptible,
&Body, 0});
continue;
}
if (refersToGotEntry(Expr)) {
if (Config->EMachine == EM_MIPS) {
// MIPS ABI has special rules to process GOT entries
// and doesn't require relocation entries for them.
// See "Global Offset Table" in Chapter 5 in the following document
// for detailed description:
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Out<ELFT>::Got->addMipsEntry(Body, Addend, Expr);
if (Body.isTls())
AddDyn({Target->TlsGotRel, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
!Preemptible, &Body, 0});
continue;
}
if (Body.isInGot())
continue;
Out<ELFT>::Got->addEntry(Body);
if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
uint32_t DynType;
if (Body.isTls())
DynType = Target->TlsGotRel;
else if (Preemptible)
DynType = Target->GotRel;
else
DynType = Target->RelativeRel;
AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
!Preemptible, &Body, 0});
}
continue;
}
}
}
template <class ELFT> void scanRelocations(InputSection<ELFT> &C) {
typedef typename ELFT::Shdr Elf_Shdr;
// Scan all relocations. Each relocation goes through a series
// of tests to determine if it needs special treatment, such as
// creating GOT, PLT, copy relocations, etc.
// Note that relocations for non-alloc sections are directly
// processed by InputSection::relocateNonAlloc.
if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
for (const Elf_Shdr *RelSec : C.RelocSections)
scanRelocations(C, *RelSec);
}
template <class ELFT>
void scanRelocations(InputSectionBase<ELFT> &S,
const typename ELFT::Shdr &RelSec) {
ELFFile<ELFT> &EObj = S.getFile()->getObj();
if (RelSec.sh_type == SHT_RELA)
scanRelocs(S, EObj.relas(&RelSec));
else
scanRelocs(S, EObj.rels(&RelSec));
}
template void scanRelocations<ELF32LE>(InputSection<ELF32LE> &);
template void scanRelocations<ELF32BE>(InputSection<ELF32BE> &);
template void scanRelocations<ELF64LE>(InputSection<ELF64LE> &);
template void scanRelocations<ELF64BE>(InputSection<ELF64BE> &);
template void scanRelocations<ELF32LE>(InputSectionBase<ELF32LE> &,
const ELF32LE::Shdr &);
template void scanRelocations<ELF32BE>(InputSectionBase<ELF32BE> &,
const ELF32BE::Shdr &);
template void scanRelocations<ELF64LE>(InputSectionBase<ELF64LE> &,
const ELF64LE::Shdr &);
template void scanRelocations<ELF64BE>(InputSectionBase<ELF64BE> &,
const ELF64BE::Shdr &);
}
}
| 40.160284 | 80 | 0.645781 | oscourse-tsinghua |
c09e50a22c50058c83d458917f2448e63981aad9 | 3,919 | cpp | C++ | src/placeholder.cpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | 7 | 2017-10-08T08:08:25.000Z | 2020-04-27T09:25:00.000Z | src/placeholder.cpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | null | null | null | src/placeholder.cpp | matt-harvey/swx | e7b10fe7d4bf0bd6581ceada53ad14b08bc1d852 | [
"Apache-2.0"
] | 1 | 2020-04-27T09:24:42.000Z | 2020-04-27T09:24:42.000Z | /*
* Copyright 2014 Matthew Harvey
*
* 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 "placeholder.hpp"
#include "stream_utilities.hpp"
#include "string_utilities.hpp"
#include "time_log.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
using std::back_inserter;
using std::copy;
using std::endl;
using std::ostream;
using std::ostringstream;
using std::size_t;
using std::string;
using std::vector;
namespace swx
{
namespace
{
char const k_tree_traversal_char = '_';
/**
* @returns \e true if p_str successfully expands into an
* activity string, in the context of p_time_log; otherwise, returns \e
* false.
*
* If successful, pushes the resulting activity components to \e p_vec;
* otherwise, it leaves \e p_vec unchanged.
*/
bool parse_placeholder
( string const& p_str,
vector<string>& p_vec,
TimeLog& p_time_log
)
{
size_t depth = 0;
if (p_str.empty())
{
return false;
}
for (char c: p_str)
{
if (c == k_tree_traversal_char) ++depth;
else return false;
}
if (p_time_log.is_active())
{
auto const last_activities = p_time_log.last_activities(1);
assert (!last_activities.empty());
string const activity = last_activities.front();
auto const components = split(activity);
assert (depth > 0);
--depth;
auto const b = components.begin();
auto it = components.end();
for ( ; (it != b) && (depth != 0); --it, --depth)
{
}
copy(b, it, back_inserter(p_vec));
}
else
{
p_vec.push_back("");
}
return true;
}
} // end anonymous namespace
string
expand_placeholders(vector<string> const& p_components, TimeLog& p_time_log)
{
vector<string> vec;
vec.reserve(p_components.size());
for (auto const& component: p_components)
{
if (!parse_placeholder(component, vec, p_time_log))
{
if (!component.empty()) vec.push_back(component);
}
}
return squish(vec.begin(), vec.end());
}
void
write_placeholder_help(ostream& p_os, string::size_type p_margin, string::size_type p_width)
{
string::size_type const num_lines = 3;
string::size_type const min_margin = num_lines + 1;
if (min_margin > p_margin) p_margin = min_margin;
for (string::size_type i = 1; i <= num_lines; ++i)
{
assert (p_margin >= i);
p_os << endl;
p_os << " " << string(i, k_tree_traversal_char)
<< string(p_margin - i, ' ') << ": ";
string help;
switch (i)
{
case 1:
help = "Expands into name of current activity (or empty string if inactive)";
break;
case 2:
help = "Expands into name of parent of current activity (or empty string if "\
"no parent)";
break;
case 3:
help = "Expands into name of parent of parent (etc.)";
break;
default:
assert (false);
}
p_os << wrap(help, p_margin + 4, p_width);
}
}
} // namespace swx
| 27.405594 | 92 | 0.592498 | matt-harvey |
c0a474de71bc395d6c17a885e849620c4148b3ec | 965 | cpp | C++ | src/physical_device.cpp | QSXW/VKCPP | c3fed2159dca0d63b4eb5e15b9a1e5fbcf05bfb8 | [
"Apache-2.0"
] | null | null | null | src/physical_device.cpp | QSXW/VKCPP | c3fed2159dca0d63b4eb5e15b9a1e5fbcf05bfb8 | [
"Apache-2.0"
] | null | null | null | src/physical_device.cpp | QSXW/VKCPP | c3fed2159dca0d63b4eb5e15b9a1e5fbcf05bfb8 | [
"Apache-2.0"
] | null | null | null | #include "physical_device.h"
namespace VKCPP
{
PFN_vkGetPhysicalDeviceFeatures PhysicalDevice::GetFeatures;
PFN_vkGetPhysicalDeviceFormatProperties PhysicalDevice::GetFormatProperties;
PFN_vkGetPhysicalDeviceImageFormatProperties PhysicalDevice::GetImageFormatProperties;
PFN_vkGetPhysicalDeviceMemoryProperties PhysicalDevice::GetMemoryProperties;
PFN_vkGetPhysicalDeviceProperties PhysicalDevice::GetProperties;
PFN_vkGetPhysicalDeviceQueueFamilyProperties PhysicalDevice::GetQueueFamilyProperties;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties PhysicalDevice::GetSparseImageFormatProperties;
PhysicalDevice::PhysicalDevice(Primitive other) :
handle{ other }
{
uint32_t count = 0;
get_queue_family_properties(&count, nullptr);
queue_family_properties.resize(count);
get_queue_family_properties(&count, queue_family_properties.data());
}
}
| 38.6 | 99 | 0.781347 | QSXW |
c0a51fdae624a6940332dab6737455c8882ef07a | 290 | cpp | C++ | Tools/HttpConnect/HttpConnect_1/main.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | Tools/HttpConnect/HttpConnect_1/main.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | Tools/HttpConnect/HttpConnect_1/main.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z |
#include <iostream>
#include "HttpConnect.h"
int main()
{
HttpConnect *http = new HttpConnect();
// http->getData("127.0.0.1", "/login", "id=Administrator&pw=\"\"");
http->postData("http://192.168.0.116/upImg/upimg", "/login","id=Administrator&pw=123");
system("pause");
return 0;
} | 22.307692 | 88 | 0.648276 | liangjisheng |
c0a5c0dc7967767d9dbb0f8cd037f6ec48e651b5 | 101 | cpp | C++ | InterviewBit/C++/FunctionBasic.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | 1 | 2021-07-22T07:37:31.000Z | 2021-07-22T07:37:31.000Z | InterviewBit/C++/FunctionBasic.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | InterviewBit/C++/FunctionBasic.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | int compute(int A, int B) {
// Your code goes here
int ans = A * A + B * B;
return ans;
} | 20.2 | 28 | 0.524752 | ShubhamJagtap2000 |
c0a5d4076e8dd25ef54dfc89b93189856dc85667 | 3,598 | cpp | C++ | C_Code/basics/test/test.cpp | xiaoandx/learningCode | 2c41bc7199ef21a70d1935f32296d520e18f719f | [
"MIT"
] | 13 | 2020-10-25T15:38:15.000Z | 2022-02-21T02:21:24.000Z | C_Code/basics/test/test.cpp | xiaoandx/learningCode | 2c41bc7199ef21a70d1935f32296d520e18f719f | [
"MIT"
] | 4 | 2020-10-26T08:37:27.000Z | 2020-12-14T08:49:51.000Z | C_Code/basics/test/test.cpp | xiaoandx/learningCode | 2c41bc7199ef21a70d1935f32296d520e18f719f | [
"MIT"
] | 10 | 2020-10-25T15:38:30.000Z | 2021-09-15T03:54:39.000Z | /*
* @explain: Copyright (c) 2020 WEI.ZHOU. All rights reserved.
* The following code is only used for learning and communication, not for illegal and commercial use.
* If the code is used, no consent is required, but the author has nothing to do with any problems
* and consequences.
*
* In case of code problems, feedback can be made through the following email address.
* <xiaoandx@gmail.com>
*
* @Description: 输入三条边判断是否构成三角形,并判断构成什么类型的三角形
* @Author: WEI.ZHOU
* @Date: 2020-12-14 16:33:58
* @Version: V1.0
* @Others: Running test instructions
* 1.输入三角形三边时,每输入一条边就进行回车 eg:3 \n
*
*/
#include <stdlib.h>
#include <iostream>
#define OPERATION_SUCCESS 1
#define OPERATION_ERROR 0
#define ONE 1
#define TWO 2
#define ZERO 0
#define LF '\n'
#define N 3
/**
* @brief 输入三角形三条边
* @Date 2020-12-15 14:11:51
* @return {int *} 包含三角形三条边的数组
*/
int* getTriangleSideArray();
/**
* @brief 判断3条边是否构成三角形并判断什么类型
* @Date 2020-12-14 17:05:45
* @param int *T 三角形三边长度
* @return 0->error; 1->等腰; 2->等边; 3->直角; 4->一般
*/
int judgeTriangle(int* T);
/**
* @brief 输出判断结果
* @Date 2020-12-14 17:34:28
* @param int V 判断状态
*/
void printResult(int V);
int main() {
// int* sideArray = getTriangleSideArray();
// int resut = judgeTriangle(sideArray);
// printResult(resut);
printResult(judgeTriangle(getTriangleSideArray()));
return OPERATION_SUCCESS;
}
int* getTriangleSideArray() {
int* sideArray;
int i;
sideArray = (int*)malloc(N * sizeof(int));
for (i = ZERO; i < N; i++) {
std::cout << "输入三角形第" << (i + ONE) << "条边: ";
int data;
std::cin >> data;
for (; (data > 100 || data < 1);) {
std::cout << "输入第" << (i + ONE) << "错误 !!" << LF;
std::cout << "再次输入三角形第" << (i + ONE) << "条边: ";
std::cin >> data;
}
sideArray[i] = data;
}
return sideArray;
}
int judgeTriangle(int* T) {
/**
* @brief 变量说明
* int result 判断结果
* 0->error; 1->等腰; 2->等边; 3->直角; 4->一般
*/
if ((T[ZERO] + T[ONE] > T[TWO]) && (T[ZERO] + T[TWO] > T[ONE]) &&
(T[ONE] + T[TWO] > T[ZERO])) {
if ((T[ZERO] == T[ONE] && T[ONE] != T[TWO]) ||
(T[ZERO] == T[TWO] && T[TWO] != T[ONE]) ||
(T[ONE] == T[TWO] && T[ZERO] != T[TWO])) {
free(T);
return ONE;
}
if (T[ZERO] == T[ONE] && T[ZERO] == T[TWO]) {
free(T);
return TWO;
} else {
if ((T[ZERO] * T[ZERO] + T[ONE] * T[ONE] == T[TWO] * T[TWO]) ||
(T[ZERO] * T[ZERO] + T[TWO] * T[TWO] == T[ONE] * T[ONE]) ||
(T[TWO] * T[TWO] + T[ONE] * T[ONE] == T[ZERO] * T[ZERO])) {
free(T);
return (ONE + TWO);
}
free(T);
return (TWO * TWO);
}
if ((T[ZERO] == T[ONE] && T[ONE] != T[TWO]) ||
(T[ZERO] == T[TWO] && T[TWO] != T[ONE]) ||
(T[ONE] == T[TWO] && T[ZERO] != T[TWO])) {
free(T);
return ONE;
}
}
free(T);
return ZERO;
}
void printResult(int V) {
switch (V) {
case ZERO:
std::cout << "input error! It's not a triangle" << LF;
break;
case ONE:
std::cout << "等腰三角形" << LF;
break;
case TWO:
std::cout << "等边三角形" << LF;
break;
case TWO + ONE:
std::cout << "直角三角形" << LF;
break;
default:
std::cout << "一般三角形" << LF;
break;
}
} | 26.651852 | 102 | 0.481934 | xiaoandx |
c0a645232f88d2368775fc3ec7c5af5b1bb8e760 | 3,684 | cpp | C++ | external/webkit/Source/WebCore/page/PluginHalter.cpp | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 15 | 2016-01-05T12:43:41.000Z | 2022-03-15T10:34:47.000Z | Source/WebCore/page/PluginHalter.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | Source/WebCore/page/PluginHalter.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2020-11-30T18:36:01.000Z | 2021-02-05T23:20:24.000Z | /*
* Copyright (C) 2009 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "PluginHalter.h"
#include "HaltablePlugin.h"
#include "PlatformString.h"
#include <wtf/CurrentTime.h>
#include <wtf/Vector.h>
using namespace std;
namespace WebCore {
PluginHalter::PluginHalter(PluginHalterClient* client)
: m_client(client)
, m_timer(this, &PluginHalter::timerFired)
, m_pluginAllowedRunTime(numeric_limits<unsigned>::max())
{
ASSERT_ARG(client, client);
}
void PluginHalter::didStartPlugin(HaltablePlugin* obj)
{
ASSERT_ARG(obj, obj);
ASSERT_ARG(obj, !m_plugins.contains(obj));
if (!m_client->enabled())
return;
double currentTime = WTF::currentTime();
m_plugins.add(obj, currentTime);
if (m_plugins.size() == 1)
m_oldestStartTime = currentTime;
startTimerIfNecessary();
}
void PluginHalter::didStopPlugin(HaltablePlugin* obj)
{
if (!m_client->enabled())
return;
m_plugins.remove(obj);
}
void PluginHalter::timerFired(Timer<PluginHalter>*)
{
if (m_plugins.isEmpty())
return;
Vector<HaltablePlugin*> plugins;
copyKeysToVector(m_plugins, plugins);
// Plug-ins older than this are candidates to be halted.
double pluginCutOffTime = WTF::currentTime() - m_pluginAllowedRunTime;
m_oldestStartTime = numeric_limits<double>::max();
for (size_t i = 0; i < plugins.size(); ++i) {
double thisStartTime = m_plugins.get(plugins[i]);
if (thisStartTime > pluginCutOffTime) {
// This plug-in is too young to be halted. We find the oldest
// plug-in that is not old enough to be halted and use it to set
// the timer's next fire time.
if (thisStartTime < m_oldestStartTime)
m_oldestStartTime = thisStartTime;
continue;
}
if (m_client->shouldHaltPlugin(plugins[i]->node(), plugins[i]->isWindowed(), plugins[i]->pluginName()))
plugins[i]->halt();
m_plugins.remove(plugins[i]);
}
startTimerIfNecessary();
}
void PluginHalter::startTimerIfNecessary()
{
if (m_timer.isActive())
return;
if (m_plugins.isEmpty())
return;
double nextFireInterval = static_cast<double>(m_pluginAllowedRunTime) - (currentTime() - m_oldestStartTime);
m_timer.startOneShot(nextFireInterval < 0 ? 0 : nextFireInterval);
}
} // namespace WebCore
| 30.957983 | 112 | 0.698426 | ghsecuritylab |