blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e26f968391fbd11cd585e996bb5085a78b0e43ec | 033e6cc7dbcc51a21b5579aa88f2ef01cea0b0b6 | /TrajectoryDataConverter/Area.h | 592b0e73045b1e0197309654002801180c911a98 | [] | no_license | niuxinzan/MapMatching | d7c1092e48f9f8484bf946d570fcc698d1198e37 | da02ac1cdb8e03b6b2566f9ae45de1ea55b86319 | refs/heads/master | 2023-01-05T10:17:27.336759 | 2020-11-08T04:06:53 | 2020-11-08T04:06:53 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 883 | h | #pragma once
#include <iostream>
//表示区域的类,MapDrawer与Map引用同一个Area对象以保持区域的一致性
class Area
{
public:
double minLat;
double maxLat;
double minLon;
double maxLon;
void setArea(double _minLat, double _maxLat, double _minLon, double _maxLon)
{
this->minLat = _minLat;
this->maxLat = _maxLat;
this->minLon = _minLon;
this->maxLon = _maxLon;
}
Area()
{
minLat = 0;
maxLat = 0;
minLon = 0;
maxLon = 0;
}
Area(double _minLat, double _maxLat, double _minLon, double _maxLon)
{
setArea(_minLat, _maxLat, _minLon, _maxLon);
}
bool inArea(double lat, double lon)
{
//返回(lat,lon)是否在该区间内
return (lat > minLat && lat < maxLat && lon > minLon && lon < maxLon);
}
void print()
{
printf("area: minLat = %lf, maxLat = %lf, minLon = %lf, maxLat = %lf\n", minLat, maxLat, minLon, maxLon);
}
}; | [
"knightykc@gmail.com"
] | knightykc@gmail.com |
edd664964dc84580011f3b15f609d250b82d9b88 | d7a0f3dfdfce7f26a3b3716f9f5f1389324f6c94 | /conditionalstatements.cpp | 097a738a50b5f9424fdc7246630cc977c52e6f72 | [] | no_license | GulawarSailoo/Conditional_Statements | 5c8ce37d98ccc9ff3363482e758f20b104c3a73d | 417e6ba387fb5842deafecab23f4a428cad03f8c | refs/heads/master | 2020-05-21T14:42:59.866424 | 2019-05-11T04:47:17 | 2019-05-11T04:47:17 | 186,088,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int N;
cin >> N;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if(N%2==0){
if(N>=2 && N<=5){
cout<<"Not Weird";
}
if(N>=6 && N<=20){
cout<<"Weird";
}
if(N>20){
cout<<"Not Weird";
}
}
else{
cout<<"Weird";
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
3ce04e4dad39fb68a566e8e2754a2ede4258ebd1 | 488706ddcd860941510ddd5c8f35bbd065de9ca1 | /visualtext/EnglishInflectionsDlg.h | 2c85c46d161902636c0e0d493c0a774b16e616ee | [] | no_license | VisualText/legacy | 8fabbf1da142dfac1a47f4759103671c84ee64fe | 73d3dee26ab988e61507713ca37c4e9c0416aee5 | refs/heads/main | 2023-08-14T08:14:25.178165 | 2021-09-27T22:41:00 | 2021-09-27T22:41:00 | 411,052,445 | 0 | 0 | null | 2021-09-27T22:40:55 | 2021-09-27T21:48:09 | C++ | UTF-8 | C++ | false | false | 966 | h | #pragma once
#include "afxwin.h"
// CEnglishInflectionsDlg dialog
class CEnglishInflectionsDlg : public CDialog
{
DECLARE_DYNAMIC(CEnglishInflectionsDlg)
public:
CEnglishInflectionsDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CEnglishInflectionsDlg();
bool HasPOS(CString posStr);
void AddPOS(CString posStr);
// Dialog Data
enum { IDD = IDD_ENGLISH_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
void FillPOS();
void UpdateItemsActivitation();
void SetEnable(UINT id, bool value);
void UpdatePOSStringList();
DECLARE_MESSAGE_MAP()
public:
CString m_strWord;
CListBox m_listBoxPOS;
CString m_strPlural;
CString m_strPast;
CString m_strGerund;
CStringList m_strListPOS;
afx_msg void OnBnClickedGuess();
afx_msg void OnBnClickedClear();
afx_msg void OnLbnSelchangePos();
afx_msg void OnClose();
BOOL m_boolYPlural;
afx_msg void OnBnClickedY();
};
| [
"david.dehilster@lexisnexisrisk.com"
] | david.dehilster@lexisnexisrisk.com |
174f9c0e9161361205a71bc9d732b005e6270d3b | 8d6a54e327449043e5b0ba7c95fcb80b73bb518b | /src/shader.h | be3a8d9d47e3a45e57a55691af2d89f0708c88e9 | [] | no_license | Ashu308/Major2 | 8236584fba06a166c12e8aa6cffa1f59f5dcd732 | f62f2330c71cadff85b0cd67a31a45ccb421b503 | refs/heads/master | 2020-04-16T22:42:25.346621 | 2019-01-16T05:38:54 | 2019-01-16T05:38:54 | 165,979,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | h | #ifndef SHADER_H_
#define SHADER_H_
#include <GL/glew.h>
#include <string>
#include <unordered_map>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "material.h"
class Shader {
public:
Shader(const std::string& fileName);
void bind();
void printActiveUniforms();
void addUniform(const std::string& uniform);
//methods for setting uniform values
void setUniformI(const std::string& name, int value);
void setUniformF(const std::string& name, float value);
void setUniformVec3(const std::string& name, const glm::vec3& value);
void setUniformMat4(const std::string& name, const glm::mat4& value);
virtual void updateUniforms(const glm::mat4&, const glm::mat4&, const Material*, const glm::vec3&) = 0;
virtual ~Shader();
private:
static const unsigned int NUM_SHADERS = 2; //since we will only be using vertex and fragment shaders(for now)
GLuint m_program;
GLuint m_shaders[NUM_SHADERS];
std::unordered_map<std::string, int> uniforms;//stores the variable name and location of GLSL uniforms
};
#endif // SHADER_H_
| [
"noreply@github.com"
] | noreply@github.com |
65c6454fa4afb6b100a63ea5b0a14dcf82184427 | 17c21d3b81a09fa5330a7664c52c486664552eee | /MMap/MMap.h | f8d6de9de49953a2133fd16de8f9bea64db8d7e7 | [] | no_license | Qazwar/MMap | a07766695e553281a20f499fb786077cfa372771 | d19bd0e2af02acdc56efd00f92d6594462677cc4 | refs/heads/master | 2021-05-01T10:01:59.633865 | 2016-12-20T18:34:37 | 2016-12-20T18:34:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,646 | h | #pragma once
#include "Process.h"
#include "PE.h"
#include "Utils.h"
#include "asmjit\x86\x86assembler.h"
#include <vector>
class MMap
{
public:
Process _pe;
Memory workerCode;
std::vector<std::pair<DWORD, PE>> images;
public:
MMap(Process& pe) : _pe(pe) {}
void CreateRPCEnvironment()
{
workerCode = _pe.Alloc(100);
}
bool MapModule(std::string path)
{
if (!MapModuleInternal(path))
{
std::cout << "MapModuleInternal fail" << std::endl;
return false;
}
else
std::cout << path.c_str() << " mapped correctly " << std::endl;
//TRACE();
for (auto mod : images)
WipePEHeader(mod.first, mod.second.headerSize);
//TRACE("Wiped PE Headers");
std::cout << "Wiped PE Headers"<< std::endl;
workerCode.Free();
_pe.Detach();
return true;
}
bool MapModule(void* buffer)
{
if (!MapModuleInternal(buffer))
{
std::cout << "MapModuleInternal fail" << std::endl;
return false;
}
else
std::cout << "File mapped correctly" << std::endl;
//TRACE("File mapped correctly");
for (auto mod : images)
WipePEHeader(mod.first, mod.second.headerSize);
//TRACE("Wiped PE Headers");
std::cout << "Wiped PE Headers" << std::endl;
workerCode.Free();
_pe.Detach();
return true;
}
void WipePEHeader(DWORD base, DWORD headerSize)
{
DWORD n;
BYTE* zeroBuff = new BYTE[headerSize];
memset(zeroBuff, 0, headerSize);
WriteProcessMemory(_pe._proc, (void*)base, zeroBuff, headerSize, &n);
delete[] zeroBuff;
}
bool MapModuleInternal(void* buffer)
{
if (_pe.IsAttached())
{
PE file;
if (file.Load(buffer))
{
TRACE("Loading file");
if (file.Parse())
{
TRACE("Parsing PE file");
Memory block = _pe.Alloc(file.imageSize);
if (block.isValid())
{
//PE Header
block.Write(file.pFileBase, 0, file.headerSize);
//Sections
CopySections(block, file);
//Fix Relocs
FixRelocs(block, file);
//Fix Imports
FixImports(block, file);
//Run module initalizer
RunModuleInitializer(block, file);
images.push_back(std::make_pair((DWORD)block._base, file));
TRACE("PE file loaded at: 0x%X", (DWORD)block._base);
return true;
}
}
}
}
return false;
}
bool MapModuleInternal(std::string path)
{
if (_pe.IsAttached())
{
std::cout << "Mapping file " << path.c_str() << std::endl;
// TRACE("Mapping file %s", path.c_str());
//module is already in the process
if (_pe.GetModuleBase(Utils::GetFileNameWithExtensionFromPath(path)) != 0)
return true;
PE file;
if (file.Load(path))
{
std::cout << " Loading file " << path.c_str() << std::endl;
//TRACE("Loading file %s", path.c_str());
if (file.Parse())
{
std::cout << "Parsing PE file" << std::endl;
//TRACE("Parsing PE file");
Memory block = _pe.Alloc(file.imageSize);
std::cout << "Allocated space" << std::endl;
//TRACE("Allocated space");
if (block.isValid())
{
//TRACE("block is valid");
std::cout << "block is valid" << std::endl;
//PE Header
block.Write(file.pFileBase, 0, file.headerSize);
//TRACE("write pe header");
std::cout << "write pe header" << std::endl;
//Sections
CopySections(block, file);
//TRACE("copy sections");
std::cout << "copy sections" << std::endl;
//Fix Relocs
FixRelocs(block, file);
//TRACE("fix relocs");
std::cout << "fix relocs" << std::endl;
AddManualModule((DWORD)block._base, path);
//Fix Imports
FixImports(block, file);
//TRACE("imports fixed of %s", path.c_str());
std::cout << "imports fixed of" << path.c_str() << std::endl;
//Run module initalizer
RunModuleInitializer(block, file);
images.push_back(std::make_pair((DWORD)block._base, file));
//TRACE("PE file loaded at: 0x%X", (DWORD)block._base);
std::cout << "PE file loaded at: " << std::endl;
return true;
}
}
}
}
return false;
}
void AddManualModule(DWORD base, std::string path)
{
std::string mapped = Utils::GetFileNameWithExtensionFromPath(path);
std::transform(mapped.begin(), mapped.end(), mapped.begin(), tolower);
_pe.mappedModules.emplace(mapped, (DWORD)base);
}
void RemoveManualModule(std::string path)
{
std::string mapped = Utils::GetFileNameWithExtensionFromPath(path);
std::transform(mapped.begin(), mapped.end(), mapped.begin(), tolower);
auto it = _pe.mappedModules.find(mapped);
if (it != _pe.mappedModules.end())
{
_pe.mappedModules.erase(it);
}
}
/* this is the function that actually makes the game crash and the DLL not being able to load! */
void RunModuleInitializer(Memory& mem, PE file)
{
asmjit::JitRuntime jitruntime;
asmjit::X86Assembler a(&jitruntime);
std::cout << "jitruntime" << std::endl;
//Prolog
a.push(asmjit::x86::ebp);
a.mov(asmjit::x86::ebp, asmjit::x86::esp);
std::cout << "Push?" << std::endl;
// There is an entry point in the dll. Maybe it cannot find it? i do not know.
//call Entrypoint
a.push(0);
a.push(DLL_PROCESS_ATTACH);
a.push((unsigned int)mem._base);
a.mov(asmjit::x86::eax, (unsigned int)(file.epRVA + (DWORD)mem._base));
a.call(asmjit::x86::eax);
std::cout << "Execute Code?" << std::endl;
//Epilog
a.mov(asmjit::x86::esp, asmjit::x86::ebp);
a.pop(asmjit::x86::ebp);
std::cout << "EpiLog?" << std::endl;
a.ret();
void* code = a.make();
auto size = a.getCodeSize();
workerCode.Write(code, 0, size);
auto thread = CreateRemoteThread(_pe._proc, 0, 0, (LPTHREAD_START_ROUTINE)workerCode._base, 0, 0, 0);
if (!thread)
std::cout << "CreateRemoteThread failed " << std::endl;
//TRACE("CreateRemoteThread failed");
std::cout << "ThreadIssue??" << std::endl;
WaitForSingleObject(thread, INFINITE);
std::cout << "No?" << std::endl;
}
DWORD MapDependancy(std::string szDllName)
{
auto path = Utils::LookupDependancy(szDllName);
if (path.empty()) //Error: Could not find dependancy
{
//TRACE("Could not locate dependancy: %s", szDllName.c_str());
std::cout << "Could not locate dependancy: " << szDllName.c_str() << std::endl;
return 0;
}
else
{
if (!MapModuleInternal(path)) //Error: Didnt succeed mapping dependancy
{
//TRACE("Could not manual map: %s", szDllName.c_str());
std::cout << "Could not manual map : " << szDllName.c_str() << std::endl;
return 0;
}
else
{
//it needs to exist now since we just mapped it
// TRACE("Dependancy %s mapped correctly", szDllName.c_str());
std::cout << "Dependancy " << szDllName.c_str() << "mapped correctly" << std::endl;
return _pe.GetModuleBase(szDllName);
}
}
}
void FixImports(Memory& target, PE& file)
{
auto imports = file.imports;
for (auto keyVal : imports)
{
auto dllName = keyVal.first;
auto hMod = _pe.GetModuleBase(dllName);
//TRACE("Import Dll: %s, 0x%X", dllName.c_str(), hMod);
std::cout << "Import Dll: " << dllName.c_str() << std::endl;
if (hMod == 0) //manual map this dependancy
{
//TRACE("Mapping depedendancy: %s", dllName);
std::cout << "Mapping depedendancy: " << dllName.c_str() << std::endl;
hMod = MapDependancy(dllName);
if (hMod == 0) //Error: Didnt succeed mapping dependancy
{
return;
}
}
for (auto impData : keyVal.second)
{
if (impData.byOrdinal)
{
//Import by Ordinal
//TRACE("Import by Oridnal not handled");
std::cout << "Import by Oridnal not handled" << std::endl;
}
else
{
auto functionAddr = _pe.GetExport(hMod, impData.name);
if (!functionAddr)
std::cout << "Bad function address received" << std::endl;
//TRACE("Bad function address received");
//TRACE("Fixxing import table 0x%X", impData.rva);
target.Write((void*)impData.rva, functionAddr);
}
}
}
}
void FixRelocs(Memory& target, PE& file)
{
auto Delta = (DWORD)target._base - (DWORD)file.imgBase;
auto start = file.GetDirectoryAddress(IMAGE_DIRECTORY_ENTRY_BASERELOC);
auto end = start + file.GetDirectorySize(IMAGE_DIRECTORY_ENTRY_BASERELOC);
auto relocData = (PE::RelocData*)start;
while ((DWORD)relocData < end && relocData->BlockSize)
{
auto numRelocs = (relocData->BlockSize - 8) / 2;
for (int i = 0; i < numRelocs; ++i)
{
auto offset = relocData->Item[i].Offset % 4096;
auto type = relocData->Item[i].Type;
if (type == IMAGE_REL_BASED_ABSOLUTE)
continue;
if (type == IMAGE_REL_BASED_HIGHLOW)
{
auto rva = relocData->PageRVA + offset;
auto val = *(DWORD*)file.RVA2VA(rva) + Delta;
target.Write((void*)rva, val);
}
else
std::cout << "Abnormal relocation type" << std::endl;
//TRACE("Abnormal relocation type");
}
relocData = (PE::RelocData*)((DWORD)relocData + relocData->BlockSize);
}
}
void CopySections(Memory& mem, PE& file)
{
for (int i = 0; i < file.sections.size(); ++i)
{
if (!(file.sections[i].Characteristics & IMAGE_SCN_MEM_DISCARDABLE) && file.sections[i].SizeOfRawData != 0)
{
auto pSource = file.RVA2VA(file.sections[i].VirtualAddress);
mem.Write((void*)pSource, (void*)file.sections[i].VirtualAddress, file.sections[i].SizeOfRawData);
}
}
}
};
| [
"noreply@github.com"
] | noreply@github.com |
7ec3c1468f7e23304f8f29edb0061e68a9490376 | 64e10c331676432688395951235045e10056a565 | /app/bench_function.cpp | fe18e3e3ab27d70662714695ce9e48e369d7026b | [
"MIT"
] | permissive | cyy1991/libnano | ab2ea53bbfccc67988ab76ddfa85f18b787c307e | 45564e997a506eb867d6ddb9e2942a89a0077412 | refs/heads/master | 2020-06-29T18:33:52.889013 | 2019-07-16T14:45:01 | 2019-07-16T14:45:01 | 200,592,935 | 1 | 0 | null | 2019-08-05T06:11:09 | 2019-08-05T06:11:09 | null | UTF-8 | C++ | false | false | 2,529 | cpp | #include <nano/stats.h>
#include <nano/table.h>
#include <nano/logger.h>
#include <nano/cmdline.h>
#include <nano/function.h>
using namespace nano;
static void eval_func(const function_t& function, table_t& table)
{
stats_t fval_times;
stats_t grad_times;
const auto dims = function.size();
const vector_t x = vector_t::Zero(dims);
vector_t g = vector_t::Zero(dims);
const size_t trials = 16;
volatile scalar_t fx = 0;
const auto fval_time = measure<nanoseconds_t>([&] ()
{
fx += function.vgrad(x);
}, trials).count();
volatile scalar_t gx = 0;
const auto grad_time = measure<nanoseconds_t>([&] ()
{
function.vgrad(x, &g);
gx += g.template lpNorm<Eigen::Infinity>();
}, trials).count();
scalar_t grad_accuracy = 0;
for (size_t i = 0; i < trials; ++ i)
{
grad_accuracy += function.grad_accuracy(vector_t::Random(dims));
}
auto& row = table.append();
row << function.name() << fval_time << grad_time
<< nano::precision(12) << (grad_accuracy / static_cast<scalar_t>(trials));
}
static int unsafe_main(int argc, const char* argv[])
{
// parse the command line
cmdline_t cmdline("benchmark optimization test functions");
cmdline.add("", "min-dims", "minimum number of dimensions for each test function (if feasible)", "1024");
cmdline.add("", "max-dims", "maximum number of dimensions for each test function (if feasible)", "1024");
cmdline.add("", "functions", "use this regex to select the functions to benchmark", ".+");
cmdline.process(argc, argv);
if (cmdline.has("help"))
{
cmdline.usage();
return EXIT_SUCCESS;
}
// check arguments and options
const auto min_dims = cmdline.get<tensor_size_t>("min-dims");
const auto max_dims = cmdline.get<tensor_size_t>("max-dims");
const auto functions = std::regex(cmdline.get<string_t>("functions"));
table_t table;
table.header() << "function" << "f(x)[ns]" << "f(x,g)[ns]" << "grad accuracy";
table.delim();
tensor_size_t prev_size = min_dims;
for (const auto& function : get_functions(min_dims, max_dims, functions))
{
if (function->size() != prev_size)
{
table.delim();
prev_size = function->size();
}
eval_func(*function, table);
}
std::cout << table;
// OK
return EXIT_SUCCESS;
}
int main(int argc, const char* argv[])
{
return nano::main(unsafe_main, argc, argv);
}
| [
"accosmin@gmail.com"
] | accosmin@gmail.com |
f5b4ec58e57bfd2fafe0aa277e21118173ea848d | 7098f7d65a5759278661ab0e9bde96731c297c45 | /day01/ex03/Zombie.hpp | 2b8cce58237105383eff9fe24b999d9b005e8fd3 | [] | no_license | ViktoriaLi/cpp_pool | 9838a7bb917c60c44b5d41492ae5b45fb1bbc1bd | 2c27559ea2aed8131550f91992ff5d36a2efefc5 | refs/heads/master | 2020-03-20T04:34:19.654055 | 2018-06-30T10:33:39 | 2018-06-30T10:33:39 | 137,187,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,056 | hpp | // ************************************************************************** //
// //
// ::: :::::::: //
// Zombie.hpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: vlikhotk <marvin@42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/06/19 13:22:42 by vlikhotk #+# #+# //
// Updated: 2018/06/19 13:22:45 by vlikhotk ### ########.fr //
// //
// ************************************************************************** //
#ifndef ZOMBIE_HPP
#define ZOMBIE_HPP
#include <iostream>
class Zombie{
public:
Zombie();
~Zombie();
std::string type, name;
void announce();
};
#endif
| [
"viktoria.likhotkina@gmail.com"
] | viktoria.likhotkina@gmail.com |
5bd9164ac4bca64cc22ed7a26e7efeb11abee29f | 4d4fbfd4ed5b38fb807fc23b8ab5caf30b62b32d | /opencore-linux/fileformats/mp4/composer/include/basedescriptor.h | 297e399cda5e8cbbc9208e5dae0d59004893a796 | [
"MIT",
"LicenseRef-scancode-other-permissive",
"Artistic-2.0",
"LicenseRef-scancode-philippe-de-muyter",
"Apache-2.0",
"LicenseRef-scancode-mpeg-iso",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | rcoscali/ftke | e88464f1e85502ffb9c199106bc6cb24f789efcf | e9d4e59c4387400387b65124d4b47b70072dd098 | refs/heads/master | 2021-01-10T05:01:03.546718 | 2010-09-23T02:49:21 | 2010-09-23T02:49:21 | 47,364,325 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,728 | h | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/*
This PVA_FF_BaseDescriptor Class
*/
#ifndef __BaseDescriptor_H__
#define __BaseDescriptor_H__
#include "oscl_types.h"
#include "expandablebaseclass.h"
const uint32 DEFAULT_DESCRIPTOR_SIZE = 1; // 8 bits for the tag ONLY
// _sizeOfClass is computed explicitly elsewhere!
class PVA_FF_BaseDescriptor : public PVA_FF_ExpandableBaseClass
{
public:
PVA_FF_BaseDescriptor(uint8 tag); // Constructor
virtual ~PVA_FF_BaseDescriptor();
// Rendering only the members of the PVA_FF_BaseDescriptor class
int renderBaseDescriptorMembers(MP4_AUTHOR_FF_FILE_IO_WRAP *fp) const;
virtual void recomputeSize() = 0; // Should get overridden
uint32 getSize() const
{
return _sizeOfClass;
}
uint32 getDefaultDescriptorSize() const
{
return DEFAULT_DESCRIPTOR_SIZE;
}
private:
PVA_FF_BaseDescriptor() {} // Disabling public default constructor
};
#endif
| [
"xianjimli@7eec7cec-e015-11de-ab17-5d3be3536607"
] | xianjimli@7eec7cec-e015-11de-ab17-5d3be3536607 |
c920a4a63008cdedd5f56d32b6c56df99d3cb4bc | 1c08c04bb2e21d6c255adc71ba3f3a3bf12c2e13 | /src/modules/cuda32/thermal_cuda/spinoperationthermal.h | 0689a020946ddf92e6518bd9e9536b34d2db77a1 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | denkisdeng/maglua | 0e0b9faeee92b266c4b0aa8aca82dda4e8f49d58 | 48a26a7bced05ae8d840a06afc6f0b3a686133b6 | refs/heads/master | 2020-03-24T22:40:43.935202 | 2016-08-02T00:37:23 | 2016-08-02T00:37:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,988 | h | /******************************************************************************
* Copyright (C) 2008-2011 Jason Mercer. All rights reserved.
*
* 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 SPINOPERATIONTHERMAL
#define SPINOPERATIONTHERMAL
#include "spinoperation.h"
#include <stdint.h>
#ifdef WIN32
#define strcasecmp(A,B) _stricmp(A,B)
#define strncasecmp(A,B,C) _strnicmp(A,B,C)
#pragma warning(disable: 4251)
#ifdef THERMALCUDA_EXPORTS
#define THERMALCUDA_API __declspec(dllexport)
#else
#define THERMALCUDA_API __declspec(dllimport)
#endif
#else
#define THERMALCUDA_API
#endif
class RNG;
class THERMALCUDA_API Thermal : public SpinOperation
{
public:
Thermal(int nx=32, int ny=32, int nz=1);
virtual ~Thermal();
LINEAGE2("Thermal", "SpinOperation")
static const luaL_Reg* luaMethods();
virtual int luaInit(lua_State* L);
virtual void push(lua_State* L) {luaT_push<Thermal>(L, this);}
static int help(lua_State* L);
bool apply(RNG* rand, SpinSystem* ss);
bool applyToSum(RNG* rand, SpinSystem* ss);
bool apply(SpinSystem* ss) {return false;};
bool applyToSum(SpinSystem* ss) {return false;};
void scaleSite(int px, int py, int pz, double strength);
void init();
void deinit();
double temperature;
void sync_dh(bool force=false);
void sync_hd(bool force=false);
virtual void encode(buffer* b);
virtual int decode(buffer* b);
bool new_device;
bool new_host;
private:
float* d_scale;
float* h_scale;
};
#endif
| [
"jason.mercer@gmail.com"
] | jason.mercer@gmail.com |
e10ed93ff8d94fa5a1a392cf0fedbd0a14d97b7b | ba443feeb01cf97fdb8d763c0efe6df1b5adadf5 | /Engine/Brain.h | 44be4d90e89f7508f1c71f27901cff7b6d2488ea | [] | no_license | s0lly/Steering-Behaviours | ca0640ccc5d9a04786e2e5f3315d6161eb3edafa | 11c124f81a889e07a4ee36c5c39d3482aa28d2c1 | refs/heads/master | 2020-05-09T08:29:59.153459 | 2019-05-02T20:39:27 | 2019-05-02T20:39:27 | 180,994,981 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,952 | h | #pragma once
#include "Behaviour.h"
#include "PhysicsInfo.h"
#include "Vec2.h"
#include <vector>
#include <algorithm>
class Brain
{
public:
Brain(PhysicsInfo *in_selfPtr)
:
selfPtr(in_selfPtr)
{
}
void Refresh()
{
// Reset all behaviours
for (int i = 0; i < behaviours.size(); i++)
{
behaviours[i]->targets.clear();
behaviours[i]->allBehaviours = behaviours;
//behaviours[i]->info.desiredVelocity = Vec2();
behaviours[i]->info.steeringVelocity = Vec2();
behaviours[i]->info.currentTargets = 0;
}
// Reset all total velocity infos
selfPtr->totalDesiredVelocity = Vec2();
selfPtr->totalSteeringVelocity = Vec2();
}
void DetermineVelocities(std::vector<PhysicsInfo*> worldObjectPhysicsInfos)
{
// Remove relativeInfo from PhysicsInfo for mt... doesn't belong there anyway??
std::vector<RelativeInfo> worldObjectRelativeInfos;
for (int j = 0; j < worldObjectPhysicsInfos.size(); j++)
{
worldObjectRelativeInfos.push_back(RelativeInfo());
worldObjectRelativeInfos[j].SetRelativeInfo(selfPtr, worldObjectPhysicsInfos[j]);
}
std::sort(worldObjectRelativeInfos.begin(), worldObjectRelativeInfos.end(), [](RelativeInfo &a, RelativeInfo &b) { return a < b; });
for (int j = 0; j < worldObjectRelativeInfos.size(); j++)
{
int physicsInfoIndex = -1;
for (int k = 0; k < worldObjectPhysicsInfos.size(); k++)
{
if (worldObjectPhysicsInfos[k]->ID == worldObjectRelativeInfos[j].ID)
{
physicsInfoIndex = k;
break;
}
}
if (selfPtr->ID != worldObjectPhysicsInfos[physicsInfoIndex]->ID && worldObjectRelativeInfos[j].isInEyesight)
{
for (int b = 0; b < behaviours.size(); b++)
{
if (worldObjectRelativeInfos[j].relativeDistSqrd > behaviours[b]->info.addTargetsInDistSqrdMin &&
worldObjectPhysicsInfos[physicsInfoIndex]->brainType == behaviours[b]->info.targetBrainType)
{
if (behaviours[b]->info.currentTargets < behaviours[b]->info.maxTargets &&
worldObjectRelativeInfos[j].relativeDistSqrd < behaviours[b]->info.addTargetsInDistSqrdMax)
{
behaviours[b]->AddTarget(worldObjectPhysicsInfos[physicsInfoIndex], worldObjectRelativeInfos[j]);
behaviours[b]->info.currentTargets++;
}
else
{
break;
}
}
}
}
}
for (int b = 0; b < behaviours.size(); b++)
{
if (behaviours[b]->info.isActive)
{
behaviours[b]->PerformLogicAndSetVelocityVectors();
// Think about this!!
selfPtr->totalSteeringVelocity = selfPtr->totalSteeringVelocity + behaviours[b]->info.steeringVelocity * behaviours[b]->info.intensity;
}
}
//if (selfPtr->totalDesiredVelocity.GetMagnitude() > selfPtr->maxSpeed)
//{
// selfPtr->totalDesiredVelocity = selfPtr->totalDesiredVelocity.Normalize() * selfPtr->maxSpeed;
//}
if (selfPtr->totalSteeringVelocity.GetMagnitude() > selfPtr->maxSpeed)
{
selfPtr->totalSteeringVelocity = selfPtr->totalSteeringVelocity.Normalize() * selfPtr->maxSpeed;
}
selfPtr->totalDesiredVelocity = selfPtr->totalSteeringVelocity + selfPtr->velocity;
}
PhysicsInfo *selfPtr;
std::vector<Behaviour*> behaviours;
float randomness;
};
// REDO THESE CLASSES SO THAT THEY ARE JUST ALL IN BRAIN WITH FACTORY GENERATOR!!!!
//static void BrainFactory()
//{
//
//}
class SharkBrain : public Brain
{
public:
SharkBrain(PhysicsInfo *in_selfPtr)
:
Brain(in_selfPtr)
{
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SEEK GROUP", SEEK, BRAIN_TYPE::BEE, 0.0f, 60000.0f * 60000.0f, 1.0f, 10 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SEEK SINGLE", SEEK, BRAIN_TYPE::BEE, 0.0f, 500.0f * 500.0f, 5.0f, 1 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "ARRIVE SINGLE", ARRIVE, BRAIN_TYPE::BEE, 0.0f, 10000.0f * 10000.0f, 10000.0f, 1 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "PURSUE SINGLE", PURSUE, BRAIN_TYPE::BEE, 0.0f, 10000.0f * 10000.0f, 10000.0f, 1 }));
//behaviours.push_back(CreateBehaviour(in_selfPtr, { "WANDER", WANDER, BRAIN_TYPE::FISH, 0.0f, 0.0f, 1.0f, 0 }));
//behaviours.push_back(CreateBehaviour(in_selfPtr, { "SLOW DOWN", SLOW_DOWN, BRAIN_TYPE::FISH, 0.0f, 0.0f, 1.0f, 0 }));
//behaviours.push_back(CreateBehaviour(in_selfPtr, { "FLEE WALLS", FLEE, BRAIN_TYPE::NONE, 0.0f, 300.0f * 300.0f, 10000000.0f, 1 }));
}
};
class FishBrain : public Brain
{
public:
FishBrain(PhysicsInfo *in_selfPtr)
:
Brain(in_selfPtr)
{
behaviours.push_back(CreateBehaviour(in_selfPtr, { "ALIGN TO FISH", ALIGN, BRAIN_TYPE::FISH, 0.0f, 1000.0f * 1000.0f, 2.0f, 10 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SEEK FAR FISH", SEEK, BRAIN_TYPE::FISH, 0.0f, 60000.0f * 60000.0f, 1.0f, 10 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SEPARATE FISH", SEPARATION, BRAIN_TYPE::FISH, 0.0f, 200.0f * 200.0f, 3.0f, 10 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "FLEE SHARK", EVADE, BRAIN_TYPE::SHARK, 0.0f, 400.0f * 400.0f, 10.0f, 1 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "WANDER", WANDER, BRAIN_TYPE::FISH, 0.0f, 0.0f, 1.0f, 0 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SLOW DOWN", SLOW_DOWN, BRAIN_TYPE::FISH, 0.0f, 0.0f, 1.0f, 0 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "FLEE WALLS", FLEE, BRAIN_TYPE::NONE, 0.0f, 300.0f * 300.0f, 10000000.0f, 1 }));
}
};
class BeeBrain : public Brain
{
public:
BeeBrain(PhysicsInfo *in_selfPtr)
:
Brain(in_selfPtr)
{
//behaviours.push_back(CreateBehaviour(in_selfPtr, { "ALIGN TO FISH", ALIGN, BRAIN_TYPE::BEE, 0.0f, 1000.0f * 1000.0f, 0.0f, 10 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SEEK FAR BEES", SEEK, BRAIN_TYPE::BEE, 400.0f * 400.0f, 60000.0f * 60000.0f, 5000.0f, 1000 }));
//behaviours.push_back(CreateBehaviour(in_selfPtr, { "SEPARATION NEAR FISH", SEPARATION, BRAIN_TYPE::BEE, 0.0f, 500.0f * 500.0f, 0.0f, 10 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "FLEE SHARK", FLEE, BRAIN_TYPE::SHARK, 0.0f, 400.0f * 400.0f, 10000.0f, 1 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "FLEE FISH", FLEE, BRAIN_TYPE::FISH, 0.0f, 400.0f * 400.0f, 10000.0f, 1 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "WANDER", WANDER, BRAIN_TYPE::BEE, 0.0f, 0.0f, 1000.0f, 0 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SLOW DOWN", SLOW_DOWN, BRAIN_TYPE::BEE, 0.0f, 0.0f, 1.0f, 0 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "FLEE WALLS", FLEE, BRAIN_TYPE::NONE, 0.0f, 300.0f * 300.0f, 10000000.0f, 1 }));
}
};
class ObstacleBrain : public Brain
{
public:
ObstacleBrain(PhysicsInfo *in_selfPtr)
:
Brain(in_selfPtr)
{
// why slow down not working without seek/evade etc?
behaviours.push_back(CreateBehaviour(in_selfPtr, { "WANDER", WANDER, BRAIN_TYPE::BEE, 0.0f, 0.0f, 1000.0f, 1 }));
behaviours.push_back(CreateBehaviour(in_selfPtr, { "SLOW DOWN", SLOW_DOWN, BRAIN_TYPE::BEE, 0.0f, 0.0f, 1.0f, 0 }));
}
};
| [
"s0lly@users.noreply.github.com"
] | s0lly@users.noreply.github.com |
7de334e8cb11392be9402138c24b1404f4aff750 | fcddb939ac434d1397701a741df43662caebe392 | /c++/3.cpp | f9ca652da55dc1429176238534529dd84e9c30f3 | [] | no_license | kjsr7/coding | f93cfe2a2bd6de0f06b94af3c0ac82af8d2ec668 | 35ce3bdf814cf5085023707301ce93d1c073032b | refs/heads/master | 2020-03-30T19:12:14.104667 | 2018-10-23T17:08:58 | 2018-10-23T17:08:58 | 149,289,730 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 137 | cpp | #include <iostream>
using namespace std;
int main()
{
int a = 5, b = 10, c = 15;
int *arr[ ] = {&a, &b, &c};
cout << arr[1];
return 0;
}
| [
"kommurujaishankarreddy@gmail.com"
] | kommurujaishankarreddy@gmail.com |
c667f38ddd16e940fdcdc214447504ffdc32f1a5 | 2c811434dd9cc3bb54d64f92733c40ddd3fa0383 | /Codeforces-AC/CF 282D Yet Another Number Game.cpp | 6aaba5f35c5af36fc952c250270a25db25a56c2f | [] | no_license | gmtranthanhtu/competitive-programming | 457e5cc16ede75d9496ac195de845ebe8d6e5664 | d765002704e2a8cf547cbe67f0f9a31db88bfc9b | refs/heads/master | 2021-01-23T08:56:52.594506 | 2014-11-01T09:52:12 | 2014-11-01T09:52:12 | 26,047,176 | 3 | 3 | null | 2020-10-01T14:15:30 | 2014-11-01T09:55:03 | C++ | UTF-8 | C++ | false | false | 4,304 | cpp | /*
Name: CF 282D Yet Another Number Game
Author: 3T - mailto: gm.tranthanhtu@gmail.com
Date: 13/3/2013
Algorithm: dp, games, Nim
Time Limit: 2.000s
*/
//COMPETITIVE PROGRAMMING TEMPLATE
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <utility>
#include <deque>
#include <list>
#include <sstream>
#include <fstream>
#include <complex>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <cassert>
#include <iostream>
#include <utility>
#include <iterator>
#include <numeric>
#include <climits>
using namespace std;
#define fr(i,a,b) for (int i = (a), _b = (b); i <= _b; i++)
#define frr(i,a,b) for (int i = (a), _b = (b); i >= _b; i--)
#define rep(i,n) for (int i = 0, _n = (n); i < _n; i++)
#define repr(i,n) for (int i = (n) - 1; i >= 0; i--)
#define foreach(it,ar) for ( typeof(ar.begin()) it = ar.begin(); it != ar.end(); it++ )
#define fill(ar,val) memset(ar, val, sizeof(ar))
#define fill0(ar) fill((ar), 0)
#define fillinf(ar, n) fr(i,0,(n)) ar[i] = INF
#define debug(x) cout<<#x<<": "<<x<<endl
#define arr1d(a,n) cout << #a << " : "; fr(_,1,n) cout << a[_] << ' '; cout << endl;
#define arr1d0(a,n) cout << #a << " : "; rep(_,n) cout << a[_] << ' '; cout << endl;
#define arr2d(a,n,m) cout << #a << " :" << endl; fr(_,1,n) {fr(__,1,m) cout << a[_][__] << ' '; cout << endl;}
#define arr2d0(a,n,m) cout << #a << " :" << endl; rep(_,n) {rep(__,m) cout << a[_][__] << ' '; cout << endl;}
#define ull unsigned long long
#define ll long long
#define ld double
#define ui unsigned int
#define all(ar) ar.begin(), ar.end()
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define y0 yyyyyy0
#define y1 yyyyyy1
#define BIT(n) (1<<(n))
#define SQR(x) ((x) * (x))
#define CUBE(x) ((x) * (x) * (x))
#define LSOne(S) (S) & (-S)
inline bool EQ(double a, double b) {return fabs(a - b) < 1e-9;}
typedef pair<int, int> ii;
typedef pair<int, ii> iii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef vector<string> vs;
template<typename T>inline T gcd(T a, T b){if (b == 0)return a;else return gcd(b, a % b);}
template<typename T>inline T lcm(T a, T b){return (a * b) / gcd(a, b);}
template<typename T> string toStr(T x) {stringstream st; st << x; string s; st >> s; return s;}
template<class T>
void splitStr(const string &s, vector<T> &out)
{
istringstream in(s);
out.clear();
copy(istream_iterator<T>(in), istream_iterator<T>(), back_inserter(out));
}
inline int two(int n) {return 1 << n;}
inline int isOnBit(int n, int b) {return (n >> b) & 1;}
inline void onBit(int & n, int b) {n |= two(b);}
inline void offBit(int & n, int b) {n &= ~two(b);}
inline int lastBit(int n) {return n & (-n);}
inline int cntBit(int n) {int res = 0; while(n && ++res) n -= n &(-n); return res;}
const int dx4[] = {-1, 0, 1, 0};
const int dy4[] = {0, 1, 0, -1};
const int dx8[] = {-1, 0, 1, 0, -1, -1, 1, 1};
const int dy8[] = {0, 1, 0, -1, -1, 1, -1, 1};
#define INP "test.inp"
#define OUT "test.out"
#define PI 3.1415926535897932385
#define INF 1000111222
#define EPS 1e-7
#define MAXN 301
#define MOD 1000000007
//END OF COMPETITVE PROGRAMMING TEMPLATE
int f[MAXN][MAXN][MAXN], n, a[4];
int go(int a, int b, int c) {
int &res = f[a][b][c];
if(res != -1) return res;
if(!(a + b + c)) return res = 0;
res = 0;
fr(i, 1, a) if(!go(a - i, b, c)) return res = 1;
fr(i, 1, b) if(!go(a, b - i, c)) return res = 1;
fr(i, 1, c) if(!go(a, b, c - i)) return res = 1;
int Min;
if(n == 1) Min = a;
else if(n == 2) Min = min(a, b);
fr(i, 1, Min) if(!go(max(a - i, 0), max(b - i, 0), max(c - i, 0))) return res = 1;
return res;
}
int main () {
#ifndef ONLINE_JUDGE
freopen(INP, "r", stdin); freopen(OUT, "w", stdout);
#endif
scanf("%d", &n);
fill0(a);
rep(i, n) scanf("%d", &a[i]);
fill(f, -1);
if(n == 3) {
int x = a[0] ^ a[1] ^ a[2];
printf("%s\n", x ? "BitLGM" : "BitAryo");
return 0;
}
printf("%s\n", go(a[0], a[1], a[2]) ? "BitLGM" : "BitAryo");
return 0;
}
| [
"tutt@designveloper.com"
] | tutt@designveloper.com |
9b46927fb659ecadcf992e592811017118fb039d | 9b86131182f9c46a96b96acf7a238073ebaa9556 | /chapter-01/exercise-1.3-dw.cpp | 6589e022d3e8a683a503eed7702045418de7e860 | [] | no_license | SBU-Cpp-Club/cpp-exercises | a39e7a97b5b6b5dfcdc61fb1e1f07e14b8f04c64 | f12e3dc0370d80f23712190e5de52a5e5d5cb783 | refs/heads/master | 2023-08-16T19:40:22.262570 | 2023-08-13T14:19:56 | 2023-08-13T14:19:56 | 75,423,067 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 92 | cpp | #include <iostream>
int main()
{
std::cout << "Hello, World" << std::endl;
return 0;
}
| [
"eugene.willcox@gmail.com"
] | eugene.willcox@gmail.com |
24b142df9b16aeb6a750581a09ea26054bcf1147 | b4405caa385b9807724de579906a6bb4844370fa | /GeneratedFiles/ui_DopFrom.h | 1c7b46e0662a01b90a772de78593ce89b83a4680 | [] | no_license | eglrp/SatelliteDetectionSystem | 5c2533785f933ceded85bca85ba950de3ea239a0 | 874b8343497ab2a7f2eb2621ad8ae21de1f1e86c | refs/heads/master | 2020-04-07T04:23:16.289455 | 2017-09-02T07:55:52 | 2017-09-02T07:55:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | h | /********************************************************************************
** Form generated from reading UI file 'DopFrom.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DOPFROM_H
#define UI_DOPFROM_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_DopFrom
{
public:
void setupUi(QWidget *DopFrom)
{
if (DopFrom->objectName().isEmpty())
DopFrom->setObjectName(QStringLiteral("DopFrom"));
DopFrom->resize(155, 80);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(DopFrom->sizePolicy().hasHeightForWidth());
DopFrom->setSizePolicy(sizePolicy);
retranslateUi(DopFrom);
QMetaObject::connectSlotsByName(DopFrom);
} // setupUi
void retranslateUi(QWidget *DopFrom)
{
DopFrom->setWindowTitle(QApplication::translate("DopFrom", "Dop\345\233\276", 0));
} // retranslateUi
};
namespace Ui {
class DopFrom: public Ui_DopFrom {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DOPFROM_H
| [
"928683372@qq.com"
] | 928683372@qq.com |
7f3958c3d2b617b5938353e524ce884adebeb856 | 3a0fa123260acb378bf02345b50cd57abb6cc9d3 | /client/menu.h | c61e60589e23feae836622c4bc4d89bc2630693d | [] | no_license | andriygav/PokerRoom | c4072676794dc5ad628724e673b5c1f8f3c4965a | 019d1a5bf86c3ad1b863f5314780b52234ebe4ec | refs/heads/master | 2020-04-09T02:05:51.561262 | 2018-12-09T17:58:51 | 2018-12-09T17:58:51 | 159,928,479 | 1 | 0 | null | 2018-12-02T06:34:12 | 2018-12-01T09:22:41 | C++ | UTF-8 | C++ | false | false | 768 | h | #pragma once
#include <SDL.h>
#include <SDL_ttf.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <signal.h>
#include "button.h"
#include "client.h"
class menu{
public:
SDL_Surface* screen;
SDL_Surface* back;
button* but[256];
TTF_Font* font;
int show();
menu(SDL_Surface*, client_t*);
~menu();
int action(SDL_Event* event);
client_t* my;
};
struct menu_scene_argument_t{
client_t* my;
pthread_mutex_t* mut_exit;
class menu* scene;
};
struct menu_scanf_argument_t{
client_t* my;
pthread_mutex_t* mut_exit;
};
struct menu_get_info_from_server_argument_t{
client_t* my;
pthread_mutex_t* mut_exit;
};
void* menu_get_info_from_server(void* arguments);
void* menu_scanf(void* arguments);
void* menu_scene(void* arguments);
| [
"andriy.graboviy@mail.ru"
] | andriy.graboviy@mail.ru |
62286efc8f88e85a2db03261f95d819587afb27e | aadf31061666fc9fd95583710a34d01fa571b09f | /include/LLVMExternalGlobalDeclaration.hpp | 97782125497e13c88ab6bceeef16e86e93d161b1 | [] | no_license | vladfridman/wisey | 6198cf88387ea82175ea6e1734edb7f9f7cf20c6 | 9d0efcee32e05c7b8dc3dfd22293737324294fea | refs/heads/master | 2022-04-14T08:00:42.743194 | 2020-03-12T14:22:45 | 2020-03-12T14:22:45 | 74,822,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | hpp | //
// LLVMExternalGlobalDeclaration.hpp
// Wisey
//
// Created by Vladimir Fridman on 8/16/18.
// Copyright © 2018 Vladimir Fridman. All rights reserved.
//
#ifndef LLVMExternalGlobalDeclaration_h
#define LLVMExternalGlobalDeclaration_h
#include "IGlobalStatement.hpp"
#include "ITypeSpecifier.hpp"
namespace wisey {
/**
* Externally defined global variable
*/
class LLVMExternalGlobalDeclaration : public IGlobalStatement {
const ITypeSpecifier* mTypeSpecifier;
std::string mName;
public:
LLVMExternalGlobalDeclaration(const ITypeSpecifier* typeSpecifier,
std::string mName);
~LLVMExternalGlobalDeclaration();
IObjectType* prototypeObject(IRGenerationContext& context,
ImportProfile* importProfile) const override;
void prototypeMethods(IRGenerationContext& context) const override;
void generateIR(IRGenerationContext& context) const override;
};
} /* namespace wisey */
#endif /* LLVMExternalGlobalDeclaration_h */
| [
"vlad.fridman@gmail.com"
] | vlad.fridman@gmail.com |
94bb0f479cdd880a42783e7ae19ae7f6eb8a1461 | 3fd9df379502ce8f72c59350635d0f0107c6e8b8 | /Lesson21/src/Lesson21.cpp | 424680f74359e71101d478be7df00a5681f447aa | [] | no_license | akash682/Cpp_UDEMY | 8e2ecab9bbd11d22a1ac5bcbf36a1aa3edb49781 | b69f2039a9fc1661999c294835975e4fb33b42b0 | refs/heads/master | 2020-04-27T03:06:42.814968 | 2019-03-05T20:31:07 | 2019-03-05T20:31:07 | 174,015,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | /*
* Lesson21.cpp
*
* Created on: Nov 9, 2018
* Author: Akash Lohani
*/
#include <iostream>
using namespace std;
int main(){
/*
for(int i =1; i<=10; i++){
if(i==5){
continue;
}
if(i==9){
break;
}
for(int j=1; j<=10; j++){
cout.width(4);
cout<<i*j;
}
cout<<endl;
}
*/
for (int i =1,j=1; i<=10; i++){
cout.width(4);
cout << i*j;
if (i==10){
j++;
i=0;
cout<< endl;
}
if(j == 10 + 1){
break;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
f43eb64c18154c34760a06ae30a948be4ed116cc | 65b7ee5b4b84af8f47b2c811e380bf9390fa730a | /Quiz/quiz2V2/A.cpp | cf2320f68e1efd0daab3f2d2ffac0ef0b842aa68 | [] | no_license | zethuman/PP1 | 1171b1cba1929752f96a91466c202464a92b0e39 | d49c2d83fb80166d501e61d64a49b46c665ec5e4 | refs/heads/master | 2020-09-01T23:49:46.533544 | 2019-11-02T01:46:40 | 2019-11-02T01:46:40 | 219,089,135 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[n];
int g = 0;
for (int i = 0; i < n; i++ )
{
cin >> a[i];
}
for (int i = 0; i < n; i++ )
{
if (a[i] == 0 )
{
g++;
}
}
for (int i = 0; i < n; i++ )
{
if (a[i] == 0 && a[i + 1] != 1 )
{
g--;
}
}
cout << g ;
}
| [
"51375666+zethuman@users.noreply.github.com"
] | 51375666+zethuman@users.noreply.github.com |
b3977626468566bac7ee34cd3f22f9f28d82fb27 | d307bf61956911cad61029350a9fd203b8fdf7af | /Ziggurat Scenario/main.cpp | 276bb927c463a3d0c509590bad815aa013ba982e | [] | no_license | NayeemHasan807/learning-computer-graphics-fall-2020-2021 | 9c1da4f93bccb1eb3884c0290a7fae8d14cecc8f | 14ed5f3ae924e97a7536aa8441f1246a859ea8f7 | refs/heads/main | 2023-02-15T03:18:38.317107 | 2021-01-09T15:27:32 | 2021-01-09T15:27:32 | 321,104,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,992 | cpp | #include <windows.h> // for MS Windows
#include <GL/glut.h> // GLUT, include glu.h and gl.h
#include <math.h>
void init() {
gluOrtho2D(-5,5,-5,5);
}
void ziggurat_background() //f_z_1
{
glBegin(GL_POLYGON); //sky
glColor3ub(78,230,200); //blue
glVertex2f(-5.0f, -1.0f);
glVertex2f(5.0f, -1.0f);
glVertex2f(5.0f, 5.0f);
glVertex2f(-5.0f, 5.0f);
glEnd();
glBegin(GL_POLYGON); //ground
glColor3ub(230,165,78); //green
glVertex2f(-5.0f, -1.0f);
glVertex2f(5.0f, -1.0f);
glVertex2f(5.0f, -5.0f);
glVertex2f(-5.0f, -5.0f);
glEnd();
}
void ziggurat_layer4() //f_z_2
{
//layer 4 top
glBegin(GL_POLYGON);
glColor3ub(205,168,33);
glVertex2f(2.0f, 0.0f);
glVertex2f(-3.8f, 0.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(4.0f, -2.0f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(2.0f, 0.0f);
glVertex2f(-3.8f, 0.0f);
glVertex2f(-3.8f, 0.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(4.0f, -2.0f);
glVertex2f(4.0f, -2.0f);
glVertex2f(2.0f, 0.0f);
glEnd();
//layer 4 body
glBegin(GL_POLYGON);
glColor3ub(255, 255, 102);
glVertex2f(4.0f, -2.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(4.0f, -3.0f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(255, 210, 77);
glVertex2f(-3.8f, 0.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(-3.8f, -1.0f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(4.0f, -2.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(4.0f, -3.0f);
glVertex2f(4.0f, -3.0f);
glVertex2f(4.0f, -2.0f);
glVertex2f(-3.8f, 0.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -2.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(-3.8f, -1.0f);
glVertex2f(-3.8f, -1.0f);
glVertex2f(-3.8f, 0.0f);
glEnd();
}
void ziggurat_layer3() //f_z_3
{
//layer 3 top
glBegin(GL_POLYGON);
glColor3ub(205,168,33);
glVertex2f(1.5f, 1.0f);
glVertex2f(-3.0f, 1.0f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(3.5f, -0.5f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(1.5f, 1.0f);
glVertex2f(-3.0f, 1.0f);
glVertex2f(-3.0f, 1.0f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(3.5f, -0.5f);
glVertex2f(3.5f, -0.5f);
glVertex2f(1.5f, 1.0f);
glEnd();
//layer 3 body
glBegin(GL_POLYGON);
glColor3ub(255, 255, 102);
glVertex2f(3.5f, -0.5f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -1.5f);
glVertex2f(3.5f, -1.5f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(255, 210, 77);
glVertex2f(-3.0f, 1.0f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -1.5f);
glVertex2f(-3.0f, 0.0f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(3.5f, -0.5f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -1.5f);
glVertex2f(-1.5f, -1.5f);
glVertex2f(3.5f, -1.5f);
glVertex2f(3.5f, -1.5f);
glVertex2f(3.5f, -0.5f);
glVertex2f(-3.0f, 1.0f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -0.5f);
glVertex2f(-1.5f, -1.5f);
glVertex2f(-1.5f, -1.5f);
glVertex2f(-3.0f, 0.0f);
glVertex2f(-3.0f, 0.0f);
glVertex2f(-3.0f, 1.0f);
glEnd();
}
void ziggurat_layer2() //f_z_4
{
//layer 2 top
glBegin(GL_POLYGON);
glColor3ub(205,168,33);
glVertex2f(1.0f, 2.0f);
glVertex2f(-2.2f, 2.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(2.8f, 1.0f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(1.0f, 2.0f);
glVertex2f(-2.2f, 2.0f);
glVertex2f(-2.2f, 2.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(2.8f, 1.0f);
glVertex2f(2.8f, 1.0f);
glVertex2f(1.0f, 2.0f);
glEnd();
//layer 2 body
glBegin(GL_POLYGON);
glColor3ub(255, 255, 102);
glVertex2f(2.8f, 1.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 0.0f);
glVertex2f(2.8f, 0.0f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(255, 210, 77);
glVertex2f(-2.2f, 2.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 0.0f);
glVertex2f(-2.2f, 1.0f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(2.8f, 1.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 0.0f);
glVertex2f(-1.2f, 0.0f);
glVertex2f(2.8f, 0.0f);
glVertex2f(2.8f, 0.0f);
glVertex2f(2.8f, 1.0f);
glVertex2f(-2.2f, 2.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 1.0f);
glVertex2f(-1.2f, 0.0f);
glVertex2f(-1.2f, 0.0f);
glVertex2f(-2.2f, 1.0f);
glVertex2f(-2.2f, 1.0f);
glVertex2f(-2.2f, 2.0f);
glVertex2f(-2.2f, 2.0f);
glEnd();
}
void ziggurat_layer1() //f_z_5
{
//layer 1 top
glBegin(GL_POLYGON);
glColor3ub(205,168,33);
glVertex2f(1.0f, 3.0f);
glVertex2f(-1.6f, 3.0f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(1.8f, 2.5f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(1.0f, 3.0f);
glVertex2f(-1.6f, 3.0f);
glVertex2f(-1.6f, 3.0f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(1.8f, 2.5f);
glVertex2f(1.8f, 2.5f);
glVertex2f(1.0f, 3.0f);
glEnd();
//layer 1 body
glBegin(GL_POLYGON);
glColor3ub(255, 255, 102);
glVertex2f(-1.0f, 2.5f);
glVertex2f(1.8f, 2.5f);
glVertex2f(1.8f, 1.5f);
glVertex2f(-1.0f, 1.5f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(255, 210, 77);
glVertex2f(-1.6f, 3.0f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(-1.0f, 1.5f);
glVertex2f(-1.6f, 2.0f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(-1.0f, 2.5f);
glVertex2f(1.8f, 2.5f);
glVertex2f(1.8f, 2.5f);
glVertex2f(1.8f, 1.5f);
glVertex2f(1.8f, 1.5f);
glVertex2f(-1.0f, 1.5f);
glVertex2f(-1.0f, 1.5f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(-1.6f, 3.0f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(-1.0f, 2.5f);
glVertex2f(-1.0f, 1.5f);
glVertex2f(-1.0f, 1.5f);
glVertex2f(-1.6f, 2.0f);
glVertex2f(-1.6f, 2.0f);
glVertex2f(-1.6f, 3.0f);
glEnd();
//level 1 entrance1
glBegin(GL_POLYGON);
glColor3ub(0,0,0);
glVertex2f(0.5f, 1.5f);
glVertex2f(0.0f, 1.5f);
glVertex2f(0.0f, 2.0f);
glVertex2f(0.5f, 2.0f);
glEnd();
//level 1 entrance2
glBegin(GL_POLYGON);
glColor3ub(0,0,0);
glVertex2f(-1.45f, 1.89f);
glVertex2f(-1.25f, 1.7f);
glVertex2f(-1.25f, 2.1f);
glVertex2f(-1.45f, 2.3f);
glEnd();
}
void ziggurat_stairway1() //f_z_6
{
glBegin(GL_POLYGON);
glColor3ub(220, 220, 96);
glVertex2f(0.6,1.0f);
glVertex2f(0.0,1.0f);
glVertex2f(0.5,-3.3f);
glVertex2f(1.4,-3.3f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(0.6,1.0f);
glVertex2f(0.0,1.0f);
glVertex2f(0.0,1.0f);
glVertex2f(0.5,-3.3f);
glVertex2f(0.5,-3.3f);
glVertex2f(1.4,-3.3f);
glVertex2f(1.4,-3.3f);
glVertex2f(0.6,1.0f);
glEnd();
glLineWidth(4.5);
glBegin(GL_LINES);
glVertex2f(0.03f,0.8f);
glVertex2f(0.64f,0.8f);
glVertex2f(0.06f,0.4f);
glVertex2f(0.72f,0.4f);
glVertex2f(0.11f,0.0f);
glVertex2f(0.8f,0.0f);
glVertex2f(0.16f,-0.4f);
glVertex2f(0.86f,-0.4f);
glVertex2f(0.21f,-0.8f);
glVertex2f(0.93f,-0.8f);
glVertex2f(0.25f,-1.2f);
glVertex2f(1.0f,-1.2f);
glVertex2f(0.30f,-1.6f);
glVertex2f(1.09f,-1.6f);
glVertex2f(0.35f,-2.0f);
glVertex2f(1.17f,-2.0f);
glVertex2f(0.39f,-2.4f);
glVertex2f(1.24f,-2.4f);
glVertex2f(0.44f,-2.8f);
glVertex2f(1.30f,-2.8f);
glEnd();
}
void ziggurat_stairway2() //f_z_7
{
glBegin(GL_POLYGON);
glColor3ub(220, 220, 96);
glVertex2f(-1.5,1.3f);
glVertex2f(-1.9,1.7f);
glVertex2f(-3.7,-1.9f);
glVertex2f(-3.1,-2.4f);
glEnd();
glLineWidth(2.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(-1.5,1.3f);
glVertex2f(-1.9,1.7f);
glVertex2f(-1.9,1.7f);
glVertex2f(-3.7,-1.9f);
glVertex2f(-3.7,-1.9f);
glVertex2f(-3.1,-2.4f);
glVertex2f(-3.1,-2.4f);
glVertex2f(-1.5,1.3f);
glEnd();
glLineWidth(4.5);
glBegin(GL_LINES);
glColor3f(0.0f, 0.0f, 0.0f); //black
glVertex2f(-1.59f,1.1f);
glVertex2f(-2.01f,1.5f);
glVertex2f(-1.72f,0.8f);
glVertex2f(-2.155f,1.2f);
glVertex2f(-1.85f,0.5f);
glVertex2f(-2.299f,0.9f);
glVertex2f(-1.98f,0.2f);
glVertex2f(-2.45f,0.6f);
glVertex2f(-2.095f,-0.1f);
glVertex2f(-2.60f,0.3f);
glVertex2f(-2.23f,-0.4f);
glVertex2f(-2.75f,0.0f);
glVertex2f(-2.355f,-0.7f);
glVertex2f(-2.89f,-0.3f);
glVertex2f(-2.5f,-1.0f);
glVertex2f(-3.05f,-0.6f);
glVertex2f(-2.62f,-1.3f);
glVertex2f(-3.20f,-0.9f);
glVertex2f(-2.75f,-1.6f);
glVertex2f(-3.35f,-1.2f);
glVertex2f(-2.89f,-1.9f);
glVertex2f(-3.5f,-1.5f);
glVertex2f(-3.01f,-2.2f);
glVertex2f(-3.64f,-1.75f);
glEnd();
}
void ziggurat() //f_z_8
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
ziggurat_layer4();
glPopMatrix();
glPushMatrix();
ziggurat_layer3();
glPopMatrix();
glPushMatrix();
ziggurat_layer2();
glPopMatrix();
glPushMatrix();
ziggurat_layer1();
glPopMatrix();
glPushMatrix();
ziggurat_stairway1();
glPopMatrix();
glPushMatrix();
ziggurat_stairway2();
glPopMatrix();
}
void display_z()
{
glClearColor(0.0f, 0.8f, 1.0f, 1.0f); // Set background color to white and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background)
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
ziggurat_background();
glPopMatrix();
glPushMatrix();
ziggurat();
glPopMatrix();
glutSwapBuffers();
glFlush(); // Render now
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
glutInit(&argc, argv); // Initialize GLUT
glutInitWindowSize(480, 300); // Set the window's initial width & height
glutInitWindowPosition(50, 50);
glutCreateWindow("Ziggurat"); // Create a window with the given title
glutDisplayFunc(display_z); // Register display callback handler for window re-paint
init(); // Enter the event-processing loop
glutMainLoop();
return 0;
}
| [
"moonnayeem87@gmail.com"
] | moonnayeem87@gmail.com |
47270b32456b5bf92c470ee02ebb341a747f54d1 | 3ed138cc29ecc6afecba4052d78d6502636e6911 | /fboss/agent/hw/bcm/oss/BcmCosQueueManager.cpp | 781e15c003f635f39c2e429c2b3827bf6e9039c4 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | soumithx/fboss | 0196d9e0b2b22eb25543d46d50ce78e9eeef4f7b | 84e921dcef19174c4c61d93e04736d80ba0b2b1c | refs/heads/master | 2020-07-31T01:52:42.107843 | 2019-09-23T19:49:07 | 2019-09-23T19:50:43 | 210,440,470 | 0 | 0 | NOASSERTION | 2019-09-23T19:54:37 | 2019-09-23T19:54:37 | null | UTF-8 | C++ | false | false | 2,215 | cpp | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/agent/hw/bcm/BcmCosQueueManager.h"
namespace facebook {
namespace fboss {
int BcmCosQueueManager::getControlValue(
cfg::StreamType /*streamType*/,
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
BcmCosQueueControlType /*ctrlType*/) const {
return 0;
}
void BcmCosQueueManager::programControlValue(
cfg::StreamType /*streamType*/,
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
BcmCosQueueControlType /*ctrlType*/,
int /*value*/) {}
void BcmCosQueueManager::getSchedulingAndWeight(
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
PortQueue* /*queue*/) const {}
void BcmCosQueueManager::programSchedulingAndWeight(
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
const PortQueue& /*queue*/) {}
void BcmCosQueueManager::getReservedBytes(
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
PortQueue* /*queue*/) const {}
void BcmCosQueueManager::programReservedBytes(
opennsl_gport_t /*gport*/,
int /*queueIdx*/,
const PortQueue& /*queue*/) {}
void BcmCosQueueManager::getSharedBytes(
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
PortQueue* /*queue*/) const {}
void BcmCosQueueManager::programSharedBytes(
opennsl_gport_t /*gport*/,
int /*queueIdx*/,
const PortQueue& /*queue*/) {}
void BcmCosQueueManager::getBandwidth(
opennsl_gport_t /*gport*/,
int /*queueIdx*/,
PortQueue* /*queue*/) const {}
void BcmCosQueueManager::programBandwidth(
opennsl_gport_t /*gport*/,
opennsl_cos_queue_t /*cosQ*/,
const PortQueue& /*queue*/) {}
void BcmCosQueueManager::updateQueueAggregatedStat(
const BcmCosQueueCounterType& /*type*/,
facebook::stats::MonotonicCounter* /*counter*/,
std::chrono::seconds /*now*/,
HwPortStats* /*portStats*/) {}
} // namespace fboss
} // namespace facebook
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
beb8b85cee2daef1ff7e299ca18eb9ee01a28a94 | 1044c0c5f35252259197616aa88d064b141b9e28 | /二叉树的前序遍历.cpp | 752c5b3e82ea11e7e717e6e845e05cad3bf422d0 | [] | no_license | LJComeo/1010 | ace919baa2f1a9e4518cf43c5379bf103a6eaeeb | 8430328e4a3baed5bd989ca1be3de36eaeb381c0 | refs/heads/master | 2020-08-09T19:56:44.508555 | 2019-10-11T14:04:54 | 2019-10-11T14:04:54 | 214,161,440 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | cpp | #include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
stack<TreeNode*> m_st;
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> v;
if (!root)
{
return v;
}
while (root)
{
v.push_back(root->val);
if (root->right)
{
m_st.push(root->right);
}
if (root->left)
{
root = root->left;
}
else
{
if (!m_st.empty())
{
root = m_st.top();
m_st.pop();
}
else
{
break;
}
}
}
return v;
}
};
int main()
{
return 0;
} | [
"572670014@qq.com"
] | 572670014@qq.com |
5030dff32edbb83f3573cf34dd141312d6b9d070 | d1b788585475204e43745d080ad5bbb507b79722 | /helloworld/helloworld.cpp | 5edbc80b26c205528a3b6a116556a2808c017d32 | [] | no_license | yuchengdeng/Personal_Training_Deng | fa59970c1613040b3139a9100fecbcc64cf5e76a | aaa2c7d68481e05cddf108d87232d700eacbd888 | refs/heads/master | 2021-07-12T04:17:28.966783 | 2020-10-03T08:58:59 | 2020-10-03T08:58:59 | 210,610,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 106 | cpp | #include <iostream>
using namespace std;
int main() {
cout << "Hello world !" << endl;
return 0;
} | [
"corndeng@hotmail.com"
] | corndeng@hotmail.com |
9d10f35f4204721341d4a326a73f34c0efd1f421 | b49e48485ae9b44a5b31cfcb8e4066cf9b7ec95f | /Examples/Transition1.h | 3612ea5209a17be0a02331d1b68dc3f721632c51 | [] | no_license | ElliottWaterman/state-machine | 049a7d9de46f8c6eefbefb9f83edbdb87be3bc91 | 78e3b9d63be4583a2b52d331ad5704e61c3e488e | refs/heads/master | 2022-09-15T04:28:32.484061 | 2020-06-03T12:28:53 | 2020-06-03T12:28:53 | 266,729,685 | 0 | 0 | null | 2020-05-25T08:49:08 | 2020-05-25T08:49:08 | null | UTF-8 | C++ | false | false | 391 | h | #ifndef EXAMPLES_TRANSITION1_H
#define EXAMPLES_TRANSITION1_H
#include "../StateMachine/ITransition.h"
namespace Examples
{
class Transition1 : public StateMachine::ITransition
{
public:
static StateMachine::ITransition* GetInstance();
private:
Transition1();
static StateMachine::ITransition* _instance;
};
}
#endif //EXAMPLES_TRANSITION1_H
| [
"ysa.angel@gmail.com"
] | ysa.angel@gmail.com |
85ec9176b377dd143c18ac64dde199af32f16f39 | 28a9ced3f079aa23a5db1d44a87b744621de283d | /checker/VODONCAY-12481.cpp | a4935a491922308747dce63d22683b17f4022fb9 | [] | no_license | leduythuccs/VOJ-rebuild-discord-bot | 9803ca3ff0aa55bea4aaba512eaae44d4932ae0e | df4b61a7430c97f18429907a665b2dcea1731553 | refs/heads/master | 2022-09-01T17:48:00.489164 | 2020-05-17T12:49:55 | 2020-05-17T12:49:55 | 240,027,864 | 22 | 4 | null | 2022-08-20T15:03:52 | 2020-02-12T14:06:21 | C++ | UTF-8 | C++ | false | false | 979 | cpp | #include<spoj.h>
#include<bits/stdc++.h>
using namespace std;
int n, h[4000005], ans, cut[4000005],fall[4000005];
void readInput()
{
fscanf(spoj_p_in,"%d",&n);
for(int i=1; i<=n; i++) fscanf(spoj_p_in,"%d",&h[i]);
}
void readAnswer()
{
fscanf(spoj_p_out,"%d",&ans);
}
void Try(int u)
{
fall[u] = 1;
int last = u+h[u]*cut[u];
for(int i=u+cut[u]; i!=0 && i!=n+1 && i!=last; i+=cut[u])
{
fall[i] = 1;
spoj_assert(!cut[i]);
int nlast = i+h[i]*cut[u];
if(cut[u]<0) last = min(last,nlast);
else last = max(last,nlast);
}
}
void readOutput()
{
int res,x;
spoj_assert(fscanf(spoj_t_out,"%d",&res)==1);
spoj_assert(res<=ans);
for(int i=1; i<=res; i++)
{
spoj_assert(fscanf(spoj_t_out,"%d",&x)==1);
spoj_assert(abs(x)>=1 && abs(x)<=n);
cut[abs(x)] = x/abs(x);
}
for(int i=1; i<=n; i++)
if(cut[i]) Try(i);
for(int i=1; i<=n; i++)
spoj_assert(fall[i]);
}
int main()
{
spoj_init();
readInput();
readAnswer();
readOutput();
return 0;
}
| [
"leduykhongngu@gmail.com"
] | leduykhongngu@gmail.com |
5b8b629c8ed35e623baed426b9af3c718e5ae0db | bba899946b2080060e222196c3b887071bbccac4 | /ZViewer/ZViewer/src/CacheManagerDetail/JobInterface.h | a4aa0809cf9dcad6e9aaa08ce06dcedb85964dbe | [] | no_license | chaidy/ZViewer | 87c614d7fe059f1e4b019baa55ad80bd672c467d | 2ff01b645abe023958f08c146812821c12f133c6 | refs/heads/master | 2020-12-07T00:31:57.754398 | 2015-03-14T03:24:30 | 2015-03-14T13:10:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | h | #pragma once
class JobInterface {
public:
virtual ~JobInterface() {}
virtual void DoJob() = 0;
};
typedef std::shared_ptr<JobInterface> JobInterfacePtr;
| [
"zelonion@gmail.com"
] | zelonion@gmail.com |
78143526a1b3ddb4cf37447bf098a8ffa8030c15 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14044/function14044_schedule_8/function14044_schedule_8.cpp | bd3fea74f144053d20a9b32066a2caf0d588e957 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 911 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14044_schedule_8");
constant c0("c0", 8192), c1("c1", 8192);
var i0("i0", 0, c0), i1("i1", 0, c1), i100("i100", 1, c0 - 1), i101("i101", 1, c1 - 1), i01("i01"), i02("i02"), i03("i03"), i04("i04");
input input0("input0", {i0, i1}, p_int32);
computation comp0("comp0", {i100, i101}, (input0(i100, i101) - input0(i100 + 1, i101) + input0(i100 - 1, i101)));
comp0.tile(i100, i101, 128, 128, i01, i02, i03, i04);
comp0.parallelize(i01);
buffer buf00("buf00", {8192, 8192}, p_int32, a_input);
buffer buf0("buf0", {8192, 8192}, p_int32, a_output);
input0.store_in(&buf00);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf0}, "../data/programs/function14044/function14044_schedule_8/function14044_schedule_8.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
0b8354dde9848dc9adc3aa0ac71b3f16f5e96d61 | 949401d77cb61b54343aa2fa8f34ee166302a1fb | /Test.cpp | 2c42dc915af4c99c7c7eb4afa7b4ef06dc5782e0 | [] | no_license | TaoJun724/Project_Memory_House_Keeper | 0a3254302d905f6c0b67376af8dd70036cfc4956 | 6c1982f8cb7aec3cf9926f003f1e7581cf7ec500 | refs/heads/master | 2020-04-27T23:44:05.962155 | 2019-08-04T20:53:31 | 2019-08-04T20:53:31 | 174,788,281 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,950 | cpp | #include"ConcurrentAlloc.h"
void TestThreadCache()
{
//1.验证分配的threadcache不同
//std::thread t1(ConcurrentAlloc, 10);
//std::thread t2(ConcurrentAlloc, 10);
//t1.join();
//t2.join();
//2.验证内存的反复使用
//(1)第一次申请
std::vector<void*> v;
for (size_t i = 0; i < 10; ++i)
{
v.push_back(ConcurrentAlloc(10));
cout << v.back() << endl;
}
cout << endl << endl;
for (size_t i = 0; i < 10; ++i)
{
ConcurrentFree(v[i]);
}
v.clear();
//(2)第二次申请
for (size_t i = 0; i < 10; ++i)
{
v.push_back(ConcurrentAlloc(10));
cout << v.back() << endl;
}
for (size_t i = 0; i < 10; ++i)
{
ConcurrentFree(v[i]);
}
v.clear();
}
//验证页号与地址的对应
void TestPageCache()
{
void* ptr = VirtualAlloc(NULL, (NPAGES - 1) << PAGE_SHIFT, MEM_RESERVE, PAGE_READWRITE);//按页分配
//void* ptr = malloc((NPAGES - 1) << PAGE_SHIFT);//malloc不可以
cout << ptr << endl;
if (ptr == nullptr)
{
throw std::bad_alloc();
}
PageID pageid = (PageID)ptr >> PAGE_SHIFT;
cout << pageid << endl;
void* shiftptr = (void*)(pageid << PAGE_SHIFT);
cout << shiftptr << endl;
}
//会源源不断的申请内存
void TestConcurrentAlloc()
{
size_t n = 100000;
std::vector<void*> v;
for (size_t i = 0; i < n; ++i)
{
v.push_back(ConcurrentAlloc(10));
cout << v.back() << endl;
}
cout << endl << endl;
for (size_t i = 0; i < n; ++i)
{
ConcurrentFree(v[i]);
}
v.clear();
for (size_t i = 0; i < n; ++i)
{
v.push_back(ConcurrentAlloc(10));
cout << v.back() << endl;
}
for (size_t i = 0; i < n; ++i)
{
ConcurrentFree(v[i]);
}
v.clear();
}
void TestLargeAlloc()
{
void* ptr1 = ConcurrentAlloc(MAXBYTES * 2);
void* ptr2 = ConcurrentAlloc(129 << PAGE_SHIFT);
ConcurrentFree(ptr1);
ConcurrentFree(ptr2);
}
//int main()
//{
// //TestThreadCache();
// //TestPageCache();
// //TestConcurrentAlloc();
// TestLargeAlloc();
// system("pause");
// return 0;
//} | [
"2086239852@qq.com"
] | 2086239852@qq.com |
d6221dc0a211cce38da04c7b36517477271f1ae5 | 15dc3ba64b2b0751752ad77cc857707e150f3244 | /DNA1160-S/ui/CyberTanATS(New)/CModelSel.cpp | e34715685e041e2fe095675afb0682428a87ade9 | [] | no_license | lsy1599/DNA1160-s | 6939b3aeb230830c185470c2513e9255a07c0f35 | 7de73222d00b9b1492ae8c92806c716db2543207 | refs/heads/master | 2020-04-29T01:51:39.653976 | 2018-05-16T06:26:51 | 2018-05-16T06:26:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,903 | cpp | // CModelSel.cpp : 实现文件
//
#include "stdafx.h"
#include "CyberTanATS.h"
#include "CModelSel.h"
#include "afxdialogex.h"
#include <io.h>
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
//tree ADD END
extern CString modelname;
//tree ADD
void GetAllFolders(string path, vector<string>& files)
{
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;//用来存储文件信息的结构体
string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) //第一次查找
{
do
{
if ((fileinfo.attrib & _A_SUBDIR)) //如果查找到的是文件夹
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) //进入文件夹查找
{
files.push_back(p.assign(fileinfo.name));
}
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);//结束查找
}
}
// CCModelSel 对话框
IMPLEMENT_DYNAMIC(CCModelSel, CDialogEx)
CCModelSel::CCModelSel(CWnd* pParent /*=NULL*/)
: CDialogEx(IDD_Model_Select, pParent)
{
}
CCModelSel::~CCModelSel()
{
}
void CCModelSel::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_StaModel, m_StaModel);
DDX_Control(pDX, IDC_ModelComb, m_ModelComb);
}
BEGIN_MESSAGE_MAP(CCModelSel, CDialogEx)
ON_CBN_SELCHANGE(IDC_ModelComb, &CCModelSel::OnCbnSelchangeModelcomb)
ON_BN_CLICKED(IDC_BtnOk, &CCModelSel::OnBnClickedBtnok)
END_MESSAGE_MAP()
// CCModelSel 消息处理程序
BOOL CCModelSel::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: 在此添加额外的初始化
m_Font.CreatePointFont(100, "Arial");
m_StaModel.SetFont(&m_Font, false);
CString csTemp, csPath;
char PATH[MAX_PATH];
//tree ADD
string filePath = "D:";
vector<string> files;
CString cstr;
string st;
::GetCurrentDirectory(MAX_PATH, PATH);
csTemp.Format("%s\\Models", PATH);
csPath.Format("%s", csTemp);
filePath = csPath.GetBuffer(0);
//st = filePath;
//cstr = st.c_str();
//AfxMessageBox(cstr);
//read all folders
GetAllFolders(filePath, files);
int size = files.size();
for (int i = 0; i<size; i++)
{
st = files[i];
cstr = st.c_str();
((CComboBox*)GetDlgItem(IDC_ModelComb))->AddString(cstr);
}
((CComboBox*)GetDlgItem(IDC_ModelComb))->SetCurSel(0);
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void CCModelSel::OnCbnSelchangeModelcomb()
{
// TODO: 在此添加控件通知处理程序代码
m_ModelComb.GetLBText(m_ModelComb.GetCurSel(), m_csModel);
}
CString CCModelSel::DisplayDlg()
{
DoModal();
return m_csModel;
}
void CCModelSel::OnBnClickedBtnok()
{
// TODO: 在此添加控件通知处理程序代码
m_ModelComb.GetLBText(m_ModelComb.GetCurSel(), m_csModel);
modelname = m_csModel;
OnOK();
}
| [
"Schopenhuaer@users.noreply.github.com"
] | Schopenhuaer@users.noreply.github.com |
ea9b489199d29785fb8acff861e0c60c18b2cc2f | 69fe376f63cf4347bbda41d69c2d2964e53188d5 | /Common/Dundas/ug97mfc/Source/UGHint.cpp | 67cd6895bd8b52731d13d40e80456932fa3a3aa1 | [
"Apache-2.0"
] | permissive | radtek/IMClassic | d71875ecb7fcff65383fe56c8512d060ca09c099 | 419721dacda467f796842c1a43a3bb90467f82fc | refs/heads/master | 2020-05-29T14:05:56.423961 | 2018-01-06T14:43:17 | 2018-01-06T14:43:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,315 | cpp | // UGHint.cpp : implementation file
//
#include "stdafx.h"
#include "UGCtrl.h"
//#include "UGHint.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/********************************************
*********************************************/
CUGHint::CUGHint()
{
//alloc memory
}
/********************************************
*********************************************/
CUGHint::~CUGHint()
{
//perform clean-up
}
/********************************************
*********************************************/
BEGIN_MESSAGE_MAP(CUGHint, CWnd)
//{{AFX_MSG_MAP(CUGHint)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/********************************************
*********************************************/
void CUGHint::OnPaint()
{
CDC* dc =GetDC();
if(m_hFont != NULL)
dc->SelectObject(m_hFont);
RECT rect;
GetClientRect(&rect);
dc->SetTextColor(m_textColor);
dc->SetBkColor(m_backColor);
dc->SetBkMode(OPAQUE);
dc->DrawText(m_text,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
ReleaseDC(dc);
ValidateRect(NULL);
}
BOOL CUGHint::Create(CWnd* pParentWnd, HBRUSH hbrBackground)
{
ASSERT_VALID(pParentWnd);
ASSERT(::IsWindow(pParentWnd->GetSafeHwnd()));
/// m_pParentWnd=pParentWnd;
// creation of window
//
if(hbrBackground==NULL)
{
hbrBackground=(HBRUSH) (COLOR_INFOBK+1);
}
WNDCLASS wndClass;
wndClass.style=CS_SAVEBITS|CS_DBLCLKS;
wndClass.lpfnWndProc=AfxWndProc;
wndClass.cbClsExtra=0;
wndClass.cbWndExtra=0;
wndClass.hInstance=AfxGetInstanceHandle();
wndClass.hIcon=::LoadCursor(NULL,IDC_ARROW);
wndClass.hCursor=0;
wndClass.hbrBackground=hbrBackground;
wndClass.lpszMenuName=NULL;
wndClass.lpszClassName=_T("HintWnd");
if(!AfxRegisterClass(&wndClass))
{
return FALSE;
}
CRect rect(0,0,0,0);
if(!CWnd::CreateEx(WS_EX_TOOLWINDOW|WS_EX_TOPMOST, wndClass.lpszClassName, _T(""),
WS_BORDER|WS_POPUP, rect, NULL, 0, NULL))
{
return FALSE;
}
//init the variables
m_text=_T(""); //display text
m_textColor = RGB(0,0,0); //text color
m_backColor = RGB(255,255,224); //background color
m_windowAlign = UG_ALIGNLEFT; //UG_ALIGNLEFT,UG_ALIGNRIGHT,UG_ALIGNCENTER
//UG_ALIGNTOP,UG_ALIGNBOTTOM,UG_ALIGNVCENTER
m_textAlign = UG_ALIGNLEFT; //UG_ALIGNLEFT,UG_ALIGNRIGHT,UG_ALIGNCENTER
m_hFont = NULL; //font handle
//get the font height
CDC * dc =GetDC();
CSize s = dc->GetTextExtent(_T("X"),1);
m_fontHeight = s.cy;
ReleaseDC(dc);
return TRUE;
}
/********************************************
*********************************************/
int CUGHint::SetFont(CFont * font){
m_hFont = font;
//get the font height
CDC * dc =GetDC();
if(m_hFont != NULL)
dc->SelectObject(m_hFont);
CSize s = dc->GetTextExtent(_T("Xy"),2);
m_fontHeight = s.cy + 3;
ReleaseDC(dc);
return UG_SUCCESS;
}
/********************************************
align = UG_ALIGNLEFT or UG_ALIGNRIGHT or UG_ALIGNCENTER
+ UG_ALIGNTOP or UG_ALIGNBOTTOM or UG_ALIGNVCENTER
*********************************************/
int CUGHint::SetWindowAlign(int align){
m_windowAlign = align;
return UG_SUCCESS;
}
/********************************************
align = UG_ALIGNLEFT or UG_ALIGNRIGHT or UG_ALIGNCENTER
*********************************************/
int CUGHint::SetTextAlign(int align){
m_textAlign = align;
return UG_SUCCESS;
}
/********************************************
*********************************************/
int CUGHint::SetTextColor(COLORREF color){
m_textColor = color;
return UG_SUCCESS;
}
/********************************************
*********************************************/
int CUGHint::SetBackColor(COLORREF color){
m_backColor = color;
return UG_SUCCESS;
}
/********************************************
*********************************************/
int CUGHint::SetText(LPCTSTR string,int update){
m_text = string;
if(update)
Invalidate();
return UG_SUCCESS;
}
/********************************************
*********************************************/
int CUGHint::MoveHintWindow(int x,int y,int width){
RECT rect;
//get the width of the string and reset the
//specified width if needed
CDC * dc =GetDC();
// TD first select font...
if(m_hFont != NULL)
dc->SelectObject(m_hFont);
CSize s = dc->GetTextExtent(m_text,m_text.GetLength());
if((s.cx+4) > width)
width = s.cx+4;
ReleaseDC(dc);
//set up the horizontal pos
if(m_windowAlign&UG_ALIGNCENTER){ //center
rect.left = x-(width/2);
rect.right = x+width;
}
else if(m_windowAlign&UG_ALIGNRIGHT){ //right
rect.left = x-width;
rect.right = x;
}
else{ //left
rect.left = x;
rect.right = x+width;
}
//set up the vertical pos
if(m_windowAlign&UG_ALIGNVCENTER){ //center
rect.top = y-(m_fontHeight/2);
rect.bottom = rect.top+m_fontHeight;
}
else if(m_windowAlign&UG_ALIGNBOTTOM){ //bottom
rect.top = y-m_fontHeight;
rect.bottom = y;
}
else{ //top
rect.top = y;
rect.bottom = y+m_fontHeight;
}
//make sure the position is within the parent
RECT parentRect;
int dif;
m_ctrl->GetClientRect(&parentRect);
if(rect.left < 0){
dif = 0 - rect.left;
rect.left+=dif;
rect.right +=dif;
}
if(rect.top <0){
dif = 0 - rect.top;
rect.top +=dif;
rect.bottom +=dif;
}
if(rect.right > parentRect.right){
dif = rect.right - parentRect.right;
rect.right -=dif;
rect.left -=dif;
}
if(rect.bottom > parentRect.bottom){
dif = rect.bottom - parentRect.bottom;
rect.top -= dif;
rect.bottom -= dif;
}
m_ctrl->ClientToScreen(&rect);
Hide();
MoveWindow(&rect,TRUE);
Show();
SendMessage(WM_PAINT,0,0);
return UG_SUCCESS;
}
/********************************************
*********************************************/
int CUGHint::Hide(){
ShowWindow(SW_HIDE);
return UG_SUCCESS;
}
/********************************************
*********************************************/
int CUGHint::Show(){
if(IsWindowVisible() == FALSE)
ShowWindow(SW_SHOWNA);
return UG_SUCCESS;
}
| [
"robert.raboud@outlook.com"
] | robert.raboud@outlook.com |
9792cee782c614399214407fa626bb94ad725ffd | 455551be0dbdeb5d80ea7775ce534fd34fafa7ac | /src/base58.h | 6289764ec8679598da907818884a4eb591d62300 | [
"MIT"
] | permissive | crypto-mint/ceuro | 694e330176a7e0b4a7fb612aaae3bd6ac5bf24a1 | a109741d0d0a9c308ac69fc085963e8dbbd73985 | refs/heads/master | 2016-09-05T17:58:12.578535 | 2014-01-16T15:11:55 | 2014-01-16T15:11:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,380 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Double-clicking selects the whole number as one word if it's all alphanumeric.
//
#ifndef EUROCOIN_BASE58_H
#define EUROCOIN_BASE58_H
#include <string>
#include <vector>
#include "bignum.h"
#include "key.h"
#include "script.h"
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// Encode a byte sequence as a base58-encoded string
inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to std::string
std::string str;
// Expected size increase from base58 conversion is approximately 137%
// use 138% to be safe
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian std::string to big endian
reverse(str.begin(), str.end());
return str;
}
// Encode a byte vector as a base58-encoded string
inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
// Decode a base58-encoded string str into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
// Encode a byte vector to a base58-encoded string, including checksum
inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
// Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
// Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
/** Base class for all base58-encoded data */
class CBase58Data
{
protected:
// the version byte
unsigned char nVersion;
// the actually encoded data
std::vector<unsigned char> vchData;
CBase58Data()
{
nVersion = 0;
vchData.clear();
}
~CBase58Data()
{
// zero the memory, as it may contain sensitive data
if (!vchData.empty())
memset(&vchData[0], 0, vchData.size());
}
void SetData(int nVersionIn, const void* pdata, size_t nSize)
{
nVersion = nVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
{
SetData(nVersionIn, (void*)pbegin, pend - pbegin);
}
public:
bool SetString(const char* psz)
{
std::vector<unsigned char> vchTemp;
DecodeBase58Check(psz, vchTemp);
if (vchTemp.empty())
{
vchData.clear();
nVersion = 0;
return false;
}
nVersion = vchTemp[0];
vchData.resize(vchTemp.size() - 1);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[1], vchData.size());
memset(&vchTemp[0], 0, vchTemp.size());
return true;
}
bool SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string ToString() const
{
std::vector<unsigned char> vch(1, nVersion);
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CompareTo(const CBase58Data& b58) const
{
if (nVersion < b58.nVersion) return -1;
if (nVersion > b58.nVersion) return 1;
if (vchData < b58.vchData) return -1;
if (vchData > b58.vchData) return 1;
return 0;
}
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded CEuro addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CCEuroAddress;
class CCEuroAddressVisitor : public boost::static_visitor<bool>
{
private:
CCEuroAddress *addr;
public:
CCEuroAddressVisitor(CCEuroAddress *addrIn) : addr(addrIn) { }
bool operator()(const CKeyID &id) const;
bool operator()(const CScriptID &id) const;
bool operator()(const CNoDestination &no) const;
};
class CCEuroAddress : public CBase58Data
{
public:
enum
{
PUBKEY_ADDRESS = 0,
SCRIPT_ADDRESS = 5,
PUBKEY_ADDRESS_TEST = 111,
SCRIPT_ADDRESS_TEST = 196,
};
bool Set(const CKeyID &id) {
SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
return true;
}
bool Set(const CScriptID &id) {
SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
return true;
}
bool Set(const CTxDestination &dest)
{
return boost::apply_visitor(CCEuroAddressVisitor(this), dest);
}
bool IsValid() const
{
unsigned int nExpectedSize = 20;
bool fExpectTestNet = false;
switch(nVersion)
{
case PUBKEY_ADDRESS:
nExpectedSize = 20; // Hash of public key
fExpectTestNet = false;
break;
case SCRIPT_ADDRESS:
nExpectedSize = 20; // Hash of CScript
fExpectTestNet = false;
break;
case PUBKEY_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
case SCRIPT_ADDRESS_TEST:
nExpectedSize = 20;
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
}
CCEuroAddress()
{
}
CCEuroAddress(const CTxDestination &dest)
{
Set(dest);
}
CCEuroAddress(const std::string& strAddress)
{
SetString(strAddress);
}
CCEuroAddress(const char* pszAddress)
{
SetString(pszAddress);
}
CTxDestination Get() const {
if (!IsValid())
return CNoDestination();
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CKeyID(id);
}
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
return CScriptID(id);
}
}
return CNoDestination();
}
bool GetKeyID(CKeyID &keyID) const {
if (!IsValid())
return false;
switch (nVersion) {
case PUBKEY_ADDRESS:
case PUBKEY_ADDRESS_TEST: {
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
default: return false;
}
}
bool IsScript() const {
if (!IsValid())
return false;
switch (nVersion) {
case SCRIPT_ADDRESS:
case SCRIPT_ADDRESS_TEST: {
return true;
}
default: return false;
}
}
void ToggleTestnet() {
switch (nVersion) {
case PUBKEY_ADDRESS:
nVersion = PUBKEY_ADDRESS_TEST;
break;
case SCRIPT_ADDRESS:
nVersion = SCRIPT_ADDRESS_TEST;
break;
case PUBKEY_ADDRESS_TEST:
nVersion = PUBKEY_ADDRESS;
break;
case SCRIPT_ADDRESS_TEST:
nVersion = SCRIPT_ADDRESS;
break;
}
}
};
bool inline CCEuroAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
bool inline CCEuroAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
bool inline CCEuroAddressVisitor::operator()(const CNoDestination &id) const { return false; }
/** A base58-encoded secret key */
class CCEuroSecret : public CBase58Data
{
public:
void SetSecret(const CSecret& vchSecret, bool fCompressed)
{
assert(vchSecret.size() == 32);
SetData(fTestNet ? 239 : 128, &vchSecret[0], vchSecret.size());
if (fCompressed)
vchData.push_back(1);
}
CSecret GetSecret(bool &fCompressedOut)
{
CSecret vchSecret;
vchSecret.resize(32);
memcpy(&vchSecret[0], &vchData[0], 32);
fCompressedOut = vchData.size() == 33;
return vchSecret;
}
bool IsValid() const
{
bool fExpectTestNet = false;
switch(nVersion)
{
case 128:
break;
case 239:
fExpectTestNet = true;
break;
default:
return false;
}
return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
}
bool SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
CCEuroSecret(const CSecret& vchSecret, bool fCompressed)
{
SetSecret(vchSecret, fCompressed);
}
CCEuroSecret()
{
}
};
#endif
| [
"root@s1.owncloud.omc.net"
] | root@s1.owncloud.omc.net |
fccdb979712215e5f1e1682cd4a3428a8e4b55dd | 6d2f20fa4dd8713ae3189251cf6be80d3254b582 | /src/qt/guiutil.cpp | 1c9b4b0493fa1107d783872c01f5171ac19fa4f7 | [
"MIT"
] | permissive | RTCcoin/RTCcoin | 339848841ecc9276f7dd689fefc10f8ab394a5f7 | 2d86f7dae7092f989579d7843d510f6672ac51c1 | refs/heads/master | 2021-01-11T02:23:10.546479 | 2016-10-17T04:10:31 | 2016-10-17T04:10:31 | 70,971,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,302 | cpp | #include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "RTCcoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "RTCcoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=RTCcoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("RTCcoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" RTCcoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("RTCcoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
| [
"hjb@674cb710-5ea2-11e6-92b7-b59c1ec08205"
] | hjb@674cb710-5ea2-11e6-92b7-b59c1ec08205 |
2b4e5f7bdb3782273b1c2503e958d97bdba995fa | 6b3093caefa34de517d984a6341f826dd394989f | /src/primitives/block.h | 8b1f5a3ce038ef205b459d5d2782bceb7fa25f4f | [
"MIT"
] | permissive | kingscrypto/KGS | 98fadb2d537dea84d7d47ee07103e16e864203a6 | 1c329f80277663270d3421631dae54b10ff95c56 | refs/heads/master | 2020-04-27T07:08:38.627240 | 2019-03-06T11:02:44 | 2019-03-06T11:02:44 | 174,128,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,676 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019 The KGS developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_BLOCK_H
#define BITCOIN_PRIMITIVES_BLOCK_H
#include "primitives/transaction.h"
#include "keystore.h"
#include "serialize.h"
#include "uint256.h"
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE_CURRENT = 2000000;
static const unsigned int MAX_BLOCK_SIZE_LEGACY = 1000000;
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int32_t CURRENT_VERSION=5; // Version 5 supports CLTV activation
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
uint256 nAccumulatorCheckpoint;
CBlockHeader()
{
SetNull();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
//zerocoin active, header changes to include accumulator checksum
if(nVersion > 3)
READWRITE(nAccumulatorCheckpoint);
}
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
nTime = 0;
nBits = 0;
nNonce = 0;
nAccumulatorCheckpoint = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const;
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable CScript payee;
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
if(vtx.size() > 1 && vtx[1].IsCoinStake())
READWRITE(vchBlockSig);
}
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
payee = CScript();
vchBlockSig.clear();
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
return block;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
bool IsZerocoinStake() const;
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// Build the in-memory merkle tree for this block and return the merkle root.
// If non-NULL, *mutated is set to whether mutation was detected in the merkle
// tree (a duplication of transactions in the block leading to an identical
// merkle root).
uint256 BuildMerkleTree(bool* mutated = NULL) const;
std::vector<uint256> GetMerkleBranch(int nIndex) const;
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
std::string ToString() const;
void print() const;
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
struct CBlockLocator
{
std::vector<uint256> vHave;
CBlockLocator() {}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
}
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
};
#endif // BITCOIN_PRIMITIVES_BLOCK_H
| [
"PaulH-RESQ"
] | PaulH-RESQ |
40d24af22474adc8a5333f767cb62bfea0de9e84 | 9f4d78761c9d187b8eb049530ce0ec4c2b9b2d78 | /Tools/ModelMigrate/FrontEnd/Extractor.cpp | 0cd7bd38312ea63b6e6e7685efcd3984447ce5ab | [] | no_license | ksmyth/GME | d16c196632fbeab426df0857d068809a9b7c4ec9 | 873f0e394cf8f9a8178ffe406e3dd3b1093bf88b | refs/heads/master | 2023-01-25T03:33:59.342181 | 2023-01-23T19:22:37 | 2023-01-23T19:22:37 | 119,058,056 | 0 | 1 | null | 2019-11-26T20:54:31 | 2018-01-26T14:01:52 | C++ | UTF-8 | C++ | false | false | 3,693 | cpp | #include "StdAfx.h"
#include ".\extractor.h"
#include <fstream>
#include <algorithm>
Extractor::Extractor(void)
{
}
Extractor::~Extractor(void)
{
}
void Extractor::init()
{
m_names.clear();
m_attrs.clear();
}
void Extractor::doJob( std::string& pName)
{
init();
std::ofstream ofile( ( pName + ".parsed").c_str(), std::ios_base::out);
std::ifstream file( pName.c_str());
if( !file) return;
char buff[1024];
bool global_attr = true;
std::string last_kind = "";
while( file)
{
//
file.getline( buff, 1024);
std::string bf( buff);
unsigned int i = 0;
for (; i < bf.length() && (bf[i] == ' ' || bf[i] == 9); ++i);
const int kindsNo = 6;
std::string kinds[ kindsNo ] =
{ "<atom name"
, "<set name"
, "<reference name"
, "<connection name"
, "<model name"
, "<folder name"
};
bool found = false;
unsigned int j = 0;
for( ; !found && j < kindsNo; ++j)
{
found = 0 == kinds[j].compare( bf.substr( i, kinds[j].length()));
}
if( found)
{
--j;
std::string one_name = get( " name", bf.substr(i)); // whitespaces stripped off
last_kind = one_name;
if( std::find( m_names.begin(), m_names.end(), one_name) != m_names.end()) // already there
ASSERT(0); // how come?
else
m_names.push_back( one_name);
// my attributes are inserted there
std::string myattrs = get( " attributes", bf.substr(i));
if( !myattrs.empty())
m_attrs[ one_name ] = myattrs;
}
}
for( NAMES::iterator it = m_names.begin(); it != m_names.end(); ++it)
{
ofile << "k" << ' ' << *it << ' ' << std::endl;
if( m_attrs.find( *it) != m_attrs.end()) // found, key/value really exists
ofile << "a" << ' ' << *it << ' ' << m_attrs[ *it ] << std::endl; // the attributes of *it
}
file.close();
ofile.close();
}
void Extractor::doPlainLoad( std::string& pName)
{
init();
std::basic_ifstream<char> f( pName.c_str());
while( f)
{
std::string type;
std::string one_name;
f >> type >> one_name;
if( type == "k")
{
if( std::find( m_names.begin(), m_names.end(), one_name) != m_names.end()) // already there
ASSERT(0); // how come?
else
m_names.push_back( one_name);
}
else if( type == "a")
{
char buffer[5024];
f.getline( buffer, 5024);
m_attrs[ one_name ] = buffer; // one_name in this case is the owner of the attributes
}
}
f.close();
}
const Extractor::NAMES& Extractor::getKinds()
{
return m_names;
}
const Extractor::ATTRS& Extractor::getAttrs()
{
return m_attrs;
}
/*static*/ std::string Extractor::get( const std::string& attr, const std::string& buff)
{
std::string res;
size_t attr_start = buff.find( attr);
if( attr_start == std::string::npos) return "";
size_t quot_begin = buff.find( '"', attr_start + attr.length());
size_t quot_end = buff.find( '"', quot_begin + 1);
if( quot_begin == std::string::npos || quot_end == std::string::npos) return "";
return buff.substr( quot_begin + 1, quot_end - quot_begin - 1);
}
/*static*/ Extractor::NAMES Extractor::tokenize( const std::string& source)
{
NAMES result;
if( source.empty()) return result;
const std::string whsp = " "; // whitespaces to ignore
unsigned int last = 0;
do
{
unsigned int curr_token_start = source.find_first_not_of( whsp, last);
unsigned int curr_token_end = source.find( whsp, curr_token_start);
if( curr_token_end > curr_token_start)
result.push_back( source.substr( curr_token_start, curr_token_end - curr_token_start));
last = curr_token_end;
}
while( last != std::string::npos );
return result;
}
| [
"ksmyth@b35830b6-564f-0410-ac5f-b387e50cb686"
] | ksmyth@b35830b6-564f-0410-ac5f-b387e50cb686 |
fd6c022c04b4b0d32169437d6317010af7481931 | 91e3e30fd6ccc085ca9dccb5c91445fa9ab156a2 | /Examples/Display/SineScroll/Sources/sinescroll.h | 5fe75bd0989364f72c8cde7ac5a176f075732532 | [
"Zlib"
] | permissive | Pyrdacor/ClanLib | 1bc4d933751773e5bca5c3c544d29f351a2377fb | 72426fd445b59aa0b2e568c65ceccc0b3ed6fcdb | refs/heads/master | 2020-04-06T06:41:34.252331 | 2014-10-03T21:47:06 | 2014-10-03T21:47:06 | 23,551,359 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,493 | h | /*
** ClanLib SDK
** Copyright (c) 1997-2013 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
** Mark Page
*/
#pragma once
// This is the Application class (That is instantiated by the Program Class)
class SineScroll
{
public:
int start(const std::vector<std::string> &args);
private:
void on_input_up(const clan::InputEvent &key);
void on_window_close();
void draw_demo(clan::Canvas &canvas, int delta_ms);
private:
bool quit;
clan::Texture2D texture;
float sin_offset;
};
| [
"rombust@hotmail.co.uk"
] | rombust@hotmail.co.uk |
adea52f7a2228ac2f43b6387399b43bc96517626 | 0a61c2f789216047508384651840abd73092aae1 | /DuiVision/include/Frame.h | 5014e17bb9766504873369238fe70b14b26738e0 | [] | no_license | ALEXGUOQ/DuiVision | 745787007df8dafaf70baaff2d9f3d2171336b9e | d740217a2e0c64f85db6b179db5baca983e02d1a | refs/heads/master | 2021-01-14T14:11:36.008495 | 2014-08-27T00:29:49 | 2014-08-27T00:29:49 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 879 | h | // 边框控件,在区域周围画出边框,可以设置区域的渐变透明度,不能响应鼠标
#pragma once
#include "ControlBase.h"
class CFrame : public CControlBase
{
DUIOBJ_DECLARE_CLASS_NAME(CFrame, "frame")
public:
CFrame(HWND hWnd, CDuiObject* pDuiObject);
CFrame(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, int nBeginTransparent = 50, int nEndTransparent = 50,
COLORREF clr = RGB(255, 255, 255), BOOL bIsVisible = TRUE);
virtual ~CFrame(void);
protected:
virtual void DrawControl(CDC &dc, CRect rcUpdate);
public:
int m_nBeginTransparent;
int m_nEndTransparent;
COLORREF m_clr;
DUI_DECLARE_ATTRIBUTES_BEGIN()
DUI_RGBCOLOR_ATTRIBUTE("color", m_clr, FALSE)
DUI_INT_ATTRIBUTE("begin-transparent", m_nBeginTransparent, FALSE)
DUI_INT_ATTRIBUTE("end-transparent", m_nEndTransparent, FALSE)
DUI_DECLARE_ATTRIBUTES_END()
};
| [
"blueantst@gmail.com"
] | blueantst@gmail.com |
ab97f4d03a7dbe180c4d9a4cd936d91a252ee775 | 092d638d7e00daeac2b08a448c78dabb3030c5a9 | /gcj/gcj/188266/EternalVortex/168107/0/extracted/Main.cpp | b81d56ef667800bc2140625618240edb79ab6814 | [] | no_license | Yash-YC/Source-Code-Plagiarism-Detection | 23d2034696cda13462d1f7596718a908ddb3d34e | 97cfdd458e851899b6ec6802a10343db68824b8b | refs/heads/main | 2023-08-03T01:43:59.185877 | 2021-10-04T15:00:25 | 2021-10-04T15:00:25 | 399,349,460 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,124 | cpp | #include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <numeric>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <utility>
using namespace std;
typedef int uint;
class DisjointSet
{
private:
std::vector<int> _parentVector;
std::vector<int> _rankVector;
public:
DisjointSet(uint n) : _parentVector(n)
{
for (uint i = 0; i < n; ++i)
_parentVector[i] = i;
}
uint Find(uint n)
{
if (_parentVector[n] == n)
return n;
return (_parentVector[n] = Find(_parentVector[n]));
}
void Union(uint n, uint m)
{
n = Find(n);
m = Find(m);
// Union by smallest rep
if (m > n)
_parentVector[m] = n;
else
_parentVector[n] = m;
}
};
struct Matrix
{
int* _data;
int _rows, _cols;
Matrix(int rows, int cols) : _data(new int[rows * cols]), _rows(rows), _cols(cols)
{
fill(_data, _data + (rows * cols), 0);
}
~Matrix()
{
delete [] _data;
}
int& operator()(int r, int c)
{
return _data[r * _cols + c];
}
int operator()(int r, int c) const
{
return _data[r * _cols + c];
}
};
Matrix M(11, 100000); // 1 = happy, 2 = unhappy, 3 = seen
int IsHappy(int i, int base)
{
int sum = 0;
int num = i;
if (M(base, i) == 3)
return (M(base, i) = 2);
if (M(base, i) != 0)
return M(base, i);
while (i > 0)
{
int j = i % base;
sum += j * j;
i /= base;
}
if (sum == 1)
return (M(base, num) = 1);
M(base, num) = 3; // mark seen
return (M(base, num) = IsHappy(sum, base)); // save value
}
int Smallest(const vector<int>& v)
{
for (int i = 2; ;++i)
{
// Check i for happiness
bool flag = true;
for (int j = 0; j < v.size(); ++j)
{
if (IsHappy(i, v[j]) == 2)
{
flag = false;
break;
}
}
if (flag) return i;
}
}
void Bases()
{
int T;
ifstream cin("A-small.in");
ofstream cout("A.out");
cin >> T;
string s;
getline(cin, s);
for (int cs = 1; cs <= T; ++cs)
{
getline(cin, s);
istringstream istr(s);
vector<int> v;
int tmp;
while (istr >> tmp)
v.push_back(tmp);
cout << "Case #" << cs << ": " << Smallest(v) << endl;
}
}
int main()
{
Bases();
while (true) ;
} | [
"54931238+yash-YC@users.noreply.github.com"
] | 54931238+yash-YC@users.noreply.github.com |
446a20ca71c868e2529350da9b3937bc3c81a8f5 | e798011f1f41e2f9000aebb329813ec91eb44778 | /rdpfuzz-winafl/cmake-3.16.0/Source/cmCacheManager.h | faa60c5287d4aa92726e28cd3a2536b00929cb47 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fengjixuchui/rdpfuzz | 3a7f210f1fa56d9b75dd26cdf6be310a9cf0fee4 | 4561b6fbf73ada553ce78ad44918fd0930ee4e85 | refs/heads/main | 2023-07-28T02:29:12.829741 | 2021-09-10T09:35:59 | 2021-09-10T09:35:59 | 401,266,187 | 0 | 0 | Apache-2.0 | 2021-09-10T09:36:00 | 2021-08-30T08:12:51 | null | UTF-8 | C++ | false | false | 8,176 | h | /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef cmCacheManager_h
#define cmCacheManager_h
#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "cmPropertyMap.h"
#include "cmStateTypes.h"
class cmMessenger;
/** \class cmCacheManager
* \brief Control class for cmake's cache
*
* Load and Save CMake cache files.
*
*/
class cmCacheManager
{
public:
cmCacheManager();
class CacheIterator;
friend class cmCacheManager::CacheIterator;
private:
struct CacheEntry
{
std::string Value;
cmStateEnums::CacheEntryType Type = cmStateEnums::UNINITIALIZED;
cmPropertyMap Properties;
std::vector<std::string> GetPropertyList() const;
const char* GetProperty(const std::string&) const;
void SetProperty(const std::string& property, const char* value);
void AppendProperty(const std::string& property, const char* value,
bool asString = false);
bool Initialized = false;
};
public:
class CacheIterator
{
public:
void Begin();
bool Find(const std::string&);
bool IsAtEnd() const;
void Next();
std::string GetName() const { return this->Position->first; }
std::vector<std::string> GetPropertyList() const;
const char* GetProperty(const std::string&) const;
bool GetPropertyAsBool(const std::string&) const;
bool PropertyExists(const std::string&) const;
void SetProperty(const std::string& property, const char* value);
void AppendProperty(const std::string& property, const char* value,
bool asString = false);
void SetProperty(const std::string& property, bool value);
const char* GetValue() const { return this->GetEntry().Value.c_str(); }
bool GetValueAsBool() const;
void SetValue(const char*);
cmStateEnums::CacheEntryType GetType() const
{
return this->GetEntry().Type;
}
void SetType(cmStateEnums::CacheEntryType ty)
{
this->GetEntry().Type = ty;
}
bool Initialized() { return this->GetEntry().Initialized; }
cmCacheManager& Container;
std::map<std::string, CacheEntry>::iterator Position;
CacheIterator(cmCacheManager& cm)
: Container(cm)
{
this->Begin();
}
CacheIterator(cmCacheManager& cm, const char* key)
: Container(cm)
{
if (key) {
this->Find(key);
}
}
private:
CacheEntry const& GetEntry() const { return this->Position->second; }
CacheEntry& GetEntry() { return this->Position->second; }
};
//! return an iterator to iterate through the cache map
cmCacheManager::CacheIterator NewIterator() { return { *this }; }
//! Load a cache for given makefile. Loads from path/CMakeCache.txt.
bool LoadCache(const std::string& path, bool internal,
std::set<std::string>& excludes,
std::set<std::string>& includes);
//! Save cache for given makefile. Saves to output path/CMakeCache.txt
bool SaveCache(const std::string& path, cmMessenger* messenger);
//! Delete the cache given
bool DeleteCache(const std::string& path);
//! Print the cache to a stream
void PrintCache(std::ostream&) const;
//! Get the iterator for an entry with a given key.
cmCacheManager::CacheIterator GetCacheIterator(const char* key = nullptr);
//! Remove an entry from the cache
void RemoveCacheEntry(const std::string& key);
//! Get the number of entries in the cache
int GetSize() { return static_cast<int>(this->Cache.size()); }
//! Get a value from the cache given a key
const std::string* GetInitializedCacheValue(const std::string& key) const;
const char* GetCacheEntryValue(const std::string& key)
{
cmCacheManager::CacheIterator it = this->GetCacheIterator(key.c_str());
if (it.IsAtEnd()) {
return nullptr;
}
return it.GetValue();
}
const char* GetCacheEntryProperty(std::string const& key,
std::string const& propName)
{
return this->GetCacheIterator(key.c_str()).GetProperty(propName);
}
cmStateEnums::CacheEntryType GetCacheEntryType(std::string const& key)
{
return this->GetCacheIterator(key.c_str()).GetType();
}
bool GetCacheEntryPropertyAsBool(std::string const& key,
std::string const& propName)
{
return this->GetCacheIterator(key.c_str()).GetPropertyAsBool(propName);
}
void SetCacheEntryProperty(std::string const& key,
std::string const& propName,
std::string const& value)
{
this->GetCacheIterator(key.c_str()).SetProperty(propName, value.c_str());
}
void SetCacheEntryBoolProperty(std::string const& key,
std::string const& propName, bool value)
{
this->GetCacheIterator(key.c_str()).SetProperty(propName, value);
}
void SetCacheEntryValue(std::string const& key, std::string const& value)
{
this->GetCacheIterator(key.c_str()).SetValue(value.c_str());
}
void RemoveCacheEntryProperty(std::string const& key,
std::string const& propName)
{
this->GetCacheIterator(key.c_str()).SetProperty(propName, nullptr);
}
void AppendCacheEntryProperty(std::string const& key,
std::string const& propName,
std::string const& value,
bool asString = false)
{
this->GetCacheIterator(key.c_str())
.AppendProperty(propName, value.c_str(), asString);
}
std::vector<std::string> GetCacheEntryKeys()
{
std::vector<std::string> definitions;
definitions.reserve(this->GetSize());
cmCacheManager::CacheIterator cit = this->GetCacheIterator();
for (cit.Begin(); !cit.IsAtEnd(); cit.Next()) {
definitions.push_back(cit.GetName());
}
return definitions;
}
/** Get the version of CMake that wrote the cache. */
unsigned int GetCacheMajorVersion() const { return this->CacheMajorVersion; }
unsigned int GetCacheMinorVersion() const { return this->CacheMinorVersion; }
protected:
//! Add an entry into the cache
void AddCacheEntry(const std::string& key, const char* value,
const char* helpString,
cmStateEnums::CacheEntryType type);
//! Get a cache entry object for a key
CacheEntry* GetCacheEntry(const std::string& key);
//! Clean out the CMakeFiles directory if no CMakeCache.txt
void CleanCMakeFiles(const std::string& path);
// Cache version info
unsigned int CacheMajorVersion;
unsigned int CacheMinorVersion;
private:
using CacheEntryMap = std::map<std::string, CacheEntry>;
static void OutputHelpString(std::ostream& fout,
const std::string& helpString);
static void OutputWarningComment(std::ostream& fout,
std::string const& message,
bool wrapSpaces);
static void OutputNewlineTruncationWarning(std::ostream& fout,
std::string const& key,
std::string const& value,
cmMessenger* messenger);
static void OutputKey(std::ostream& fout, std::string const& key);
static void OutputValue(std::ostream& fout, std::string const& value);
static void OutputValueNoNewlines(std::ostream& fout,
std::string const& value);
static const char* PersistentProperties[];
bool ReadPropertyEntry(std::string const& key, CacheEntry& e);
void WritePropertyEntries(std::ostream& os, CacheIterator i,
cmMessenger* messenger);
CacheEntryMap Cache;
// Only cmake and cmState should be able to add cache values
// the commands should never use the cmCacheManager directly
friend class cmState; // allow access to add cache values
friend class cmake; // allow access to add cache values
};
#endif
| [
"obporath@gmail.com"
] | obporath@gmail.com |
9b99733311f24fcd1963582ba8ca4eca51e17a35 | eefd99751be04a79078444787a1767cd035e6c8a | /lista4/Zakres.cpp | e702888c4640a00d2904443002e5e883220695e0 | [] | no_license | skarzynski/TEP_lab4 | 2a488f822c1eb81aeac54208e2e7c030b1723c9f | e596ea98a688cb382f0759b88b17b1f2bf61d1d2 | refs/heads/master | 2020-09-03T20:57:40.187796 | 2019-11-19T17:07:12 | 2019-11-19T17:07:12 | 219,568,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,757 | cpp | #include <string>
#include "pch.h"
#include "Zakres.h"
using namespace std;
bool Zakres::lastError;
bool Zakres::getLastError() {
return Zakres::lastError;
}
Zakres::Zakres() {
this->from = -1;
this->to = -1;
this->value = -1;
lastError = false;
}
Zakres::Zakres(string value, int from, int to) {
lastError = false;
this->from = from;
this->to = to;
for (int i = 0; i < value.length(); i++) {
if (!isdigit(value[i])) {
lastError = true;
this->value = -1;
return;
}
}
int correctValue = atoi(value.c_str());
if (correctValue >= from && correctValue <= to) {
this->value = correctValue;
}
else {
lastError = true;
this->value = -1;
return;
}
}
Zakres::Zakres(char* value, int from, int to) {
lastError = false;
this->from = from;
this->to = to;
char* copy;
for (copy = value; *value != '\0'; copy++) {
if (!isdigit(*value)) {
lastError = true;
}
}
if (this->getLastError()) {
this->value = -1;
return;
}
int correctValue = atoi(value);
if (correctValue >= from && correctValue <= to) {
this->value = correctValue;
}
else {
lastError = true;
this->value = -1;
return;
}
}
int Zakres::getValue() {
return this->value;
}
Zakres & Zakres::operator=(const string &newValue) {
lastError = false;
for (int i = 0; i < newValue.length(); i++) {
if (!isdigit(newValue[i])) {
lastError = true;
return *this;
}
}
int correctValue = atoi(newValue.c_str());
if (correctValue < this->from || correctValue > this->to) {
lastError = true;
return *this;
}
this->value = correctValue;
return *this;
}
Zakres & Zakres::operator=(const Zakres &newValue) {
lastError = false;
this->from = newValue.from;
this->to = newValue.to;
this->value = newValue.value;
return *this;
} | [
"szymon3301@gmail.com"
] | szymon3301@gmail.com |
f893ede9b2dbf274b4a70b9a3d642158b57516f6 | 569bb635b9e54b88db1f7fba6d77f05fa21fcfd3 | /other_code/json_cpp_study.cpp | 79a29b2273a2ae834a1f583737a71e8708e55a87 | [] | no_license | yangdianxp/myStudyCode | 242215015017a498d200c1574b977cf38f35fad9 | dcaf9addd724c2c0bc573897c83e5ebc88c27c42 | refs/heads/master | 2020-03-25T07:52:14.265393 | 2020-02-24T10:10:54 | 2020-02-24T10:10:54 | 143,585,538 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,860 | cpp | #include <iostream>
#include <fstream>
#include <json.h>
#pragma comment(lib, "lib_json.lib")
using namespace std;
int main()
{
ifstream ifs;
ifs.open("test.json");
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return -1;
}
Json::Value &add_value = root["address"];
Json::Value append_value;
append_value["name"] = "append";
append_value["email"] = "append@163.com";
add_value.append(append_value);
Json::Value &change_value = add_value[1];
change_value["name"] = Json::Value("zoujiemeng");
change_value["email"] = Json::Value("zzz-oo-u@163.com");
add_value[2].removeMember("name");
for (int i = 0; i < add_value.size(); ++i)
{
Json::Value temp_value = add_value[i];
string strName = temp_value["name"].asString();
string strMail = temp_value["email"].asString();
cout << "name: " << strName << " email: " << strMail << endl;
}
Json::FastWriter writer;
string json_append_file = writer.write(root);
string strOut = root.toStyledString();
ofstream ofs;
ofs.open("test_append.json", 'w');
ofs << json_append_file;
ofs << strOut;
system("pause");
return 0;
}
#if 0
ifstream ifs;
ifs.open("test.json");
Json::Reader reader;
Json::Value root;
if(!reader.parse(ifs, root, false))
{
return -1;
}
Json::Value add_value = root["address"];
for (std::size_t i = 0; i < add_value.size(); ++i)
{
Json::Value temp_value = add_value[i];
string strName = temp_value["name"].asString();
string strMail = temp_value["email"].asString();
cout << "name: " << strName << " email: " << strMail << endl;
}
WriteJsonData("test.json");
void WriteJsonData(const char* filename)
{
Json::Reader reader;
Json::Value root;
/*ifstream is;*/
/*is.open(filename, std::ios::binary);
if (reader.parse(is, root, false))
{*/
Json::Value item;
root["key"] = "value1";
item["arrayKey"] = 2;
root["array"].append(item);
Json::FastWriter writer;
string strWrite = writer.write(root);
ofstream ofs;
ofs.open(filename, 'w');
ofs << strWrite;
ofs.close();
/*}
is.close()*/;
}
Json::Value root;
Json::Value arrayObj;
Json::Value item;
root["key"] = "value1";
for (int i = 0; i < 10; ++i)
{
item["arrayKey"] = i;
arrayObj.append(item);
}
root["array"] = arrayObj;
std::string out = root.toStyledString();
std::cout << out << std::endl;
const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
Json::Reader reader;
Json::Value root;
if (reader.parse(str, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
{
std::string upload_id = root["uploadid"].asString(); // 访问节点,upload_id = "UP000000"
int code = root["code"].asInt(); // 访问节点,code = 100
cout << "upload_id: " << upload_id << endl;
cout << "code: " << code << endl;
}
#endif | [
"yangdianxp@163.com"
] | yangdianxp@163.com |
d7787968fefb94a4f92ff60786d268578a1bcdfb | 77b2d29d2cbf8345e0c9aba85c443a33946b2a1c | /sources/Z3/src/smt/smt_internalizer.cpp | c38ef4e4aba1c1d2707b607f2bcd93ed37260358 | [
"MIT",
"MS-PL",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ssaha6/NPI | a43242f0e492b2b5b6cd434e3fe251afa5255d0d | 0b9a9e620a139d89fda883906a393c0b7d793357 | refs/heads/master | 2020-12-05T13:52:09.926354 | 2020-01-06T15:43:35 | 2020-01-06T15:43:35 | 232,130,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67,043 | cpp | /*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smt_internalizer.cpp
Abstract:
<abstract>
Author:
Leonardo de Moura (leonardo) 2008-02-20.
Revision History:
--*/
#include "smt/smt_context.h"
#include "ast/expr_stat.h"
#include "ast/ast_pp.h"
#include "ast/ast_ll_pp.h"
#include "ast/ast_smt2_pp.h"
#include "smt/smt_model_finder.h"
#include "ast/for_each_expr.h"
namespace smt {
/**
\brief Return true if the expression is viewed as a logical gate.
*/
inline bool is_gate(ast_manager const & m, expr * n) {
if (is_app(n) && to_app(n)->get_family_id() == m.get_basic_family_id()) {
switch (to_app(n)->get_decl_kind()) {
case OP_AND:
case OP_OR:
case OP_IFF:
case OP_ITE:
return true;
default:
return false;
}
}
return false;
}
#define White 0
#define Grey 1
#define Black 2
static int get_color(svector<int> & tcolors, svector<int> & fcolors, expr * n, bool gate_ctx) {
svector<int> & colors = gate_ctx ? tcolors : fcolors;
if (colors.size() > n->get_id())
return colors[n->get_id()];
return White;
}
static void set_color(svector<int> & tcolors, svector<int> & fcolors, expr * n, bool gate_ctx, int color) {
svector<int> & colors = gate_ctx ? tcolors : fcolors;
if (colors.size() <= n->get_id()) {
colors.resize(n->get_id()+1, White);
}
colors[n->get_id()] = color;
}
/**
\brief Return the foreign descendants of n. That is, the descendants of n where the family_id is different from fid.
For example the descendants of (+ a (+ (f b) (* 2 (h (+ c d))))) are:
- a
- (f b)
- (h (+ c d))
*/
static void get_foreign_descendants(app * n, family_id fid, ptr_buffer<expr> & descendants) {
SASSERT(n->get_family_id() == fid);
SASSERT(fid != null_family_id);
ptr_buffer<expr> todo;
todo.push_back(n);
ast_mark visited;
while (!todo.empty()) {
expr * curr = todo.back();
todo.pop_back();
if (visited.is_marked(n)) {
continue;
}
visited.mark(n, true);
if (!is_app(curr) || to_app(curr)->get_family_id() != fid) {
descendants.push_back(curr);
continue;
}
SASSERT(is_app(curr));
SASSERT(to_app(curr)->get_family_id() == fid);
unsigned j = to_app(curr)->get_num_args();
while (j > 0) {
--j;
todo.push_back(to_app(curr)->get_arg(j));
}
}
}
void context::ts_visit_child(expr * n, bool gate_ctx, svector<int> & tcolors, svector< int> & fcolors, svector<expr_bool_pair> & todo, bool & visited) {
if (get_color(tcolors, fcolors, n, gate_ctx) == White) {
todo.push_back(expr_bool_pair(n, gate_ctx));
visited = false;
}
}
bool context::ts_visit_children(expr * n, bool gate_ctx, svector<int> & tcolors, svector<int> & fcolors, svector<expr_bool_pair> & todo) {
if (is_quantifier(n))
return true;
SASSERT(is_app(n));
if (m_manager.is_bool(n)) {
if (b_internalized(n))
return true;
}
else {
if (e_internalized(n))
return true;
}
bool visited = true;
family_id fid = to_app(n)->get_family_id();
theory * th = m_theories.get_plugin(fid);
bool def_int = th == 0 || th->default_internalizer();
if (!def_int) {
ptr_buffer<expr> descendants;
get_foreign_descendants(to_app(n), fid, descendants);
ptr_buffer<expr>::iterator it = descendants.begin();
ptr_buffer<expr>::iterator end = descendants.end();
for (; it != end; ++it) {
expr * arg = *it;
ts_visit_child(arg, false, tcolors, fcolors, todo, visited);
}
return visited;
}
SASSERT(def_int);
if (m_manager.is_term_ite(n)) {
ts_visit_child(to_app(n)->get_arg(0), true, tcolors, fcolors, todo, visited);
ts_visit_child(to_app(n)->get_arg(1), false, tcolors, fcolors, todo, visited);
ts_visit_child(to_app(n)->get_arg(2), false, tcolors, fcolors, todo, visited);
return visited;
}
bool new_gate_ctx = m_manager.is_bool(n) && (is_gate(m_manager, n) || m_manager.is_not(n));
unsigned j = to_app(n)->get_num_args();
while (j > 0) {
--j;
expr * arg = to_app(n)->get_arg(j);
ts_visit_child(arg, new_gate_ctx, tcolors, fcolors, todo, visited);
}
return visited;
}
void context::top_sort_expr(expr * n, svector<expr_bool_pair> & sorted_exprs) {
svector<expr_bool_pair> todo;
svector<int> tcolors;
svector<int> fcolors;
todo.push_back(expr_bool_pair(n, true));
while (!todo.empty()) {
expr_bool_pair & p = todo.back();
expr * curr = p.first;
bool gate_ctx = p.second;
switch (get_color(tcolors, fcolors, curr, gate_ctx)) {
case White:
set_color(tcolors, fcolors, curr, gate_ctx, Grey);
ts_visit_children(curr, gate_ctx, tcolors, fcolors, todo);
break;
case Grey:
SASSERT(ts_visit_children(curr, gate_ctx, tcolors, fcolors, todo));
set_color(tcolors, fcolors, curr, gate_ctx, Black);
if (n != curr && !m_manager.is_not(curr))
sorted_exprs.push_back(expr_bool_pair(curr, gate_ctx));
break;
case Black:
todo.pop_back();
break;
default:
UNREACHABLE();
}
}
}
#define DEEP_EXPR_THRESHOLD 1024
/**
\brief Internalize an expression asserted into the logical context using the given proof as a justification.
\remark pr is 0 if proofs are disabled.
*/
void context::internalize_assertion(expr * n, proof * pr, unsigned generation) {
TRACE("internalize_assertion", tout << mk_pp(n, m_manager) << "\n";);
TRACE("internalize_assertion_ll", tout << mk_ll_pp(n, m_manager) << "\n";);
TRACE("generation", tout << "generation: " << m_generation << "\n";);
TRACE("incompleteness_bug", tout << "[internalize-assertion]: #" << n->get_id() << "\n";);
flet<unsigned> l(m_generation, generation);
m_stats.m_max_generation = std::max(m_generation, m_stats.m_max_generation);
if (get_depth(n) > DEEP_EXPR_THRESHOLD) {
// if the expression is deep, then execute topological sort to avoid
// stack overflow.
// a caveat is that theory internalizers do rely on recursive descent so
// internalization over these follows top-down
TRACE("deep_internalize", tout << "expression is deep: #" << n->get_id() << "\n" << mk_ll_pp(n, m_manager););
svector<expr_bool_pair> sorted_exprs;
top_sort_expr(n, sorted_exprs);
TRACE("deep_internalize", for (auto & kv : sorted_exprs) tout << "#" << kv.first->get_id() << " " << kv.second << "\n"; );
for (auto & kv : sorted_exprs) {
expr* e = kv.first;
if (!is_app(e) ||
to_app(e)->get_family_id() == null_family_id ||
to_app(e)->get_family_id() == m_manager.get_basic_family_id())
internalize(e, kv.second);
}
}
SASSERT(m_manager.is_bool(n));
if (is_gate(m_manager, n)) {
switch(to_app(n)->get_decl_kind()) {
case OP_AND:
UNREACHABLE();
case OP_OR: {
literal_buffer lits;
unsigned num = to_app(n)->get_num_args();
for (unsigned i = 0; i < num; i++) {
expr * arg = to_app(n)->get_arg(i);
internalize(arg, true);
lits.push_back(get_literal(arg));
}
mk_root_clause(lits.size(), lits.c_ptr(), pr);
add_or_rel_watches(to_app(n));
break;
}
case OP_IFF: {
expr * lhs = to_app(n)->get_arg(0);
expr * rhs = to_app(n)->get_arg(1);
internalize(lhs, true);
internalize(rhs, true);
literal l1 = get_literal(lhs);
literal l2 = get_literal(rhs);
mk_root_clause(l1, ~l2, pr);
mk_root_clause(~l1, l2, pr);
break;
}
case OP_ITE: {
expr * c = to_app(n)->get_arg(0);
expr * t = to_app(n)->get_arg(1);
expr * e = to_app(n)->get_arg(2);
internalize(c, true);
internalize(t, true);
internalize(e, true);
literal cl = get_literal(c);
literal tl = get_literal(t);
literal el = get_literal(e);
mk_root_clause(~cl, tl, pr);
mk_root_clause(cl, el, pr);
add_ite_rel_watches(to_app(n));
break;
}
default:
UNREACHABLE();
}
mark_as_relevant(n);
}
else if (m_manager.is_distinct(n)) {
assert_distinct(to_app(n), pr);
mark_as_relevant(n);
}
else {
assert_default(n, pr);
}
}
void context::assert_default(expr * n, proof * pr) {
internalize(n, true);
literal l = get_literal(n);
if (l == false_literal) {
set_conflict(mk_justification(justification_proof_wrapper(*this, pr)));
}
else {
assign(l, mk_justification(justification_proof_wrapper(*this, pr)));
mark_as_relevant(l);
}
}
#define DISTINCT_SZ_THRESHOLD 32
void context::assert_distinct(app * n, proof * pr) {
TRACE("assert_distinct", tout << mk_pp(n, m_manager) << "\n";);
unsigned num_args = n->get_num_args();
if (num_args == 0 || num_args <= DISTINCT_SZ_THRESHOLD || m_manager.proofs_enabled()) {
assert_default(n, pr);
return;
}
sort * s = m_manager.get_sort(n->get_arg(0));
sort_ref u(m_manager.mk_fresh_sort("distinct-elems"), m_manager);
func_decl_ref f(m_manager.mk_fresh_func_decl("distinct-aux-f", "", 1, &s, u), m_manager);
for (unsigned i = 0; i < num_args; i++) {
expr * arg = n->get_arg(i);
app_ref fapp(m_manager.mk_app(f, arg), m_manager);
app_ref val(m_manager.mk_fresh_const("unique-value", u), m_manager);
enode * e = mk_enode(val, false, false, true);
e->mark_as_interpreted();
app_ref eq(m_manager.mk_eq(fapp, val), m_manager);
TRACE("assert_distinct", tout << "eq: " << mk_pp(eq, m_manager) << "\n";);
assert_default(eq, 0);
mark_as_relevant(eq.get());
// TODO: we may want to hide the auxiliary values val and the function f from the model.
}
}
void context::internalize(expr * n, bool gate_ctx, unsigned generation) {
flet<unsigned> l(m_generation, generation);
m_stats.m_max_generation = std::max(m_generation, m_stats.m_max_generation);
internalize(n, gate_ctx);
}
/**
\brief Internalize the given expression into the logical context.
- gate_ctx is true if the expression is in the context of a logical gate.
*/
void context::internalize(expr * n, bool gate_ctx) {
TRACE("internalize", tout << "internalizing:\n" << mk_pp(n, m_manager) << "\n";);
TRACE("internalize_bug", tout << "internalizing:\n" << mk_bounded_pp(n, m_manager) << "\n";);
if (is_var(n)) {
throw default_exception("Formulas should not contain unbound variables");
}
if (m_manager.is_bool(n)) {
SASSERT(is_quantifier(n) || is_app(n));
internalize_formula(n, gate_ctx);
}
else {
SASSERT(is_app(n));
SASSERT(!gate_ctx);
internalize_term(to_app(n));
}
}
/**
\brief Internalize the given formula into the logical context.
*/
void context::internalize_formula(expr * n, bool gate_ctx) {
TRACE("internalize_bug", tout << "internalize formula: #" << n->get_id() << ", gate_ctx: " << gate_ctx << "\n" << mk_pp(n, m_manager) << "\n";);
SASSERT(m_manager.is_bool(n));
if (m_manager.is_true(n) || m_manager.is_false(n))
return;
if (m_manager.is_not(n) && gate_ctx) {
// a boolean variable does not need to be created if n a NOT gate is in
// the context of a gate.
internalize(to_app(n)->get_arg(0), true);
return;
}
if (b_internalized(n)) {
// n was already internalized as a boolean.
bool_var v = get_bool_var(n);
TRACE("internalize_bug", tout << "#" << n->get_id() << " already has bool_var v" << v << "\n";);
// n was already internalized as boolean, but an enode was
// not associated with it. So, an enode is necessary, if
// n is not in the context of a gate and is an application.
if (!gate_ctx && is_app(n)) {
if (e_internalized(n)) {
TRACE("internalize_bug", tout << "forcing enode #" << n->get_id() << " to merge with t/f\n";);
enode * e = get_enode(to_app(n));
set_merge_tf(e, v, false);
}
else {
TRACE("internalize_bug", tout << "creating enode for #" << n->get_id() << "\n";);
mk_enode(to_app(n),
true, /* suppress arguments, we not not use CC for this kind of enode */
true, /* bool enode must be merged with true/false, since it is not in the context of a gate */
false /* CC is not enabled */ );
set_enode_flag(v, false);
if (get_assignment(v) != l_undef)
propagate_bool_var_enode(v);
}
SASSERT(has_enode(v));
}
return;
}
if (m_manager.is_eq(n))
internalize_eq(to_app(n), gate_ctx);
else if (m_manager.is_distinct(n))
internalize_distinct(to_app(n), gate_ctx);
else if (is_app(n) && internalize_theory_atom(to_app(n), gate_ctx))
return;
else if (is_quantifier(n))
internalize_quantifier(to_quantifier(n), gate_ctx);
else
internalize_formula_core(to_app(n), gate_ctx);
}
/**
\brief Internalize an equality.
*/
void context::internalize_eq(app * n, bool gate_ctx) {
TRACE("internalize", tout << mk_pp(n, m_manager) << "\n";);
SASSERT(!b_internalized(n));
SASSERT(m_manager.is_eq(n));
internalize_formula_core(n, gate_ctx);
bool_var v = get_bool_var(n);
bool_var_data & d = get_bdata(v);
d.set_eq_flag();
sort * s = m_manager.get_sort(n->get_arg(0));
theory * th = m_theories.get_plugin(s->get_family_id());
if (th)
th->internalize_eq_eh(n, v);
}
/**
\brief Internalize distinct constructor.
*/
void context::internalize_distinct(app * n, bool gate_ctx) {
TRACE("distinct", tout << "internalizing distinct: " << mk_pp(n, m_manager) << "\n";);
SASSERT(!b_internalized(n));
SASSERT(m_manager.is_distinct(n));
expr_ref def(m_manager.mk_distinct_expanded(n->get_num_args(), n->get_args()), m_manager);
internalize(def, true);
bool_var v = mk_bool_var(n);
literal l(v);
literal l_def = get_literal(def);
mk_gate_clause(~l, l_def);
mk_gate_clause(l, ~l_def);
add_relevancy_dependency(n, def);
if (!gate_ctx) {
mk_enode(n, true, true, false);
set_enode_flag(v, true);
SASSERT(get_assignment(v) == l_undef);
}
}
/**
\brief Try to internalize n as a theory atom. Return true if succeeded.
The application can be internalize as a theory atom, if there is a theory (plugin)
that can internalize n.
*/
bool context::internalize_theory_atom(app * n, bool gate_ctx) {
SASSERT(!b_internalized(n));
theory * th = m_theories.get_plugin(n->get_family_id());
TRACE("datatype_bug", tout << "internalizing theory atom:\n" << mk_pp(n, m_manager) << "\n";);
if (!th || !th->internalize_atom(n, gate_ctx))
return false;
TRACE("datatype_bug", tout << "internalization succeeded\n" << mk_pp(n, m_manager) << "\n";);
SASSERT(b_internalized(n));
TRACE("internalize_theory_atom", tout << "internalizing theory atom: #" << n->get_id() << "\n";);
bool_var v = get_bool_var(n);
if (!gate_ctx) {
// if the formula is not in the context of a gate, then it
// must be associated with an enode.
if (!e_internalized(n)) {
mk_enode(to_app(n),
true, /* suppress arguments, we not not use CC for this kind of enode */
true /* bool enode must be merged with true/false, since it is not in the context of a gate */,
false /* CC is not enabled */);
}
else {
SASSERT(e_internalized(n));
enode * e = get_enode(n);
set_enode_flag(v, true);
set_merge_tf(e, v, true);
}
}
if (e_internalized(n)) {
set_enode_flag(v, true);
if (get_assignment(v) != l_undef)
propagate_bool_var_enode(v);
}
SASSERT(!e_internalized(n) || has_enode(v));
return true;
}
#ifdef Z3DEBUG
struct check_pattern_proc {
void operator()(var * v) {}
void operator()(quantifier * q) {}
void operator()(app * n) {
if (is_ground(n))
return;
SASSERT(n->get_decl()->is_flat_associative() || n->get_num_args() == n->get_decl()->get_arity());
}
};
/**
Debugging code: check whether for all (non-ground) applications (f a_1 ... a_n) in t, f->get_arity() == n
*/
static bool check_pattern(expr * t) {
check_pattern_proc p;
for_each_expr(p, t);
return true;
}
static bool check_patterns(quantifier * q) {
for (unsigned i = 0; i < q->get_num_patterns(); i++) {
SASSERT(check_pattern(q->get_pattern(i)));
}
for (unsigned i = 0; i < q->get_num_no_patterns(); i++) {
SASSERT(check_pattern(q->get_no_pattern(i)));
}
return true;
}
#endif
/**
\brief Internalize the given quantifier into the logical
context.
*/
void context::internalize_quantifier(quantifier * q, bool gate_ctx) {
TRACE("internalize_quantifier", tout << mk_pp(q, m_manager) << "\n";);
CTRACE("internalize_quantifier_zero", q->get_weight() == 0, tout << mk_pp(q, m_manager) << "\n";);
SASSERT(gate_ctx); // limitation of the current implementation
SASSERT(!b_internalized(q));
SASSERT(q->is_forall());
SASSERT(check_patterns(q));
bool_var v = mk_bool_var(q);
unsigned generation = m_generation;
unsigned _generation;
if (!m_cached_generation.empty() && m_cached_generation.find(q, _generation)) {
generation = _generation;
}
// TODO: do we really need this flag?
bool_var_data & d = get_bdata(v);
d.set_quantifier_flag();
m_qmanager->add(q, generation);
}
/**
\brief Internalize gates and (uninterpreted and equality) predicates.
*/
void context::internalize_formula_core(app * n, bool gate_ctx) {
SASSERT(!b_internalized(n));
SASSERT(!e_internalized(n));
CTRACE("resolve_conflict_crash", m_manager.is_not(n), tout << mk_ismt2_pp(n, m_manager) << "\ngate_ctx: " << gate_ctx << "\n";);
bool _is_gate = is_gate(m_manager, n) || m_manager.is_not(n);
// process args
unsigned num = n->get_num_args();
for (unsigned i = 0; i < num; i++) {
expr * arg = n->get_arg(i);
internalize(arg, _is_gate);
}
CTRACE("internalize_bug", b_internalized(n), tout << mk_ll_pp(n, m_manager) << "\n";);
bool is_new_var = false;
bool_var v;
// n can be already internalized after its children are internalized.
// Example (ite-term): (= (ite c 1 0) 1)
//
// When (ite c 1 0) is internalized, it will force the internalization of (= (ite c 1 0) 1) and (= (ite c 1 0) 0)
//
// TODO: avoid the problem by delaying the internalization of (= (ite c 1 0) 1) and (= (ite c 1 0) 0).
// Add them to a queue.
if (!b_internalized(n)) {
is_new_var = true;
v = mk_bool_var(n);
}
else {
v = get_bool_var(n);
}
// a formula needs to be associated with an enode when:
// 1) it is not in the context of a gate, or
// 2) it has arguments and it is not a gate (i.e., uninterpreted predicate or equality).
if (!e_internalized(n) && (!gate_ctx || (!_is_gate && n->get_num_args() > 0))) {
bool suppress_args = _is_gate || m_manager.is_not(n);
bool merge_tf = !gate_ctx;
mk_enode(n, suppress_args, merge_tf, true);
set_enode_flag(v, is_new_var);
SASSERT(has_enode(v));
}
// The constraints associated with node 'n' should be asserted
// after the bool_var and enode associated with are created.
// Reason: incompleteness. An assigned boolean variable is only inserted
// in m_atom_propagation_queue if the predicate is_atom() is true.
// When the constraints for n are created, they may force v to be assigned.
// Now, if v is assigned before being associated with an enode, then
// v is not going to be inserted in m_atom_propagation_queue, and
// propagate_bool_var_enode() method is not going to be invoked for v.
if (is_new_var && n->get_family_id() == m_manager.get_basic_family_id()) {
switch (n->get_decl_kind()) {
case OP_NOT:
SASSERT(!gate_ctx);
mk_not_cnstr(to_app(n));
break;
case OP_AND:
mk_and_cnstr(to_app(n));
add_and_rel_watches(to_app(n));
break;
case OP_OR:
mk_or_cnstr(to_app(n));
add_or_rel_watches(to_app(n));
break;
case OP_IFF:
mk_iff_cnstr(to_app(n));
break;
case OP_ITE:
mk_ite_cnstr(to_app(n));
add_ite_rel_watches(to_app(n));
break;
case OP_TRUE:
case OP_FALSE:
break;
case OP_DISTINCT:
case OP_IMPLIES:
case OP_XOR:
UNREACHABLE();
case OP_OEQ:
case OP_INTERP:
UNREACHABLE();
default:
break;
}
}
CTRACE("internalize_bug", e_internalized(n),
tout << "#" << n->get_id() << ", merge_tf: " << get_enode(n)->merge_tf() << "\n";);
}
/**
\brief Trail object to disable the m_merge_tf flag of an enode.
*/
class set_merge_tf_trail : public trail<context> {
enode * m_node;
public:
set_merge_tf_trail(enode * n):
m_node(n) {
}
virtual void undo(context & ctx) {
m_node->m_merge_tf = false;
}
};
/**
\brief Enable the flag m_merge_tf in the given enode. When the
flag m_merge_tf is enabled, the enode n will be merged with the
true_enode (false_enode) whenever the Boolean variable v is
assigned to true (false).
If is_new_var is true, then trail is not created for the flag update.
*/
void context::set_merge_tf(enode * n, bool_var v, bool is_new_var) {
SASSERT(bool_var2enode(v) == n);
if (!n->m_merge_tf) {
if (!is_new_var)
push_trail(set_merge_tf_trail(n));
n->m_merge_tf = true;
lbool val = get_assignment(v);
if (val != l_undef)
push_eq(n, val == l_true ? m_true_enode : m_false_enode, eq_justification(literal(v, val == l_false)));
}
}
/**
\brief Trail object to disable the m_enode flag of a Boolean
variable. The flag m_enode is true for a Boolean variable v,
if there is an enode n associated with it.
*/
class set_enode_flag_trail : public trail<context> {
bool_var m_var;
public:
set_enode_flag_trail(bool_var v):
m_var(v) {
}
virtual void undo(context & ctx) {
bool_var_data & data = ctx.m_bdata[m_var];
data.reset_enode_flag();
}
};
/**
\brief Enable the flag m_enode in the given boolean variable. That is,
the boolean variable is associated with an enode.
If is_new_var is true, then trail is not created for the flag uodate.
*/
void context::set_enode_flag(bool_var v, bool is_new_var) {
SASSERT(e_internalized(bool_var2expr(v)));
bool_var_data & data = m_bdata[v];
if (!data.is_enode()) {
if (!is_new_var)
push_trail(set_enode_flag_trail(v));
data.set_enode_flag();
}
}
/**
\brief Internalize the given term into the logical context.
*/
void context::internalize_term(app * n) {
if (e_internalized(n)) {
theory * th = m_theories.get_plugin(n->get_family_id());
if (th != 0) {
// This code is necessary because some theories may decide
// not to create theory variables for a nested application.
// Example:
// Suppose (+ (* 2 x) y) is internalized by arithmetic
// and an enode is created for the + and * applications,
// but a theory variable is only created for the + application.
// The (* 2 x) is internal to the arithmetic module.
// Later, the core tries to internalize (f (* 2 x)).
// Now, (* 2 x) is not internal to arithmetic anymore,
// and a theory variable must be created for it.
enode * e = get_enode(n);
if (!th->is_attached_to_var(e))
internalize_theory_term(n);
}
return;
}
if (m_manager.is_term_ite(n)) {
internalize_ite_term(n);
return; // it is not necessary to apply sort constraint
}
else if (internalize_theory_term(n)) {
// skip
}
else {
internalize_uninterpreted(n);
}
SASSERT(e_internalized(n));
enode * e = get_enode(n);
apply_sort_cnstr(n, e);
}
/**
\brief Internalize an if-then-else term.
*/
void context::internalize_ite_term(app * n) {
SASSERT(!e_internalized(n));
expr * c = n->get_arg(0);
expr * t = n->get_arg(1);
expr * e = n->get_arg(2);
app_ref eq1(mk_eq_atom(n, t), m_manager);
app_ref eq2(mk_eq_atom(n, e), m_manager);
mk_enode(n,
true /* suppress arguments, I don't want to apply CC on ite terms */,
false /* it is a term, so it should not be merged with true/false */,
false /* CC is not enabled */);
internalize(c, true);
internalize(t, false);
internalize(e, false);
internalize(eq1, true);
internalize(eq2, true);
literal c_lit = get_literal(c);
literal eq1_lit = get_literal(eq1);
literal eq2_lit = get_literal(eq2);
TRACE("internalize_ite_term_bug",
tout << mk_ismt2_pp(n, m_manager) << "\n";
tout << mk_ismt2_pp(c, m_manager) << "\n";
tout << mk_ismt2_pp(t, m_manager) << "\n";
tout << mk_ismt2_pp(e, m_manager) << "\n";
tout << mk_ismt2_pp(eq1, m_manager) << "\n";
tout << mk_ismt2_pp(eq2, m_manager) << "\n";
tout << "literals:\n" << c_lit << " " << eq1_lit << " " << eq2_lit << "\n";);
mk_gate_clause(~c_lit, eq1_lit);
mk_gate_clause( c_lit, eq2_lit);
if (relevancy()) {
relevancy_eh * eh = m_relevancy_propagator->mk_term_ite_relevancy_eh(n, eq1, eq2);
TRACE("ite_term_relevancy", tout << "#" << n->get_id() << " #" << eq1->get_id() << " #" << eq2->get_id() << "\n";);
add_rel_watch(c_lit, eh);
add_rel_watch(~c_lit, eh);
add_relevancy_eh(n, eh);
}
SASSERT(e_internalized(n));
}
/**
\brief Try to internalize a theory term. That is, a theory (plugin)
will be invoked to internalize n. Return true if succeeded.
It may fail because there is no plugin or the plugin does not support it.
*/
bool context::internalize_theory_term(app * n) {
theory * th = m_theories.get_plugin(n->get_family_id());
if (!th || !th->internalize_term(n))
return false;
return true;
}
/**
\brief Internalize an uninterpreted function application or constant.
*/
void context::internalize_uninterpreted(app * n) {
SASSERT(!e_internalized(n));
// process args
unsigned num = n->get_num_args();
for (unsigned i = 0; i < num; i++) {
expr * arg = n->get_arg(i);
internalize(arg, false);
SASSERT(e_internalized(arg));
}
enode * e = mk_enode(n,
false, /* do not suppress args */
false, /* it is a term, so it should not be merged with true/false */
true);
apply_sort_cnstr(n, e);
}
/**
\brief Create a new boolean variable and associate it with n.
*/
bool_var context::mk_bool_var(expr * n) {
SASSERT(!b_internalized(n));
//SASSERT(!m_manager.is_not(n));
unsigned id = n->get_id();
bool_var v = m_b_internalized_stack.size();
#ifndef _EXTERNAL_RELEASE
if (m_fparams.m_display_bool_var2expr) {
char const * header = "(iff z3@";
int id_sz = 6;
std::cerr.width(id_sz);
std::cerr << header << std::left << v << " " << mk_pp(n, m_manager, static_cast<unsigned>(strlen(header)) + id_sz + 1) << ")\n";
}
if (m_fparams.m_display_ll_bool_var2expr) {
std::cerr << v << " ::=\n" << mk_ll_pp(n, m_manager) << "<END-OF-FORMULA>\n";
}
#endif
TRACE("mk_bool_var", tout << "creating boolean variable: " << v << " for:\n" << mk_pp(n, m_manager) << "\n";);
TRACE("mk_var_bug", tout << "mk_bool: " << v << "\n";);
set_bool_var(id, v);
m_bdata.reserve(v+1);
m_activity.reserve(v+1);
m_bool_var2expr.reserve(v+1);
m_bool_var2expr[v] = n;
literal l(v, false);
literal not_l(v, true);
unsigned aux = std::max(l.index(), not_l.index()) + 1;
m_assignment.reserve(aux);
m_assignment[l.index()] = l_undef;
m_assignment[not_l.index()] = l_undef;
m_watches.reserve(aux);
SASSERT(m_assignment.size() == m_watches.size());
m_watches[l.index()] .reset();
m_watches[not_l.index()] .reset();
if (lit_occs_enabled()) {
m_lit_occs.reserve(aux);
m_lit_occs[l.index()] .reset();
m_lit_occs[not_l.index()] .reset();
}
bool_var_data & data = m_bdata[v];
unsigned iscope_lvl = m_scope_lvl; // record when the boolean variable was internalized.
data.init(iscope_lvl);
if (m_fparams.m_random_initial_activity == IA_RANDOM || (m_fparams.m_random_initial_activity == IA_RANDOM_WHEN_SEARCHING && m_searching))
m_activity[v] = -((m_random() % 1000) / 1000.0);
else
m_activity[v] = 0.0;
m_case_split_queue->mk_var_eh(v);
m_b_internalized_stack.push_back(n);
m_trail_stack.push_back(&m_mk_bool_var_trail);
m_stats.m_num_mk_bool_var++;
SASSERT(check_bool_var_vector_sizes());
return v;
}
void context::undo_mk_bool_var() {
SASSERT(!m_b_internalized_stack.empty());
m_stats.m_num_del_bool_var++;
expr * n = m_b_internalized_stack.back();
unsigned n_id = n->get_id();
bool_var v = get_bool_var_of_id(n_id);
TRACE("undo_mk_bool_var", tout << "undo_bool: " << v << "\n" << mk_pp(n, m_manager) << "\n" << "m_bdata.size: " << m_bdata.size()
<< " m_assignment.size: " << m_assignment.size() << "\n";);
TRACE("mk_var_bug", tout << "undo_mk_bool: " << v << "\n";);
// bool_var_data & d = m_bdata[v];
m_case_split_queue->del_var_eh(v);
if (is_quantifier(n))
m_qmanager->del(to_quantifier(n));
set_bool_var(n_id, null_bool_var);
m_b_internalized_stack.pop_back();
}
/**
\brief Create an new enode.
\remark If suppress_args is true, then the enode is viewed as a constant
in the egraph.
*/
enode * context::mk_enode(app * n, bool suppress_args, bool merge_tf, bool cgc_enabled) {
TRACE("mk_enode_detail", tout << mk_pp(n, m_manager) << "\nsuppress_args: " << suppress_args << ", merge_tf: " <<
merge_tf << ", cgc_enabled: " << cgc_enabled << "\n";);
SASSERT(!e_internalized(n));
unsigned id = n->get_id();
unsigned generation = m_generation;
unsigned _generation = 0;
if (!m_cached_generation.empty() && m_cached_generation.find(n, _generation)) {
generation = _generation;
CTRACE("cached_generation", generation != m_generation,
tout << "cached_generation: #" << n->get_id() << " " << generation << " " << m_generation << "\n";);
}
enode * e = enode::mk(m_manager, m_region, m_app2enode, n, generation, suppress_args, merge_tf, m_scope_lvl, cgc_enabled, true);
TRACE("mk_enode_detail", tout << "e.get_num_args() = " << e->get_num_args() << "\n";);
if (n->get_num_args() == 0 && m_manager.is_unique_value(n))
e->mark_as_interpreted();
TRACE("mk_var_bug", tout << "mk_enode: " << id << "\n";);
TRACE("generation", tout << "mk_enode: " << id << " " << generation << "\n";);
m_app2enode.setx(id, e, 0);
m_e_internalized_stack.push_back(n);
m_trail_stack.push_back(&m_mk_enode_trail);
m_enodes.push_back(e);
if (e->get_num_args() > 0) {
if (e->is_true_eq()) {
bool_var v = enode2bool_var(e);
assign(literal(v), mk_justification(eq_propagation_justification(e->get_arg(0), e->get_arg(1))));
e->m_cg = e;
}
else {
if (cgc_enabled) {
enode_bool_pair pair = m_cg_table.insert(e);
enode * e_prime = pair.first;
if (e != e_prime) {
e->m_cg = e_prime;
bool used_commutativity = pair.second;
push_new_congruence(e, e_prime, used_commutativity);
}
else {
e->m_cg = e;
}
}
else {
e->m_cg = e;
}
}
if (!e->is_eq()) {
unsigned decl_id = n->get_decl()->get_decl_id();
if (decl_id >= m_decl2enodes.size())
m_decl2enodes.resize(decl_id+1);
m_decl2enodes[decl_id].push_back(e);
}
}
SASSERT(e_internalized(n));
m_stats.m_num_mk_enode++;
TRACE("mk_enode", tout << "created enode: #" << e->get_owner_id() << " for:\n" << mk_pp(n, m_manager) << "\n";
if (e->get_num_args() > 0) {
tout << "is_true_eq: " << e->is_true_eq() << " in cg_table: " << m_cg_table.contains_ptr(e) << " is_cgr: "
<< e->is_cgr() << "\n";
});
if (m_manager.has_trace_stream())
m_manager.trace_stream() << "[attach-enode] #" << n->get_id() << " " << m_generation << "\n";
return e;
}
void context::undo_mk_enode() {
SASSERT(!m_e_internalized_stack.empty());
m_stats.m_num_del_enode++;
expr * n = m_e_internalized_stack.back();
TRACE("undo_mk_enode", tout << "undo_enode: #" << n->get_id() << "\n" << mk_pp(n, m_manager) << "\n";);
TRACE("mk_var_bug", tout << "undo_mk_enode: " << n->get_id() << "\n";);
unsigned n_id = n->get_id();
SASSERT(is_app(n));
enode * e = m_app2enode[n_id];
m_app2enode[n_id] = 0;
if (e->is_cgr() && !e->is_true_eq() && e->is_cgc_enabled()) {
SASSERT(m_cg_table.contains_ptr(e));
m_cg_table.erase(e);
}
if (e->get_num_args() > 0 && !e->is_eq()) {
unsigned decl_id = to_app(n)->get_decl()->get_decl_id();
SASSERT(decl_id < m_decl2enodes.size());
SASSERT(m_decl2enodes[decl_id].back() == e);
m_decl2enodes[decl_id].pop_back();
}
e->del_eh(m_manager);
SASSERT(m_e_internalized_stack.size() == m_enodes.size());
m_enodes.pop_back();
m_e_internalized_stack.pop_back();
}
/**
\brief Apply sort constraints on e.
*/
void context::apply_sort_cnstr(app * term, enode * e) {
sort * s = term->get_decl()->get_range();
theory * th = m_theories.get_plugin(s->get_family_id());
if (th)
th->apply_sort_cnstr(e, s);
}
/**
\brief Return the literal associated with n.
*/
literal context::get_literal(expr * n) const {
if (m_manager.is_not(n)) {
CTRACE("get_literal_bug", !b_internalized(to_app(n)->get_arg(0)), tout << mk_ll_pp(n, m_manager) << "\n";);
SASSERT(b_internalized(to_app(n)->get_arg(0)));
return literal(get_bool_var(to_app(n)->get_arg(0)), true);
}
else if (m_manager.is_true(n)) {
return true_literal;
}
else if (m_manager.is_false(n)) {
return false_literal;
}
else {
SASSERT(b_internalized(n));
return literal(get_bool_var(n), false);
}
}
/**
\brief Simplify the literals of an auxiliary clause. An
auxiliary clause is transient. So, the current assignment can
be used for simplification.
The following simplifications are applied:
- Duplicates are removed.
- Literals assigned to false are removed
- If l and ~l are in lits, then return false (the clause is equivalent to true)
- If a literal in source is assigned to true, then return false.
\remark The removed literals are stored in simp_lits
It is safe to use the current assignment to simplify aux
clauses because they are deleted during backtracking.
*/
bool context::simplify_aux_clause_literals(unsigned & num_lits, literal * lits, literal_buffer & simp_lits) {
std::sort(lits, lits + num_lits);
literal prev = null_literal;
unsigned j = 0;
for (unsigned i = 0; i < num_lits; i++) {
literal curr = lits[i];
lbool val = get_assignment(curr);
switch(val) {
case l_false:
TRACE("simplify_aux_clause_literals", display_literal(tout << get_assign_level(curr) << " " << get_scope_level() << " ", curr); tout << "\n"; );
simp_lits.push_back(~curr);
break; // ignore literal
// fall through
case l_undef:
if (curr == ~prev)
return false; // clause is equivalent to true
if (curr != prev) {
prev = curr;
if (i != j)
lits[j] = lits[i];
j++;
}
break;
case l_true:
return false; // clause is equivalent to true
}
}
num_lits = j;
return true;
}
/**
\brief Simplify the literals of an auxiliary lemma. An
auxiliary lemma has the status of a learned clause, but it is
not created by conflict resolution.
A dynamic ackermann clause is an example of auxiliary lemma.
The following simplifications are applied:
- Duplicates are removed.
- If a literal is assigned to true at a base level, then return
false (the clause is equivalent to true).
- If l and ~l are in lits, then return false (source is
irrelevant, that is, it is equivalent to true)
\remark Literals assigned to false at the base level are not
removed because I don't want to create a justification for this
kind of simplification.
*/
bool context::simplify_aux_lemma_literals(unsigned & num_lits, literal * lits) {
TRACE("simplify_aux_lemma_literals", tout << "1) "; display_literals(tout, num_lits, lits); tout << "\n";);
std::sort(lits, lits + num_lits);
TRACE("simplify_aux_lemma_literals", tout << "2) "; display_literals(tout, num_lits, lits); tout << "\n";);
literal prev = null_literal;
unsigned i = 0;
unsigned j = 0;
for (; i < num_lits; i++) {
literal curr = lits[i];
bool_var var = curr.var();
lbool val = l_undef;
if (get_assign_level(var) <= m_base_lvl)
val = get_assignment(curr);
if (val == l_true)
return false; // clause is equivalent to true
if (curr == ~prev)
return false; // clause is equivalent to true
if (curr != prev) {
prev = curr;
if (i != j)
lits[j] = lits[i];
j++;
}
}
num_lits = j;
TRACE("simplify_aux_lemma_literals", tout << "3) "; display_literals(tout, num_lits, lits); tout << "\n";);
return true;
}
/**
\brief A clause (lemma or aux lemma) may need to be reinitialized for two reasons:
1) Lemmas and aux lemmas may contain literals that were created during the search,
and the maximum internalization scope level of its literals is scope_lvl.
Since the clauses may remain alive when scope_lvl is backtracked, it must
be reinitialised. In this case, reinitialize_atoms must be true.
2) An aux lemma is in conflict or propagated a literal when it was created.
Then, we should check whether the aux lemma is still in conflict or propagating
a literal after backtracking the current scope level.
*/
void context::mark_for_reinit(clause * cls, unsigned scope_lvl, bool reinternalize_atoms) {
SASSERT(scope_lvl >= m_base_lvl);
cls->m_reinit = true;
cls->m_reinternalize_atoms = reinternalize_atoms;
if (scope_lvl >= m_clauses_to_reinit.size())
m_clauses_to_reinit.resize(scope_lvl+1, clause_vector());
m_clauses_to_reinit[scope_lvl].push_back(cls);
}
/**
\brief Return max({ get_intern_level(var) | var \in lits })
*/
unsigned context::get_max_iscope_lvl(unsigned num_lits, literal const * lits) const {
unsigned r = 0;
for (unsigned i = 0; i < num_lits; i++) {
unsigned ilvl = get_intern_level(lits[i].var());
if (ilvl > r)
r = ilvl;
}
return r;
}
/**
\brief Return true if it safe to use the binary clause optimization at this point in time.
*/
bool context::use_binary_clause_opt(literal l1, literal l2, bool lemma) const {
if (!binary_clause_opt_enabled())
return false;
// When relevancy is enable binary clauses should not be used.
// Reason: when a learned clause becomes unit, it should mark the
// unit literal as relevant. When binary_clause_opt is used,
// it is not possible to distinguish between learned and non-learned clauses.
if (lemma && m_fparams.m_relevancy_lvl >= 2)
return false;
if (m_base_lvl > 0)
return false;
if (!lemma && m_scope_lvl > 0)
return false;
if (get_intern_level(l1.var()) > 0)
return false;
if (get_intern_level(l2.var()) > 0)
return false;
return true;
}
/**
\brief The learned clauses (lemmas) produced by the SAT solver
have the property that the first literal will be implied by it
after backtracking. All other literals are assigned to (or
implied to be) false when the learned clause is created. The
first watch literal will always be the first literal. The
second watch literal is computed by this method. It should be
the literal with the highest decision level.
If a literal is not assigned, it means it was re-initialized
after backtracking. So, its level is assumed to be m_scope_lvl.
*/
int context::select_learned_watch_lit(clause const * cls) const {
SASSERT(cls->get_num_literals() >= 2);
int max_false_idx = -1;
unsigned max_lvl = UINT_MAX;
int num_lits = cls->get_num_literals();
for (int i = 1; i < num_lits; i++) {
literal l = cls->get_literal(i);
lbool val = get_assignment(l);
SASSERT(val == l_false || val == l_undef);
unsigned lvl = val == l_false ? get_assign_level(l) : m_scope_lvl;
if (max_false_idx == -1 || lvl > max_lvl) {
max_false_idx = i;
max_lvl = lvl;
}
}
return max_false_idx;
}
/**
\brief Select a watch literal from a set of literals which is
different from the literal in position other_watch_lit.
I use the following rules to select a watch literal.
1- select a literal l in idx >= starting_at such that get_assignment(l) = l_true,
and for all l' in idx' >= starting_at . get_assignment(l') = l_true implies get_level(l) <= get_level(l')
The purpose of this rule is to make the clause inactive for as long as possible. A clause
is inactive when it contains a literal assigned to true.
2- if there isn't a literal assigned to true, then select an unassigned literal l is in idx >= starting_at
3- if there isn't a literal l in idx >= starting_at such that get_assignment(l) = l_true or
get_assignment(l) = l_undef (that is, all literals different from other_watch_lit are assigned
to false), then peek the literal l different starting at starting_at such that for all l' starting at starting_at
get_level(l) >= get_level(l')
Without rule 3, boolean propagation is incomplete, that is, it may miss possible propagations.
\remark The method select_lemma_watch_lit is used to select the
watch literal for regular learned clauses.
*/
int context::select_watch_lit(clause const * cls, int starting_at) const {
SASSERT(cls->get_num_literals() >= 2);
int min_true_idx = -1;
int max_false_idx = -1;
int unknown_idx = -1;
int n = cls->get_num_literals();
for (int i = starting_at; i < n; i++) {
literal l = cls->get_literal(i);
switch(get_assignment(l)) {
case l_false:
if (max_false_idx == -1 || get_assign_level(l.var()) > get_assign_level(cls->get_literal(max_false_idx).var()))
max_false_idx = i;
break;
case l_undef:
unknown_idx = i;
break;
case l_true:
if (min_true_idx == -1 || get_assign_level(l.var()) < get_assign_level(cls->get_literal(min_true_idx).var()))
min_true_idx = i;
break;
}
}
if (min_true_idx != -1)
return min_true_idx;
if (unknown_idx != -1)
return unknown_idx;
SASSERT(max_false_idx != -1);
return max_false_idx;
}
/**
\brief Add watch literal to the given clause.
\pre idx must be 0 or 1.
*/
void context::add_watch_literal(clause * cls, unsigned idx) {
SASSERT(idx == 0 || idx == 1);
literal l = cls->get_literal(idx);
unsigned l_idx = (~l).index();
watch_list & wl = const_cast<watch_list &>(m_watches[l_idx]);
wl.insert_clause(cls);
CASSERT("watch_list", check_watch_list(l_idx));
}
/**
\brief Create a new clause using the given literals, justification, kind and deletion event handler.
The deletion event handler is ignored if binary clause optimization is applicable.
*/
clause * context::mk_clause(unsigned num_lits, literal * lits, justification * j, clause_kind k, clause_del_eh * del_eh) {
TRACE("mk_clause", tout << "creating clause:\n"; display_literals_verbose(tout, num_lits, lits); tout << "\n";);
switch (k) {
case CLS_AUX: {
literal_buffer simp_lits;
if (!simplify_aux_clause_literals(num_lits, lits, simp_lits))
return 0; // clause is equivalent to true;
DEBUG_CODE({
for (unsigned i = 0; i < simp_lits.size(); i++) {
SASSERT(get_assignment(simp_lits[i]) == l_true);
}
});
if (!simp_lits.empty()) {
j = mk_justification(unit_resolution_justification(m_region, j, simp_lits.size(), simp_lits.c_ptr()));
}
break;
}
case CLS_AUX_LEMMA: {
if (!simplify_aux_lemma_literals(num_lits, lits))
return 0; // clause is equivalent to true
// simplify_aux_lemma_literals does not delete literals assigned to false, so
// it is not necessary to create a unit_resolution_justification
break;
}
default:
break;
}
TRACE("mk_clause", tout << "after simplification:\n"; display_literals(tout, num_lits, lits); tout << "\n";);
unsigned activity = 0;
if (activity == 0)
activity = 1;
bool lemma = k != CLS_AUX;
m_stats.m_num_mk_lits += num_lits;
switch (num_lits) {
case 0:
if (j && !j->in_region())
m_justifications.push_back(j);
TRACE("mk_clause", tout << "empty clause... setting conflict\n";);
set_conflict(j == 0 ? b_justification::mk_axiom() : b_justification(j));
SASSERT(inconsistent());
return 0;
case 1:
if (j && !j->in_region())
m_justifications.push_back(j);
assign(lits[0], j);
return 0;
case 2:
if (use_binary_clause_opt(lits[0], lits[1], lemma)) {
literal l1 = lits[0];
literal l2 = lits[1];
m_watches[(~l1).index()].insert_literal(l2);
m_watches[(~l2).index()].insert_literal(l1);
if (get_assignment(l2) == l_false)
assign(l1, b_justification(~l2));
m_stats.m_num_mk_bin_clause++;
return 0;
}
default: {
m_stats.m_num_mk_clause++;
unsigned iscope_lvl = lemma ? get_max_iscope_lvl(num_lits, lits) : 0;
SASSERT(m_scope_lvl >= iscope_lvl);
bool save_atoms = lemma && iscope_lvl > m_base_lvl;
bool reinit = save_atoms;
SASSERT(!lemma || j == 0 || !j->in_region());
clause * cls = clause::mk(m_manager, num_lits, lits, k, j, del_eh, save_atoms, m_bool_var2expr.c_ptr());
if (lemma) {
cls->set_activity(activity);
if (k == CLS_LEARNED) {
int w2_idx = select_learned_watch_lit(cls);
cls->swap_lits(1, w2_idx);
}
else {
SASSERT(k == CLS_AUX_LEMMA);
int w1_idx = select_watch_lit(cls, 0);
cls->swap_lits(0, w1_idx);
int w2_idx = select_watch_lit(cls, 1);
cls->swap_lits(1, w2_idx);
TRACE("mk_th_lemma", display_clause(tout, cls); tout << "\n";);
}
m_lemmas.push_back(cls);
add_watch_literal(cls, 0);
add_watch_literal(cls, 1);
if (get_assignment(cls->get_literal(0)) == l_false) {
set_conflict(b_justification(cls));
if (k == CLS_AUX_LEMMA && m_scope_lvl > m_base_lvl) {
reinit = true;
iscope_lvl = m_scope_lvl;
}
}
else if (get_assignment(cls->get_literal(1)) == l_false) {
assign(cls->get_literal(0), b_justification(cls));
if (k == CLS_AUX_LEMMA && m_scope_lvl > m_base_lvl) {
reinit = true;
iscope_lvl = m_scope_lvl;
}
}
if (reinit)
mark_for_reinit(cls, iscope_lvl, save_atoms);
}
else {
m_aux_clauses.push_back(cls);
add_watch_literal(cls, 0);
add_watch_literal(cls, 1);
if (get_assignment(cls->get_literal(0)) == l_false)
set_conflict(b_justification(cls));
else if (get_assignment(cls->get_literal(1)) == l_false)
assign(cls->get_literal(0), b_justification(cls));
}
if (lit_occs_enabled())
add_lit_occs(cls);
TRACE("add_watch_literal_bug", display_clause_detail(tout, cls););
TRACE("mk_clause_result", display_clause_detail(tout, cls););
CASSERT("mk_clause", check_clause(cls));
return cls;
}}
}
void context::add_lit_occs(clause * cls) {
unsigned num_lits = cls->get_num_literals();
for (unsigned i = 0; i < num_lits; i++) {
literal l = cls->get_literal(i);
m_lit_occs[l.index()].insert(cls);
}
}
void context::mk_clause(literal l1, literal l2, justification * j) {
literal ls[2] = { l1, l2 };
mk_clause(2, ls, j);
}
void context::mk_clause(literal l1, literal l2, literal l3, justification * j) {
literal ls[3] = { l1, l2, l3 };
mk_clause(3, ls, j);
}
void context::mk_th_axiom(theory_id tid, unsigned num_lits, literal * lits, unsigned num_params, parameter * params) {
justification * js = 0;
TRACE("mk_th_axiom",
display_literals_verbose(tout, num_lits, lits);
tout << "\n";);
if (m_manager.proofs_enabled()) {
js = mk_justification(theory_axiom_justification(tid, m_region, num_lits, lits, num_params, params));
}
if (m_fparams.m_smtlib_dump_lemmas) {
literal_buffer tmp;
neg_literals(num_lits, lits, tmp);
SASSERT(tmp.size() == num_lits);
display_lemma_as_smt_problem(tmp.size(), tmp.c_ptr(), false_literal, m_fparams.m_logic);
}
mk_clause(num_lits, lits, js);
}
void context::mk_th_axiom(theory_id tid, literal l1, literal l2, unsigned num_params, parameter * params) {
literal ls[2] = { l1, l2 };
mk_th_axiom(tid, 2, ls, num_params, params);
}
void context::mk_th_axiom(theory_id tid, literal l1, literal l2, literal l3, unsigned num_params, parameter * params) {
literal ls[3] = { l1, l2, l3 };
mk_th_axiom(tid, 3, ls, num_params, params);
}
proof * context::mk_clause_def_axiom(unsigned num_lits, literal * lits, expr * root_gate) {
ptr_buffer<expr> new_lits;
for (unsigned i = 0; i < num_lits; i++) {
literal l = lits[i];
bool_var v = l.var();
expr * atom = m_bool_var2expr[v];
new_lits.push_back(l.sign() ? m_manager.mk_not(atom) : atom);
}
if (root_gate)
new_lits.push_back(m_manager.mk_not(root_gate));
SASSERT(num_lits > 1);
expr * fact = m_manager.mk_or(new_lits.size(), new_lits.c_ptr());
return m_manager.mk_def_axiom(fact);
}
void context::mk_gate_clause(unsigned num_lits, literal * lits) {
if (m_manager.proofs_enabled()) {
proof * pr = mk_clause_def_axiom(num_lits, lits, 0);
TRACE("gate_clause", tout << mk_ll_pp(pr, m_manager););
mk_clause(num_lits, lits, mk_justification(justification_proof_wrapper(*this, pr)));
}
else {
mk_clause(num_lits, lits, 0);
}
}
void context::mk_gate_clause(literal l1, literal l2) {
literal ls[2] = { l1, l2 };
mk_gate_clause(2, ls);
}
void context::mk_gate_clause(literal l1, literal l2, literal l3) {
literal ls[3] = { l1, l2, l3 };
mk_gate_clause(3, ls);
}
void context::mk_gate_clause(literal l1, literal l2, literal l3, literal l4) {
literal ls[4] = { l1, l2, l3, l4 };
mk_gate_clause(4, ls);
}
void context::mk_root_clause(unsigned num_lits, literal * lits, proof * pr) {
if (m_manager.proofs_enabled()) {
SASSERT(m_manager.get_fact(pr));
expr * fact = m_manager.get_fact(pr);
if (!m_manager.is_or(fact)) {
proof * def = mk_clause_def_axiom(num_lits, lits, m_manager.get_fact(pr));
TRACE("gate_clause", tout << mk_ll_pp(def, m_manager) << "\n";
tout << mk_ll_pp(pr, m_manager););
proof * prs[2] = { def, pr };
pr = m_manager.mk_unit_resolution(2, prs);
}
mk_clause(num_lits, lits, mk_justification(justification_proof_wrapper(*this, pr)));
}
else {
mk_clause(num_lits, lits, 0);
}
}
void context::mk_root_clause(literal l1, literal l2, proof * pr) {
literal ls[2] = { l1, l2 };
mk_root_clause(2, ls, pr);
}
void context::mk_root_clause(literal l1, literal l2, literal l3, proof * pr) {
literal ls[3] = { l1, l2, l3 };
mk_root_clause(3, ls, pr);
}
void context::add_and_rel_watches(app * n) {
if (relevancy()) {
relevancy_eh * eh = m_relevancy_propagator->mk_and_relevancy_eh(n);
unsigned num = n->get_num_args();
for (unsigned i = 0; i < num; i++) {
// if one child is assigned to false, the and-parent must be notified
literal l = get_literal(n->get_arg(i));
add_rel_watch(~l, eh);
}
}
}
void context::add_or_rel_watches(app * n) {
if (relevancy()) {
relevancy_eh * eh = m_relevancy_propagator->mk_or_relevancy_eh(n);
unsigned num = n->get_num_args();
for (unsigned i = 0; i < num; i++) {
// if one child is assigned to true, the or-parent must be notified
literal l = get_literal(n->get_arg(i));
add_rel_watch(l, eh);
}
}
}
void context::add_ite_rel_watches(app * n) {
if (relevancy()) {
relevancy_eh * eh = m_relevancy_propagator->mk_ite_relevancy_eh(n);
literal l = get_literal(n->get_arg(0));
// when the condition of an ite is assigned to true or false, the ite-parent must be notified.
TRACE("propagate_relevant_ite", tout << "#" << n->get_id() << ", eh: " << eh << "\n";);
add_rel_watch(l, eh);
add_rel_watch(~l, eh);
}
}
void context::mk_not_cnstr(app * n) {
SASSERT(b_internalized(n));
bool_var v = get_bool_var(n);
literal l(v, false);
literal c = get_literal(n->get_arg(0));
mk_gate_clause(~l, ~c);
mk_gate_clause(l, c);
}
void context::mk_and_cnstr(app * n) {
literal l = get_literal(n);
TRACE("mk_and_cnstr", tout << "l: "; display_literal(tout, l); tout << "\n";);
literal_buffer buffer;
buffer.push_back(l);
unsigned num_args = n->get_num_args();
for (unsigned i = 0; i < num_args; i++) {
literal l_arg = get_literal(n->get_arg(i));
TRACE("mk_and_cnstr", tout << "l_arg: "; display_literal(tout, l_arg); tout << "\n";);
mk_gate_clause(~l, l_arg);
buffer.push_back(~l_arg);
}
mk_gate_clause(buffer.size(), buffer.c_ptr());
}
void context::mk_or_cnstr(app * n) {
literal l = get_literal(n);
literal_buffer buffer;
buffer.push_back(~l);
unsigned num_args = n->get_num_args();
for (unsigned i = 0; i < num_args; i++) {
literal l_arg = get_literal(n->get_arg(i));
mk_gate_clause(l, ~l_arg);
buffer.push_back(l_arg);
}
mk_gate_clause(buffer.size(), buffer.c_ptr());
}
void context::mk_iff_cnstr(app * n) {
literal l = get_literal(n);
literal l1 = get_literal(n->get_arg(0));
literal l2 = get_literal(n->get_arg(1));
TRACE("mk_iff_cnstr", tout << "l: " << l << ", l1: " << l1 << ", l2: " << l2 << "\n";);
mk_gate_clause(~l, l1, ~l2);
mk_gate_clause(~l, ~l1 , l2);
mk_gate_clause( l, l1, l2);
mk_gate_clause( l, ~l1, ~l2);
}
void context::mk_ite_cnstr(app * n) {
literal l = get_literal(n);
literal l1 = get_literal(n->get_arg(0));
literal l2 = get_literal(n->get_arg(1));
literal l3 = get_literal(n->get_arg(2));
mk_gate_clause(~l, ~l1, l2);
mk_gate_clause(~l, l1, l3);
mk_gate_clause(l, ~l1, ~l2);
mk_gate_clause(l, l1, ~l3);
}
/**
\brief Trail for add_th_var
*/
class add_th_var_trail : public trail<context> {
enode * m_enode;
theory_id m_th_id;
#ifdef Z3DEBUG
theory_var m_th_var;
#endif
public:
add_th_var_trail(enode * n, theory_id th_id):
m_enode(n),
m_th_id(th_id) {
DEBUG_CODE(m_th_var = n->get_th_var(th_id););
SASSERT(m_th_var != null_theory_var);
}
virtual void undo(context & ctx) {
theory_var v = m_enode->get_th_var(m_th_id);
SASSERT(v != null_theory_var);
SASSERT(m_th_var == v);
m_enode->del_th_var(m_th_id);
enode * root = m_enode->get_root();
if (root != m_enode && root->get_th_var(m_th_id) == v)
root->del_th_var(m_th_id);
}
};
/**
\brief Trail for replace_th_var
*/
class replace_th_var_trail : public trail<context> {
enode * m_enode;
unsigned m_th_id:8;
unsigned m_old_th_var:24;
public:
replace_th_var_trail(enode * n, theory_id th_id, theory_var old_var):
m_enode(n),
m_th_id(th_id),
m_old_th_var(old_var) {
}
virtual void undo(context & ctx) {
SASSERT(m_enode->get_th_var(m_th_id) != null_theory_var);
m_enode->replace_th_var(m_old_th_var, m_th_id);
}
};
/**
\brief Attach theory var v to the enode n.
Enode n is to attached to any theory variable of th.
This method should be invoked whenever the theory creates a new theory variable.
\remark The methods new_eq_eh and new_diseq_eh of th may be invoked before this method
returns.
*/
void context::attach_th_var(enode * n, theory * th, theory_var v) {
SASSERT(!th->is_attached_to_var(n));
theory_id th_id = th->get_id();
theory_var old_v = n->get_th_var(th_id);
if (old_v == null_theory_var) {
enode * r = n->get_root();
theory_var v2 = r->get_th_var(th_id);
n->add_th_var(v, th_id, m_region);
push_trail(add_th_var_trail(n, th_id));
if (v2 == null_theory_var) {
if (r != n)
r->add_th_var(v, th_id, m_region);
push_new_th_diseqs(r, v, th);
}
else if (r != n) {
push_new_th_eq(th_id, v2, v);
}
}
else {
// Case) there is a variable old_v in the var-list of n.
//
// Remark: This variable was moved to the var-list of n due to a add_eq.
SASSERT(th->get_enode(old_v) != n); // this varialbe is not owned by n
SASSERT(n->get_root()->get_th_var(th_id) != null_theory_var); // the root has also a variable in its var-list.
n->replace_th_var(v, th_id);
push_trail(replace_th_var_trail(n, th_id, old_v));
push_new_th_eq(th_id, v, old_v);
}
SASSERT(th->is_attached_to_var(n));
}
};
| [
"ssaha6@illinois.edu"
] | ssaha6@illinois.edu |
223133d81dad0ca3dbed54b5c70531debaa9abeb | 731dea91b45da634938b9c94e66e4cfa43a33190 | /cpp/hello.pb.cc | b6ea7c3169fbcf61a67ba93a0b00f754f97a8510 | [
"MIT"
] | permissive | avinassh/grpc-errors | 9bd798b4a8f9ad2b5656f76e5f7421ab9289fd2c | 3494f846416668dd5b813bbae1ff73fbaa2b08e7 | refs/heads/master | 2023-03-20T17:23:27.047547 | 2021-11-22T10:33:47 | 2021-11-22T10:33:47 | 86,557,631 | 586 | 89 | MIT | 2023-09-03T17:38:20 | 2017-03-29T08:33:44 | C# | UTF-8 | C++ | false | true | 23,422 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: hello.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "hello.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace hello {
class HelloReqDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<HelloReq> {
} _HelloReq_default_instance_;
class HelloRespDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<HelloResp> {
} _HelloResp_default_instance_;
namespace protobuf_hello_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[2];
} // namespace
const ::google::protobuf::uint32 TableStruct::offsets[] = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloReq, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloReq, name_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloResp, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HelloResp, result_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] = {
{ 0, -1, sizeof(HelloReq)},
{ 5, -1, sizeof(HelloResp)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_HelloReq_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_HelloResp_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"hello.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 2);
}
} // namespace
void TableStruct::Shutdown() {
_HelloReq_default_instance_.Shutdown();
delete file_level_metadata[0].reflection;
_HelloResp_default_instance_.Shutdown();
delete file_level_metadata[1].reflection;
}
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
_HelloReq_default_instance_.DefaultConstruct();
_HelloResp_default_instance_.DefaultConstruct();
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] = {
"\n\013hello.proto\022\005hello\"\030\n\010HelloReq\022\014\n\004Name"
"\030\001 \001(\t\"\033\n\tHelloResp\022\016\n\006Result\030\001 \001(\t2v\n\014H"
"elloService\022/\n\010SayHello\022\017.hello.HelloReq"
"\032\020.hello.HelloResp\"\000\0225\n\016SayHelloStrict\022\017"
".hello.HelloReq\032\020.hello.HelloResp\"\000b\006pro"
"to3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 203);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"hello.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown);
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_hello_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int HelloReq::kNameFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
HelloReq::HelloReq()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_hello_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:hello.HelloReq)
}
HelloReq::HelloReq(const HelloReq& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
// @@protoc_insertion_point(copy_constructor:hello.HelloReq)
}
void HelloReq::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_cached_size_ = 0;
}
HelloReq::~HelloReq() {
// @@protoc_insertion_point(destructor:hello.HelloReq)
SharedDtor();
}
void HelloReq::SharedDtor() {
name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void HelloReq::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* HelloReq::descriptor() {
protobuf_hello_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_hello_2eproto::file_level_metadata[0].descriptor;
}
const HelloReq& HelloReq::default_instance() {
protobuf_hello_2eproto::InitDefaults();
return *internal_default_instance();
}
HelloReq* HelloReq::New(::google::protobuf::Arena* arena) const {
HelloReq* n = new HelloReq;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void HelloReq::Clear() {
// @@protoc_insertion_point(message_clear_start:hello.HelloReq)
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
bool HelloReq::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:hello.HelloReq)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string Name = 1;
case 1: {
if (tag == 10u) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"hello.HelloReq.Name"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:hello.HelloReq)
return true;
failure:
// @@protoc_insertion_point(parse_failure:hello.HelloReq)
return false;
#undef DO_
}
void HelloReq::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:hello.HelloReq)
// string Name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"hello.HelloReq.Name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// @@protoc_insertion_point(serialize_end:hello.HelloReq)
}
::google::protobuf::uint8* HelloReq::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:hello.HelloReq)
// string Name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"hello.HelloReq.Name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:hello.HelloReq)
return target;
}
size_t HelloReq::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:hello.HelloReq)
size_t total_size = 0;
// string Name = 1;
if (this->name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void HelloReq::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:hello.HelloReq)
GOOGLE_DCHECK_NE(&from, this);
const HelloReq* source =
::google::protobuf::internal::DynamicCastToGenerated<const HelloReq>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:hello.HelloReq)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:hello.HelloReq)
MergeFrom(*source);
}
}
void HelloReq::MergeFrom(const HelloReq& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:hello.HelloReq)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.name().size() > 0) {
name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_);
}
}
void HelloReq::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:hello.HelloReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void HelloReq::CopyFrom(const HelloReq& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:hello.HelloReq)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool HelloReq::IsInitialized() const {
return true;
}
void HelloReq::Swap(HelloReq* other) {
if (other == this) return;
InternalSwap(other);
}
void HelloReq::InternalSwap(HelloReq* other) {
name_.Swap(&other->name_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata HelloReq::GetMetadata() const {
protobuf_hello_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_hello_2eproto::file_level_metadata[0];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// HelloReq
// string Name = 1;
void HelloReq::clear_name() {
name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& HelloReq::name() const {
// @@protoc_insertion_point(field_get:hello.HelloReq.Name)
return name_.GetNoArena();
}
void HelloReq::set_name(const ::std::string& value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:hello.HelloReq.Name)
}
#if LANG_CXX11
void HelloReq::set_name(::std::string&& value) {
name_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), std::move(value));
// @@protoc_insertion_point(field_set_rvalue:hello.HelloReq.Name)
}
#endif
void HelloReq::set_name(const char* value) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:hello.HelloReq.Name)
}
void HelloReq::set_name(const char* value, size_t size) {
name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:hello.HelloReq.Name)
}
::std::string* HelloReq::mutable_name() {
// @@protoc_insertion_point(field_mutable:hello.HelloReq.Name)
return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* HelloReq::release_name() {
// @@protoc_insertion_point(field_release:hello.HelloReq.Name)
return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void HelloReq::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name);
// @@protoc_insertion_point(field_set_allocated:hello.HelloReq.Name)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int HelloResp::kResultFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
HelloResp::HelloResp()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_hello_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:hello.HelloResp)
}
HelloResp::HelloResp(const HelloResp& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
result_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.result().size() > 0) {
result_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.result_);
}
// @@protoc_insertion_point(copy_constructor:hello.HelloResp)
}
void HelloResp::SharedCtor() {
result_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_cached_size_ = 0;
}
HelloResp::~HelloResp() {
// @@protoc_insertion_point(destructor:hello.HelloResp)
SharedDtor();
}
void HelloResp::SharedDtor() {
result_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void HelloResp::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* HelloResp::descriptor() {
protobuf_hello_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_hello_2eproto::file_level_metadata[1].descriptor;
}
const HelloResp& HelloResp::default_instance() {
protobuf_hello_2eproto::InitDefaults();
return *internal_default_instance();
}
HelloResp* HelloResp::New(::google::protobuf::Arena* arena) const {
HelloResp* n = new HelloResp;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void HelloResp::Clear() {
// @@protoc_insertion_point(message_clear_start:hello.HelloResp)
result_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
bool HelloResp::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:hello.HelloResp)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string Result = 1;
case 1: {
if (tag == 10u) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_result()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->result().data(), this->result().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"hello.HelloResp.Result"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:hello.HelloResp)
return true;
failure:
// @@protoc_insertion_point(parse_failure:hello.HelloResp)
return false;
#undef DO_
}
void HelloResp::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:hello.HelloResp)
// string Result = 1;
if (this->result().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->result().data(), this->result().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"hello.HelloResp.Result");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->result(), output);
}
// @@protoc_insertion_point(serialize_end:hello.HelloResp)
}
::google::protobuf::uint8* HelloResp::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:hello.HelloResp)
// string Result = 1;
if (this->result().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->result().data(), this->result().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"hello.HelloResp.Result");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->result(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:hello.HelloResp)
return target;
}
size_t HelloResp::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:hello.HelloResp)
size_t total_size = 0;
// string Result = 1;
if (this->result().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->result());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void HelloResp::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:hello.HelloResp)
GOOGLE_DCHECK_NE(&from, this);
const HelloResp* source =
::google::protobuf::internal::DynamicCastToGenerated<const HelloResp>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:hello.HelloResp)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:hello.HelloResp)
MergeFrom(*source);
}
}
void HelloResp::MergeFrom(const HelloResp& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:hello.HelloResp)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.result().size() > 0) {
result_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.result_);
}
}
void HelloResp::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:hello.HelloResp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void HelloResp::CopyFrom(const HelloResp& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:hello.HelloResp)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool HelloResp::IsInitialized() const {
return true;
}
void HelloResp::Swap(HelloResp* other) {
if (other == this) return;
InternalSwap(other);
}
void HelloResp::InternalSwap(HelloResp* other) {
result_.Swap(&other->result_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata HelloResp::GetMetadata() const {
protobuf_hello_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_hello_2eproto::file_level_metadata[1];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// HelloResp
// string Result = 1;
void HelloResp::clear_result() {
result_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& HelloResp::result() const {
// @@protoc_insertion_point(field_get:hello.HelloResp.Result)
return result_.GetNoArena();
}
void HelloResp::set_result(const ::std::string& value) {
result_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:hello.HelloResp.Result)
}
#if LANG_CXX11
void HelloResp::set_result(::std::string&& value) {
result_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), std::move(value));
// @@protoc_insertion_point(field_set_rvalue:hello.HelloResp.Result)
}
#endif
void HelloResp::set_result(const char* value) {
result_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:hello.HelloResp.Result)
}
void HelloResp::set_result(const char* value, size_t size) {
result_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:hello.HelloResp.Result)
}
::std::string* HelloResp::mutable_result() {
// @@protoc_insertion_point(field_mutable:hello.HelloResp.Result)
return result_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* HelloResp::release_result() {
// @@protoc_insertion_point(field_release:hello.HelloResp.Result)
return result_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void HelloResp::set_allocated_result(::std::string* result) {
if (result != NULL) {
} else {
}
result_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), result);
// @@protoc_insertion_point(field_set_allocated:hello.HelloResp.Result)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace hello
// @@protoc_insertion_point(global_scope)
| [
"hi@avi.im"
] | hi@avi.im |
c3cf115666629c4ae7a2a1416c9e7102497a1d02 | 468cd559cb5374e737bb1b5f42f5fe73dd98dd8b | /source/frontend/views/snapshot/resource_overview_pane.cpp | 01ec7e5b44053f6b3dfc7588663efa0adec5106e | [
"MIT"
] | permissive | GPUOpen-Tools/radeon_memory_visualizer | 31b84ceeb44573e654876df7af9cbf0063015898 | 87d9ca84492432f384e1cc8e93e59c3700ef0e3f | refs/heads/master | 2023-09-01T00:41:37.480829 | 2023-07-12T15:02:57 | 2023-08-16T18:44:26 | 245,466,905 | 117 | 17 | null | null | null | null | UTF-8 | C++ | false | false | 17,240 | cpp | //=============================================================================
// Copyright (c) 2018-2023 Advanced Micro Devices, Inc. All rights reserved.
/// @author AMD Developer Tools Team
/// @file
/// @brief Implementation of the Resource Overview pane.
//=============================================================================
#include "views/snapshot/resource_overview_pane.h"
#include <QCheckBox>
#include "qt_common/custom_widgets/colored_legend_scene.h"
#include "qt_common/utils/scaling_manager.h"
#include "rmt_data_snapshot.h"
#include "managers/trace_manager.h"
#include "managers/message_manager.h"
#include "managers/pane_manager.h"
#include "managers/snapshot_manager.h"
#include "models/heap_combo_box_model.h"
#include "models/resource_usage_combo_box_model.h"
#include "models/snapshot/resource_overview_model.h"
#include "settings/rmv_settings.h"
#include "util/widget_util.h"
#include "views/custom_widgets/rmv_colored_checkbox.h"
ResourceOverviewPane::ResourceOverviewPane(QWidget* parent)
: BasePane(parent)
, ui_(new Ui::ResourceOverviewPane)
, selected_resource_(nullptr)
, resource_details_(nullptr)
, allocation_details_scene_(nullptr)
, slice_mode_map_{}
{
ui_->setupUi(this);
ui_->empty_page_->SetEmptyTitleText();
rmv::widget_util::ApplyStandardPaneStyle(this, ui_->main_content_, ui_->main_scroll_area_);
model_ = new rmv::ResourceOverviewModel();
model_->InitializeModel(ui_->total_available_size_value_, rmv::kResourceOverviewTotalAvailableSize, "text");
model_->InitializeModel(ui_->total_allocated_and_used_value_, rmv::kResourceOverviewTotalAllocatedAndUsed, "text");
model_->InitializeModel(ui_->total_allocated_and_unused_value_, rmv::kResourceOverviewTotalAllocatedAndUnused, "text");
model_->InitializeModel(ui_->allocations_value_, rmv::kResourceOverviewAllocationCount, "text");
model_->InitializeModel(ui_->resources_value_, rmv::kResourceOverviewResourceCount, "text");
rmv::widget_util::InitMultiSelectComboBox(this, ui_->preferred_heap_combo_box_, rmv::text::kPreferredHeap);
rmv::widget_util::InitMultiSelectComboBox(this, ui_->actual_heap_combo_box_, rmv::text::kActualHeap);
rmv::widget_util::InitMultiSelectComboBox(this, ui_->resource_usage_combo_box_, rmv::text::kResourceUsage);
rmv::widget_util::InitSingleSelectComboBox(this, ui_->slicing_button_one_, "", false, "Level 1: ");
rmv::widget_util::InitSingleSelectComboBox(this, ui_->slicing_button_two_, "", false, "Level 2: ");
rmv::widget_util::InitSingleSelectComboBox(this, ui_->slicing_button_three_, "", false, "Level 3: ");
// Hide actual heap as it's not that useful currently.
ui_->actual_heap_combo_box_->hide();
tree_map_models_.preferred_heap_model = new rmv::HeapComboBoxModel();
tree_map_models_.actual_heap_model = new rmv::HeapComboBoxModel();
tree_map_models_.resource_usage_model = new rmv::ResourceUsageComboBoxModel();
colorizer_ = new rmv::Colorizer();
tree_map_models_.preferred_heap_model->SetupHeapComboBox(ui_->preferred_heap_combo_box_);
connect(tree_map_models_.preferred_heap_model, &rmv::HeapComboBoxModel::FilterChanged, this, &ResourceOverviewPane::ComboFiltersChanged);
tree_map_models_.actual_heap_model->SetupHeapComboBox(ui_->actual_heap_combo_box_);
connect(tree_map_models_.actual_heap_model, &rmv::HeapComboBoxModel::FilterChanged, this, &ResourceOverviewPane::ComboFiltersChanged);
tree_map_models_.resource_usage_model->SetupResourceComboBox(ui_->resource_usage_combo_box_);
connect(tree_map_models_.resource_usage_model, &rmv::ResourceUsageComboBoxModel::FilterChanged, this, &ResourceOverviewPane::ComboFiltersChanged);
// Set up a list of required coloring modes, in order.
// The list is terminated with kColorModeCount.
static const rmv::Colorizer::ColorMode mode_list[] = {
rmv::Colorizer::kColorModeResourceUsageType,
rmv::Colorizer::kColorModePreferredHeap,
rmv::Colorizer::kColorModeAllocationAge,
rmv::Colorizer::kColorModeResourceCreateAge,
rmv::Colorizer::kColorModeResourceBindAge,
rmv::Colorizer::kColorModeResourceGUID,
rmv::Colorizer::kColorModeResourceCPUMapped,
rmv::Colorizer::kColorModeNotAllPreferred,
rmv::Colorizer::kColorModeAliasing,
rmv::Colorizer::kColorModeCommitType,
rmv::Colorizer::kColorModeCount,
};
// Initialize the "color by" UI elements. Set up the combo box, legends and signals etc.
colorizer_->Initialize(parent, ui_->color_combo_box_, ui_->legends_view_, mode_list);
ui_->tree_map_view_->SetModels(model_, &tree_map_models_, colorizer_);
struct SliceMapping
{
int slice_id;
QString slice_text;
};
static const std::vector<SliceMapping> slice_map = {
{RMVTreeMapBlocks::kSliceTypeNone, "no slicing"},
{RMVTreeMapBlocks::kSliceTypeResourceUsageType, "slice by resource usage"},
{RMVTreeMapBlocks::kSliceTypePreferredHeap, "slice by preferred heap"},
{RMVTreeMapBlocks::kSliceTypeAllocationAge, "slice by allocation age"},
{RMVTreeMapBlocks::kSliceTypeResourceCreateAge, "slice by resource create time"},
{RMVTreeMapBlocks::kSliceTypeResourceBindAge, "slice by resource bind time"},
{RMVTreeMapBlocks::kSliceTypeVirtualAllocation, "slice by virtual allocation"},
//{RMVTreeMapBlocks::kSliceTypeActualHeap, "slice by actual heap"},
{RMVTreeMapBlocks::kSliceTypeCpuMapped, "slice by CPU mapped"},
//{RMVTreeMapBlocks::kSliceTypeResourceOwner, "slice by resource owner"},
{RMVTreeMapBlocks::kSliceTypeInPreferredHeap, "slice by not all in preferred heap"}
//{RMVTreeMapBlocks::kSliceTypeResourceCommitType, "slice by commit type"}
};
int index = 0;
for (auto it = slice_map.begin(); it != slice_map.end(); ++it)
{
const QString& slice_string = (*it).slice_text;
ui_->slicing_button_one_->AddItem(slice_string);
ui_->slicing_button_two_->AddItem(slice_string);
ui_->slicing_button_three_->AddItem(slice_string);
// Add the indices to a map of combo box index to slice type.
slice_mode_map_[index] = (*it).slice_id;
index++;
}
ui_->resource_details_view_->setFrameStyle(QFrame::NoFrame);
ui_->resource_details_view_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui_->resource_details_view_->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui_->resource_details_view_->setFixedHeight(ScalingManager::Get().Scaled(kResourceDetailsHeight));
allocation_details_scene_ = new QGraphicsScene();
ui_->resource_details_view_->setScene(allocation_details_scene_);
RMVResourceDetailsConfig config = {};
config.width = ui_->resource_details_view_->width();
config.height = ui_->resource_details_view_->height();
config.resource_valid = false;
config.allocation_thumbnail = true;
config.colorizer = colorizer_;
resource_details_ = new RMVResourceDetails(config);
allocation_details_scene_->addItem(resource_details_);
ui_->resource_details_checkbox_->Initialize(true, rmv::kCheckboxEnableColor, Qt::black);
rmv::widget_util::InitDoubleSlider(ui_->size_slider_);
connect(ui_->size_slider_, &DoubleSliderWidget::SpanChanged, this, &ResourceOverviewPane::FilterBySizeSliderChanged);
connect(ui_->resource_details_checkbox_, &RMVColoredCheckbox::Clicked, this, &ResourceOverviewPane::ToggleResourceDetails);
connect(ui_->slicing_button_one_, &ArrowIconComboBox::SelectionChanged, this, &ResourceOverviewPane::SlicingLevelChanged);
connect(ui_->slicing_button_two_, &ArrowIconComboBox::SelectionChanged, this, &ResourceOverviewPane::SlicingLevelChanged);
connect(ui_->slicing_button_three_, &ArrowIconComboBox::SelectionChanged, this, &ResourceOverviewPane::SlicingLevelChanged);
connect(ui_->tree_map_view_->BlocksWidget(), &RMVTreeMapBlocks::ResourceSelected, this, &ResourceOverviewPane::SelectedResource);
connect(ui_->tree_map_view_->BlocksWidget(), &RMVTreeMapBlocks::UnboundResourceSelected, this, &ResourceOverviewPane::SelectedUnboundResource);
connect(ui_->color_combo_box_, &ArrowIconComboBox::SelectionChanged, this, &ResourceOverviewPane::ColorModeChanged);
connect(&rmv::MessageManager::Get(), &rmv::MessageManager::ResourceSelected, this, &ResourceOverviewPane::SelectResource);
connect(&ScalingManager::Get(), &ScalingManager::ScaleFactorChanged, this, &ResourceOverviewPane::OnScaleFactorChanged);
}
ResourceOverviewPane::~ResourceOverviewPane()
{
disconnect(&ScalingManager::Get(), &ScalingManager::ScaleFactorChanged, this, &ResourceOverviewPane::OnScaleFactorChanged);
delete tree_map_models_.preferred_heap_model;
delete tree_map_models_.actual_heap_model;
delete tree_map_models_.resource_usage_model;
delete colorizer_;
delete model_;
}
void ResourceOverviewPane::Refresh()
{
bool use_unbound = tree_map_models_.resource_usage_model->ItemInList(kRmtResourceUsageTypeFree);
model_->Update(use_unbound);
}
void ResourceOverviewPane::showEvent(QShowEvent* event)
{
ResizeItems();
QWidget::showEvent(event);
}
void ResourceOverviewPane::resizeEvent(QResizeEvent* event)
{
ResizeItems();
QWidget::resizeEvent(event);
}
int ResourceOverviewPane::GetRowForSliceType(int slice_type)
{
for (int i = 0; i < RMVTreeMapBlocks::SliceType::kSliceTypeCount; i++)
{
if (slice_mode_map_[i] == slice_type)
{
return i;
}
}
return 0;
}
void ResourceOverviewPane::Reset()
{
selected_resource_ = nullptr;
resource_details_->UpdateResource(selected_resource_);
ui_->slicing_button_one_->SetSelectedRow(GetRowForSliceType(RMVTreeMapBlocks::kSliceTypePreferredHeap));
ui_->slicing_button_two_->SetSelectedRow(GetRowForSliceType(RMVTreeMapBlocks::kSliceTypeVirtualAllocation));
ui_->slicing_button_three_->SetSelectedRow(GetRowForSliceType(RMVTreeMapBlocks::kSliceTypeResourceUsageType));
tree_map_models_.preferred_heap_model->ResetHeapComboBox(ui_->preferred_heap_combo_box_);
tree_map_models_.actual_heap_model->ResetHeapComboBox(ui_->actual_heap_combo_box_);
tree_map_models_.resource_usage_model->ResetResourceComboBox(ui_->resource_usage_combo_box_);
ui_->color_combo_box_->SetSelectedRow(0);
colorizer_->ApplyColorMode();
ui_->size_slider_->SetLowerValue(0);
ui_->size_slider_->SetUpperValue(rmv::kSizeSliderRange);
UpdateDetailsTitle();
}
void ResourceOverviewPane::ChangeColoring()
{
ui_->tree_map_view_->UpdateColorCache();
resource_details_->UpdateResource(selected_resource_);
colorizer_->UpdateLegends();
Refresh();
}
void ResourceOverviewPane::OpenSnapshot(RmtDataSnapshot* snapshot)
{
Q_UNUSED(snapshot);
if (rmv::SnapshotManager::Get().LoadedSnapshotValid())
{
ui_->pane_stack_->setCurrentIndex(rmv::kSnapshotIndexPopulatedPane);
selected_resource_ = nullptr;
resource_details_->UpdateResource(selected_resource_);
UpdateDetailsTitle();
bool use_unbound = tree_map_models_.resource_usage_model->ItemInList(kRmtResourceUsageTypeFree);
model_->Update(use_unbound);
UpdateSlicingLevel();
UpdateComboFilters();
ui_->tree_map_view_->UpdateTreeMap();
}
else
{
ui_->pane_stack_->setCurrentIndex(rmv::kSnapshotIndexEmptyPane);
}
}
void ResourceOverviewPane::ToggleResourceDetails()
{
if (ui_->resource_details_checkbox_->isChecked())
{
ui_->resource_details_->show();
}
else
{
ui_->resource_details_->hide();
}
UpdateDetailsTitle();
}
void ResourceOverviewPane::UpdateComboFilters()
{
tree_map_models_.preferred_heap_model->SetupState(ui_->preferred_heap_combo_box_);
tree_map_models_.actual_heap_model->SetupState(ui_->actual_heap_combo_box_);
tree_map_models_.resource_usage_model->SetupState(ui_->resource_usage_combo_box_);
}
void ResourceOverviewPane::ComboFiltersChanged(bool checked)
{
RMT_UNUSED(checked);
UpdateComboFilters();
Refresh();
selected_resource_ = nullptr;
resource_details_->UpdateResource(selected_resource_);
UpdateDetailsTitle();
ui_->tree_map_view_->UpdateTreeMap();
}
void ResourceOverviewPane::UpdateSlicingLevel()
{
QVector<RMVTreeMapBlocks::SliceType> slicingTypes;
RMVTreeMapBlocks::SliceType typeLevelOne = (RMVTreeMapBlocks::SliceType)slice_mode_map_[ui_->slicing_button_one_->CurrentRow()];
RMVTreeMapBlocks::SliceType typeLevelTwo = (RMVTreeMapBlocks::SliceType)slice_mode_map_[ui_->slicing_button_two_->CurrentRow()];
RMVTreeMapBlocks::SliceType typeLevelThree = (RMVTreeMapBlocks::SliceType)slice_mode_map_[ui_->slicing_button_three_->CurrentRow()];
if (typeLevelOne || typeLevelTwo || typeLevelThree)
{
if (typeLevelOne)
{
slicingTypes.push_back(typeLevelOne);
}
if (typeLevelTwo)
{
slicingTypes.push_back(typeLevelTwo);
}
if (typeLevelThree)
{
slicingTypes.push_back(typeLevelThree);
}
}
ui_->tree_map_view_->UpdateSliceTypes(slicingTypes);
}
void ResourceOverviewPane::SlicingLevelChanged()
{
UpdateSlicingLevel();
ui_->tree_map_view_->UpdateTreeMap();
}
void ResourceOverviewPane::ColorModeChanged()
{
ChangeColoring();
}
void ResourceOverviewPane::SelectedResource(RmtResourceIdentifier resource_identifier, bool broadcast, bool navigate_to_pane)
{
if (broadcast == true)
{
emit rmv::MessageManager::Get().ResourceSelected(resource_identifier);
}
else
{
SelectResource(resource_identifier);
}
if (navigate_to_pane == true)
{
emit rmv::MessageManager::Get().PaneSwitchRequested(rmv::kPaneIdSnapshotResourceDetails);
}
}
void ResourceOverviewPane::SelectedUnboundResource(const RmtResource* unbound_resource, bool broadcast, bool navigate_to_pane)
{
if (broadcast == true)
{
if (unbound_resource != nullptr)
{
emit rmv::MessageManager::Get().UnboundResourceSelected(unbound_resource->bound_allocation);
}
}
SelectUnboundResource(unbound_resource);
emit rmv::MessageManager::Get().ResourceSelected(0);
if (navigate_to_pane == true)
{
emit rmv::MessageManager::Get().PaneSwitchRequested(rmv::kPaneIdSnapshotAllocationExplorer);
}
}
void ResourceOverviewPane::SelectResource(RmtResourceIdentifier resource_identifier)
{
if (resource_identifier == 0)
{
return;
}
ui_->tree_map_view_->SelectResource(resource_identifier);
RmtDataSnapshot* open_snapshot = rmv::SnapshotManager::Get().GetOpenSnapshot();
if (rmv::TraceManager::Get().DataSetValid() && open_snapshot != nullptr)
{
selected_resource_ = nullptr;
const RmtErrorCode error_code = RmtResourceListGetResourceByResourceId(&open_snapshot->resource_list, resource_identifier, &selected_resource_);
if (error_code == kRmtOk)
{
resource_details_->UpdateResource(selected_resource_);
}
UpdateDetailsTitle();
}
}
void ResourceOverviewPane::SelectUnboundResource(const RmtResource* unbound_resource)
{
if (unbound_resource == nullptr)
{
return;
}
resource_details_->UpdateResource(unbound_resource);
UpdateDetailsTitle();
}
void ResourceOverviewPane::FilterBySizeSliderChanged(int min_value, int max_value)
{
bool use_unbound = tree_map_models_.resource_usage_model->ItemInList(kRmtResourceUsageTypeFree);
model_->FilterBySizeChanged(min_value, max_value, use_unbound);
ui_->tree_map_view_->UpdateTreeMap();
}
void ResourceOverviewPane::UpdateDetailsTitle()
{
if (selected_resource_ == nullptr)
{
ui_->resource_name_label_->setText("Select a resource");
if (ui_->resource_details_checkbox_->isChecked())
{
ui_->resource_name_label_minimized_->setText("");
}
else
{
ui_->resource_name_label_minimized_->setText("Select a resource");
}
}
else
{
ui_->resource_name_label_->setText(selected_resource_->name);
if (ui_->resource_details_checkbox_->isChecked())
{
ui_->resource_name_label_minimized_->setText("");
}
else
{
ui_->resource_name_label_minimized_->setText(selected_resource_->name);
}
}
}
void ResourceOverviewPane::ResizeItems()
{
if (allocation_details_scene_ != nullptr)
{
const QRectF scene_rect = QRectF(0, 0, ui_->resource_details_view_->width(), ui_->resource_details_view_->height());
allocation_details_scene_->setSceneRect(scene_rect);
resource_details_->UpdateDimensions(ui_->resource_details_view_->width(), ui_->resource_details_view_->height());
}
}
void ResourceOverviewPane::OnScaleFactorChanged()
{
ui_->resource_details_view_->setFixedHeight(ScalingManager::Get().Scaled(kResourceDetailsHeight));
}
| [
"Anthony.Hosier@amd.com"
] | Anthony.Hosier@amd.com |
bf299bbb2b58e1ad41b6e43b0b828a8a27ef8b03 | f79f2e21bd86d6439d29bafa5123cc5de57330bb | /csci1113/sample1_8.cpp | ca7303f0fd25bf9a54eb58167d60cbbd50a3a622 | [] | no_license | nielscol/undegrad | d8ee13146fdf3f331b4a8bbbf8c5949d91a7787a | b82d4de14426443c4a79aaf9487140f594f397e9 | refs/heads/master | 2022-11-30T23:38:50.664991 | 2020-08-04T15:16:25 | 2020-08-04T15:16:25 | 277,909,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | cpp | #include <iostream>
using namespace std;
int main()
{
int number_of_pods, peas_per_pod, total_peas;
cout << "Press return after entering a number.\n";
cout << "Enter the number of pods:\n";
cin >> number_of_pods;
cout << "Enter the number of peas per pod\n";
cin >> peas_per_pod;
total_peas = number_of_pods * peas_per_pod;
cout << "If you have ";
cout << number_of_pods;
cout << " pea pods\n";
cout << "and ";
cout << peas_per_pod;
cout << " peas in each pod, then\n";
cout << "you have ";
cout << total_peas;
cout << " peas in all the pods.\n";
return 0;
}
| [
"nielscol@gmail.com"
] | nielscol@gmail.com |
aac65b9e366fc21a6eee3c5e9a67b9ac68e6b5c9 | 9c335f33334cdb652b6f169654ff6b42fddf8542 | /include/LiveProfiler/Analyzers/BaseAnalyzer.hpp | ef7e20f39096dcfe7d696fbb51a919c0bc4c171e | [
"MIT"
] | permissive | skyformat99/live-profiler | 0d07dcff7275ee4ef554935212ef1084b0aefd9a | 177c73fc679e7a0e2300521a2f6abd102a0f47bb | refs/heads/master | 2021-08-22T04:39:25.106923 | 2017-11-29T09:05:49 | 2017-11-29T09:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 839 | hpp | #pragma once
#include <memory>
#include <chrono>
namespace LiveProfiler {
/**
* The base class for the analyzer
*
* Terms:
* - The analyzer should be able to reset the state to it's initial state
* - The analyzer should be able to receive performance data at any time
* - The analyzer should provide a function named `getResult`, this function can return any type
* - The analysis of performance data can be done in real time, or at the time of `getResult`
* - The analyzer should not know there is a class called Profiler
*/
template <class Model>
class BaseAnalyzer :
public std::enable_shared_from_this<BaseAnalyzer<Model>> {
public:
/** Reset the state to it's initial state */
virtual void reset() = 0;
/** Receive performance data */
virtual void feed(const std::vector<Model>& models) = 0;
};
}
| [
"dudes@qq.com"
] | dudes@qq.com |
74113f73c17f72c29697d144423f973695f20c42 | 2078e3b6353878762d2f88925ee52ad42eef1591 | /webrevs/8188102_3/raw_files/new/src/hotspot/share/runtime/jniHandles.hpp | b7cd76685494aaa555498f50232c727f0ed64b1f | [] | no_license | dougxc/dougxc.github.io | 8519f877d4b9627f50621b2cfab531068a1cb516 | d49b6dc476b0a048a70e67300810737fdba07256 | refs/heads/master | 2020-08-30T20:53:12.552268 | 2020-07-01T13:38:13 | 2020-07-01T13:38:13 | 218,481,292 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,928 | hpp | /*
* Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_RUNTIME_JNIHANDLES_HPP
#define SHARE_VM_RUNTIME_JNIHANDLES_HPP
#include "memory/allocation.hpp"
#include "runtime/handles.hpp"
class JNIHandleBlock;
// Interface for creating and resolving local/global JNI handles
class JNIHandles : AllStatic {
friend class VMStructs;
private:
static JNIHandleBlock* _global_handles; // First global handle block
static JNIHandleBlock* _weak_global_handles; // First weak global handle block
static oop _deleted_handle; // Sentinel marking deleted handles
inline static bool is_jweak(jobject handle);
inline static oop& jobject_ref(jobject handle); // NOT jweak!
inline static oop& jweak_ref(jobject handle);
template<bool external_guard> inline static oop guard_value(oop value);
template<bool external_guard> inline static oop resolve_impl(jobject handle);
template<bool external_guard> static oop resolve_jweak(jweak handle);
public:
// Low tag bit in jobject used to distinguish a jweak. jweak is
// type equivalent to jobject, but there are places where we need to
// be able to distinguish jweak values from other jobjects, and
// is_weak_global_handle is unsuitable for performance reasons. To
// provide such a test we add weak_tag_value to the (aligned) byte
// address designated by the jobject to produce the corresponding
// jweak. Accessing the value of a jobject must account for it
// being a possibly offset jweak.
static const uintptr_t weak_tag_size = 1;
static const uintptr_t weak_tag_alignment = (1u << weak_tag_size);
static const uintptr_t weak_tag_mask = weak_tag_alignment - 1;
static const int weak_tag_value = 1;
// Resolve handle into oop
inline static oop resolve(jobject handle);
// Resolve externally provided handle into oop with some guards
inline static oop resolve_external_guard(jobject handle);
// Resolve handle into oop, result guaranteed not to be null
inline static oop resolve_non_null(jobject handle);
// Local handles
static jobject make_local(oop obj);
static jobject make_local(JNIEnv* env, oop obj); // Fast version when env is known
static jobject make_local(Thread* thread, oop obj); // Even faster version when current thread is known
inline static void destroy_local(jobject handle);
// Global handles
static jobject make_global(Handle obj);
static void destroy_global(jobject handle);
// Weak global handles
static jobject make_weak_global(Handle obj);
static void destroy_weak_global(jobject handle);
static bool is_global_weak_cleared(jweak handle); // Test jweak without resolution
// Sentinel marking deleted handles in block. Note that we cannot store NULL as
// the sentinel, since clearing weak global JNI refs are done by storing NULL in
// the handle. The handle may not be reused before destroy_weak_global is called.
static oop deleted_handle() { return _deleted_handle; }
// Initialization
static void initialize();
// Debugging
static void print_on(outputStream* st);
static void print() { print_on(tty); }
static void verify();
static bool is_local_handle(Thread* thread, jobject handle);
static bool is_frame_handle(JavaThread* thr, jobject obj);
static bool is_global_handle(jobject handle);
static bool is_weak_global_handle(jobject handle);
static long global_handle_memory_usage();
static long weak_global_handle_memory_usage();
// Garbage collection support(global handles only, local handles are traversed from thread)
// Traversal of regular global handles
static void oops_do(OopClosure* f);
// Traversal of weak global handles. Unreachable oops are cleared.
static void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f);
// Traversal of weak global handles.
static void weak_oops_do(OopClosure* f);
};
// JNI handle blocks holding local/global JNI handles
class JNIHandleBlock : public CHeapObj<mtInternal> {
friend class VMStructs;
friend class CppInterpreter;
private:
enum SomeConstants {
block_size_in_oops = 32 // Number of handles per handle block
};
oop _handles[block_size_in_oops]; // The handles
int _top; // Index of next unused handle
JNIHandleBlock* _next; // Link to next block
// The following instance variables are only used by the first block in a chain.
// Having two types of blocks complicates the code and the space overhead in negligible.
JNIHandleBlock* _last; // Last block in use
JNIHandleBlock* _pop_frame_link; // Block to restore on PopLocalFrame call
oop* _free_list; // Handle free list
int _allocate_before_rebuild; // Number of blocks to allocate before rebuilding free list
// Check JNI, "planned capacity" for current frame (or push/ensure)
size_t _planned_capacity;
#ifndef PRODUCT
JNIHandleBlock* _block_list_link; // Link for list below
static JNIHandleBlock* _block_list; // List of all allocated blocks (for debugging only)
#endif
static JNIHandleBlock* _block_free_list; // Free list of currently unused blocks
static int _blocks_allocated; // For debugging/printing
// Fill block with bad_handle values
void zap();
// Free list computation
void rebuild_free_list();
// No more handles in the both the current and following blocks
void clear() { _top = 0; }
public:
// Handle allocation
jobject allocate_handle(oop obj);
// Release Handle
void release_handle(jobject);
// Block allocation and block free list management
static JNIHandleBlock* allocate_block(Thread* thread = NULL);
static void release_block(JNIHandleBlock* block, Thread* thread = NULL);
// JNI PushLocalFrame/PopLocalFrame support
JNIHandleBlock* pop_frame_link() const { return _pop_frame_link; }
void set_pop_frame_link(JNIHandleBlock* block) { _pop_frame_link = block; }
// Stub generator support
static int top_offset_in_bytes() { return offset_of(JNIHandleBlock, _top); }
// Garbage collection support
// Traversal of regular handles
void oops_do(OopClosure* f);
// Traversal of weak handles. Unreachable oops are cleared.
void weak_oops_do(BoolObjectClosure* is_alive, OopClosure* f);
// Checked JNI support
void set_planned_capacity(size_t planned_capacity) { _planned_capacity = planned_capacity; }
const size_t get_planned_capacity() { return _planned_capacity; }
const size_t get_number_of_live_handles();
// Debugging
bool chain_contains(jobject handle) const; // Does this block or following blocks contain handle
bool contains(jobject handle) const; // Does this block contain handle
int length() const; // Length of chain starting with this block
long memory_usage() const;
#ifndef PRODUCT
static bool any_contains(jobject handle); // Does any block currently in use contain handle
static void print_statistics();
#endif
};
inline bool JNIHandles::is_jweak(jobject handle) {
STATIC_ASSERT(weak_tag_size == 1);
STATIC_ASSERT(weak_tag_value == 1);
return (reinterpret_cast<uintptr_t>(handle) & weak_tag_mask) != 0;
}
inline oop& JNIHandles::jobject_ref(jobject handle) {
assert(!is_jweak(handle), "precondition");
return *reinterpret_cast<oop*>(handle);
}
inline oop& JNIHandles::jweak_ref(jobject handle) {
assert(is_jweak(handle), "precondition");
char* ptr = reinterpret_cast<char*>(handle) - weak_tag_value;
return *reinterpret_cast<oop*>(ptr);
}
// external_guard is true if called from resolve_external_guard.
// Treat deleted (and possibly zapped) as NULL for external_guard,
// else as (asserted) error.
template<bool external_guard>
inline oop JNIHandles::guard_value(oop value) {
if (!external_guard) {
assert(value != badJNIHandle, "Pointing to zapped jni handle area");
assert(value != deleted_handle(), "Used a deleted global handle");
} else if ((value == badJNIHandle) || (value == deleted_handle())) {
value = NULL;
}
return value;
}
// external_guard is true if called from resolve_external_guard.
template<bool external_guard>
inline oop JNIHandles::resolve_impl(jobject handle) {
assert(handle != NULL, "precondition");
oop result;
if (is_jweak(handle)) { // Unlikely
result = resolve_jweak<external_guard>(handle);
} else {
result = jobject_ref(handle);
// Construction of jobjects canonicalize a null value into a null
// jobject, so for non-jweak the pointee should never be null.
assert(external_guard || result != NULL,
"Invalid value read from jni handle");
result = guard_value<external_guard>(result);
}
return result;
}
inline oop JNIHandles::resolve(jobject handle) {
oop result = NULL;
if (handle != NULL) {
result = resolve_impl<false /* external_guard */ >(handle);
}
return result;
}
// Resolve some erroneous cases to NULL, rather than treating them as
// possibly unchecked errors. In particular, deleted handles are
// treated as NULL (though a deleted and later reallocated handle
// isn't detected).
inline oop JNIHandles::resolve_external_guard(jobject handle) {
oop result = NULL;
if (handle != NULL) {
result = resolve_impl<true /* external_guard */ >(handle);
}
return result;
}
inline oop JNIHandles::resolve_non_null(jobject handle) {
assert(handle != NULL, "JNI handle should not be null");
oop result = resolve_impl<false /* external_guard */ >(handle);
assert(result != NULL, "NULL read from jni handle");
return result;
}
inline void JNIHandles::destroy_local(jobject handle) {
if (handle != NULL) {
jobject_ref(handle) = deleted_handle();
}
}
#endif // SHARE_VM_RUNTIME_JNIHANDLES_HPP
| [
"doug.simon@oracle.com"
] | doug.simon@oracle.com |
d39783b95dfcb2e5d6b5b07eff32274ceb8a2228 | a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e | /codeforces/complete/615C.cpp | dbf78fa1051b68df1bbb433c53440f7f594cb8b2 | [
"Apache-2.0"
] | permissive | tangjz/acm-icpc | 45764d717611d545976309f10bebf79c81182b57 | f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d | refs/heads/master | 2023-04-07T10:23:07.075717 | 2022-12-24T15:30:19 | 2022-12-26T06:22:53 | 13,367,317 | 53 | 20 | Apache-2.0 | 2022-12-26T06:22:54 | 2013-10-06T18:57:09 | C++ | UTF-8 | C++ | false | false | 3,259 | cpp | #include <map>
#include <set>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long LL;
typedef double DB;
typedef long double LDB;
const int maxs = 2222, maxm = 4256233;
const int seed1 = 29, seed2 = 31;
const int mod1 = 998244353, mod2 = 985661441;
int n, m, f[maxs], p[maxs], L[maxs], R[maxs], pw1[maxs], pw2[maxs], g1[maxs], g2[maxs], h1[maxs], h2[maxs], ansL[maxs], ansR[maxs];
char s[maxs], t[maxs];
int tot, lnk[maxm];
struct Hash
{
int nxt, L, R, v1, v2;
} e[maxs * maxs];
void insert(int l, int r, int a1, int a2)
{
//printf("ins [%d,%d] : %d, %d\n", l, r, a1, a2);
int pos = (((LL)a1 << 31LL) ^ a2) % maxm;
for(int it = lnk[pos]; it != -1; it = e[it].nxt)
if(e[it].v1 == a1 && e[it].v2 == a2)
return;
e[tot] = (Hash){lnk[pos], l, r, a1, a2};
lnk[pos] = tot++;
}
int idx(int a1, int a2)
{
//printf("fnd %d, %d\n", a1, a2);
int pos = (((LL)a1 << 31LL) ^ a2) % maxm;
for(int it = lnk[pos]; it != -1; it = e[it].nxt)
if(e[it].v1 == a1 && e[it].v2 == a2)
return it;
return -1;
}
int main()
{
pw1[0] = pw2[0] = 1;
for(int i = 1; i < maxs; ++i)
{
pw1[i] = (LL)pw1[i - 1] * seed1 % mod1;
pw2[i] = (LL)pw2[i - 1] * seed2 % mod2;
}
memset(lnk, -1, sizeof lnk);
scanf("%s%s", s + 1, t + 1);
n = strlen(s + 1);
m = strlen(t + 1);
for(int i = 1; i <= n; ++i)
{
g1[i] = ((LL)g1[i - 1] * seed1 + (s[i] - '0')) % mod1;
g2[i] = ((LL)g2[i - 1] * seed2 + (s[i] - '0')) % mod2;
}
for(int i = 1; i <= n + 1 >> 1; ++i)
swap(s[i], s[n - i + 1]);
for(int i = 1; i <= n; ++i)
{
h1[i] = ((LL)h1[i - 1] * seed1 + (s[i] - '0')) % mod1;
h2[i] = ((LL)h2[i - 1] * seed2 + (s[i] - '0')) % mod2;
}
for(int i = 1; i <= n; ++i)
for(int j = i; j <= n; ++j)
{
int val11 = g1[j] - (LL)g1[i - 1] * pw1[j - i + 1] % mod1, val12 = h1[j] - (LL)h1[i - 1] * pw1[j - i + 1] % mod1;
if(val11 < 0)
val11 += mod1;
if(val12 < 0)
val12 += mod1;
int val21 = g2[j] - (LL)g2[i - 1] * pw2[j - i + 1] % mod2, val22 = h2[j] - (LL)h2[i - 1] * pw2[j - i + 1] % mod2;
if(val21 < 0)
val21 += mod2;
if(val22 < 0)
val22 += mod2;
insert(i, j, val11, val21);
if(i < j)
insert(n - i + 1, n - j + 1, val12, val22);
}
for(int i = 1; i <= m; ++i)
{
g1[i] = ((LL)g1[i - 1] * seed1 + (t[i] - '0')) % mod1;
g2[i] = ((LL)g2[i - 1] * seed2 + (t[i] - '0')) % mod2;
}
for(int i = 1; i <= m; ++i)
{
f[i] = -1;
for(int j = 0; j < i; ++j)
{
if(f[j] == -1)
continue;
int val1 = g1[i] - (LL)g1[j] * pw1[i - j] % mod1, val2 = g2[i] - (LL)g2[j] * pw2[i - j] % mod2, d;
if(val1 < 0)
val1 += mod1;
if(val2 < 0)
val2 += mod2;
//printf("chr [%d, %d] : %d, %d\n", j + 1, i, val1, val2);
if((d = idx(val1, val2)) != -1 && (f[i] == -1 || f[i] > f[j]))
{
p[i] = j;
L[i] = e[d].L;
R[i] = e[d].R;
f[i] = f[j];
}
}
if(f[i] != -1)
++f[i];
}
if(f[m] == -1)
{
puts("-1");
return 0;
}
printf("%d\n", f[m]);
for(int i = 0, o = m; o; ++i, o = p[o])
{
ansL[i] = L[o];
ansR[i] = R[o];
}
for(int i = f[m] - 1; i >= 0; --i)
printf("%d %d\n", ansL[i], ansR[i]);
return 0;
}
| [
"t251346744@gmail.com"
] | t251346744@gmail.com |
124b457432398bbe8eda9dd1826beb9cc6ab619d | 41d51f22377c4dbe4aa52b1ba6e0faa839971bf0 | /0502_ShallowCopyError/ShallowCopyError.cpp | 946045d1dbedf8b778b6399b9729f45d058f853e | [] | no_license | tonnac/CPPLang | 6f56ab83d902f7163a72a87aa543527618e7900a | 7d5810ce43b3e8b1ce244ab9d87af42e056e07f6 | refs/heads/master | 2021-06-29T02:38:39.968684 | 2020-09-20T16:21:20 | 2020-09-20T16:21:20 | 143,169,822 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 600 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private:
char * name;
int age;
public:
Person(const char * myname, int myage)
{
int len = strlen(myname) + 1;
name = new char[len];
strcpy(name, myname);
age = myage;
}
void ShowPersonInfo() const
{
cout << "À̸§: " << name << endl;
cout << "³ªÀÌ: " << age << endl;
}
~Person()
{
delete[]name;
cout << "called destructor!" << endl;
}
};
int main()
{
Person man1("Lee dong woo", 29);
Person man2 = man1;
man1.ShowPersonInfo();
man2.ShowPersonInfo();
} | [
"tonnac35@gmail.com"
] | tonnac35@gmail.com |
e4bb87dd68b7f35a60f2bf984bd9b7677291107c | c816d974ff77f0cc2a0853e870c2348e68bdc445 | /pratica10/contaPalavras.cpp | 861f9177b88bc4a52ae10fd1153c86f2864a0558 | [] | no_license | bragalucas1/ED | 01529803f093815fb4e233809e7196c895521d09 | a91e0a86acd063be7e2990395516a2a09dd2178b | refs/heads/main | 2023-08-29T10:44:54.353074 | 2021-10-19T22:25:29 | 2021-10-19T22:25:29 | 388,488,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | cpp | #include <iostream>
#include "MyVecNewIterator.h"
#include "MySet.h"
#include <string>
#include <cstring>
using namespace std;
int main(int argc, char **argv){
string s;
int cont = 0;
bool auxiliar = false;
if(strcmp(argv[1], "myvec") == 0){ //tratamos o caso de entrada como myVec
MyVec<string> v;
while(cin >> s){
auxiliar = false;
for(int i = 0; i < v.size(); i++){
if(v[i] == s){
auxiliar = true;
break;
}
}
if(!auxiliar){
v.push_back(s);
}
cont++;
//cout << cont << " " << v.size() << endl;
}
cout << cont << " " << v.size() << endl;
}
else{//caso sobresssalente -- MYSET
MySet<string> v;
while(cin >> s){
v.insert(s);
cont++;
}
cout << cont << " " << v.size() << endl;
}
return 0;
} | [
"lucas.b.moura@ufv.br"
] | lucas.b.moura@ufv.br |
b34a9287f12f6be2cbac5c6c1d25bd40428a6493 | 305f319fa96d62e021f319f11ac86c0addd7e90b | /Seatalk2NMEA.ino | 850cc1ea648a6cee44e281afe72279beaba1ca6f | [] | no_license | Daven005/Seatalk2NMEA | 31f28abbbfcf3fbebbdbd092a0a6a2dbdc16fcf7 | 79e4251b09dcf91784320f6a47b5d0f25e0e92a4 | refs/heads/master | 2023-01-05T20:53:48.781510 | 2020-11-07T13:06:15 | 2020-11-07T13:06:15 | 310,847,274 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,074 | ino | #include <Signal.h>
#include <Timer.h>
#include "Arduino.h"
#include "seatalkOut.h"
#include "seatalkIn.h"
#include "flashLED.h"
#include "defs.h"
#include "ByteBuffer.h"
#include "CharBuffer.h"
#include "PCD8544.h"
#include <WiFi.h>
#include "BLE.h"
#include "dataStore.h"
#include "nmea.h"
#include <SimpleCLI.h>
PCD8544 lcd(LCD_CLK, LCD_DIN, LCD_DC, LCD_RST_, LCD_CE_);
SeaTalkIn stInput;
SeaTalkOut stOutput;
FlashLED flash; // Reqd for seatalkOut.cpp
FlashLED flashYellow;
FlashLED flashGreen;
Timer t;
unsigned long lastMsgTime = millis();
bool sendSeaTalk_BLE = true;
BLE ble;
DataStore ds;
Nmea nmea;
SimpleCLI cli;
Command set;
void cliSetup();
void cmdError(cmd_error* e);
void setCommand(cmd* c);
char version[] = "SeaTalk NMEA & BLE - V0.13";
void setup() {
WiFi.mode(WIFI_OFF);
Serial.begin(115200);
nmea.begin();
lcd.begin(); // Use defaults
Serial.println(version);
ble.begin("ST-NMEA");
ble.send(version);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print(version);
lcd.setCursor(0, 5);
if (nmea.txMode()) {
nmea.println(version);
}
lcd.printf("NMEA %cx Mode", nmea.txMode() ? 'T' : 'R');
pinMode(STIN, INPUT);
pinMode(STOUT, OUTPUT);
pinMode(RED_LED, OUTPUT);
pinMode(NMEA_TX, OUTPUT);
pinMode(LCD_LT_, OUTPUT);
digitalWrite(LCD_LT_, 1);
stInput.begin(STIN);
stOutput.begin(STOUT, STIN);
flash.begin(RED_LED);
flashYellow.begin(YELLOW_LED);
flashGreen.begin(GREEN_LED);
flash.start(5, 200);
flashYellow.start(5, 100);
flashGreen.start(5, 210);
Serial.println("Ready");
t.every(2000, checkDataStore);
digitalWrite(LCD_LT_, 0); // ON
cliSetup();
}
bool isHex(const char c, word *b) {
if (isDigit(c)) {
*b |= c - '0';
return true;
}
if ('A' <= c && c <= 'F') {
*b |= c - 'A' + 10;
return true;
}
if ('a' <= c && c <= 'f') {
*b |= c - 'a' + 10;
return true;
}
return false;
}
byte decodeMsg(const char *bfr, ByteBuffer *msg) {
word b = 0;
while (*bfr) {
while (isHex(*bfr, &b)) {
b = b << 4;
bfr++;
}
if (!msg->add((byte)(b >> 4)))
return false;
while (*bfr && !isHex(*bfr, &b)) {
bfr++;
}
}
return true;
}
void decodeSeaTalkMsg(word cmd) {
static word msg[20];
static byte idx = 0;
static byte expectedLength = 10;
if (cmd & 0x100) {
Serial.println();
idx = 0;
}
if (idx == 1)
expectedLength = (cmd & 0xf) + 3;
msg[idx++] = cmd;
Serial.print(cmd, HEX);
Serial.print(" ");
if (idx >= expectedLength) {
idx = 0;
if (ble.connected()) {
flashGreen.turnOn();
if (sendSeaTalk_BLE) ble.send(msg, expectedLength);
flashYellow.start(1, 100);
} else {
flashGreen.turnOff();
flash.start(1, 100);
}
ds.decodeSeaTalk(msg, expectedLength);
}
}
byte checkSum(char *bfr) {
byte sum = 0;
while (*bfr) {
sum ^= *bfr;
bfr++;
}
return sum;
}
void checkDataStore() {
char bfr[100];
int lineNo = 0;
if (ds.isValidPosition()) {
char latitude[40];
char longitude[40];
ds.printLongitude(longitude);
ds.printLatitude(latitude);
lcd.setCursor(0, lineNo++); lcd.clearLine();
lcd.print("Lat: "); lcd.print(latitude);
lcd.setCursor(0, lineNo++); lcd.clearLine();
lcd.print("Long: "); lcd.print(longitude);
sprintf(bfr, "$GPGGA,");
sprintf(ds.printTime(bfr + strlen(bfr)), ",");
sprintf(bfr + strlen(bfr), "%s,", latitude);
sprintf(bfr + strlen(bfr), "%s,1,,,,", longitude);
sprintf(bfr + strlen(bfr), "*%02X\r\n", checkSum(bfr));
nmea.print(bfr);
Serial.print(bfr);
}
if (ds.isValidDepth()) {
char depth[40];
ds.printDepth(depth);
lcd.setCursor(0, lineNo++); lcd.clearLine();
lcd.print("Depth: "); lcd.print(depth);
sprintf(bfr, "$GPDBT,,f,%s,M,,F", depth);
sprintf(bfr + strlen(bfr), "*%02X\r\n", checkSum(bfr));
nmea.print(bfr);
Serial.print(bfr);
}
if (ds.isValidApparentWind()) {
char angle[40];
char speed[40];
ds.printApparentWindAngle(angle);
ds.printApparentWindSpeed(speed);
lcd.setCursor(0, lineNo++); lcd.clearLine();
lcd.print("Wind: ");
lcd.print(angle);
lcd.print("/");
lcd.print(speed);
sprintf(bfr, "$GPMWV,%s,R,%s,K,A", angle, speed);
sprintf(bfr + strlen(bfr), "*%02X\r\n", checkSum(bfr));
nmea.print(bfr);
Serial.print(bfr);
}
}
void cliSetup() {
cli.setOnError(cmdError);
set = cli.addCommand("set", setCommand);
set.addArgument("n/mea", "x");
set.addArgument("s/eatalk", "x");
set.setCaseSensetive(false);
}
void cmdError(cmd_error* e) {
CommandError cmdError(e);
Serial.print("Cmd err: ");
Serial.println(cmdError.toString());
}
void setCommand(cmd* c) {
Command cmd(c);
if (cmd == set) {
Argument n = cmd.getArgument("nmea");
if (n) {
String v = n.getValue();
std::transform(v.begin(), v.end(), v.begin(),
[](unsigned char c) {
return std::toupper(c);
});
if (v == "RX") nmea.setMode(Nmea::Mode_t::RX);
if (v == "TX") nmea.setMode(Nmea::Mode_t::TX);
lcd.setCursor(0, 5);
lcd.printf("NMEA %cx Mode", nmea.txMode() ? 'T' : 'R');
}
Argument s = cmd.getArgument("seatalk");
if (s) {
String v = s.getValue();
std::transform(v.begin(), v.end(), v.begin(),
[](unsigned char c) { return std::toupper(c); });
if (v == "ON") sendSeaTalk_BLE = true;
if (v == "OFF") sendSeaTalk_BLE = false;
lcd.setCursor(0, 5);
lcd.printf("ST-BLE %s ", sendSeaTalk_BLE ? "ON" : "OFF");
}
}
}
void checkNmeaInput(char c, ProcessNmeaInput_t respond) {
static std::string bfr;
int lineLen;
bfr.push_back(c);
if ((lineLen = bfr.find('\n')) != std::string::npos) {
std::string line (bfr, 0, lineLen);
bfr.erase(0, lineLen + 1);
if (line.find(">", 0) == 0) {
line.erase(0, 1);
respond(COMMAND_ACTION, line.c_str());
} else if (line.find("$GP", 0) == 0) {
respond(PRINT_ACTION, line.c_str());
} else if (line.find("%", 0) == 0) {
respond(SEATALK_ACTION, line.c_str()+1);
} else {
flash.start(2, 300);
Serial.println(line.c_str());
}
}
}
void processCommand(const char *cmd) {
cli.parse(cmd);
}
void processNmeaInput(NmeaAction_t action, const char *line) {
char bfr[200];
switch (action) {
case PRINT_ACTION:
Serial.println(line);
sprintf(bfr, "%s\n", line);
ble.send(bfr);
break;
case COMMAND_ACTION:
processCommand(line);
break;
case SEATALK_ACTION:
ByteBuffer msg;
if (decodeMsg(line, &msg)) {
if (msg.length() >= 3) { // Minimum SeaTalk msg length
stOutput.send(msg.string(), msg.length());
}
msg.clear();
}
break;
}
}
void loop() {
const byte goPort[] = {0x86, 0x11, 0x05, 0xFA};
const byte goStbd[] = {0x86, 0x11, 0x07, 0xf8};
static CharBuffer inputBfrSer;
static CharBuffer inputBfrBle;
stOutput.check(lastMsgTime);
if (Serial.available()) {
if (inputBfrSer.add(Serial.read())) {
processCommand(inputBfrSer.string());
inputBfrSer.clear();
}
}
if (stInput.available()) {
decodeSeaTalkMsg(stInput.get());
lastMsgTime = millis();
}
if (ble.available()) {
if (inputBfrBle.add(ble.read())) {
// Complete line terminated with \n
switch (inputBfrBle.string()[0]) {
case '>': processCommand(inputBfrBle.string() + 1); break;
case '%': {
ByteBuffer msg;
if (decodeMsg(inputBfrBle.string()+1, &msg)) {
if (msg.length() >= 3) { // Minimum SeaTalk msg length
stOutput.send(msg.string(), msg.length());
}
msg.clear();
}
}
break;
case '$': nmea.println(inputBfrBle.string()); break;
}
inputBfrBle.clear();
}
}
if (nmea.available()) {
flashYellow.start(2, 50);
checkNmeaInput(nmea.read(), processNmeaInput);
}
flash.check();
flashYellow.check();
flashGreen.check();
ble.check();
t.update();
}
| [
"david@norburys.me.uk"
] | david@norburys.me.uk |
362f1e5f5cda607718f83ec7525c16400b91066f | 9f4390685064b06f8093ab221100b6d4a93b8519 | /source/Graphics/ConstantBuffer.cpp | df0c9336979b18b14104336c4fdf533efe9a32b6 | [] | no_license | Darkyon0831/EndGine | 316a302607961a6b6362e658aebc976cd98a0a78 | 46f4fbecb8ba843794765c875dce606afd51a79d | refs/heads/master | 2020-08-29T04:33:25.031785 | 2020-07-22T13:47:29 | 2020-07-22T13:47:29 | 216,434,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | cpp | #include "ConstantBuffer.h"
#include "Globals/Macro.h"
#include "Graphics/Device.h"
EG::ConstantBuffer::ConstantBuffer(const size_t size)
: m_pBuffer(nullptr)
, m_size(size)
{
ID3D11Device* pDevice = Device::GetInstance().GetDevice();
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.ByteWidth = size;
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
EGCHECKHR(pDevice->CreateBuffer(&bufferDesc, nullptr, &m_pBuffer));
}
EG::ConstantBuffer::~ConstantBuffer()
{
if (m_pBuffer)
m_pBuffer->Release();
}
void EG::ConstantBuffer::Update(void* pMem) const
{
ID3D11DeviceContext* pDeviceContext = Device::GetInstance().GetDeviceContext();
D3D11_MAPPED_SUBRESOURCE bufferResource;
EGCHECKHR(pDeviceContext->Map(m_pBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &bufferResource));
memcpy(bufferResource.pData, pMem, m_size);
pDeviceContext->Unmap(m_pBuffer, 0);
}
| [
"adrian.rondahl@live.se"
] | adrian.rondahl@live.se |
03f163106899e91bd0bbd878bb1ce0cf1c743361 | a64b58d52dcfce4544a9fc18cefbcdb41ad62de8 | /decisionTree.cpp | f6ba014a193a601ac96086c033a99141727f0a41 | [] | no_license | kingofyeti/decisionTree | aa07c26592af196fac668958bc1cdd8ba4e8e92f | 6ea856b82bcc5e10edfc3ba3f02f53d095b14b29 | refs/heads/master | 2021-01-10T08:26:59.986903 | 2015-09-25T19:02:57 | 2015-09-25T19:02:57 | 43,096,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,817 | cpp | #include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <memory>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
int maxTreeHeight = 0;
int nodeNum = 0;
struct TreeNode {
vector<vector<char>> table;
vector<int> colIndex;
vector<shared_ptr<TreeNode>> children;
int fatherPartition;
char fatherPartitionVal;
int curHeight;
TreeNode(vector<vector<char>>
_table,
vector<int>_colIndex,vector<shared_ptr<TreeNode>>
_children,int _fatherPartition,char
_fatherPartitionVal,int _curHeight) :
table(_table) ,colIndex(_colIndex), children(_children)
,fatherPartition(_fatherPartition),fatherPartitionVal(_fatherPartitionVal),curHeight(_curHeight) {}
};
void printNode(shared_ptr<TreeNode> node){
cout << "Tabel: " << endl;
for(auto x : node->table){
for(auto y : x) {
cout << " " << y;
}
cout << endl;
}
cout << "Column index: " <<endl;
for(auto x : node->colIndex){
cout << " " << x;
}
cout << endl << "Father partition: " << node->fatherPartition << endl;
cout << endl << "Father partition value: " << node->fatherPartitionVal << endl;
cout << endl << "Cur height: " << node->curHeight << endl;
cout << "========================" << endl;
}
void partitionNode(shared_ptr<TreeNode> node,int partitionCol){
auto nodeTable = node->table;
int curHeight = node->curHeight + 1;
maxTreeHeight = max(maxTreeHeight,curHeight);
while(nodeTable.size()!=0){
char curVal = nodeTable[0][partitionCol];
auto newColIndex = node->colIndex;
newColIndex.erase(newColIndex.begin()+partitionCol);
int fatherPartitionVal = curVal;
vector<vector<char>> newTable;
vector<shared_ptr<TreeNode>> newChildren;
for(int i=0;i<nodeTable.size();i++){
if(nodeTable[i][partitionCol] == curVal){
auto curRow = nodeTable[i];
curRow.erase(curRow.begin()+partitionCol);
newTable.push_back(curRow);
nodeTable.erase(nodeTable.begin()+i);
i--;
}
}
auto newNode
=make_shared<TreeNode>(newTable,newColIndex,newChildren,partitionCol,curVal,curHeight);
nodeNum ++;
node->children.push_back(newNode);
}
}
shared_ptr<TreeNode> inputData(){
string oneline;
vector<vector<char>> inputTable;
vector<int> colIndex;
vector<shared_ptr<TreeNode>> children;
while(getline(cin,oneline)){
vector<char> onelineTable;
for(int i=0;i<oneline.length();i++){
if(oneline[i] != ','){
onelineTable.push_back(oneline[i]);
}
}
onelineTable.pop_back();
inputTable.push_back(onelineTable);
}
for(int i=0;i<inputTable[0].size();i++){
colIndex.push_back(i);
}
auto root =make_shared<TreeNode>(inputTable,colIndex,children,-1,'-',0);
return root;
}
float calEntropy(shared_ptr<TreeNode> node,int col){
vector<vector<char>> nodeTable = node->table;
int tableRowSize = node->table.size();
float entropy = 0;
while(nodeTable.size() != 0){
char curVal = nodeTable[0][col];
int curValPosNum = 0;
int curValNegNum = 0;
for(int i=0;i<nodeTable.size();i++){
if(nodeTable[i][col] == curVal){
if(nodeTable[i][0] == 'p')
curValPosNum++;
if(nodeTable[i][0] == 'e')
curValNegNum++;
nodeTable.erase(nodeTable.begin()+i);
i--;
}
}
int curValNum = curValPosNum + curValNegNum;
if(curValPosNum != 0 && curValNegNum != 0 && col != 0){
entropy += - ((float)curValNum/tableRowSize) *
( ((float)curValPosNum/curValNum * (float)log((float)curValPosNum/curValNum) / log(2))
+
((float)curValNegNum/curValNum * (float)log((float)curValNegNum/curValNum) / log(2)) );
}
if(col == 0){
entropy += -
( ((float)curValNum/tableRowSize *
(float)log((float)curValNum/tableRowSize) / log(2))
);
}
}
return entropy;
}
int calPartitionCol(shared_ptr<TreeNode> node){
float info = calEntropy(node,0);
int maxGainCol = -1;
float maxGain = -1;
for(int i=1;i<node->table[0].size();i++){
float gain = info - calEntropy(node,i);
if(gain > maxGain){
maxGain = gain;
maxGainCol = i;
}
}
return maxGainCol;
}
bool isPure(shared_ptr<TreeNode> node){
if(node->table.size() == 0) return true;
if(node->table[0].size() == 2) return true;
char sign = node->table[0][0];
for(int i=1;i<node->table.size();i++){
if(node->table[i][0] != sign )
return false;
}
return true;
}
bool buildTree(shared_ptr<TreeNode> node){
if(isPure(node))
return true;
cout << isPure(node) << endl;
int partitionCol = calPartitionCol(node);
partitionNode(node,partitionCol);
for(auto x : node->children){
printNode(x);
buildTree(x);
}
return true;
}
int main(){
auto root = inputData();
printNode(root);
if(buildTree(root))
cout << "Tree build finished! " << endl;
cout << "Max tree height: " << maxTreeHeight << endl;
}
| [
"kingofyeti@gmail.com"
] | kingofyeti@gmail.com |
376cf42f41812dc06224e5e8f2760fdb15d9e87c | 04bd521453254be10ee61a94789950f2d43d4dab | /miscellaneous/encd12-oneside.cpp | 532269b704d71b1c8087b47ebd9bac17fa4d4ee7 | [] | no_license | nitinkedia7/competitive-coding | 0dd19f98f81b144ead95b540aaa88c2f33981a15 | c2fc743f71a60846650387edf50f2ef2828e2119 | refs/heads/master | 2023-04-28T01:18:04.917804 | 2020-08-20T14:47:23 | 2020-08-20T14:47:23 | 163,924,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,390 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1000000007;
int swap(string &s, int i, int j) { // i --> j
int c = 0;
char temp;
while (i < j) {
temp = s[i];
s[i] = s[i+1];
s[i+1] = temp;
c++;
i++;
}
return c;
}
int isPossible(string &s) {
int n = s.length();
vector<int> count(26);
for (int i = 0; i < n; i++) {
count[s[i] - 'a']++;
}
int x = 0;
for (int i = 0; i < 26; i++) {
if (count[i] % 2) {
x++;
}
}
return n % 2 == x;
}
void sherlock(string s) {
if (!isPossible(s)) {
cout << "Impossible" << endl;
return;
}
int n = s.length();
int swaps = 0;
for (int i = 0; i < n / 2; i++) {
bool found = false;
for (int j = n - 1 - i; j > i; j--) {
if (s[j] == s[i]) {
found = true;
swaps += swap(s, j, n - 1 - i);
break;
}
}
if (found == false) {
swaps += swap(s, i, n / 2);
i--;
}
cout << s << endl;
}
cout << swaps << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string s;
while (1) {
cin >> s;
if (s[0] == '0') break;
sherlock(s);
s.clear();
}
return 0;
} | [
"nitinkedia7@gmail.com"
] | nitinkedia7@gmail.com |
2d3b6964859f7d157ef86d8451551b8208b6dcc8 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /components/ukm/content/source_url_recorder.cc | 573ead4113669a4904b77cc8c44e7108f171997c | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 5,163 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/ukm/content/source_url_recorder.h"
#include <utility>
#include "base/containers/flat_map.h"
#include "base/macros.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "url/gurl.h"
namespace {
bool IsValidUkmUrl(const GURL& url) {
return url.SchemeIsHTTPOrHTTPS();
}
// SourceUrlRecorderWebContentsObserver is responsible for recording UKM source
// URLs, for all main frame navigations in a given WebContents.
// SourceUrlRecorderWebContentsObserver records both the final URL for a
// navigation, and, if the navigation was redirected, the initial URL as well.
class SourceUrlRecorderWebContentsObserver
: public content::WebContentsObserver,
public content::WebContentsUserData<
SourceUrlRecorderWebContentsObserver> {
public:
// Creates a SourceUrlRecorderWebContentsObserver for the given
// WebContents. If a SourceUrlRecorderWebContentsObserver is already
// associated with the WebContents, this method is a no-op.
static void CreateForWebContents(content::WebContents* web_contents);
void DidStartNavigation(
content::NavigationHandle* navigation_handle) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
private:
explicit SourceUrlRecorderWebContentsObserver(
content::WebContents* web_contents);
friend class content::WebContentsUserData<
SourceUrlRecorderWebContentsObserver>;
void MaybeRecordUrl(content::NavigationHandle* navigation_handle,
const GURL& initial_url);
// Map from navigation ID to the initial URL for that navigation.
base::flat_map<int64_t, GURL> pending_navigations_;
DISALLOW_COPY_AND_ASSIGN(SourceUrlRecorderWebContentsObserver);
};
SourceUrlRecorderWebContentsObserver::SourceUrlRecorderWebContentsObserver(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {}
void SourceUrlRecorderWebContentsObserver::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
// UKM only records URLs for main frame (web page) navigations, so ignore
// non-main frame navs. Additionally, at least for the time being, we don't
// track metrics for same-document navigations (e.g. changes in URL fragment,
// or URL changes due to history.pushState) in UKM.
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
// UKM doesn't want to record URLs for downloads. However, at the point a
// navigation is started, we don't yet know if the navigation will result in a
// download. Thus, we record the URL at the time a navigation was initiated,
// and only record it later, once we verify that the navigation didn't result
// in a download.
pending_navigations_.insert(std::make_pair(
navigation_handle->GetNavigationId(), navigation_handle->GetURL()));
}
void SourceUrlRecorderWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
auto it = pending_navigations_.find(navigation_handle->GetNavigationId());
if (it == pending_navigations_.end())
return;
GURL initial_url = std::move(it->second);
pending_navigations_.erase(it);
// UKM doesn't want to record URLs for navigations that result in downloads.
if (navigation_handle->IsDownload())
return;
MaybeRecordUrl(navigation_handle, initial_url);
}
void SourceUrlRecorderWebContentsObserver::MaybeRecordUrl(
content::NavigationHandle* navigation_handle,
const GURL& initial_url) {
ukm::UkmRecorder* ukm_recorder = ukm::UkmRecorder::Get();
if (!ukm_recorder)
return;
const ukm::SourceId source_id = ukm::ConvertToSourceId(
navigation_handle->GetNavigationId(), ukm::SourceIdType::NAVIGATION_ID);
if (IsValidUkmUrl(initial_url))
ukm_recorder->UpdateSourceURL(source_id, initial_url);
const GURL& final_url = navigation_handle->GetURL();
if (final_url != initial_url && IsValidUkmUrl(final_url))
ukm_recorder->UpdateSourceURL(source_id, final_url);
}
// static
void SourceUrlRecorderWebContentsObserver::CreateForWebContents(
content::WebContents* web_contents) {
if (!SourceUrlRecorderWebContentsObserver::FromWebContents(web_contents)) {
web_contents->SetUserData(
SourceUrlRecorderWebContentsObserver::UserDataKey(),
base::WrapUnique(
new SourceUrlRecorderWebContentsObserver(web_contents)));
}
}
} // namespace
DEFINE_WEB_CONTENTS_USER_DATA_KEY(SourceUrlRecorderWebContentsObserver);
namespace ukm {
void InitializeSourceUrlRecorderForWebContents(
content::WebContents* web_contents) {
SourceUrlRecorderWebContentsObserver::CreateForWebContents(web_contents);
}
} // namespace ukm
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
da7e3492dea24caa573144e03b5be6e74a385fdb | 4352b5c9e6719d762e6a80e7a7799630d819bca3 | /tutorials/oldd/old/CYCLIC/0/backup/p | de89a686d648bb5907e856d50440dcc9320ee796 | [] | no_license | dashqua/epicProject | d6214b57c545110d08ad053e68bc095f1d4dc725 | 54afca50a61c20c541ef43e3d96408ef72f0bcbc | refs/heads/master | 2022-02-28T17:20:20.291864 | 2019-10-28T13:33:16 | 2019-10-28T13:33:16 | 184,294,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,451 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | foam-extend: Open Source CFD |
| \\ / O peration | Version: 4.0 |
| \\ / A nd | Web: http://www.foam-extend.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
// internalField uniform 100000;
#include "init/internalp"
boundaryField
{
inlet
{
//type slip;
/*
type fixedValue;
value uniform 3;
*/
type cyclic;
}
outlet
{
type cyclic; //slip;
}
left
{
type cyclic;
}
right
{
type cyclic;
}
top
{
type cyclic;
}
bottom
{
type cyclic;
}
defaultFaces
{
type empty;
}
}
// ************************************************************************* //
| [
"thomasdigiusto@me.com"
] | thomasdigiusto@me.com | |
6da64d8ffcac598cf7c23cbabc30dff996e8bf1a | e55a9b18d509163c55875da7451ccc6aec06023e | /9.GUI/GUIApplication.h | 8e8a8b6fcb31c331646db8962f814c0f04ddefc3 | [] | no_license | lukeplaisance/Open_GL-Graphics-Engine | 6d9e4bf457664387321837c44f0fc641a6f51650 | d6f2fa1c4ca3cda1bbd71833905030d275e093b3 | refs/heads/master | 2020-03-28T16:31:58.043711 | 2018-10-11T22:52:24 | 2018-10-11T22:52:24 | 148,704,838 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | h | #pragma once
#include "Application.h"
#include <Transform.h>
#include "MeshRenderer.h"
#include "Shader.h"
#include "Camera.h"
class GUIApplication : public Application
{
public:
MeshRenderer* mesh;
Shader* shader;
unsigned int m_program;
glm::mat4 m_model;
glm::mat4 m_view;
glm::mat4 m_projection;
int v4[4];
Transform* m_transform;
Camera* m_camera;
std::vector<glm::vec4> GenHalfCircle(int np, int radius);
void GenSphere(int radius, int np, int nm);
std::vector<unsigned int> GenIndices(unsigned int np, unsigned int nm);
std::vector<glm::vec4> RotatePoints(std::vector<glm::vec4> points,
unsigned int numMeridians);
std::vector<MeshRenderer::Vertex> GenCube(std::vector<MeshRenderer::Vertex> vertices);
std::vector<unsigned int> genCubeIndices();
GUIApplication();
~GUIApplication();
// Inherited via Application
virtual void startup() override;
virtual void shutdown() override;
virtual void update(float dt) override;
virtual void draw() override;
};
| [
"31013260+lukeplaisance17@users.noreply.github.com"
] | 31013260+lukeplaisance17@users.noreply.github.com |
b401e84daff039e0af11bf83ea97b8e07071245a | eac06ff87667da09610755999479ccd714c5e5c2 | /9/e9.2.cc | 4e822295bc17aad176dbead9c78afe340cae5473 | [] | no_license | pendulm/cpp_primer_5th_exercises | af632212282908d89581815a18dc83959ae2103e | 971a034347478e98c350349c044088eefa267d91 | refs/heads/master | 2021-01-24T06:09:07.671809 | 2013-05-13T05:37:44 | 2013-05-13T05:37:44 | 9,639,969 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121 | cc | #include <list>
#include <deque>
using std::list;
using std::deque;
int main() {
list<deque<int>> cont;
return 0;
}
| [
"lonependulm@gmail.com"
] | lonependulm@gmail.com |
be30f2b7a1669c213cb60e6763a5aa89bf588acd | defb6e1cfb398f804259134b8ba57685d037a59e | /TZ_Asteroids/InitializeAsteroidsSystem.h | 0069b51378ec50c24b5c27ae0ad2589e038b61a6 | [] | no_license | Volodymyr1337/Asteroids_TZ | 28288db206c060ae5188e3b26ecea46608edf8d3 | 37e05b5ea8410a5642800c6f3ca987668e7cb464 | refs/heads/master | 2022-11-16T09:44:54.624563 | 2022-11-06T17:29:47 | 2022-11-06T17:29:47 | 239,865,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | h | #pragma once
#include "EntitasPP/ISystem.hpp"
#include "vec2.h"
using namespace EntitasPP;
class InitializeAsteroidsSystem : public IInitializeSystem, public ISetPoolSystem
{
private:
Pool* _pool;
const float _minVelocity = 40;
const float _maxVelocity = 60;
int _screenX;
int _screenY;
void SpawnAsteroid(vec2f shipPos);
public:
void SetPool(Pool* pool) override;
void Initialize() override;
~InitializeAsteroidsSystem();
};
| [
"docentkafedru@gmail.com"
] | docentkafedru@gmail.com |
ac9aaad32e3fab0bd563805fe061bde75cc9bbee | 4dbb45758447dcfa13c0be21e4749d62588aab70 | /iOS/Classes/Native/UnityEngine_UnityEngine_GUI_ScrollViewState2687015188.h | 35f0baf5c1af9c869b204ed1f21b0150efeabaf6 | [
"MIT"
] | permissive | mopsicus/unity-share-plugin-ios-android | 6dd6ccd2fa05c73f0bf5e480a6f2baecb7e7a710 | 3ee99aef36034a1e4d7b156172953f9b4dfa696f | refs/heads/master | 2020-12-25T14:38:03.861759 | 2016-07-19T10:06:04 | 2016-07-19T10:06:04 | 63,676,983 | 12 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Object4170816371.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.GUI/ScrollViewState
struct ScrollViewState_t2687015188 : public Il2CppObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"lii@rstgames.com"
] | lii@rstgames.com |
aa4bff811541bf007071261dfcfb6cbc410d70b4 | 16387a9f6a3bebd13ff1008510f06e6d6d3e631d | /release_number/01.21.00/examples/cpp/pstream_inetd_server.cpp | 05b0dbb0b17c7ab9e68407a0a1790c85682c9d97 | [] | no_license | joelnb/xmlrpc-c | 2f54d5b417f8567863fd0778cb858c77fd94237c | 742687b2d131fed7a2901d9b4981a9944017c80f | refs/heads/master | 2022-09-25T22:28:19.886435 | 2022-08-22T18:39:39 | 2022-08-22T18:39:39 | 125,525,941 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,530 | cpp | /* A simple standalone RPC server based on an Xmlrpc-c packet socket.
This program expects the invoker to provide an established connection
to a client as Standard Input (E.g. Inetd can do this). It processes
RPCs from that connection until the client closes the connection.
This is not an XML-RPC server, because it uses a simple packet socket
instead of HTTP. See xmlrpc_sample_add_server.cpp for an example of
an XML-RPC server.
The advantage of this example over XML-RPC is that it has a connection
concept. The client can be connected indefinitely and the server gets
notified when the client terminates, even if it gets aborted by its OS.
Here's an example of running this:
$ socketexec -accept -local_port=8080 ./pstream_inetd_server
*/
#ifndef WIN32
#include <unistd.h>
#endif
#include <cassert>
#include <iostream>
#include <sys/signal.h>
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/registry.hpp>
#include <xmlrpc-c/server_pstream.hpp>
using namespace std;
class sampleAddMethod : public xmlrpc_c::method {
public:
sampleAddMethod() {
// signature and help strings are documentation -- the client
// can query this information with a system.methodSignature and
// system.methodHelp RPC.
this->_signature = "i:ii"; // method's arguments are two integers
this->_help = "This method adds two integers together";
}
void
execute(xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP) {
int const addend(paramList.getInt(0));
int const adder(paramList.getInt(1));
paramList.verifyEnd(2);
*retvalP = xmlrpc_c::value_int(addend + adder);
}
};
int
main(int const,
const char ** const) {
// It's a good idea to disable SIGPIPE signals; if client closes his end
// of the pipe/socket, we'd rather see a failure to send a response than
// get killed by the OS.
signal(SIGPIPE, SIG_IGN);
try {
xmlrpc_c::registry myRegistry;
xmlrpc_c::methodPtr const sampleAddMethodP(new sampleAddMethod);
myRegistry.addMethod("sample.add", sampleAddMethodP);
xmlrpc_c::serverPstreamConn server(
xmlrpc_c::serverPstreamConn::constrOpt()
.socketFd(STDIN_FILENO)
.registryP(&myRegistry));
server.run();
} catch (exception const& e) {
cerr << "Something threw an error: " << e.what() << endl;
}
return 0;
}
| [
"giraffedata@98333e67-4a24-44d7-a75c-e53540dd3050"
] | giraffedata@98333e67-4a24-44d7-a75c-e53540dd3050 |
46aca1db5e943c529471eac4e0f388b8128e5d83 | d8535083c1b50151203e2d33dbb490479cb28661 | /hashing/chaining.cpp | 6afd2d13b2cfaf0c73f23ebc5f5968e8465d6ae7 | [
"MIT",
"CC-BY-SA-4.0"
] | permissive | anishkasachdeva/C-Plus-Plus | 848ec535e6c7546a403008130bf9471cffbc94bc | 5baf1ad89fee29b5b394bcfe4eafc2327613eaff | refs/heads/master | 2022-11-11T14:53:57.302606 | 2020-07-02T12:48:35 | 2020-07-02T12:48:35 | 276,822,243 | 2 | 2 | MIT | 2020-07-03T06:13:18 | 2020-07-03T06:13:18 | null | UTF-8 | C++ | false | false | 2,696 | cpp | #include <math.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
} * head[100], *curr;
void init() {
for (int i = 0; i < 100; i++) head[i] = NULL;
}
void add(int x, int h) {
struct Node *temp = new Node;
temp->data = x;
temp->next = NULL;
if (!head[h]) {
head[h] = temp;
curr = head[h];
} else {
curr = head[h];
while (curr->next) curr = curr->next;
curr->next = temp;
}
}
void display(int mod) {
struct Node *temp;
int i;
for (i = 0; i < mod; i++) {
if (!head[i]) {
cout << "Key " << i << " is empty" << endl;
} else {
cout << "Key " << i << " has values = ";
temp = head[i];
while (temp->next) {
cout << temp->data << " ";
temp = temp->next;
}
cout << temp->data;
cout << endl;
}
}
}
int hash(int x, int mod) { return x % mod; }
void find(int x, int h) {
struct Node *temp = head[h];
if (!head[h]) {
cout << "Element not found";
return;
}
while (temp->data != x && temp->next) temp = temp->next;
if (temp->next)
cout << "Element found";
else {
if (temp->data == x)
cout << "Element found";
else
cout << "Element not found";
}
}
int main(void) {
init();
int c, x, mod, h;
cout << "Enter the size of Hash Table. = ";
cin >> mod;
bool loop = true;
while (loop) {
cout << endl;
cout << "PLEASE CHOOSE -" << endl;
cout << "1. Add element." << endl;
cout << "2. Find element." << endl;
cout << "3. Generate Hash." << endl;
cout << "4. Display Hash table." << endl;
cout << "5. Exit." << endl;
cin >> c;
switch (c) {
case 1:
cout << "Enter element to add = ";
cin >> x;
h = hash(x, mod);
h = fabs(h);
add(x, h);
break;
case 2:
cout << "Enter element to search = ";
cin >> x;
h = hash(x, mod);
find(x, h);
break;
case 3:
cout << "Enter element to generate hash = ";
cin >> x;
cout << "Hash of " << x << " is = " << hash(x, mod);
break;
case 4:
display(mod);
break;
default:
loop = false;
break;
}
cout << endl;
}
/*add(1,&head1);
add(2,&head1);
add(3,&head2);
add(5,&head1);
display(&head1);
display(&head2);*/
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
12e8dd377067f5237dd2cd79af571087afad9f32 | f1c01a3b5b35b59887bf326b0e2b317510deef83 | /SDK/SoT_ClusterDesc_3Items_2Wood1Fruit_classes.hpp | f80fdb68ede6762d71b51a0b1bcc1ed4e47291ec | [] | no_license | codahq/SoT-SDK | 0e4711e78a01f33144acf638202d63f573fa78eb | 0e6054dddb01a83c0c1f3ed3e6cdad5b34b9f094 | refs/heads/master | 2023-03-02T05:00:26.296260 | 2021-01-29T13:03:35 | 2021-01-29T13:03:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_ClusterDesc_3Items_2Wood1Fruit_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ClusterDesc_3Items_2Wood1Fruit.ClusterDesc_3Items_2Wood1Fruit_C
// 0x0000 (0x0150 - 0x0150)
class UClusterDesc_3Items_2Wood1Fruit_C : public UClusterDescription
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass ClusterDesc_3Items_2Wood1Fruit.ClusterDesc_3Items_2Wood1Fruit_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
49eea2eb3053a54de98b639320ff61b2118e23df | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/protobuf/src/google/protobuf/compiler/zip_writer.h | 42895530621b5d478210b1e6fe8dba6cdbfc0a54 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-protobuf",
"MIT"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 2,299 | h | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: kenton@google.com (Kenton Varda)
#include <vector>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/io/zero_copy_stream.h>
namespace google {
namespace protobuf {
namespace compiler {
class ZipWriter {
public:
ZipWriter(io::ZeroCopyOutputStream* raw_output);
~ZipWriter();
bool Write(const string& filename, const string& contents);
bool WriteDirectory();
private:
struct FileInfo {
string name;
uint32 offset;
uint32 size;
uint32 crc32;
};
io::ZeroCopyOutputStream* raw_output_;
vector<FileInfo> files_;
};
} // namespace google
} // namespace protobuf
} // namespace compiler
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
b68ccbdb0d019c088b6701208f2861ca5f5b8421 | d04f271d0ff83cde4ce122edca7cbeae2dd28bde | /knob.h | 28cb56ed841bf23a9f8e82ed731eaefc351eaddf | [
"MIT"
] | permissive | curoles/knobcpp | 7c101263975992e47f4db233065379899416cd84 | 9d7faf5ed5973ac7d75939e128d2ce028ffa5907 | refs/heads/master | 2020-03-17T02:55:41.164998 | 2018-05-18T05:01:27 | 2018-05-18T05:01:27 | 133,212,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,580 | h | /**
* @file
* @brief Knob - constant with name
* @author Igor Lesik
* @copyright 2018 Igor Lesik
*
* Some programs (simulators) need many input "knobs" to set
* desired configuration. Usually knobs are of very few types:
* {boolean|numeric|string}. Usualy knobs in C/C++ are implemented
* as `union`, not as different types of knobs.
*
* Benifits of implementing knob as union/variant:
* 1. Single type makes it easy to place knobs in containers.
* 2. Type of initializing value "defines" knob type,
* as a result shorter almost typeless code.
*/
#pragma once
#ifndef KNOBCPP_KNOB_H_INCLUDED
#define KNOBCPP_KNOB_H_INCLUDED
#include <string>
#include <vector>
#include <map>
#include <tuple>
#include <algorithm>
#include <variant>
#include <functional>
#include "static_knob.h"
namespace knb {
using str = std::string;
using strv = std::string_view;
using cstr = const char*;
class Group;
class Knob final
{
std::string name_;
std::variant<bool,int,float,std::string> v;
std::string desc_;
public:
enum class T : std::size_t { Bool=0, Int, Float, String};
public:
Knob(const str& nm, bool b, const str& d=""):name_(nm),v(b),desc_(d){}
Knob(const str& nm, int i, const str& d=""):name_(nm),v(i),desc_(d){}
Knob(const str& nm, float f, const str& d=""):name_(nm),v(f),desc_(d){}
Knob(const str& nm, const str& s, const str& d=""):name_(nm),v(s),desc_(d){}
//NOTE: next ctor is important, we need temp std::string, otherwise
//Knob's copy/move ctor and op= do not work, exception -> variant looses
//its value, gcc 7.3.
Knob(const std::string& nm, cstr s, const str& d=""):
name_(nm),v(std::string(s)),desc_(d){}
Knob():Knob("",false){}
//Compiler made defaults for us already.
//Knob(Knob&& other) = default;
//Knob(const Knob& other) = default;
//Knob& operator=(const Knob&) = default;
const std::string& name() const {return name_;}
const std::string& desc() const {return desc_;}
Knob::T type() const {return static_cast<Knob::T>(v.index());}
std::size_t typeId() const {return v.index();}
public:
bool asBool() const {return std::get<bool>(v);}
int asInt() const {return std::get<int>(v);}
float asFloat() const {return std::get<float>(v);}
str asString() const {
switch (type()){
case T::Bool: return (asBool()==true)? "true":"false";
case T::Int: return std::to_string(asInt());
case T::Float: return std::to_string(asFloat());
case T::String: return std::get<str>(v);
}
return std::get<str>(v);
}
explicit operator bool() const { return asBool(); }
explicit operator int() const { return asInt(); }
explicit operator float() const { return asFloat(); }
bool operator< (const Knob& other)const {return this->v < other.v;}
bool operator<=(const Knob& other)const {return this->v <= other.v;}
bool operator> (const Knob& other)const {return this->v > other.v;}
bool operator>=(const Knob& other)const {return this->v >= other.v;}
bool operator==(const Knob& other)const {return this->v == other.v;}
bool operator!=(const Knob& other)const {return this->v != other.v;}
bool operator==(bool v) const {return asBool() == v;}
bool operator!=(bool v) const {return asBool() != v;}
friend class knb::Group;
};
/** Array of knobs.
*
* Facility to add a knob to the container and find a knob by its name.
*/
class Array
{
std::string name_;
std::vector<Knob> knobs_;
public:
explicit Array(const std::string& nm):name_(nm){}
void addKnob(const Knob& kb){knobs_.push_back(kb);}
template< class... Args >
void addKnob(Args&&... args){knobs_.emplace_back(args...);}
std::tuple<bool,Knob> findKnob(std::string_view name) const
{
auto knob = std::find_if(
std::begin(knobs_), std::end(knobs_),
[name](const Knob& k)->bool{return k.name()==name;}
);
return (knob==std::end(knobs_))? std::make_tuple(false, Knob()):
std::make_tuple(true, *knob);
}
const Knob& at(std::size_t pos) const {return knobs_.at(pos);}
};
/** Hierarchy of groups of knobs.
*
*/
class Group
{
std::string name_;
std::map<std::string,Knob> knobs_;
std::map<std::string,Group> groups_;
bool immutable_;
public:
explicit Group(const std::string& nm, bool immutable=true):
name_(nm),immutable_(immutable){}
Group& addKnob(const Knob& kb){
knobs_.insert_or_assign(kb.name(), kb);
return *this;
}
template< class... Args >
Group& addKnob(const std::string& name, Args&&... args){
knobs_.try_emplace(name,name,args...);
return *this;
}
const Knob& at(const std::string& knobName) const {
return knobs_.at(knobName);
}
const Group& gr(const std::string& groupName) const {
return groups_.at(groupName);
}
Group& getGroup(const std::string& groupName) {
auto g = groups_.find(groupName);
if (g == std::end(groups_)) {
auto [ig, inserted] = groups_.emplace(groupName,groupName);
return (inserted)? ig->second : *this;
}
return g->second;
}
std::tuple<bool,std::string,const Knob*> findKnob(const std::string& name) const
{
if (const auto knob = knobs_.find(name); knob != std::end(knobs_)) {
return std::make_tuple(true, name_+":"+name, &(knob->second));
}
for (const auto& kv : groups_) {
if (auto [foundInSubgr, path, knob] = kv.second.findKnob(name); foundInSubgr) {
return std::make_tuple(true, name_+":"+path, knob);
}
}
return std::make_tuple(false, "", nullptr);
}
void visit(std::function<void(const Knob&)> visitor) const
{
for (const auto& name_knob : knobs_) visitor(name_knob.second);
for (const auto& name_group : groups_) name_group.second.visit(visitor);
}
void finalize() { immutable_ = true; }
void changeValue(const Knob* knob, const std::string& s){
if (immutable_) return;
Knob* mutant = const_cast<Knob*>(knob);
switch (mutant->type()){
case Knob::T::Bool: mutant->v = !s.empty(); break;
case Knob::T::Int: mutant->v = std::stoi(s); break;
case Knob::T::Float: mutant->v = std::stof(s); break;
case Knob::T::String: mutant->v = s; break;
}
}
};
}
#endif
| [
"curoles@yahoo.com"
] | curoles@yahoo.com |
7fa242661797c9cebe3607d6ee2430178f2af9a1 | 8a2508c0916ba33a8f7b8103c7a3e784ad4a48aa | /control works/final pp1/c.cpp | 26c09b02d3bb6c6d0e3da878714f79d978826f7c | [] | no_license | SemaMolchanov/cpp-basics | 85a628c0afca793f84ef4f35e316e2305510e0ca | 1e44e0e7b462d123ce8e31e3f37f587629ea9af3 | refs/heads/main | 2023-05-27T15:25:40.672669 | 2021-03-16T12:51:52 | 2021-03-16T12:51:52 | 348,340,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | #include <iostream>
#include <cmath>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;
int main(){
vector<int> v;
int n;
cin >> n;
for (int i = 0; i < n; i++){
int x;
cin >> x;
v.push_back(x);
}
vector<int>::iterator it = max_element(v.begin(), v.end());
int maxi = *it;
int sum = 0; int count = 1;
for_each(it + 1, v.end(), [&sum, &count](int a){
sum += a;
count++;
});
if (sum - maxi <= 0){
cout << count;
}
else{
cout << 1;
}
return 0;
} | [
"sema.molchanov@gmail.com"
] | sema.molchanov@gmail.com |
1e288deb783d72649df2d1faa8bec4dedf6f27eb | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /extensions/browser/api/networking_private/networking_private_delegate.cc | 03be932348a6c6a0a27e77c170b27f20292bf484 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 2,879 | cc | // 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 "extensions/browser/api/networking_private/networking_private_delegate.h"
#include "extensions/browser/api/networking_private/networking_private_api.h"
namespace extensions {
NetworkingPrivateDelegate::VerifyDelegate::VerifyDelegate() {
}
NetworkingPrivateDelegate::VerifyDelegate::~VerifyDelegate() {
}
NetworkingPrivateDelegate::UIDelegate::UIDelegate() {}
NetworkingPrivateDelegate::UIDelegate::~UIDelegate() {}
NetworkingPrivateDelegate::NetworkingPrivateDelegate(
std::unique_ptr<VerifyDelegate> verify_delegate)
: verify_delegate_(std::move(verify_delegate)) {}
NetworkingPrivateDelegate::~NetworkingPrivateDelegate() {
}
void NetworkingPrivateDelegate::AddObserver(
NetworkingPrivateDelegateObserver* observer) {
NOTREACHED() << "Class does not use NetworkingPrivateDelegateObserver";
}
void NetworkingPrivateDelegate::RemoveObserver(
NetworkingPrivateDelegateObserver* observer) {
NOTREACHED() << "Class does not use NetworkingPrivateDelegateObserver";
}
void NetworkingPrivateDelegate::StartActivate(
const std::string& guid,
const std::string& carrier,
const VoidCallback& success_callback,
const FailureCallback& failure_callback) {
failure_callback.Run(networking_private::kErrorNotSupported);
}
void NetworkingPrivateDelegate::VerifyDestination(
const VerificationProperties& verification_properties,
const BoolCallback& success_callback,
const FailureCallback& failure_callback) {
if (!verify_delegate_) {
failure_callback.Run(networking_private::kErrorNotSupported);
return;
}
verify_delegate_->VerifyDestination(verification_properties, success_callback,
failure_callback);
}
void NetworkingPrivateDelegate::VerifyAndEncryptCredentials(
const std::string& guid,
const VerificationProperties& verification_properties,
const StringCallback& success_callback,
const FailureCallback& failure_callback) {
if (!verify_delegate_) {
failure_callback.Run(networking_private::kErrorNotSupported);
return;
}
verify_delegate_->VerifyAndEncryptCredentials(
guid, verification_properties, success_callback, failure_callback);
}
void NetworkingPrivateDelegate::VerifyAndEncryptData(
const VerificationProperties& verification_properties,
const std::string& data,
const StringCallback& success_callback,
const FailureCallback& failure_callback) {
if (!verify_delegate_) {
failure_callback.Run(networking_private::kErrorNotSupported);
return;
}
verify_delegate_->VerifyAndEncryptData(verification_properties, data,
success_callback, failure_callback);
}
} // namespace extensions
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
52f961d33fae3c1730c5c1d1bc52378d5dcd511c | bf72a3eee6c286534cf56d594b9c5c91bc8a912c | /tarF/Classes/PosBase.cpp | 8c8d10c504295342395c3d37f747cc2818a42912 | [] | no_license | lg878398509/gameproject | 7ee724f48fd38de4271af8ce0dc271d5550f0c3a | 42224ae9a5141caa595514e058958e713ae14605 | refs/heads/master | 2021-01-21T04:46:55.571853 | 2016-06-07T11:40:32 | 2016-06-07T11:40:32 | 52,573,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include "PosBase.h"
PosBase::PosBase() {
m_pos = Point(0, 0);
m_isDebug = false;
}
PosBase::~PosBase() {
}
PosBase* PosBase::create(Point pos) {
PosBase* tPos = new PosBase();
if (tPos && tPos->init(pos)) {
tPos->autorelease();
}
else {
CC_SAFE_DELETE(tPos);
}
return tPos;
}
PosBase* PosBase::create(Point pos, bool isDebug) {
PosBase* tPos = new PosBase();
if (tPos && tPos->init(pos, isDebug)) {
tPos->autorelease();
}
else {
CC_SAFE_DELETE(tPos);
}
return tPos;
}
bool PosBase::init(Point pos) {
bool bRet = false;
do {
setPos(pos);
bRet = true;
} while (0);
return bRet;
}
bool PosBase::init(Point pos, bool isDebug) {
bool bRet = false;
do {
CC_BREAK_IF(!init(pos));
m_isDebug = isDebug;
bRet = true;
} while (0);
return bRet;
}
void PosBase::setDebug(bool isDebug) {
this->m_isDebug = isDebug;
}
bool PosBase::isClickMe(Point pos)
{
return false;
}
| [
"878398509@qq.com"
] | 878398509@qq.com |
ed448b22a1f435ce4a8680f34281c73a7dd89b42 | 7234a10f7f421d000aacc0224bf05ea8a0d4605b | /include/rafale/sql/tools.hh | a86dec2a64c77c81e2334567fc5bb7ca7ac619d7 | [] | no_license | redpist/Rafale | 6034bdfb8449c0b743d342151db875cd0e4ec740 | 393c87f9c9f4cc4b265be74fb6be0a2add41b2f7 | refs/heads/master | 2020-05-20T16:45:05.429372 | 2013-01-30T00:12:16 | 2013-07-13T03:20:20 | 3,275,742 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,250 | hh | //////////////////
// Copyright (c) 2012, Jeremy Lecerf
// 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 Rafale 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 JEREMY LECERF 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
//////////////////
#ifndef _RAFALE_SQL_TOOLS_H_
#define _RAFALE_SQL_TOOLS_H_
#include <sstream>
#include <cppconn/resultset.h>
namespace Rafale
{
namespace SQL
{
namespace Tools
{
namespace Internal_
{
template <typename T>
struct Traits
{
typedef const T &Result;
};
template <>
struct Traits<int>
{
typedef int Result;
};
}
template <class Set, typename T>
float GetFloat(Set &set, typename Internal_::Traits<T>::Result data)
{
std::stringstream ss;
ss << set->getString(data);
float f;
ss >> f;
return f;
}
}
}
}
#endif /* _RAFALE_SQL_TOOLS_H_ */
| [
"redpist@redpist.com"
] | redpist@redpist.com |
2ea96d0f940648376bd7220539fbde6dfe9ff07e | 44227276cdce0d15ee0cdd19a9f38a37b9da33d7 | /arcane/src/arcane/corefinement/surfaceutils/geometrykernelsurfacetools/GeometryKernelSurfaceInternalUtils.h | 1a2a7e8e254a2ca960ec3ebf1170d6fba71d1c68 | [
"Apache-2.0",
"LGPL-2.1-or-later"
] | permissive | arcaneframework/framework | 7d0050f0bbceb8cc43c60168ba74fff0d605e9a3 | 813cfb5eda537ce2073f32b1a9de6b08529c5ab6 | refs/heads/main | 2023-08-19T05:44:47.722046 | 2023-08-11T16:22:12 | 2023-08-11T16:22:12 | 357,932,008 | 31 | 21 | Apache-2.0 | 2023-09-14T16:42:12 | 2021-04-14T14:21:07 | C++ | UTF-8 | C++ | false | false | 4,360 | h | // -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
#ifndef ARCGEOSIM_SURFACEUTILS_GEOMETRYKERNELSURFACETOOLS_GEOMETRYKERNELSURFACEINTERNALUTILS_H
#define ARCGEOSIM_SURFACEUTILS_GEOMETRYKERNELSURFACETOOLS_GEOMETRYKERNELSURFACEINTERNALUTILS_H
/* Author : havep at Wed Apr 1 14:31:35 2009
* Generated by createNew
*/
#include <arcane/Item.h>
#include <arcane/utils/Array.h>
#include <arcane/utils/Real3.h>
#include "arcane/VariableTypes.h"
#include <arcane/ItemGroup.h>
#include <arcane/IMeshSubMeshTransition.h>
#include <GeometryKernel/datamodel/micro/surface/triangulation-data-structure.h>
#include <GeometryKernel/datamodel/geometry/vector.h>
#include <map>
ARCANE_BEGIN_NAMESPACE
NUMERICS_BEGIN_NAMESPACE
using namespace Arcane;
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
//! Build GK triangulation and additional data from a face group
void buildFaceGroupSurface(FaceGroup group,
GeometryKernel::TriangulationDataStructurePtr m_triangulation,
Array<Node> & m_node_array,
Array<Face> & m_face_array,
Array<bool> & m_face_reorient,
Real3 & m_mean_normal);
//! Save surface utility for debugging purpose (binary format)
void saveSurface(const char * filename, GeometryKernel::TriangulationDataStructure & tr);
//! Load surface utility for debugging purpose (binary format)
void loadSurface(const char * filename, GeometryKernel::TriangulationDataStructure & tr);
//! convert GeometryKernel vector to Real3
inline Real3 convertGKVector(const GeometryKernel::Vector & v) { return Real3(v.getX(),v.getY(),v.getZ()); }
inline GeometryKernel::Vector convertGKVector(const Real3 & v) { return GeometryKernel::Vector(v.x,v.y,v.z); }
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
class NodeMapping {
public:
NodeMapping(IMesh * mesh,
Array<Node> & node_array,
GeometryKernel::TriangulationDataStructure & triangulation)
: m_nodes_coordinates(PRIMARYMESH_CAST(mesh)->nodesCoordinates()),
m_node_array(node_array),
m_triangulation(triangulation)
{
;
}
GeometryKernel::TObjectId getNodeId(const Node node)
{
const Integer inode = node.localId();
std::pair<KnownNodes::iterator,bool> inserter = m_known_nodes.insert(KnownNodes::value_type(inode,NULL_ID));
if (inserter.second)
{ // New value
const Real3 coords = m_nodes_coordinates[node];
const GeometryKernel::TObjectId new_id = m_triangulation.newVertex(GeometryKernel::Vector(coords.x,coords.y,coords.z));
ARCANE_ASSERT(((Integer)m_node_array.size()==(Integer)new_id),("Non-synchronized GeometryKernel with internal SurfaceImpl [%d vs %d]",new_id,m_node_array.size()));
m_node_array.add(node);
return (inserter.first->second = new_id);
}
else
{ // Already existing value
return inserter.first->second;
}
}
Real3 computeNormal(const Node node1, const Node node2, const Node node3) {
const Real3 node1_coord = m_nodes_coordinates[node1];
const Real3 node2_coord = m_nodes_coordinates[node2];
const Real3 node3_coord = m_nodes_coordinates[node3];
return math::vecMul(node2_coord-node1_coord,node3_coord-node1_coord);
}
private:
const VariableNodeReal3 & m_nodes_coordinates;
Array<Node> & m_node_array;
GeometryKernel::TriangulationDataStructure & m_triangulation;
typedef std::map<Integer,GeometryKernel::TObjectId> KnownNodes;
KnownNodes m_known_nodes;
};
/*---------------------------------------------------------------------------*/
NUMERICS_END_NAMESPACE
ARCANE_END_NAMESPACE
#endif /* ARCGEOSIM_SURFACEUTILS_GEOMETRYKERNELSURFACETOOLS_GEOMETRYKERNELSURFACEINTERNALUTILS_H */
| [
"Gilles.Grospellier@cea.fr"
] | Gilles.Grospellier@cea.fr |
400b4fc0021462ceabfbedfda2c774c9c400126e | 7824a119dd558f3779b578580e25e766e54abb85 | /tbb/examples/qsort1.cpp | ea3355cbe6517085deb78fe84f05ed1e025a32ed | [
"CC0-1.0"
] | permissive | eruffaldi/course_openmpgpu | c0ddbd381c9f701f5b6ec12182f09078b0146df3 | 81a53977c0799dbe7f88786ce0ce39263938c15d | refs/heads/master | 2021-05-04T11:46:25.265365 | 2016-12-13T05:49:58 | 2016-12-13T05:49:58 | 55,499,336 | 1 | 0 | null | 2016-12-12T22:47:29 | 2016-04-05T10:35:42 | C | UTF-8 | C++ | false | false | 2,568 | cpp | /*
* Emanuele Ruffaldi 2016
* As several algorithms also quick sort can be paralellized
*
* Take the following quicksort serial and paralellize it. Which other sorting algorithms can be parallelized
*/
#include <iostream>
#include <iterator>
#include <vector>
#include <list>
#include <random>
#include <algorithm>
#include "tbb/task_group.h"
#include "tbb/task_scheduler_init.h"
#include "tbb/tick_count.h"
// check lexicographic ordering
template <class I>
bool check(I b, I e)
{
if(b == e) return true;
auto p = *b++;
while(b != e)
{
if(p > *b)
return false;
p = *b++;
}
return true;
}
std::vector<int>::iterator bb; // hack for diagnostics
// This is a non-stable quick sort
// can we use OpenMP tasks for this?
template <class I>
void qsort1(I b, I e,bool top = false)
{
if(b == e)
return;
auto d = std::distance(b,e);
auto p = *std::next(b, d/2);
using W = decltype(p);
// NOTE: see http://en.cppreference.com/w/cpp/algorithm/partition for alternative/better
//C++14 auto mid1 = std::partition(b,e,[p] (const auto & em) { return em < p; });
//C++14 auto mid2 = std::partition(mid1,e,[p] (const auto & em) { return !(p < em); });
auto mid1 = std::partition(b,e,[p] (const W & em) { return em < p; });
auto mid2 = std::partition(mid1,e,[p] (const W & em) { return !(p < em); });
decltype(mid1) ps[2] = { b,mid2};
decltype(mid1) pe[2] = { mid1,e};
if(d > 20)
{
tbb::task_group g;
g.run([&] { qsort1(ps[0],pe[0]); });
g.run([&] { qsort1(ps[1],pe[1]); });
g.wait();
}
else
{
qsort1(ps[0],pe[0]);
qsort1(ps[1],pe[1]);
}
}
int main(int argc, char * argv[])
{
std::random_device rd();
std::seed_seq seed1({1,2,3,4,5});
std::mt19937 gen(seed1); // rd());
std::uniform_int_distribution<> dis(1, 100);
std::vector<int> q(argc == 1 ? 10000000 : atoi(argv[1]));
std::cout << "problem size is " << q.size() << std::endl;
for(int i = 0; i < q.size(); i++)
q[i] = dis(gen);
//std::vector<int> q0 = q;
//std::sort(q0.begin(),q0.end());
//std::cout << "regular sort gives " << check(q0.begin(),q0.end()) << std::endl;
auto t00 = tbb::tick_count::now();
int n = argc > 2 ? atoi(argv[2]) : tbb::task_scheduler_init::default_num_threads();
tbb::task_scheduler_init init(n);
bb = q.begin();
auto t0 = tbb::tick_count::now();
qsort1(q.begin(),q.end(),true);
auto t1 = tbb::tick_count::now();
std::cout << "parallel sort check " << check(q.begin(),q.end()) << " total " << (t1-t00).seconds() << " = net " << (t1-t0).seconds() << " + setup " << (t0-t00).seconds() << std::endl;
return 0;
} | [
"emanuele.ruffaldi@gmail.com"
] | emanuele.ruffaldi@gmail.com |
8d94532735eb0d24da2140b43a0f65f3f36a3104 | 6f874ccb136d411c8ec7f4faf806a108ffc76837 | /code/VCSamples/VC2010Samples/MFC/general/hello/hello.cpp | 40a2d1b1c7636b1c419153d590a7c85fb32c6e60 | [
"MIT"
] | permissive | JetAr/ZDoc | c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435 | e81a3adc354ec33345e9a3303f381dcb1b02c19d | refs/heads/master | 2022-07-26T23:06:12.021611 | 2021-07-11T13:45:57 | 2021-07-11T13:45:57 | 33,112,803 | 8 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 3,334 | cpp | // hello.cpp : Defines the class behaviors for the application.
// Hello is a simple program which consists of a main window
// and an "About" dialog which can be invoked by a menu choice.
// It is intended to serve as a starting-point for new
// applications.
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "resource.h"
#include "hello.h"
/////////////////////////////////////////////////////////////////////////////
// theApp:
// Just creating this application object runs the whole application.
//
CTheApp NEAR theApp;
/////////////////////////////////////////////////////////////////////////////
// CMainWindow constructor:
// Create the window with the appropriate style, size, menu, etc.
//
CMainWindow::CMainWindow()
{
LoadFrame(IDR_MAINFRAME);
}
// OnPaint:
// This routine draws the string "Hello, Windows!" in the center of the
// client area. It is called whenever Windows sends a WM_PAINT message.
// Note that creating a CPaintDC automatically does a BeginPaint and
// an EndPaint call is done when it is destroyed at the end of this
// function. CPaintDC's constructor needs the window (this).
//
void CMainWindow::OnPaint()
{
CRect rect;
GetClientRect(rect);
CPaintDC dc(this);
dc.SetTextAlign(TA_BASELINE | TA_CENTER);
dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
dc.SetBkMode(TRANSPARENT);
CString s;
s.LoadString(IDS_HELLO);
dc.TextOut((rect.right / 2), (rect.bottom / 2), s);
}
// OnAbout:
// This member function is called when a WM_COMMAND message with an
// ID_APP_ABOUT code is received by the CMainWindow class object. The
// message map below is responsible for this routing.
//
// We create a ClDialog object using the "AboutBox" resource (see
// hello.rc), and invoke it.
//
void CMainWindow::OnAbout()
{
CDialog about(IDD_ABOUTBOX);
about.DoModal();
}
// CMainWindow message map:
// Associate messages with member functions.
//
// It is implied that the ON_WM_PAINT macro expects a member function
// "void OnPaint()".
//
// It is implied that members connected with the ON_COMMAND macro
// receive no arguments and are void of return type, e.g., "void OnAbout()".
//
BEGIN_MESSAGE_MAP( CMainWindow, CFrameWnd )
//{{AFX_MSG_MAP( CMainWindow )
ON_WM_PAINT()
ON_COMMAND(ID_APP_ABOUT, OnAbout)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTheApp
// InitInstance:
// When any CTheApp object is created, this member function is automatically
// called. Any data may be set up at this point.
//
// Also, the main window of the application should be created and shown here.
// Return TRUE if the initialization is successful.
//
BOOL CTheApp::InitInstance()
{
TRACE0("CTheApp::InitInstance\n");
m_pMainWnd = new CMainWindow;
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
| [
"126.org@gmail.com"
] | 126.org@gmail.com |
e5a601241f5947beac9f77f755676daf82a685e9 | b60c027c6f430cd0b334ff8e31635a408076ef60 | /practice-websites/codechef-ccdsap/Binary Search/SCHEDULE2_incomplete.cpp | 80c060c4d2cb44ce6c98c69b5f39071dd6d2077d | [] | no_license | ankushgarg1998/Competitive_Coding | 9fb7502c889e8566c4fa39909934e94800d0c3c7 | 2f5d9a92f847b77dce33873a0177a763ceac868f | refs/heads/master | 2023-03-06T05:06:19.510288 | 2023-02-10T18:37:16 | 2023-02-10T18:37:16 | 85,623,384 | 15 | 5 | null | 2018-11-06T18:37:42 | 2017-03-20T20:29:18 | C++ | UTF-8 | C++ | false | false | 1,739 | cpp | #include<bits/stdc++.h>
#define FastIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define lli long long int
#define li long int
#define MOD 1000000007
#define test int t; cin>>t; while(t--)
#define init(arr,val) memset(arr,val,sizeof(arr))
#define loop(i,a,b) for(int i=a;i<b;i++)
#define loopr(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
int main() {
test {
li n, k, kk;
cin>>n>>k;
kk = k;
string s;
cin>>s;
multiset<li, greater<li> > ms;
char curr = s[0];
li count = 1;
loop(i, 1, n) {
if(s[i] != curr) {
ms.insert(count);
curr = s[i];
count = 1;
} else
++count;
}
ms.insert(count);
while(k--) {
li val = *(ms.begin());
if(val <= 2) {
break;
}
ms.erase(ms.begin());
ms.insert(val/2);
if(val % 2 == 0) {
ms.insert((val/2)-1);
} else {
ms.insert(val/2);
}
}
li val = *(ms.begin());
if(val > 2) {
cout<<val<<"\n";
} else {
string st = "01", s1="", s2="";
int a=0, b=1;
loop(i, 0, n) {
s1 += st[(a++)%2];
s2 += st[(b++)%2];
}
li k1=0, k2=0;
loop(i, 0, n) {
if(s[i] != s1[i])
++k1;
if(s[i] != s2[i])
++k2;
}
if(min(k1, k2) <= kk)
cout<<"1\n";
else
cout<<"2\n";
}
}
return 0;
} | [
"1998anky@gmail.com"
] | 1998anky@gmail.com |
1e6a0df101ffe64aef72467e3328f3ac88d7e21d | 2f152ca3533e05d3d851fa9d5d618b631fa1ac5d | /include/virus.h | 4db2d915e61839fe7b832d134c2e4e97c9799591 | [] | no_license | PixelRetroGames/MalwareWarfare | 27d6cc63ef404a8936e1e14e11c6f6d417f0e33a | b5986a1692d4d3295388d6955ba975f2aeaea86e | refs/heads/master | 2022-09-22T18:22:06.544230 | 2022-09-18T10:28:16 | 2022-09-18T10:28:16 | 126,689,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | h | #ifndef VIRUS_H
#define VIRUS_H
#include "combat_unit.h"
class Virus: public Combat_unit
{
protected:
int health=0;
int damage=0;
public:
Virus();
virtual void Load(char *filename,int _id);
void Load_images(char *path_to_image,char *path_to_attack_image,char *path_to_dying_image,char *path_to_walking_image,
char *path_to_taking_damage_image,char *path_to_splash_image,char *path_to_portal_in_image,
char *path_to_portal_out_image);
void Create_menu_image(char *name,char *description);
void Clear();
int Get_damage();
int Get_health();
};
#endif // VIRUS_H
| [
"pixelretrogames@github.com"
] | pixelretrogames@github.com |
57d2e7404933dcb8247b9954ef6fa94f352d854d | c9748aa3a0f75169f382498d7aea380ecec1d96f | /folly/experimental/fibers/test/StackOverflow.cpp | d8462e1ea36e6f653fc5782a062e063eb6b0856d | [
"Apache-2.0"
] | permissive | tianguanghui/folly | d5976a9eadba56ebc3c501f08b9d5396efca9231 | 75f97748ba727ad5762910e10939632f4ad4990b | refs/heads/master | 2021-01-15T21:45:08.741314 | 2016-05-19T00:39:53 | 2016-05-19T00:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,109 | cpp | /*
* Copyright 2016 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/experimental/fibers/FiberManagerMap.h>
#include <folly/experimental/symbolizer/SignalHandler.h>
#include <folly/init/Init.h>
void f(int* p) {
// Make sure recursion is not optimized out
int a[100];
for (size_t i = 0; i < 100; ++i) {
a[i] = i;
++(a[i]);
if (p) {
a[i] += p[i];
}
}
f(a);
}
int main(int argc, char* argv[]) {
folly::init(&argc, &argv);
folly::EventBase evb;
folly::fibers::getFiberManager(evb).addTask([&]() { f(nullptr); });
evb.loop();
}
| [
"facebook-github-bot-1-bot@fb.com"
] | facebook-github-bot-1-bot@fb.com |
49bbbe6441eca293fa8f49ec9a2a3242648cf936 | 328aa43cffe647ed2d971cbf8a4f864d54635643 | /152. Maximum Product Subarray/solution1.cpp | f7b2742ecc2cec579e0e9be1d6cec2bea9c6cd66 | [] | no_license | diwujiahao/leetcode | 24fa5990af640fcab6c8ca2f20e61db8058e7968 | 58f49db3fd532eee4630c86f62786d36fcb1f9d2 | refs/heads/master | 2021-05-08T22:31:20.014373 | 2019-06-17T15:27:28 | 2019-06-17T15:27:28 | 119,675,284 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,165 | cpp | class Solution {
// 假设begin和end间没有0
// 返回最大子串乘积
int maxProductWithout0(vector<int> nums, int begin, int end){
int count = 0; // 负数个数统计
int product = 1; // 所有数字乘积
// 统计 count 和 product
for (auto i = begin; i <= end; i++){
if (nums[i] < 0){
count++;
}
product *= nums[i];
}
// 负数有偶数个--返回product
if (count % 2 == 0){
return product;
}
// 负数有奇数个--拿掉第一个或最后一个负数比大小
else{
// 正
int product1 = product;
int index = begin;
while(nums[index] > 0){
product1 /= nums[index++];
}
if (index < end){
product1 /= nums[index];
}
// 反
int product2 = product;
index = end;
while(nums[index] > 0){
product2 /= nums[index--];
}
if (index > begin){
product2 /= nums[index];
}
return max(product1, product2);
}
}
public:
int maxProduct(vector<int>& nums) {
vector<int> result; // 备选答案
bool zero = false; // 标记是否出现0
// 用0将所有子串分开,分别调用子函数 maxProductWithout0
int begin = 0;
while(begin < nums.size() && nums[begin] == 0){
begin++;
zero = true;
}
while(begin < nums.size()){
int end = begin;
while(end + 1 < nums.size() && nums[end + 1] != 0){
end++;
zero = true;
}
result.push_back(maxProductWithout0(nums, begin, end));
begin = end + 1;
while(begin < nums.size() && nums[begin] == 0){
begin++;
zero = true;
}
}
if (zero){
result.push_back(0);
}
return (result.size() > 0) ? *max_element(result.begin(), result.end()) : 0;
}
}; | [
""
] | |
73a48e9f6f51288616428dbaee4b0328d723dbc4 | ff8575d1570712a94a2f278840b13c1f2f5e6b53 | /radis/RedisClient/impl/redisasyncclient.cpp | a1896e4629dc5f3368adede1d1048314bee52f02 | [] | no_license | macervantes72/other | 3bc43af9bf6742e8b9adf6c655c80a3dfabf9cc9 | 394f3be5778432fa87714752428fdea90495fd0e | refs/heads/master | 2021-09-02T00:06:02.708648 | 2017-12-29T07:21:57 | 2017-12-29T07:21:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,698 | cpp | /*
* Copyright (C) Alex Nekipelov (alex@nekipelov.net)
* License: MIT
*/
#ifndef REDISASYNCCLIENT_REDISASYNCCLIENT_CPP
#define REDISASYNCCLIENT_REDISASYNCCLIENT_CPP
#include <boost/make_shared.hpp>
#include "../redisclient.h"
#include <boost/bind.hpp>
RedisAsyncClient::RedisAsyncClient(boost::asio::io_service &ioService)
: pimpl(boost::make_shared<RedisClientImpl>(boost::ref(ioService)))
{
pimpl->errorHandler = boost::bind(&RedisClientImpl::defaulErrorHandler,
pimpl, _1);
}
RedisAsyncClient::~RedisAsyncClient()
{
pimpl->close();
}
void RedisAsyncClient::connect(const boost::asio::ip::address &address,
unsigned short port,
const boost::function<void(bool, const std::string &)> &handler)
{
boost::asio::ip::tcp::endpoint endpoint(address, port);
connect(endpoint, handler);
}
void RedisAsyncClient::connect(const boost::asio::ip::tcp::endpoint &endpoint,
const boost::function<void(bool, const std::string &)> &handler)
{
pimpl->socket.async_connect(endpoint, boost::bind(&RedisClientImpl::handleAsyncConnect,
pimpl, _1, handler));
}
void RedisAsyncClient::installErrorHandler(
const boost::function<void(const std::string &)> &handler)
{
pimpl->errorHandler = handler;
}
void RedisAsyncClient::command(const std::string &s, const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(1);
items[0] = s;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(2);
items[0] = cmd;
items[1] = arg1;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const RedisBuffer &arg2,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(3);
items[0] = cmd;
items[1] = arg1;
items[2] = arg2;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const RedisBuffer &arg2, const RedisBuffer &arg3,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(4);
items[0] = cmd;
items[1] = arg1;
items[2] = arg2;
items[3] = arg3;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const RedisBuffer &arg2, const RedisBuffer &arg3,
const RedisBuffer &arg4,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(5);
items[0] = cmd;
items[1] = arg1;
items[2] = arg2;
items[3] = arg3;
items[4] = arg4;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const RedisBuffer &arg2, const RedisBuffer &arg3,
const RedisBuffer &arg4, const RedisBuffer &arg5,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(6);
items[0] = cmd;
items[1] = arg1;
items[2] = arg2;
items[3] = arg3;
items[4] = arg4;
items[5] = arg5;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const RedisBuffer &arg2, const RedisBuffer &arg3,
const RedisBuffer &arg4, const RedisBuffer &arg5,
const RedisBuffer &arg6,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(7);
items[0] = cmd;
items[1] = arg1;
items[2] = arg2;
items[3] = arg3;
items[4] = arg4;
items[5] = arg5;
items[6] = arg6;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const RedisBuffer &arg1,
const RedisBuffer &arg2, const RedisBuffer &arg3,
const RedisBuffer &arg4, const RedisBuffer &arg5,
const RedisBuffer &arg6, const RedisBuffer &arg7,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(8);
items[0] = cmd;
items[1] = arg1;
items[2] = arg2;
items[3] = arg3;
items[4] = arg4;
items[5] = arg5;
items[6] = arg6;
items[7] = arg7;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
void RedisAsyncClient::command(const std::string &cmd, const std::list<RedisBuffer> &args,
const boost::function<void(const RedisValue &)> &handler)
{
if(stateValid())
{
std::vector<RedisBuffer> items(1);
items[0] = cmd;
items.reserve(1 + args.size());
std::copy(args.begin(), args.end(), std::back_inserter(items));
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
}
RedisAsyncClient::Handle RedisAsyncClient::subscribe(
const std::string &channel,
const boost::function<void(const std::vector<char> &msg)> &msgHandler,
const boost::function<void(const RedisValue &)> &handler)
{
assert( pimpl->state == RedisClientImpl::Connected ||
pimpl->state == RedisClientImpl::Subscribed);
static const std::string subscribeStr = "SUBSCRIBE";
if( pimpl->state == RedisClientImpl::Connected || pimpl->state == RedisClientImpl::Subscribed )
{
Handle handle = {pimpl->subscribeSeq++, channel};
std::vector<RedisBuffer> items(2);
items[0] = subscribeStr;
items[1] = channel;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
pimpl->msgHandlers.insert(std::make_pair(channel, std::make_pair(handle.id, msgHandler)));
pimpl->state = RedisClientImpl::Subscribed;
return handle;
}
else
{
std::stringstream ss;
ss << "RedisAsyncClient::command called with invalid state "
<< pimpl->state;
pimpl->errorHandler(ss.str());
return Handle();
}
}
void RedisAsyncClient::unsubscribe(const Handle &handle)
{
#ifdef DEBUG
static int recursion = 0;
assert( recursion++ == 0 );
#endif
assert( pimpl->state == RedisClientImpl::Connected ||
pimpl->state == RedisClientImpl::Subscribed);
static const std::string unsubscribeStr = "UNSUBSCRIBE";
if( pimpl->state == RedisClientImpl::Connected ||
pimpl->state == RedisClientImpl::Subscribed )
{
// Remove subscribe-handler
typedef RedisClientImpl::MsgHandlersMap::iterator iterator;
std::pair<iterator, iterator> pair = pimpl->msgHandlers.equal_range(handle.channel);
for(iterator it = pair.first; it != pair.second;)
{
if( it->second.first == handle.id )
{
pimpl->msgHandlers.erase(it++);
}
else
{
++it;
}
}
std::vector<RedisBuffer> items(2);
items[0] = unsubscribeStr;
items[1] = handle.channel;
// Unsubscribe command for Redis
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), dummyHandler));
}
else
{
std::stringstream ss;
ss << "RedisAsyncClient::command called with invalid state "
<< pimpl->state;
#ifdef DEBUG
--recursion;
#endif
pimpl->errorHandler(ss.str());
return;
}
#ifdef DEBUG
--recursion;
#endif
}
void RedisAsyncClient::singleShotSubscribe(const std::string &channel,
const boost::function<void(const std::vector<char> &msg)> &msgHandler,
const boost::function<void(const RedisValue &)> &handler)
{
assert( pimpl->state == RedisClientImpl::Connected ||
pimpl->state == RedisClientImpl::Subscribed);
static const std::string subscribeStr = "SUBSCRIBE";
if( pimpl->state == RedisClientImpl::Connected ||
pimpl->state == RedisClientImpl::Subscribed )
{
std::vector<RedisBuffer> items(2);
items[0] = subscribeStr;
items[1] = channel;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
pimpl->singleShotMsgHandlers.insert(std::make_pair(channel, msgHandler));
pimpl->state = RedisClientImpl::Subscribed;
}
else
{
std::stringstream ss;
ss << "RedisAsyncClient::command called with invalid state "
<< pimpl->state;
pimpl->errorHandler(ss.str());
}
}
void RedisAsyncClient::publish(const std::string &channel, const RedisBuffer &msg,
const boost::function<void(const RedisValue &)> &handler)
{
assert( pimpl->state == RedisClientImpl::Connected );
static const std::string publishStr = "PUBLISH";
if( pimpl->state == RedisClientImpl::Connected )
{
std::vector<RedisBuffer> items(3);
items[0] = publishStr;
items[1] = channel;
items[2] = msg;
pimpl->post(boost::bind(&RedisClientImpl::doAsyncCommand, pimpl,
pimpl->makeCommand(items), handler));
}
else
{
std::stringstream ss;
ss << "RedisAsyncClient::command called with invalid state "
<< pimpl->state;
pimpl->errorHandler(ss.str());
}
}
bool RedisAsyncClient::stateValid() const
{
//assert( pimpl->state == RedisClientImpl::Connected );
if( pimpl->state != RedisClientImpl::Connected )
{
std::stringstream ss;
ss << "RedisAsyncClient::command called with invalid state "
<< pimpl->state;
pimpl->errorHandler(ss.str());
return false;
}
return true;
}
#endif // REDISASYNCCLIENT_REDISASYNCCLIENT_CPP
| [
"yangnan123456789@163.com"
] | yangnan123456789@163.com |
2e409da731fbfb96e0cb52409abc02a1961f6e19 | f58365bcef42779533bcc3b93d7449b26139dfba | /av/avLine/Ropes.cpp | be21581bdc59313beb524cb4af18d17de277ba52 | [] | no_license | hl0071/test_osg | 763b83895f30e1761b6b3e86171fca5c0508a08e | 2ea41efe216e15f7a4452c6b105397a923f3b04f | refs/heads/master | 2023-03-19T09:02:48.435332 | 2017-03-16T18:32:40 | 2017-03-16T18:32:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,857 | cpp | //
// Module includes
//
#include <osg/LineWidth>
#include "av/avCore/avCore.h"
#include "av/avScene/Scene.h"
#include "av/avLine/Ropes.h"
#include "av/avUtils/materials.h"
#include "objects/arresting_gear.h"
namespace {
char vertexShaderSource[] =
"#version 430 compatibility \n"
"#extension GL_ARB_gpu_shader5 : enable \n"
"vec3 light_dir = normalize(vec3(-0.79f, 0.39f, 0.47f)); \n"
"uniform vec2 Settings; \n"
"out block\n"
"{ \n"
"centroid out vec2 texcoord; \n"
"centroid out float fade; \n"
"out float light; \n"
"} v_out; \n"
"void main(void) \n"
"{ \n"
" float w = dot(transpose(gl_ModelViewProjectionMatrix)[3], vec4(gl_Vertex.xyz, 1.0f)); \n"
" float pixel_radius = w * Settings.x; \n"
" float radius = max(Settings.y, pixel_radius); \n"
" v_out.fade = Settings.y / radius; \n"
" vec3 position = gl_Vertex.xyz + radius * gl_Normal.xyz; \n"
" v_out.texcoord = vec2( gl_MultiTexCoord0.x * (0.02f / radius), gl_MultiTexCoord0.y) ; \n"
" v_out.light = dot(light_dir,gl_Normal.xyz) * 0.5f + 0.5f; \n"
" gl_Position = gl_ModelViewProjectionMatrix * vec4(position, 1.0f) ;\n"
"}\n";
char fragmentShaderSource[] =
"#version 430 compatibility \n"
"#extension GL_ARB_gpu_shader5 : enable \n"
"in block\n"
"{ \n"
"centroid in vec2 texcoord; \n"
"centroid in float fade; \n"
"in float light; \n"
"} v_in; \n"
"uniform sampler2D colorTex; \n"
"out vec4 FragColor; \n"
"\n"
"void main(void) \n"
"{ \n"
"\n"
" FragColor = vec4(texture2D(colorTex, v_in.texcoord.xy).xyz * v_in.light, v_in.fade);"
"}\n";
osg::Program* createProgram( const std::string& name, const std::string& vertexSource, const std::string& fragmentSource )
{
osg::ref_ptr<osg::Program> program = new osg::Program;
program->setName( name );
osg::ref_ptr<osg::Shader> vertexShader = new osg::Shader(osg::Shader::VERTEX, vertexSource);
vertexShader->setName( name + "_vertex" );
program->addShader(vertexShader.get());
osg::ref_ptr<osg::Shader> fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, fragmentSource);
fragmentShader->setName( name + "_fragment" );
program->addShader(fragmentShader.get());
return program.release();
}
}
//
// Module namespaces
//
using namespace avRopes;
//
// Ropes node constructor
//
// constructor
RopesNode::RopesNode()
: m_fRadius(0.1f)
{
setName("RopesNode");
_createGeometry();
//
// create state set
//
osg::StateSet * pCurStateSet = getOrCreateStateSet();
//osg::LineWidth* linewidth = new osg::LineWidth();
//linewidth->setWidth(4.0f);
//pCurStateSet->setAttributeAndModes(linewidth,osg::StateAttribute::ON);
pCurStateSet->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
osg::ref_ptr<osg::Program> pCurProgram = avCore::GetDatabase()->LoadProgram("rope/rope.vert","rope/rope.frag", NULL);
//pCurProgram = createProgram("Arresting gear",vertexShaderSource,fragmentShaderSource);
pCurStateSet->setAttributeAndModes(pCurProgram);
pCurStateSet->addUniform(new osg::Uniform("colorTex", BASE_COLOR_TEXTURE_UNIT));
osg::StateAttribute::GLModeValue value = osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE;
pCurStateSet->setTextureAttributeAndModes( BASE_COLOR_TEXTURE_UNIT, avCore::GetDatabase()->LoadTexture("images/wire.dds", osg::Texture::REPEAT), value );
m_uniformSettings = new osg::Uniform("Settings", osg::Vec2f());
pCurStateSet->addUniform(m_uniformSettings.get());
// setup blending
osg::BlendFunc * pBlendFunc = new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
pCurStateSet->setAttributeAndModes(pBlendFunc, osg::StateAttribute::ON);
osg::BlendEquation* pBlendEquation = new osg::BlendEquation(osg::BlendEquation::FUNC_ADD);
pCurStateSet->setAttributeAndModes(pBlendEquation,osg::StateAttribute::OVERRIDE|osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
setCullCallback(Utils::makeNodeCallback(this, &RopesNode::cull));
}
void RopesNode::_createArrays()
{
_coords = new osg::Vec3Array();
_geom->setVertexArray(_coords);
_coords->setDataVariance(osg::Object::DYNAMIC);
osg::Vec4Array* color = new osg::Vec4Array(1);
(*color)[0].set(0.95f,0.0f,0.0f,1.0f) ;
_geom->setColorArray(color, osg::Array::BIND_OVERALL);
_coords->setPreserveDataType(true);
_uv = new osg::Vec2Array;
_uv->setPreserveDataType(true);
_geom->setTexCoordArray(BASE_COLOR_TEXTURE_UNIT, _uv.get(), osg::Array::BIND_PER_VERTEX);
_uv->setNormalize(true);
_normals = new osg::Vec3Array;
_normals->setPreserveDataType(true);
_geom->setNormalArray( _normals.get(), osg::Array::BIND_PER_VERTEX);
}
void RopesNode::_clearArrays()
{
}
void RopesNode::_createGeometry()
{
// dummy bounding box callback
osg::Drawable::ComputeBoundingBoxCallback * pDummyBBCompute = new osg::Drawable::ComputeBoundingBoxCallback();
// create OSG geode with 1 drawable node
setCullingActive(false);
setDataVariance(osg::Object::DYNAMIC);
_geom = new osg::Geometry;
_geom->setComputeBoundingBoxCallback(pDummyBBCompute);
_geom->setUseDisplayList(false);
_geom->setUseVertexBufferObjects(true);
_geom->setDataVariance(osg::Object::DYNAMIC);
addDrawable(_geom);
_createArrays();
}
const static unsigned sides = 8;
void RopesNode::updateRopes( const arresting_gear::ropes_state_t& rss )
{
using namespace arresting_gear;
if (rss.size()==0)
return;
_coords->clear();
_coords->resize(rss.size() * rss[0].size() * (sides + 1));
_uv->resize(rss.size() * rss[0].size() * (sides + 1));
_normals->resize(rss.size() * rss[0].size() * (sides + 1));
osg::Vec3Array::iterator it_vert( _coords->begin() );
osg::Vec2Array::iterator it_uv ( _uv->begin() );
osg::Vec3Array::iterator it_normals( _normals->begin() );
int i=0;
for (auto it = rss.begin(); it != rss.end(); ++it)
{
auto & rs = *it;
std::vector<int> Indices;
auto before_end = std::prev(rs.end());
int r = 0; auto SEGMENT_COUNT = rs.size() - 1;
Indices.reserve(SEGMENT_COUNT * (sides + 1) * 2);
for (auto it_r = rs.begin(); it_r != rs.end(); ++it_r, ++r, ++i)
{
int prev = (r > 0)? r - 1 : 0;
int next = (r < SEGMENT_COUNT)? r + 1 : SEGMENT_COUNT;
osg::Vec3 dir = to_osg_vector3(cg::normalized_safe(rs[next].coord - rs[prev].coord));
osg::Vec3 dir0 = (dir ^ osg::Vec3(0, 0, 1)); dir0.normalize();
osg::Vec3 dir1 = (dir0 ^ dir); dir1.normalize();
cg::point_3 coord (it_r->coord.x,it_r->coord.y,rs.on?it_r->coord.z:0);
auto it_uv0 = std::next(it_uv);
auto it_normals0 = std::next(it_normals);
for (int a = 0; a < sides; a++)
{
float angle = a * (2 * cg::pif / sides);
float x = cosf(angle);
float y = sinf(angle);
osg::Vec3f normal = dir0 * x + dir1 * y;
*it_vert++ = to_osg_vector3(coord);
if( it_r != before_end)
{
Indices.push_back(i * (sides + 1) + a);
Indices.push_back((i + 1) * (sides + 1) + a);
}
auto c = std::distance(rs.begin(),it_r);
(*it_uv++).set(c * 2.f, a * 1.f / sides);
(*it_normals++).set(normal);
}
(*it_vert++).set(to_osg_vector3(coord));
(*it_uv++).set((*it_uv0).x(), 1.0);
(*it_normals++).set(*it_normals0);
}
const auto cur_rope = std::distance(rss.begin(),it);
if (cur_rope < _geom->getNumPrimitiveSets() )
_geom->setPrimitiveSet(cur_rope, new osg::DrawElementsUInt ( osg::PrimitiveSet::TRIANGLE_STRIP, Indices.size() , (GLuint*)&Indices [ 0 ] ));
else
_geom->addPrimitiveSet(new osg::DrawElementsUInt ( osg::PrimitiveSet::TRIANGLE_STRIP, Indices.size() , (GLuint*)&Indices [ 0 ] ));
}
auto const prims = _geom->getNumPrimitiveSets() - rss.size();
if(prims>0)
{
_geom->removePrimitiveSet(rss.size(), prims);
}
_coords->dirty();
_uv->dirty();
_geom->dirtyBound();
}
void RopesNode::cull( osg::NodeVisitor * pNV )
{
osgUtil::CullVisitor * pCV = static_cast<osgUtil::CullVisitor *>(pNV);
avAssert(pCV);
const osg::Matrix & P = *pCV->getProjectionMatrix();
const osg::Viewport & W = *pCV->getViewport();
#if 0
m_fPixelSize = 1.f / 4.5/ 1200.f/*1024.f*/;
#else
if(W.height()>2.0 && pNV->getNodePath().size()< 5) // dirty hack with node paths
m_fPixelSize= 1.f / P(1,1) / W.height();
#endif
m_uniformSettings->set(osg::Vec2f(m_fPixelSize , m_fRadius));
float fClampedPixelSize;
osg::CullStack* cullStack = dynamic_cast<osg::CullStack*>(pNV);
if (cullStack)
{
fClampedPixelSize = cullStack->clampedPixelSize(getBound()) ;
}
} | [
"yaroslav.tarasov@gmail.com"
] | yaroslav.tarasov@gmail.com |
ecd1116aa118d57b2d2b0605c37a5232e148f75e | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_52c.cpp | ff5fa6e8dc80325902965b68f68591efb252eb6d | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,935 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_52c.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-52c.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: snprintf
* BadSink : Copy string to data using snprintf
* Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define SNPRINTF _snwprintf
#else
#define SNPRINTF snprintf
#endif
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_52
{
/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */
#ifndef OMITBAD
void badSink_c(wchar_t * data)
{
{
wchar_t source[100];
wmemset(source, L'C', 100-1); /* fill with L'C's */
source[100-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
SNPRINTF(data, 100, L"%s", source);
printWLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(wchar_t * data)
{
{
wchar_t source[100];
wmemset(source, L'C', 100-1); /* fill with L'C's */
source[100-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */
SNPRINTF(data, 100, L"%s", source);
printWLine(data);
delete [] data;
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
14dfd72d28ce7450879f436e61f538bb77e43b29 | 9fd0b6465570129c86f4892e54da27d0e9842f9b | /src/runtime/libc++/test/containers/sequences/list/list.cons/copy_alloc.pass.cpp | 453c4b580b32d6af115930b77a2e0d6ec8a44475 | [
"BSL-1.0"
] | permissive | metta-systems/metta | cdbdcda872c5b13ae4047a7ceec6c34fc6184cbf | 170dd91b5653626fb3b9bfab01547612efe531c5 | refs/heads/develop | 2022-04-06T07:25:16.069905 | 2020-02-17T08:22:10 | 2020-02-17T08:22:10 | 6,562,050 | 39 | 11 | BSL-1.0 | 2019-02-22T08:53:20 | 2012-11-06T12:54:03 | C++ | UTF-8 | C++ | false | false | 1,051 | cpp | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <list>
// list(const list& c, const allocator_type& a);
#include <list>
#include <cassert>
#include "../../../DefaultOnly.h"
#include "../../../test_allocator.h"
int main()
{
{
std::list<int, test_allocator<int> > l(3, 2, test_allocator<int>(5));
std::list<int, test_allocator<int> > l2(l, test_allocator<int>(3));
assert(l2 == l);
assert(l2.get_allocator() == test_allocator<int>(3));
}
{
std::list<int, other_allocator<int> > l(3, 2, other_allocator<int>(5));
std::list<int, other_allocator<int> > l2(l, other_allocator<int>(3));
assert(l2 == l);
assert(l2.get_allocator() == other_allocator<int>(3));
}
}
| [
"berkus@exquance.com"
] | berkus@exquance.com |
4d5ecaff5a91f3ce56a9c40ac87bc37114b92539 | 1da15e55940da1abca2286437036205f14d40ea9 | /SDK-gcc2.0/cdn/mincost.h | ef6498fc76a32270cc5ad5c635abce324fb990bf | [] | no_license | liushui9404/2017codecraft | b54c3d165b6ee9768d10b97364e86a148d93561d | fca335540092a283d1ca8e3c72a5107b919f3af7 | refs/heads/master | 2021-01-21T06:52:50.747355 | 2017-04-15T04:25:51 | 2017-04-15T04:25:51 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,752 | h | #ifndef __MINCOST__
#define __MINCOST__
#include<vector>
#include<queue>
#include"deploy.h"
#include<string.h>
const int pointmax = 5000; //总结点的最大值
#define INF 1000000
using namespace std;
extern int T;
extern int S;
//边的数据结构
struct edge
{
int from, to, cap, flow, cost;
};
//最小费用最大流的数据结构
struct MCMF
{
int n;//n表示节点个数
int m;//边的个数
int s;//超源
int t;//超汇
vector<edge> edges; //所有边的存储
vector<int> G[pointmax];//邻接表,G[i][j]表示结点i的第j条边在edge数组中的序号
int inqueue[pointmax]; //标志位用于判断你是否在队列中
int dist[pointmax]; //Bellman-Ford算法,源点到各个汇点的最小费用
int pre[pointmax]; //上一条弧
int a[pointmax]; //可以改进的量
//初始化函数
void init(int n, int S, int T)
{
this->n = n;
this->s = S;
this->t = T;
for (int i = 0; i < n; i++)
{
G[i].clear();
}
edges.clear();
}
//添加数据函数
void addEdge(int from, int to, int cap, int cost)
{
edge ed;
ed.from = from;
ed.to = to;
ed.cap = cap;
ed.cost = cost;
ed.flow = 0;
edges.push_back(ed);
ed.from = to;
ed.to = from;
ed.cap = 0;
ed.cost = -cost;
ed.flow = 0;
edges.push_back(ed);
m = edges.size();//边数
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
//最小费用流算法BF
bool bellManFord(int s, int t, int &flow, int &cost)
{
for (int i = 0; i < n; i++)
{
dist[i] = INF;//初始化源到其它结点的距离
}
memset(inqueue, 0, sizeof(inqueue));
dist[s] = 0;
inqueue[s] = 1;
pre[s] = 0;
a[s] = INF;
queue<int> q;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
inqueue[u] = 0;
for (int i = 0; i <(G[u].size()); i++)
{
edge& e = edges[G[u][i]];
if ((e.cap > e.flow) && (dist[e.to] > dist[u] + e.cost))
{
dist[e.to] = dist[u] + e.cost;
pre[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap - e.flow);
if (!inqueue[e.to])
{
q.push(e.to);
inqueue[e.to] = 1;
}
}
}
}
if (dist[t] == INF)
//s->t 不连通
return false;
flow += a[t];
cost += dist[t] * a[t];
int u = t;
while (u != s)
{
edges[pre[u]].flow += a[t];
edges[pre[u] ^ 1].flow -= a[t];
u = edges[pre[u]].from;
}
return true;
}
int MinCost(int s, int t, int totalflow)
{
int flow = 0, cost = 0;
while (bellManFord(s, t, flow, cost));
if (flow >= totalflow)
{
totalflow = flow;
return cost;
}
else
{
return INF;
}
}
};
extern MCMF mincost;
//将数据流数组化
extern int GetData(int line_num, int num_user, int num_point, int num_edge, char*topo[], int **matrix_w,int**matrix_p,int*user_w, int*user);
#endif | [
"1556711031@qq.com"
] | 1556711031@qq.com |
bce489d85cbd8de75fd539b9c884f390242e672e | e384f5467d8bcfd70845997bcbd68d950e874a61 | /example/cpp/vulkan/vulkan_utility/include/vk_utility_texture_factory.h | f3af5a2e0eb3646fb59027637a2be3c69ada3b88 | [] | no_license | Rabbid76/graphics-snippets | ee642f1ed9ceafc6d320e467d3a084d2446d22c2 | fa187afeabb9630bc1d988304fb5787e95a91385 | refs/heads/master | 2023-08-04T04:32:06.884318 | 2023-07-21T09:15:43 | 2023-07-21T09:15:43 | 109,126,544 | 177 | 12 | null | 2023-04-11T20:05:52 | 2017-11-01T12:05:56 | C++ | UTF-8 | C++ | false | false | 392 | h | #pragma once
#include "vk_utility_vulkan_include.h"
#include <tuple>
namespace vk_utility
{
namespace image
{
class TextureFactory
{
public:
virtual std::tuple<vk::Sampler, vk::ImageView, vk::Image, vk::DeviceMemory, vk::DeviceSize> New(
vk::Device device, vk::CommandPool command_pool) const = 0;
};
}
} | [
"Gernot.Steinegger@gmail.com"
] | Gernot.Steinegger@gmail.com |
9fb1e042b2e1e78c8b9f12b013d57ebe6c67c25e | 8f36dbec492228eefe336417ab70b2b251d9ea76 | /Development/src/Engine/src/console.cpp | 7de5c54bb5a49465bb4e52ef7b4d8abd3bc847fb | [] | no_license | galek/vegaEngine | a3c02d44c0502d0ded9c9db455e399eedca6bd49 | 074f7be78b9cc945241dc7469aeea8592bb50b56 | refs/heads/master | 2021-11-04T23:52:31.025799 | 2015-06-19T00:07:15 | 2015-06-19T00:07:15 | 37,155,697 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,950 | cpp | /* VG CONFIDENTIAL
* VegaEngine(TM) Package 0.5.5.0
* Copyright (C) 2009-2014 Vega Group Ltd.
* Author: Nick Galko
* E-mail: nick.galko@vegaengine.com
* All Rights Reserved.
*/
#include "EnginePrivate.h"
#include "Console.h"
#include "ConsoleCommands.h"
#include "APIEngineCommands.h"
using namespace Ogre;
using namespace std;
namespace vega
{
/**
*/
Console::Console() : BaseLayout(), now(false), prev(false) { }
/**
*/
void Console::Initialize()
{
BaseLayout::initialise("Console.layout");
assignWidget(mListHistory, "list_History");
assignWidget(mComboCommand, "combo_Command");
assignWidget(mButtonSubmit, "button_Submit");
MyGUI::Window* window = mMainWidget->castType<MyGUI::Window>(false);
if (window != nullptr) window->eventWindowButtonPressed += newDelegate(this, &Console::NotifyWindowButtonPressed);
mStringCurrent = mMainWidget->getUserString("Current");
mStringError = mMainWidget->getUserString("Error");
mStringSuccess = mMainWidget->getUserString("Success");
mStringUnknow = mMainWidget->getUserString("Unknown");
mStringFormat = mMainWidget->getUserString("Format");
mAutocomleted = false;
mComboCommand->eventComboAccept += newDelegate(this, &Console::NotifyComboAccept);
mComboCommand->eventKeyButtonPressed += newDelegate(this, &Console::NotifyButtonPressed);
mButtonSubmit->eventMouseButtonClick += newDelegate(this, &Console::NotifyMouseButtonClick);
mListHistory->setOverflowToTheLeft(true);
SetVisible(false);
RegisterBaseCommands();
Ogre::LogManager::getSingletonPtr()->getDefaultLog()->addListener(this);
}
/**
*/
void Console::NotifyWindowButtonPressed(MyGUI::Window* _sender, const std::string& _button) {
if (_button == "close")
mMainWidget->setVisible(false);
}
/**
*/
void Console::NotifyMouseButtonClick(MyGUI::Widget* _sender) {
NotifyComboAccept(mComboCommand, MyGUI::ITEM_NONE);
}
/**
*/
void Console::NotifyComboAccept(MyGUI::ComboBox* _sender, size_t _index)
{
const MyGUI::UString& command = _sender->getOnlyText();
if (command == "") return;
MyGUI::UString key = command;
MyGUI::UString value;
size_t pos = command.find(' ');
if (pos != MyGUI::UString::npos)
{
key = command.substr(0, pos);
value = command.substr(pos + 1);
}
MapDelegate::iterator iter = mDelegates.find(key);
if (iter != mDelegates.end())
iter->second(key, value);
else
{
if (eventConsoleUnknowCommand.empty())
PrintTextToConsole(mStringUnknow + "'" + key + "'");
else
eventConsoleUnknowCommand(key, value);
}
_sender->setCaption("");
}
/**
*/
void Console::NotifyButtonPressed(MyGUI::Widget* _sender, MyGUI::KeyCode _key, MyGUI::Char _char)
{
MyGUI::EditBox* edit = _sender->castType<MyGUI::EditBox>();
size_t len = edit->getCaption().length();
if ((_key == MyGUI::KeyCode::Backspace) && (len > 0) && (mAutocomleted))
{
edit->deleteTextSelection();
len = edit->getCaption().length();
edit->eraseText(len - 1);
}
MyGUI::UString command = edit->getCaption();
if (command.length() == 0)
return;
for (MapDelegate::iterator iter = mDelegates.begin(); iter != mDelegates.end(); ++iter)
{
if (iter->first.find(command) == 0)
{
if (command == iter->first) break;
edit->setCaption(iter->first);
edit->setTextSelection(command.length(), iter->first.length());
mAutocomleted = true;
return;
}
}
mAutocomleted = false;
}
/**
*/
void Console::PrintTextToConsole(const MyGUI::UString& _line)
{
if (mListHistory->getCaption().empty())
mListHistory->addText(_line);
else
mListHistory->addText("\n" + _line);
mListHistory->setTextSelection(mListHistory->getTextLength(), mListHistory->getTextLength());
}
/**
*/
void Console::CleanConsole() {
mListHistory->setCaption("");
}
/**
*/
void Console::RegisterConsoleDelegate(const MyGUI::UString& _command, const MyGUI::UString& _des, CommandDelegate::IDelegate* _delegate)
{
mComboCommand->addItem(_command);
MapDelegate::iterator iter = mDelegates.find(_command);
if (iter != mDelegates.end())
MYGUI_LOG(Warning, "console - command '" << _command << "' already exist");
mDelegates[_command] = _delegate;
//Описания
DescriptionsMap::iterator Desiter = mDescriptions.find(_command);
if (Desiter != mDescriptions.end())
MYGUI_LOG(Warning, "console - command '" << _command << "' already descripted");
mDescriptions[_command] = _des;
}
void Console::UnregisterConsoleDelegate(const MyGUI::UString& _command)
{
MapDelegate::iterator iter = mDelegates.find(_command);
if (iter != mDelegates.end())
{
mDelegates.erase(iter);
for (size_t i = 0; i < mComboCommand->getItemCount(); ++i)
{
if (mComboCommand->getItemNameAt(i) == _command)
{
mComboCommand->removeItemAt(i);
break;
}
}
}
else
MYGUI_LOG(Warning, "console - command '" << _command << "' doesn't exist");
}
/**
*/
void Console::PrintTextToConsole(const MyGUI::UString& _reason, const MyGUI::UString& _key,
const MyGUI::UString& _value) {
PrintTextToConsole(MyGUI::utility::toString(_reason, "'", _key, " ", _value, "'"));
}
/**
*/
const MyGUI::UString& Console::GetConsoleStringCurrent() const {
return mStringCurrent;
}
/**
*/
const MyGUI::UString& Console::GetConsoleStringError() const {
return mStringError;
}
/**
*/
const MyGUI::UString& Console::GetConsoleStringSuccess() const {
return mStringSuccess;
}
/**
*/
const MyGUI::UString& Console::GetConsoleStringUnknow() const {
return mStringUnknow;
}
/**
*/
const MyGUI::UString& Console::GetConsoleStringFormat() const {
return mStringFormat;
}
/**
*/
bool Console::GetVisible() {
return mMainWidget->getVisible();
}
/**
*/
void Console::SetVisible(bool _visible) {
#if 0
prev = API::IsBufferredInput();
now = !prev;
mMainWidget->setVisible(_visible);
if (prev != now)
API::SetBufferedUnBufferedMouseMode(now, API::GetShowGUICursor());
else
API::SetBufferedUnBufferedMouseMode(prev, API::GetShowGUICursor());
#else
now = _visible;
mMainWidget->setVisible(_visible);
if (prev != _visible)
API::SetBufferedUnBufferedMouseMode(prev, API::GetShowGUICursor());
else
API::SetBufferedUnBufferedMouseMode(_visible, API::GetShowGUICursor());
if (prev != API::IsBufferredInput())
prev = now;
#endif
}
/**
*/
void Console::GetListCommands()
{
//Описания
for (DescriptionsMap::iterator i = mDescriptions.begin(); i != mDescriptions.end(); i++)
PrintTextToConsole(std::string(i->first + i->second));
}
/**
*/
void Console::RegisterBaseCommands()
{
RegisterConsoleDelegate("help", " -get list commands with description", MyGUI::newDelegate(&ConsoleCommands::Help));
RegisterConsoleDelegate("clean", " -clean console", MyGUI::newDelegate(&ConsoleCommands::CleanConsole));
RegisterConsoleDelegate("quit", " -engine shoutdown", MyGUI::newDelegate(&ConsoleCommands::EngineShoutdown));
RegisterConsoleDelegate("loadlevel", " -loading new level", MyGUI::newDelegate(&ConsoleCommands::LoadLevel));
RegisterConsoleDelegate("playv", " -play video clip", MyGUI::newDelegate(&ConsoleCommands::PlayV));
RegisterConsoleDelegate("r_aa", " -render antialiasing", MyGUI::newDelegate(&ConsoleCommands::R_AA));
RegisterConsoleDelegate("r_ssao", " -render SSAO", MyGUI::newDelegate(&ConsoleCommands::R_SSAO));
RegisterConsoleDelegate("r_hdr", " -render hdr", MyGUI::newDelegate(&ConsoleCommands::R_HDR));
RegisterConsoleDelegate("runscript", " -running script", MyGUI::newDelegate(&ConsoleCommands::RunScript));
RegisterConsoleDelegate("pause", " -set pause", MyGUI::newDelegate(&ConsoleCommands::E_Pause));
RegisterConsoleDelegate("reloadcfg", " -reload config", MyGUI::newDelegate(ConsoleCommands::ReloadCfg));
}
/**
*/
void Console::messageLogged(const Ogre::String &message, Ogre::LogMessageLevel, bool, const Ogre::String &, bool &){
PrintTextToConsole("#FFE600" + message);
}
} | [
"nikolay.galko@gmail.com"
] | nikolay.galko@gmail.com |
81e6ce463f015d486d548c5b181b6c9c1e975409 | a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e | /leetcode/1-1000/973-k-closest-points-to-origin.cpp | 25565a37747653ccb6d4afa68de4767e5a81387b | [
"Apache-2.0"
] | permissive | tangjz/acm-icpc | 45764d717611d545976309f10bebf79c81182b57 | f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d | refs/heads/master | 2023-04-07T10:23:07.075717 | 2022-12-24T15:30:19 | 2022-12-26T06:22:53 | 13,367,317 | 53 | 20 | Apache-2.0 | 2022-12-26T06:22:54 | 2013-10-06T18:57:09 | C++ | UTF-8 | C++ | false | false | 632 | cpp | class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
vector<int> dist2;
dist2.reserve(points.size());
for(auto &it : points) {
int x = it[0], y = it[1];
dist2.push_back(x * x + y * y);
}
nth_element(dist2.begin(), dist2.begin() + (K - 1), dist2.end());
int upp = dist2[K - 1];
vector<vector<int> > ret;
ret.reserve(K);
for(auto &it : points) {
int x = it[0], y = it[1];
if(x * x + y * y <= upp)
ret.push_back(it);
}
return ret;
}
};
| [
"t251346744@gmail.com"
] | t251346744@gmail.com |
50af8eea2f38958449b489859a30e564cf3a9bf3 | 18f77142fef29ece8a34623180b983d5eecf4468 | /src/Texture.h | 8fffb6acf22c9b95b795d2aa3a60bc381024a531 | [] | no_license | equilibrium139/PhysicsSim | f50f3dfa1d591d811a3227de92dc97a22ea4e801 | 951833b580212ab7609a7aa05b86df33a38591d0 | refs/heads/master | 2023-06-15T22:33:27.643249 | 2021-07-15T14:51:44 | 2021-07-15T14:51:44 | 384,804,359 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 790 | h | #ifndef TEXTURE_H
#define TEXTURE_H
#include <vector>
#include "Vector.h"
#include "Utilities.h"
#include <optional>
struct Texture {
Texture(int width, int height) : size(width * height), width(width), height(height), buffer((std::size_t)width * height) {}
Texture(Color* pixels, int width, int height) : size(width * height), width(width), height(height), buffer(pixels, pixels + (std::size_t)width * height) {}
Color operator()(float u, float v) const {
auto x = int(u * width);
auto y = int(v * height);
auto index = std::size_t(y * width + x);
if (index > size - 1) index = size - 1;
return buffer[index];
}
const int size;
const int width, height;
const std::vector<Color> buffer;
};
std::optional<Texture> textureFromFile(const char* path);
#endif // !TEXTURE_H
| [
"zaidruwaishan@outlook.com"
] | zaidruwaishan@outlook.com |
d6681b818a2637fa068c67a3f11ad16bfdb07dca | aec41e793d61159771ec01295a511eb5d021f458 | /leetcode/1366-rank-teams-by-votes.cpp | 8765dc24b22de0de9f16d57965a3470c9523ffc7 | [] | no_license | FootprintGL/algo | ef043d89549685d72400275f7f4ce769028c48c8 | 1109c20921a6c573212ac9170c2aafeb5ca1da0f | refs/heads/master | 2023-04-09T02:59:00.510380 | 2021-04-16T12:59:03 | 2021-04-16T12:59:03 | 272,113,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 993 | cpp |
/* 排序 - 按名词出现次数多少将需排序,如果名词次数相同,按字母升序排序 */
bool comp(pair<char, vector<int>> &p1, pair<char, vector<int>> &p2) {
return p1.second == p2.second ? p1.first < p2.first : p1.second > p2.second;
}
class Solution {
public:
string rankTeams(vector<string>& votes) {
int cnt = votes[0].size();
/* 初始化哈希表 */
unordered_map<char, vector<int>> rank;
for (auto &c : votes[0])
rank[c].resize(cnt);
/* rank存放team i第j名的次数 */
for (auto &s : votes) {
for (int i = 0; i < cnt; i++)
rank[s[i]][i]++;
}
/* 取出键值对放入数组并排序 */
vector<std::pair<char, vector<int>> > tmp(rank.begin(), rank.end());
sort(tmp.begin(), tmp.end(), comp);
/* 构建结果 */
string res;
for (auto &[vid, rank] : tmp)
res += vid;
return res;
}
};
| [
"glbian@hotmail.com"
] | glbian@hotmail.com |
724d6a5dfe8074f401832f18c0cb78efd83289ec | f049bfc58b5f7076e03b23e4508b0e63e2089890 | /Week_07/617.合并二叉树.cpp | 9dac6209f62af1698697479ec03a5dec3c96e68c | [] | no_license | kangshuaibing/algorithm014-algorithm014 | 7335014eac544f642c961805137f39d6078fa774 | 879df27da75fac6042583d1e4a234ce7cb81c747 | refs/heads/master | 2022-12-28T20:14:26.640776 | 2020-10-16T08:32:50 | 2020-10-16T08:32:50 | 287,421,050 | 0 | 0 | null | 2020-08-14T02:04:45 | 2020-08-14T02:04:45 | null | UTF-8 | C++ | false | false | 682 | cpp | /*
* @lc app=leetcode.cn id=617 lang=cpp
*
* [617] 合并二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if(t1 == nullptr) return t2;
if(t2 == nullptr) return t1;
TreeNode* root = new TreeNode(0);
root->val = t1->val + t2->val;
root->left = mergeTrees(t1->left, t2->left);
root->right = mergeTrees(t1->right, t2->right);
return root;
}
};
// @lc code=end
| [
"1326799350@qq.com"
] | 1326799350@qq.com |
e14993267d1779f672227abf276a67f61cbf12c0 | 7e3b429db7c3c16684897e41146a99c27335e424 | /LinkedList/AddTwonosRepByLinkedLists.cpp | 4021a5d7529917dbb181ecdd827a313aa0a9259e | [] | no_license | kailasspawar/DS-ALGO-PROGRAMS | 21d2ef01bbbcc82d3894ceb48104620b79cd387e | 4ae363d1d51406248b8afb38347c3e4cd92af5c3 | refs/heads/master | 2020-04-05T20:48:26.510384 | 2018-11-12T10:28:11 | 2018-11-12T10:28:11 | 157,195,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | cpp | /*
Input:
First List: 5->6->3 // represents number 365
Second List: 8->4->2 // represents number 248
Output
Resultant list: 3->1->6 // represents number 613
*/
#include<iostream>
#include"list.h"
lnode addLists(lnode a,lnode b)
{
if(a == NULL && b == NULL)
return NULL;
int carry = 0,sum = 0;
lnode list = NULL;
while(a!=NULL || b!=NULL)
{
sum = carry + (a ? a->data : 0) + (b ? b->data : 0);
carry = (sum >=10) ? 1 : 0;
sum = sum % 10;
list = insert(list,sum);
if(a) a = a->next;
if(b) b = b->next;
}
if(carry > 0)
list = insert(list,carry);
return list;
}
int main()
{
lnode list = NULL;
lnode list2 = NULL;
lnode list3 = NULL;
list = insert(list,7);
list = insert(list,5);
list = insert(list,9);
list = insert(list,4);
list = insert(list,6);
list2 = insert(list2,8);
list2 = insert(list2,4);
list3 = addLists(list,list2);
display(list3);
return 0;
}
| [
"kailas462@gmail.com"
] | kailas462@gmail.com |
e35269f43e4e439dfd5ff7aeff0b104c0f0095a8 | 87c05e31bba5cf97d8209148f4edeb5bcbf4e8fa | /Lab5_Wskazniki/Lab5_3_solved.cpp | 14dff773e1b88046b6b5c5163be42a8fc382511d | [] | no_license | GitHub-Pawel/PodstawyInformatyki | 0be83734afba10f88ae2b0a791a49b2d3859a3fb | 8fe9d3de0fb3d5a4908803ce9b020e861b077652 | refs/heads/master | 2020-04-25T18:29:34.958706 | 2019-02-27T20:49:07 | 2019-02-27T20:49:07 | 172,986,611 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | #include <iostream>
using namespace std;
short int j=1;
int tab[1000];
int main()
{
for (int i=0; i<1000; i++){
tab[i]=j;
j+=i*i*i;
}
/*
for (int i=0; i<1000; i++){
cout<<i<<"-"<<tab[i]<<endl;
}
*/
int min=tab[0], max=tab[0], sum=0;
for (int i=0; i<1000; i++){
sum+=tab[i];
if (tab[i]>max){
max=tab[i];
}
if (tab[i]<min){
min=tab[i];
}
}
float srednia=sum/1000;
cout<<"Suma = "<<sum<<endl;
cout<<"Minimum = "<<min<<endl;
cout<<"Maksimum = "<<max<<endl;
cout<<"Srednia = "<<srednia<<endl;
return 0;
}
| [
"46169257+GitHub-Pawel@users.noreply.github.com"
] | 46169257+GitHub-Pawel@users.noreply.github.com |
a570978e41ea108891ce5df4df738afeb61faf18 | 37c051977ad94e72dd540e9064c60748c689e616 | /main.cpp | 5518f7b383b8dff2447056fdf9f5dfad0b6ca932 | [] | no_license | RoyJames/multichess | ffcd3b094bdde2d78af1c5cd8df5970bc23e6531 | 135aea7ff7993e61e8ce191d7505b89c619fd4b7 | refs/heads/master | 2020-06-10T16:13:12.848425 | 2016-12-18T15:58:39 | 2016-12-18T15:58:39 | 75,940,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,267 | cpp |
#include <iostream>
#include <vector>
#include <omp.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <engine.h>
#include <fstream>
#include "Optimizer.h"
#include "MapLocator.h"
#include <time.h>
using namespace cv;
using namespace std;
#define UNDISTORT 0
#define DETECT_CORNER 0
#define SOLVECHESS 0
#define SOLVERICOH 1
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX_LEN 1000
#define SEARCH_SCALE 2.5
float resolution = 1024;
vector<Point3d> generateChessboard3d(int row, int col, double edge)
{
vector<Point3d> points;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
points.push_back(Point3d((double)j * edge, (double)i * edge, 0.0));
//cout << (float)j * edge << " " << (float)i * edge << endl;
}
}
return points;
}
double dist3d(Point3d A, Point3d B)
{
return sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y) + (A.z - B.z)*(A.z - B.z));
}
void help()
{
cout << "Input format:"
<< "[imagelist path]"
<< "[chessboard sizes]"
<< "[envmap path]"
<< endl;
}
vector<double> getVector(const Mat &_t1f)
{
Mat t1f;
_t1f.convertTo(t1f, CV_64F);
return (vector<double>)(t1f.reshape(1, 1));
}
void printMat(const Mat &target)
{
int row = target.rows;
int col = target.cols;
cout << "[";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << target.at<double>(i, j) << " ";
}
if (i < row - 1) cout << endl;
}
cout << "]" << endl;
}
int test(int initial)
{
int a = initial;
for (int i = 0; i < 10000000; i++)
{
a+=i;
}
return a;
}
void testopenmp()
{
double t1 = (double)getTickCount();
volatile int temp;
#pragma omp parallel for
for (int i = 0; i < 1000; i++)
{
temp = test(i);
//cout << temp << endl;
}
t1 = ((double)getTickCount() - t1) / getTickFrequency();
cout << "Time elapsed: " << t1 << endl;
exit(1);
}
void refineROI(Rect &rect, Size imgsize)
{
rect.x = MAX(rect.x, 0);
rect.y = MAX(rect.y, 0);
double w = imgsize.width;
double h = imgsize.height;
rect.width = MIN(rect.width, w - rect.x);
rect.height = MIN(rect.height, h - rect.y);
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
help();
return 1;
}
//char *matname = argv[1];
//resolution = atof(argv[2]);
char *imgpath = argv[1];
char *sizepath = argv[2];
Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
cameraMatrix.at<double>(0, 0) = 22170.18826229795;//1.634296875 * resolution;
cameraMatrix.at<double>(1, 1) = 22170.18826229795;//1.634296875 * resolution;
cameraMatrix.at<double>(0, 2) = 2375.5;//(resolution - 1) / 2;
cameraMatrix.at<double>(1, 2) = 1583.5;//(resolution - 1) / 2;
Mat distCoeffs = Mat::zeros(5, 1, CV_64F);
FILE *fin;
fin = fopen(sizepath, "r");
int n_boards = -1;
vector<Size> patternSizes;
fscanf(fin, "%d", &n_boards);
for (int i_board = 0; i_board < n_boards; i_board++)
{
int w, h;
fscanf(fin, "%d%d", &w, &h);
patternSizes.push_back(Size(w, h));
}
fclose(fin);
Optimizer *optimizer = new Optimizer(n_boards, cameraMatrix);
optimizer->board_sizes = patternSizes;
#if UNDISTORT
distCoeffs.at<double>(0) = -0.37077668666130514;
distCoeffs.at<double>(1) = 8.0453921321123243;
distCoeffs.at<double>(4) = 0.11371622504317971;
fin = fopen(imgpath, "r");
int n_pic = -1;
fscanf(fin, "%d", &n_pic);
for (int i_view = 0; i_view < n_pic; i_view++)
{
char picname[MAX_LEN];
sprintf(picname, "picture %d", i_view);
fscanf(fin, "%s", &picname);
cout << "reading image " << picname << endl;
Mat view = imread(picname);
Mat rectified;
undistort(view, rectified, cameraMatrix, distCoeffs);
sprintf(picname, "undistort%d.png", i_view);
cout << "writing " << picname << endl;
//imshow("preview", view);
imwrite(picname, rectified);
cout << "undistorted view " << i_view << ":" << endl;
}
fclose(fin);
exit(1);
#endif
fin = fopen(imgpath, "r");
int n_views = -1;
fscanf(fin, "%d", &n_views);
#if DETECT_CORNER
FileStorage fs_corners("corners.yml", FileStorage::WRITE);
vector<Rect> feasible_ROI(n_boards);
for (int i_view = 0; i_view < n_views; i_view++)
{
char picname[MAX_LEN];
fscanf(fin, "%s", &picname);
Mat view = imread(picname);
Mat gray;
cvtColor(view, gray, CV_BGR2GRAY);
double t = (double)getTickCount();
//#pragma omp parallel for
for (int i_board = 0; i_board < n_boards; i_board++)
{
cout << "finding corners for pic " << i_view << " board " << i_board << endl;
vector<Point2f> corners;
bool patternfound = false;
if (i_view > 0 && feasible_ROI[i_board].width > 0)
{
Rect ROI = feasible_ROI[i_board];
ROI.x -= ROI.width * (SEARCH_SCALE - 1) / 2;
ROI.y -= ROI.height * (SEARCH_SCALE - 1) / 2;
ROI.width *= SEARCH_SCALE;
ROI.height *= SEARCH_SCALE;
refineROI(ROI, gray.size());
rectangle(view, ROI, Scalar(0, 255, 0));
patternfound = findChessboardCorners(gray(ROI), patternSizes[i_board], corners);
for (int i_point = 0; i_point < corners.size(); i_point++)
{
corners[i_point] += Point2f(ROI.x, ROI.y);
}
if (!patternfound)
{
cout << "search ROI failed, running full search" << endl;
}
}
if (!patternfound)
{
patternfound = findChessboardCorners(gray, patternSizes[i_board], corners,
CV_CALIB_CB_ADAPTIVE_THRESH + CV_CALIB_CB_NORMALIZE_IMAGE);
}
if (patternfound)
cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1),
TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
char store_name[MAX_LEN];
sprintf(store_name, "view%dboard%d", i_view, i_board);
fs_corners << store_name << corners;
int max_w = -1;
int max_h = -1;
int min_w = 100000; // we cannot deal with images that large anyway
int min_h = 100000;
for (int i_point = 0; i_point < corners.size(); i_point++)
{
max_w = MAX(max_w, corners[i_point].x);
max_h = MAX(max_h, corners[i_point].y);
min_w = MIN(min_w, corners[i_point].x);
min_h = MIN(min_h, corners[i_point].y);
}
feasible_ROI[i_board] = Rect(min_w, min_h, max_w - min_w, max_h - min_h);
rectangle(view, feasible_ROI[i_board], Scalar(255, 0, 0));
drawChessboardCorners(view, patternSizes[i_board], Mat(corners), patternfound);
}
t = ((double)getTickCount() - t) / getTickFrequency();
cout << "Procedure " << i_view << " took " << t << " seconds" << endl;
sprintf(picname, "pattern%d.png", i_view);
imwrite(picname, view);
}
fs_corners.release();
#else
cout << "Read corners from file..." << endl;
FileStorage fs_corners("corners.yml", FileStorage::READ);
for (int i_view = 0; i_view < n_views; i_view++)
{
CamView current_view;
for (int i_board = 0; i_board < n_boards; i_board++)
{
char store_name[MAX_LEN];
sprintf(store_name, "view%dboard%d", i_view, i_board);
vector<Point2d> temp;
fs_corners[store_name] >> temp;
current_view.ImagePoints.push_back(temp);
current_view.ObjectPoints.push_back(
generateChessboard3d(patternSizes[i_board].height,
patternSizes[i_board].width, CHESSBOARD_SIZE));
}
optimizer->camera_views.push_back(current_view);
}
fs_corners.release();
cout << "Finish reading corners." << endl;
#endif
fclose(fin);
#if SOLVECHESS
optimizer->optimize(500);
optimizer->visualize(imgpath);
FileStorage fs("camerapos.yml", FileStorage::WRITE);
for (int i_board = 0; i_board < n_boards; i_board++)
{
stringstream cur_label;
cur_label << "Transmat" << i_board;
fs << cur_label.str() << optimizer->relative_mat[i_board];
}
fs.release();
#else
cout << "Read transform matrices from file..." << endl;
optimizer->initialize();
FileStorage fs("camerapos.yml", FileStorage::READ);
for (int i_board = 0; i_board < n_boards; i_board++)
{
stringstream cur_label;
cur_label << "Transmat" << i_board;
fs[cur_label.str()] >> optimizer->relative_mat[i_board];
}
fs.release();
cout << "Finish reading transform matrices." << endl;
#endif
#if SOLVERICOH
char* envmap_path = argv[3];
Mat envmap = imread(envmap_path);
Mat gray_map;
cvtColor(envmap, gray_map, CV_BGR2GRAY);
MapLocator *RicohLocator = new MapLocator(n_boards, envmap.rows, true);
RicohLocator->relative_mat = optimizer->relative_mat;
RicohLocator->board_sizes = patternSizes;
for (int i_board = 0; i_board < n_boards; i_board++)
{
cout << "Detecting chessboard " << i_board << endl;
vector<Point2d> imagePoints;
vector<Point3d> objectPoints;
bool patternfound = false;
//if (i_board != 3)
patternfound = findChessboardCorners(gray_map, patternSizes[i_board],
imagePoints, CV_CALIB_CB_ADAPTIVE_THRESH + CV_CALIB_CB_NORMALIZE_IMAGE);
objectPoints = generateChessboard3d(patternSizes[i_board].height,
patternSizes[i_board].width, CHESSBOARD_SIZE);
RicohLocator->ObjectPoints.push_back(objectPoints);
RicohLocator->ImagePoints.push_back(imagePoints);
if (patternfound)
{
cout << "Found chessboard " << i_board << endl;
}
else {
cout << "Not found chessboard " << i_board << endl;
}
}
if (RicohLocator->ObjectPoints.empty())
{
cout << "no valid chessboard in the environment map!" << endl;
exit(1);
}
//RicohLocator->mannual();
RicohLocator->optimize(500);
#endif
return 0;
} | [
"roy.james0717@gmail.com"
] | roy.james0717@gmail.com |
43d0dbf6334cf7223644099cbb9b032e65070a99 | 281778f9f9015c116f951c814741a048f7681b17 | /Source/Graphics.hpp | 0e8d04c04b45855ebc1058e21739b574f0bb6f8f | [] | no_license | Fluroclad/TerrainGenerator | 8ac93f969e623b60aada5490f1f3d3e08944a5e4 | a7a828f19ea6b584a48f4655b6f1a7eacc53faf7 | refs/heads/master | 2023-03-22T19:26:53.960846 | 2021-03-09T15:15:10 | 2021-03-09T15:15:10 | 341,357,922 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | hpp | // Terrain Generator
// (c) 2021 Daniel Dickson, All Rights Reserved.
#pragma once
#include <vulkan/vulkan.h>
#include <stdexcept>
#include <vector>
#include "Window.hpp"
#include "Vulkan/Device.hpp"
#include "Vulkan/Surface.hpp"
#include "Vulkan/Swapchain.hpp"
class Graphics {
public:
Graphics(std::shared_ptr<Window>& window);
~Graphics();
void CreateInstance();
private:
std::shared_ptr<Window>& m_window;
VkInstance m_instance;
std::shared_ptr<Device> m_device;
std::shared_ptr<Surface> m_surface;
std::shared_ptr<Swapchain> m_swapchain;
VkSurfaceCapabilitiesKHR m_surface_capabilities;
std::vector<VkSurfaceFormatKHR> m_surface_formats;
std::vector<VkPresentModeKHR> m_present_modes;
bool CheckValidationLayers();
}; | [
"fluroclad@ymail.com"
] | fluroclad@ymail.com |
1b9c71d181b839a69a1dc6031f7fc18bc88f2985 | 419f182477a529f9fbb28c568ab7610583125c1b | /LCA/Water-Crisis/Water-Crisis.cpp | a4c13890c22778582fbed46dfe4c604b2b6ec4ff | [] | no_license | danielvitor2d/Problem-Set | 0810c6e51ed1b776a8cc876eabf86a9f801acb83 | 96f123c82a32293a275e579a4b597781f04a8fdb | refs/heads/main | 2023-02-12T22:15:05.562554 | 2021-01-22T17:50:26 | 2021-01-22T17:50:26 | 301,018,440 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,569 | cpp | /*
Author: [UFC-QXD] Daniel Vitor Pereira Rodrigues <danielvitor@alu.ufc.br>
Problem: Water Crisis
Link: https://www.urionlinejudge.com.br/judge/en/problems/view/2789
Origin: Mining Marathon 2018
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long i64;
typedef pair<int, int> ii;
typedef pair<i64, i64> ll;
typedef vector<int> vi;
typedef vector<i64> vi64;
typedef vector<ii> vii;
typedef vector<ll> vll;
typedef vector<vi> vvi;
const double eps = 1e-9;
#define eq(a, b) (abs(a - b) < eps)
#define lt(a, b) ((a + eps) < b)
#define gt(a, b) (a > (b + eps))
#define le(a, b) (a < (b + eps))
#define ge(a, b) ((a + eps) > b)
#define fastIO() ios_base::sync_with_stdio(0), cin.tie(0)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define ms(a, x) memset(a, x, sizeof(a))
#define len(x) (x).size()
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
const int dtx[] = { 0, 0, -1, 1, 1, -1, 1, -1};
const int dty[] = {-1, 1, 0, 0, 1, -1, -1, 1};
const int dtxc[] = {1, 1, 2, 2, -1, -1, -2, -2};
const int dtyc[] = {2, -2, 1, -1, 2, -2, 1, -1};
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const int maxn = 5e3+5;
const int mod = 1e9+7;
const int L = 20;
i64 dp[maxn];
int n, m, d, q;
int a, b, w;
vi gr[maxn];
i64 v[maxn];
int c[maxn];
int in[maxn], out[maxn], timer;
int anc[maxn][L];
void dfs(int u, int p) {
in[u] = ++timer;
anc[u][0] = p;
for (int i = 1; i < L; ++i) anc[u][i] = anc[ anc[u][i-1] ][i-1];
for (int to : gr[u]) if (to != p) dfs(to, u);
out[u] = ++timer;
}
bool is_anc(int u, int v) {
return in[u] <= in[v] and out[v] <= out[u];
}
int lca(int u, int v) {
if (is_anc(u, v)) return u;
if (is_anc(v, u)) return v;
for (int i = L-1; i >= 0; --i)
if (!is_anc(anc[u][i], v)) u = anc[u][i];
return anc[u][0];
}
i64 dfs2(int u, int p) {
for (int to : gr[u]) if (to != p) v[u] += dfs2(to, u);
return v[u];
}
int main() {
fastIO();
cin >> n >> d;
for (int i = 0; i < n-1; ++i) {
cin >> a >> b, --a, --b;
gr[a].eb(b);
gr[b].eb(a);
}
cin >> m;
while (m--) {
cin >> a, --a;
cin >> c[a];
}
dfs(0, 0);
cin >> q;
while (q--) {
cin >> a >> b >> w, --a, --b;
int lc = lca(a, b);
v[a] += w;
v[b] += w;
v[lc] -= w;
v[anc[lc][0]] -= w;
}
dfs2(0, 0);
for (int i = 0; i < n; ++i) {
if (c[i] == 0) continue;
for (int j = d; j >= c[i]; --j) {
dp[j] = max(dp[j], v[i] + dp[j - c[i]]);
}
}
i64 ans = 0LL;
for (int i = d; i >= 0; --i) {
ans = max(ans, dp[i]);
}
cout << ans << '\n';
return 0;
}
| [
"ripsea.rpg321@gmail.com"
] | ripsea.rpg321@gmail.com |
839d2f9b03144b37f9cc3ba3021ddb92d85c2826 | 5b943e9070f750db43e4b8e15eb1139b1646fb89 | /counter.cc | 157a1f2391776e01b5dfc28d58da78bc37c4ad02 | [] | no_license | HolyShif/finalrepo | 0dcbcd01f3745fbc4f458a78dcde75787d1ffe40 | 9b6efcbfe6d4eecc9bdc6aa17c6d581a2ddef1c4 | refs/heads/master | 2020-06-11T06:19:53.996713 | 2016-12-06T17:06:57 | 2016-12-06T17:06:57 | 75,747,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | cc | #include <iostream>
#include <fstream>
using namespace std;
int countLine(char* pName);
int countChar(char* pName);
int main(int argc, char **argv){
int i;
if (argc != 2){
cout << "incorrect or no file specified\n";
return 0;
}
// cout << "correct\n";
for (i=1; i<argc; ++i){
countLine(argv[i]);
countChar(argv[i]);
}
return 0;
}
int countLine(char* pName){
int lcount = 0;
string line;
ifstream file(pName);
while(getline(file,line)){
lcount++;
}
cout << "linecount = " << lcount << endl;
return lcount;
}
int countChar(char* pName){
int ccount = 0;
string line;
ifstream file(pName);
while(getline(file,line)){
ccount += line.length();
cout << "charcount = " << ccount << endl;
}
return 0;
}
| [
"kyledshiflett@hotmail.com"
] | kyledshiflett@hotmail.com |
02b82cd9e726865fe0d240a75ebbba1bdfe96bb6 | 30acaf07f82c7562c20db7dda977f78763bc7933 | /src/ui_steering_nn/steering_nn_main_window.cpp | e49a7b593879b2358062327b1fe8c4fde41c8b98 | [] | no_license | RichardToo/pilotguru | 6cd0b862af701568f5a4ae0ccc9b2ab7b1cd4f74 | 893ac0c9188f3974a15de72b2b599143f10e7f68 | refs/heads/master | 2022-04-08T08:31:53.583569 | 2020-03-19T13:26:00 | 2020-03-19T13:26:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,411 | cpp | #include "steering_nn_main_window.h"
#include <io/kia_json_loggers.hpp>
#include <ui_steering_nn_main_window.h>
#include <spoof-steering-serial-commands.h>
#include <iostream>
using pilotguru::kia::KiaControlCommand;
using pilotguru::kia::SteeringAngle;
SteeringNNMainWindow::SteeringNNMainWindow(
const std::string &can_interface, const std::string &arduino_tty,
const pilotguru::kia::SteeringAngleHolderSettings
&steering_controller_settings,
zmq::socket_t *prediction_data_socket, const std::string &log_dir,
QWidget *parent)
: QMainWindow(parent), ui(new Ui::SteeringNNMainWindow),
car_motion_data_(new pilotguru::kia::CarMotionData(10)),
car_motion_data_updater_(new pilotguru::kia::CarMotionDataUpdater(
car_motion_data_.get(), can_interface, {0x2B0, 0x4B0}, {1, 0})),
arduino_command_channel_(
new pilotguru::ArduinoCommandChannel(arduino_tty)),
steering_controller_(new pilotguru::kia::SteeringAngleHolderController(
&(car_motion_data_->steering_angles()),
arduino_command_channel_.get(), steering_controller_settings)),
prediction_updater_(new pilotguru::SingleSteeringAnglePredictionUpdater(
CHECK_NOTNULL(prediction_data_socket), 5 /* history length */)),
steering_controller_feeder_(new pilotguru::kia::SteeringAngleHolderFeeder(
steering_controller_.get(), &(prediction_updater_->Predictions()),
true /* clip_target_angle */)),
kia_commands_logger_(
new pilotguru::TimestampedJsonLogger<KiaControlCommand>(
log_dir, pilotguru::STEERING_COMMANDS_LOG_ROOT_ELEMENT,
std::unique_ptr<pilotguru::JsonSteamWriter<KiaControlCommand>>(
new pilotguru::SteeringCommandsJsonWriter()),
&(arduino_command_channel_->CommandsHistory()))),
steering_angles_logger_(
new pilotguru::TimestampedJsonLogger<SteeringAngle>(
log_dir, pilotguru::STEERING_ANGLES_LOG_ROOT_ELEMENT,
std::unique_ptr<pilotguru::JsonSteamWriter<SteeringAngle>>(
new pilotguru::SteeringAngleJsonWriter()),
&(car_motion_data_->steering_angles()))),
target_steering_angles_logger_(new pilotguru::TimestampedJsonLogger<
pilotguru::kia::TargetSteeringAngleStatus>(
log_dir, pilotguru::TARGET_STEERING_ANGLES_LOG_ROOT_ELEMENT,
std::unique_ptr<pilotguru::JsonSteamWriter<
pilotguru::kia::TargetSteeringAngleStatus>>(
new pilotguru::TargetSteeringAngleStatusJsonWriter()),
&(steering_controller_->TargetSteeringAnglesHistory()))) {
ui->setupUi(this);
prediction_updater_->Start();
steering_controller_feeder_->Start();
steering_angle_read_thread_.reset(
new SteeringAngleReadThread(&(car_motion_data_->steering_angles())));
connect(steering_angle_read_thread_.get(),
&SteeringAngleReadThread::SteeringAngleChanged, this,
&SteeringNNMainWindow::OnSteeringAngleChanged);
steering_angle_read_thread_->start();
velocity_read_thread_.reset(
new VelocityReadThread(&(car_motion_data_->velocities())));
connect(velocity_read_thread_.get(), &VelocityReadThread::VelocityChanged,
this, &SteeringNNMainWindow::OnVelocityChanged);
velocity_read_thread_->start();
steering_torque_offset_read_thread_.reset(new SteeringTorqueOffsetReadThread(
&(arduino_command_channel_->CommandsHistory())));
connect(steering_torque_offset_read_thread_.get(),
&SteeringTorqueOffsetReadThread::SteeringTorqueChanged, this,
&SteeringNNMainWindow::OnSteeringTorqueChanged);
steering_torque_offset_read_thread_->start();
// TODO separate indicators for incoming predictions and effective controller
// target angles?
steering_prediction_read_thread_.reset(new SteeringPredictionReadThread(
&(steering_controller_->TargetSteeringAnglesHistory())));
connect(steering_prediction_read_thread_.get(),
&SteeringPredictionReadThread::SteeringPredictionChanged, this,
&SteeringNNMainWindow::OnSteeringPredictionChanged);
steering_prediction_read_thread_->start();
connect(ui->predictor_start_button, &QPushButton::clicked, this,
&SteeringNNMainWindow::PredictionUpdaterStart);
connect(ui->predictor_stop_button, &QPushButton::clicked, this,
&SteeringNNMainWindow::PredictionUpdaterStop);
connect(ui->steering_start_button, &QPushButton::clicked, this,
&SteeringNNMainWindow::SteeringStart);
connect(ui->steering_stop_button, &QPushButton::clicked, this,
&SteeringNNMainWindow::SteeringStop);
}
SteeringNNMainWindow::~SteeringNNMainWindow() {
steering_angle_read_thread_->RequestStop();
velocity_read_thread_->RequestStop();
steering_torque_offset_read_thread_->RequestStop();
steering_prediction_read_thread_->RequestStop();
steering_angle_read_thread_->wait();
velocity_read_thread_->wait();
steering_torque_offset_read_thread_->wait();
steering_prediction_read_thread_->wait();
kia_commands_logger_->Stop();
steering_angles_logger_->Stop();
target_steering_angles_logger_->Stop();
steering_controller_->Stop();
car_motion_data_updater_->stop();
prediction_updater_->Stop();
steering_controller_feeder_->Stop();
delete ui;
}
void SteeringNNMainWindow::OnSteeringAngleChanged(int16_t angle_deci_degrees) {
const double angle_degrees = static_cast<double>(angle_deci_degrees) / 10.0;
ui->steering_angle_value_label->setText(QString::number(angle_degrees));
}
void SteeringNNMainWindow::OnVelocityChanged(QString text) {
ui->velocity_value_label->setText(text);
}
void SteeringNNMainWindow::OnSteeringTorqueChanged(QString text) {
ui->torque_offset_value_label->setText(text);
}
void SteeringNNMainWindow::OnSteeringPredictionChanged(QString text) {
ui->target_angle_value_label->setText(text);
}
void SteeringNNMainWindow::PredictionUpdaterStart() {
// TODO add signal to the predictor module.
steering_controller_feeder_->SetFeedEnabled(true);
}
void SteeringNNMainWindow::PredictionUpdaterStop() {
// TODO add signal to the predictor module.
steering_controller_feeder_->SetFeedEnabled(false);
}
void SteeringNNMainWindow::SteeringStart() {
car_motion_data_updater_->start();
}
void SteeringNNMainWindow::SteeringStop() { car_motion_data_updater_->stop(); }
| [
"chechetka@gmail.com"
] | chechetka@gmail.com |
d6ab73e1ef064b1f5246985effd0fb16b62dd019 | 98342d650ae520a36a7bae33ff88f207739301b7 | /Source/Plugins/mqusdRecorder/mqusdRecorder.cpp | 6188ac853965439371acd676e98981165f5f1b4a | [
"MIT"
] | permissive | i-saint/USDForMetasequoia | 0304a1fee925cfd102adcc521d13b91b80272bd7 | e589d47434df913ae4d037c503a89373b5c7938c | refs/heads/master | 2021-03-17T04:42:48.592603 | 2020-04-22T01:22:19 | 2020-04-22T01:22:19 | 246,960,766 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 771 | cpp | #include "mqusd.h"
#include "mqCommon/mqDummyPlugins.h"
MQBasePlugin* (*_mqusdGetRecorderPlugin)();
MQBasePlugin* GetPluginClass()
{
if (!_mqusdGetRecorderPlugin) {
auto mod = mu::GetModule(mqusdModuleFile);
if (!mod) {
std::string path = mqusd::GetMiscDir();
path += mqusdModuleFile;
mod = mu::LoadModule(path.c_str());
}
if (mod) {
(void*&)_mqusdGetRecorderPlugin = mu::GetSymbol(mod, "mqusdGetRecorderPlugin");
}
}
if (_mqusdGetRecorderPlugin)
return _mqusdGetRecorderPlugin();
return &mqusd::DummyStationPlugin::getInstance();
}
mqusdAPI void mqusdDummy()
{
// dummy to prevent mqsdk stripped by linker
DWORD a, b;
MQGetPlugInID(&a, &b);
}
| [
"saint.skr@gmail.com"
] | saint.skr@gmail.com |
ad034c691f282cdaab491c2b7e61a26462e60304 | b7eae4edc1008ad33917374d9f4848d012c11ce5 | /cpp-version/word-break-ii.cpp | f5df4b70cd4815e30d4f9f8a7bcc46030f62153c | [] | no_license | lifasheng/leetcode | a086c160ceda043476677ada33f327b01b94318a | 109c55517b8b4a85162fd3e6329f93552319f8b2 | refs/heads/master | 2023-09-01T04:22:38.033113 | 2023-08-21T06:28:24 | 2023-08-21T06:28:24 | 29,234,459 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,143 | cpp | class Solution {
public:
/*
动规,时间复杂度 O(n^2),空间复杂度 O(n^2)
这里需要特别注意的是,i是从1..n,因为0对应空串,而j是从0..i, 而且求子串的时候是从j开始,长度为i-j。
*/
vector<string> wordBreak(string s, unordered_set<string> &dict) {
const int n = s.size();
// 长度为 n 的字符串有 n+1 个隔板
vector<bool> f(n+1, false);
f[0] = true; // 空串
// prev[i][j] 为 true,表示 s[j, i) 是一个合法单词,可以从 j 处切开
// 第一行未用
vector<vector<bool> > prev(n+1, vector<bool>(n, false));
for(int i=1; i<=n; ++i) {
for(int j=0; j<i; ++j) {
string ts = s.substr(j, i-j);
if (dict.find(ts) != dict.end() && f[j]) {
f[i] = true;
prev[i][j] = true;
// 注意:这里不能break 提前跳出循环,不然只能找到一种解。
}
}
}
vector<string> result;
vector<string> path;
dfs(s, prev, path, n, result);
return result;
}
/*
DFS 遍历树,生成路径
该函数中i,j和上面循环中的i,j相对应。
理解: 比如s="abcd", dict=["a" "abc" "b" "cd"], 则结果应该是["a" "b" "cd"]
i 初始时是n,表示求1..n的分割。一旦找到一个有效的分割j,则s[j,i]是最终结果的一部分。
此时我们对s[1..j]进行dfs,所以此时的i=j。
*/
void dfs(string &s, vector<vector<bool> > &prev, vector<string> &path, int i, vector<string> &result) {
if (i == 0) {
string r;
for(int k=path.size()-1; k>=0; --k) {
r += path[k];
if (k!=0) r+= " ";
}
result.push_back(r);
return;
}
for(int j=0; j<i; ++j) {
if (prev[i][j]) {
path.push_back(s.substr(j, i-j));
dfs(s, prev, path, j, result);
path.pop_back();
}
}
}
};
| [
"fashengli@realnetworks.com"
] | fashengli@realnetworks.com |
cc429375231e0c18ff409bf6a48d908d31f289b6 | 3033f3892f7093f1f72cff31892782766bfde1b6 | /29.cpp | f6e84f4513b9ed4d8f6b95af0652de217f127aa9 | [] | no_license | ajtazer/cpp | a11ce4e49b4e6272b97b1a3c75724532026a249f | 7a4fe3c8d06dbcd1ee161cc13f2522cf5e2dff72 | refs/heads/master | 2020-09-25T02:21:12.730439 | 2020-05-25T15:10:21 | 2020-05-25T15:10:21 | 225,896,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | #include<iostream>
using namespace std;
int main()
{
void swap(int &,int &);
int a=1,b=9;
cout<<"Original values are :"<<endl;
cout<<"a = "<<a<<" & b = "<<b<<endl;
swap(a,b);
cout<<"The values of a & b after swaping :"<<endl;
cout<<"a = "<<a<<" & b = "<<b<<endl;
return 0;
}
void swap(int &x,int &y)
{
int temp;
temp=y;
y=x;
x=temp;
cout<<"Swapped values of x and y :"<<endl;
cout<<"x = "<<x<<" & y = "<<y<<endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
70da43cfe0e284355221622c21e5c2edb61f827c | c47efe5ab1226f316f7007926936220903ad8bf4 | /IPS 13/IPS13_Ques_3.cpp | 1d977d7584b4160cb4f3ca383dab97a96337c1c9 | [] | no_license | sddaphal/CSE1002_C_CPP | a6a2a1b9850c180c5b7ccc5500b1c7131619a6aa | d47b9ebde2a38612ba4c86b96a72c1ca293c17e1 | refs/heads/main | 2023-06-09T11:48:04.247769 | 2021-06-26T04:05:38 | 2021-06-26T04:05:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | cpp | /*
Write a C++ program to demonstrate the use of try, catch block with the argument as an integer and string using multiple catch blocks.
Exception handling means handling of abnormal or unexpected events.
Exception handling is done by 'try', 'catch', 'throw' keywords.
It transfers the control to special functions called Handlers and makes it easy to separate the error handling code.
Input : First line : Read a Number
Output : if Number possitive and a Single Digit, throw an exception to print "Single Digit Number", else through an Exception "Not a Single Digit Number" . if Number is negative, then throw an exception "Negative Number"
*/
/*
Name: Hariket Sukeshkumar Sheth
Topic: Exception Handling in CPP
*/
#include <iostream>
using namespace std;
void Exception (int num){
try{
if (num<0)
throw "Negative Number";
else if(num>0 and num<10)
throw 1;
else
throw 2;
}
catch(const char* Msg){
cout<<Msg<<endl;
}
catch(int m){
if(m==1)
cout<<"Single Digit Number"<<endl;
else
cout<<"Not a Single Digit Number"<<endl;
}
}
int main(){
int n;
cin>>n;
Exception(n);
}
| [
"noreply@github.com"
] | noreply@github.com |
7fa83df3f51f24fa0299bd58413a5c054a44c014 | 7dbce519bc1491629d4f2bf40146293fab6ecefa | /src/util/base64.cpp | 86bad59cf6bfe214a4c356363145e165f94e9bcc | [
"MIT"
] | permissive | malasiot/xg | 8b079a828623686fd40fe3881f07dc96ebc92f46 | 02bdcc208f479afb448767e4d2f2764e913e5d43 | refs/heads/master | 2021-04-28T05:20:25.883314 | 2018-03-20T14:03:42 | 2018-03-20T14:03:42 | 122,175,957 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,755 | cpp | /*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
*/
#include <xg/util/base64.hpp>
#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string xg::base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
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(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 (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string xg::base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string 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 += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (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 (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
| [
"malasiot@iti.gr"
] | malasiot@iti.gr |
7d1b23a54e700b7336c55ba2a31c064d7025010b | 2e87e838f7afb04814a009f4a0c4dbbab51c2cc4 | /src/perplexity/source.cpp | 2f00af76a62ab75ab10cb5033b970202b7076ee2 | [
"Apache-2.0"
] | permissive | tangzhenyu/topic_model_variants | fc138b8ea9a5b5f43ebe86e446fb518d35414763 | ce53e7df32809f8655c83176ebd70bd3cf5bf179 | refs/heads/master | 2021-01-01T17:25:48.351442 | 2017-07-23T04:36:31 | 2017-07-23T04:36:31 | 98,070,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | cpp | #include "test_model.h"
void show_help()
{
std::cout << "Command line usage:" << std::endl;
std::cout << "\t./perplexity --dataset <string> --testing-file <string> [--num-iterations <int>] " << std::endl;
std::cout << "--dataset <string> :\n"
<< " The location where phi matrix, param file is stored.\n"
<< "--testing-file <string> :\n"
<< " The testing data file after converting to data-pack\n"
<< "--num-iterations <int> :\n"
<< " The number of Gibbs sampling iterations for testing. The default value is 100." << std::endl;
}
int main(int argc, char ** argv)
{
// initialize the model
test_model lda;
if (lda.init(argc, argv))
{
show_help();
system("pause");
return 1;
}
// Test the model
lda.test();
system("pause");
return 0;
}
| [
"tangzhenyu_2012@163.com"
] | tangzhenyu_2012@163.com |
d879ee60782f247cd36c08ffd88bd2e7ccd56a04 | 1b5802806cdf2c3b6f57a7b826c3e064aac51d98 | /tensorrt-basic-1.10-3rd-plugin/TensorRT-main/samples/sampleNMT/model/softmaxLikelihood.cpp | 432a7f13ce5f2bd67f837803484c3cff40d28291 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"ISC",
"BSD-2-Clause"
] | permissive | jinmin527/learning-cuda-trt | def70b3b1b23b421ab7844237ce39ca1f176b297 | 81438d602344c977ef3cab71bd04995c1834e51c | refs/heads/main | 2023-05-23T08:56:09.205628 | 2022-07-24T02:48:24 | 2022-07-24T02:48:24 | 517,213,903 | 36 | 18 | null | 2022-07-24T03:05:05 | 2022-07-24T03:05:05 | null | UTF-8 | C++ | false | false | 4,208 | cpp | /*
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "softmaxLikelihood.h"
#include "common.h"
#include <math.h>
namespace nmtSample
{
void SoftmaxLikelihood::addToModel(nvinfer1::INetworkDefinition* network, int32_t beamWidth,
nvinfer1::ITensor* inputLogits, nvinfer1::ITensor* inputLikelihoods, nvinfer1::ITensor** newCombinedLikelihoods,
nvinfer1::ITensor** newRayOptionIndices, nvinfer1::ITensor** newVocabularyIndices)
{
auto softmaxLayer = network->addSoftMax(*inputLogits);
ASSERT(softmaxLayer != nullptr);
softmaxLayer->setName("Softmax in likelihood calculation");
softmaxLayer->setAxes(2);
auto softmaxTensor = softmaxLayer->getOutput(0);
ASSERT(softmaxTensor != nullptr);
auto topKLayer = network->addTopK(*softmaxTensor, nvinfer1::TopKOperation::kMAX, beamWidth, 2);
ASSERT(topKLayer != nullptr);
topKLayer->setName("TopK 1st in likelihood calculation");
auto newLikelihoods = topKLayer->getOutput(0);
ASSERT(newLikelihoods != nullptr);
auto vocabularyIndices = topKLayer->getOutput(1);
ASSERT(vocabularyIndices != nullptr);
auto eltWiseLayer
= network->addElementWise(*newLikelihoods, *inputLikelihoods, nvinfer1::ElementWiseOperation::kPROD);
ASSERT(eltWiseLayer != nullptr);
eltWiseLayer->setName("EltWise multiplication in likelihood calculation");
auto combinedLikelihoods = eltWiseLayer->getOutput(0);
ASSERT(combinedLikelihoods != nullptr);
auto shuffleLayer = network->addShuffle(*combinedLikelihoods);
ASSERT(shuffleLayer != nullptr);
shuffleLayer->setName("Reshape combined likelihoods");
nvinfer1::Dims shuffleDims{1, {beamWidth * beamWidth}};
shuffleLayer->setReshapeDimensions(shuffleDims);
auto reshapedCombinedLikelihoods = shuffleLayer->getOutput(0);
ASSERT(reshapedCombinedLikelihoods != nullptr);
auto topKLayer2 = network->addTopK(*reshapedCombinedLikelihoods, nvinfer1::TopKOperation::kMAX, beamWidth, 1);
ASSERT(topKLayer2 != nullptr);
topKLayer2->setName("TopK 2nd in likelihood calculation");
*newCombinedLikelihoods = topKLayer2->getOutput(0);
ASSERT(*newCombinedLikelihoods != nullptr);
*newRayOptionIndices = topKLayer2->getOutput(1);
ASSERT(*newRayOptionIndices != nullptr);
auto shuffleLayer2 = network->addShuffle(*vocabularyIndices);
ASSERT(shuffleLayer2 != nullptr);
shuffleLayer2->setName("Reshape vocabulary indices");
nvinfer1::Dims shuffleDims2{1, {beamWidth * beamWidth}};
shuffleLayer2->setReshapeDimensions(shuffleDims2);
auto reshapedVocabularyIndices = shuffleLayer2->getOutput(0);
ASSERT(reshapedVocabularyIndices != nullptr);
auto gatherLayer = network->addGather(*reshapedVocabularyIndices, **newRayOptionIndices, 0);
ASSERT(gatherLayer != nullptr);
gatherLayer->setName("Shuffle vocabulary indices");
*newVocabularyIndices = gatherLayer->getOutput(0);
ASSERT(*newVocabularyIndices != nullptr);
}
float SoftmaxLikelihood::SoftmaxLikelihoodCombinationOperator::combine(
float rayLikelihood, float optionLikelihood) const
{
return rayLikelihood * optionLikelihood;
}
float SoftmaxLikelihood::SoftmaxLikelihoodCombinationOperator::init() const
{
return 1.0F;
}
float SoftmaxLikelihood::SoftmaxLikelihoodCombinationOperator::smallerThanMinimalLikelihood() const
{
return -1.0F;
}
LikelihoodCombinationOperator::ptr SoftmaxLikelihood::getLikelihoodCombinationOperator() const
{
return std::make_shared<SoftmaxLikelihoodCombinationOperator>();
}
std::string SoftmaxLikelihood::getInfo()
{
return "Softmax Likelihood";
}
} // namespace nmtSample
| [
"dujw@deepblueai.com"
] | dujw@deepblueai.com |
eb9618dd865a1926657f9fd075b893b3072947b0 | 077c62a6afe36c670e63698fbc13b5c2a5e6642f | /demo/src/caxsimpleobject.h | 85939a0b5d89862130ecc875bd493c981c0cabf5 | [
"MIT"
] | permissive | shawneeshaw/pluginX | 27b4b2917f4e88d6ca9cee3023c193108a520f87 | 0fbd4d9090e7ea46d4d923962e44c955cc302b98 | refs/heads/master | 2021-05-12T14:57:30.249217 | 2018-02-08T10:03:55 | 2018-02-08T10:03:55 | 116,967,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 610 | h | #ifndef CPLSIMPLEOBJECT_H
#define CPLSIMPLEOBJECT_H
class caxSimpleObject : public caxObject {
public:
/** create instance */
static caxSimpleObject * New();
public:
/** show me.*/
virtual void ShowMe() = 0;
protected:
//constructor
caxSimpleObject() {}
//destructor.
virtual ~caxSimpleObject() {}
};
//-------------------------------------------------------------------------
inline caxSimpleObject * caxSimpleObject::New() {
caxSimpleObject* pObj = NULL;
cpl_createObject("caxSimpleObject", (void**)&pObj, 1);
return pObj;
}
#endif //CPLSIMPLEOBJECT_H
| [
"shawneeshaw@users.noreply.github.com"
] | shawneeshaw@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.