blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6e2313369c2d56080acba8d41e9e6be1e31a9e5b | ae51b683aae1549b6af8143b538199bceb57a1e6 | /Intermediate/Build/Win64/UE4Editor/Inc/ResidentEvil/BTTaskMoveToPlayer.generated.h | 42200b0c5cb30d316fe1e2288709820886728f52 | [] | no_license | kvtuyen0315/Unreal-Resident-Evil | 2b2a6f346702b705d0fd26b693fc0f7b8f6047fa | 42707bbd9d928b03619c84b3982b2e20acc3df02 | refs/heads/master | 2021-10-26T10:30:27.581789 | 2019-04-12T00:04:00 | 2019-04-12T00:04:00 | 177,728,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,892 | h | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "ObjectMacros.h"
#include "ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef RESIDENTEVIL_BTTaskMoveToPlayer_generated_h
#error "BTTaskMoveToPlayer.generated.h already included, missing '#pragma once' in BTTaskMoveToPlayer.h"
#endif
#define RESIDENTEVIL_BTTaskMoveToPlayer_generated_h
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS_NO_PURE_DECLS
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUBTTaskMoveToPlayer(); \
friend RESIDENTEVIL_API class UClass* Z_Construct_UClass_UBTTaskMoveToPlayer(); \
public: \
DECLARE_CLASS(UBTTaskMoveToPlayer, UBTTask_BlackboardBase, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/ResidentEvil"), NO_API) \
DECLARE_SERIALIZER(UBTTaskMoveToPlayer) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS \
private: \
static void StaticRegisterNativesUBTTaskMoveToPlayer(); \
friend RESIDENTEVIL_API class UClass* Z_Construct_UClass_UBTTaskMoveToPlayer(); \
public: \
DECLARE_CLASS(UBTTaskMoveToPlayer, UBTTask_BlackboardBase, COMPILED_IN_FLAGS(0), 0, TEXT("/Script/ResidentEvil"), NO_API) \
DECLARE_SERIALIZER(UBTTaskMoveToPlayer) \
enum {IsIntrinsic=COMPILED_IN_INTRINSIC};
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UBTTaskMoveToPlayer(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBTTaskMoveToPlayer) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBTTaskMoveToPlayer); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBTTaskMoveToPlayer); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UBTTaskMoveToPlayer(UBTTaskMoveToPlayer&&); \
NO_API UBTTaskMoveToPlayer(const UBTTaskMoveToPlayer&); \
public:
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UBTTaskMoveToPlayer(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UBTTaskMoveToPlayer(UBTTaskMoveToPlayer&&); \
NO_API UBTTaskMoveToPlayer(const UBTTaskMoveToPlayer&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBTTaskMoveToPlayer); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBTTaskMoveToPlayer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBTTaskMoveToPlayer)
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_PRIVATE_PROPERTY_OFFSET
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_13_PROLOG
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_PRIVATE_PROPERTY_OFFSET \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_PRIVATE_PROPERTY_OFFSET \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_RPC_WRAPPERS_NO_PURE_DECLS \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_INCLASS_NO_PURE_DECLS \
Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h_16_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Unreal_Resident_Evil_Source_ResidentEvil_Character_Enemy_BTTaskMoveToPlayer_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"kvtuyen0315@gmail.com"
] | kvtuyen0315@gmail.com |
59cddcf1832916fe599dcf4d6066e18c9a8c7a40 | 46ea21ab2cdf51d78d960299e14e94400c22bf49 | /iniFileOprattion/FileOpration.cpp | 5bb58cd6ea0250d149fbf7784e7235559e91ad47 | [] | no_license | liujunzhang007/IniFileOperation | 8072364b3607e1cdb0f5dc8b578b8cae361f4c60 | f353c1d5705e24d01055564455b3ac92c5e63f51 | refs/heads/master | 2020-04-02T18:22:57.145016 | 2019-08-21T15:06:50 | 2019-08-21T15:06:50 | 154,697,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,104 | cpp | #include "FileOpration.h"
#include<QSettings>
#include <QGuiApplication>
#include<QFile>
#include<QDebug>
FileOpration::FileOpration()
{
}
void FileOpration::fileCreate(){
QString appPath = QCoreApplication::applicationDirPath() + "/languages.ini";
qDebug()<<"QFile.exists()----Ture-------"<<appPath;
//QSettings构造函数的第一个参数是ini文件的路径,第二个参数表示针对ini文件,第三个参数可以缺省
QSettings *configIniWrite = new QSettings(appPath, QSettings::IniFormat);
//向ini文件中写入内容,setValue函数的两个参数是键值对
//向ini文件的第一个节写入内容,ip节下的第一个参数
configIniWrite->setValue("/ip/first", "192.168.0.1");
//向ini文件的第一个节写入内容,ip节下的第二个参数
configIniWrite->setValue("ip/second", "127.0.0.1");
//向ini文件的第二个节写入内容,port节下的第一个参数
configIniWrite->setValue("port/open", "2222");
//写入完成后删除指针
delete configIniWrite;
}
void FileOpration::fileRead(){
QSettings *pIni = new QSettings(QCoreApplication::applicationDirPath()+"/languages.ini", QSettings::IniFormat);
QString sArg = "";
sArg = pIni->value("/ip/first").toString();
qDebug("arg1 = %s\n", sArg.toStdString().data());
sArg = "";
sArg = pIni->value("ip/second").toString();
qDebug("arg2 = %s\n", sArg.toStdString().data());
sArg = "";
sArg = pIni->value("port/open").toString();
qDebug("arg3 = %s\n", sArg.toStdString().data());
delete pIni;
}
void FileOpration::fileWrite(){
QSettings *pIni = new QSettings(QCoreApplication::applicationDirPath()+"/languages.ini", QSettings::IniFormat);
if(!pIni->contains("Data/Language")){
pIni->setValue("Data/Language","alreadySave");
qDebug()<<"Data/Language already writed! === "<<pIni->value("Data/Language").toString().toStdString().data();
}else {
qDebug()<<"Data/Language already exisited! === "<<pIni->value("Data/Language").toString().toStdString().data();
}
delete pIni;
}
| [
"liujunzhang007@sina.cn"
] | liujunzhang007@sina.cn |
2e6d230f3813d328f3eacc7cf144d9d9206e641b | 0f1ce772c2fb5c92baab3305d2bd0d392860d0ac | /2018_exam/authentication.cpp | 56cf222c7fc5592f3c52d54a7196df37fa4ddeeb | [] | no_license | seyone22/dev | 110342dca9cf4413af09c1de132c2ea0079c242b | 901b0e6e0bd11cdea9154060898787a41e8abcef | refs/heads/master | 2023-08-24T16:01:52.830400 | 2021-10-27T11:07:21 | 2021-10-27T11:07:21 | 384,070,046 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | cpp | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
string getinput(string description = "No description provided")
{
string input;
cout << description << "\n>>";
getline(cin, input);
return input;
}
int main()
{
int attempts = 0;
while (true)
{
if (attempts == 3)
{
return 0;
}
string username = getinput("Please enter your username");
string pwd = getinput("Please enter your password");
string pwdCon = getinput("Please reenter your password");
int pwdInt = stoi(pwd);
if (pwd == pwdCon)
{
if ((pwdInt >= 1000 && pwdInt <= 9999) || pwdInt == 0000) //checks all numerical values from 0000 to 1000
{
cout << "Access granted. Good day, " << username << "!" << endl;
break;
}
else
{
cout << "The password is incorrect. Please try again.\n";
attempts += 1;
cout << "Remaining attempts: " << attempts << endl;
}
}
else
{
cout << "The passwords do not match. Please try again.\n";
attempts += 1;
cout << "Remaining attempts: " << attempts << endl;
}
};
cout << "successful break\n";
system("pause");
return 0;
} | [
"s.g.seyone@protonmail.com"
] | s.g.seyone@protonmail.com |
402b2e38e96968c2be87195a55c5914872561c93 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /bma/src/v20210624/model/CreateCRDesktopCodeRequest.cpp | 6ede5969fa5358c0a2abd3fd237f1cfbc00122de | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 2,582 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/bma/v20210624/model/CreateCRDesktopCodeRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Bma::V20210624::Model;
using namespace std;
CreateCRDesktopCodeRequest::CreateCRDesktopCodeRequest() :
m_tortIdHasBeenSet(false),
m_desktopCodeHasBeenSet(false)
{
}
string CreateCRDesktopCodeRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_tortIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TortId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_tortId, allocator);
}
if (m_desktopCodeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DesktopCode";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_desktopCode.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
int64_t CreateCRDesktopCodeRequest::GetTortId() const
{
return m_tortId;
}
void CreateCRDesktopCodeRequest::SetTortId(const int64_t& _tortId)
{
m_tortId = _tortId;
m_tortIdHasBeenSet = true;
}
bool CreateCRDesktopCodeRequest::TortIdHasBeenSet() const
{
return m_tortIdHasBeenSet;
}
string CreateCRDesktopCodeRequest::GetDesktopCode() const
{
return m_desktopCode;
}
void CreateCRDesktopCodeRequest::SetDesktopCode(const string& _desktopCode)
{
m_desktopCode = _desktopCode;
m_desktopCodeHasBeenSet = true;
}
bool CreateCRDesktopCodeRequest::DesktopCodeHasBeenSet() const
{
return m_desktopCodeHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
72f2814bb364c7eeb37e394058533fa925ab173e | a7e3dac1fff4bb7f6b3af4bd33b84f5fefdfe9fe | /ABC/abc098/arc098_a_6400694.cpp | 37f7a06f49e592bb4952aebd509d01bffd2e94ed | [] | no_license | 2019Shun/atcoder_submission | b6794a0bb1e8d2aa5c4663a15ae561dbe59d50cb | a511da6de51ed4eabd25bf2f823b9867f7650649 | refs/heads/master | 2023-04-01T14:53:46.164877 | 2021-03-28T15:00:13 | 2021-03-28T15:00:13 | 316,533,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | #include <bits/stdc++.h>
#include <vector>
#include <numeric>
#define PI 3.14159265358979323846
#define MAXINF (1e18L)
#define INF (1e9L)
#define EPS (1e-9)
#define MOD ((ll)(1e9+7))
#define REP(i, n) for(int i=0;i<int(n);++i)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define RREP(i, n) for(int i=int(n)-1;i>=0;--i)
#define ALL(v) v.begin(),v.end()
#define FIND(v,x) (binary_search(ALL(v),(x)))
#define SORT(v) sort(ALL(v))
#define RSORT(v) sort(ALL(v));reverse(ALL(v))
#define DEBUG(x) cerr<<#x<<": "<<x<<endl;
#define DEBUG_VEC(v) cerr<<#v<<":";for(int i=0;i<v.size();i++) cerr<<" "<<v[i]; cerr<<endl
#define Yes(n) cout<<((n)?"Yes":"No")<<endl
#define YES(n) cout<<((n)?"YES":"NO")<<endl
#define pb push_back
#define fi first
#define se second
using namespace std;
template<class A>void pr(A a){cout << (a) << endl;}
template<class A,class B>void pr(A a,B b){cout << a << " " ;pr(b);}
template<class A,class B,class C>void pr(A a,B b,C c){cout << a << " " ;pr(b,c);}
template<class A,class B,class C,class D>void pr(A a,B b,C c,D d){cout << a << " " ;pr(b,c,d);}
template<class T> inline bool chmin(T& a, T b){return a>b ? a=b, true : false;}
template<class T> inline bool chmax(T& a, T b){return a<b ? a=b, true : false;}
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll,ll> pll;
int main(void)
{
int n;
cin >> n;
string s;
cin >> s;
vector<int> l(n, 0);
Rep(i, 1, n){
if(s[i] == 'E') l[0]++;
}
Rep(i, 1, n){
l[i] = l[i-1];
if(s[i-1] == 'W') l[i]++;
if(s[i] == 'E') l[i]--;
}
SORT(l);
pr(l[0]);
} | [
"taka.shun.2018@gmail.com"
] | taka.shun.2018@gmail.com |
d01013b4af05631519dbd4710b1f5c3c370a4137 | 8d8cc4b3a449bd2fc11e4149c62b54e8ea10d0ee | /main.cc | 33228d96da7674e3c0b71639a72975eebfe8aa32 | [] | no_license | qwertybomb/swap-cmd | fd2c0ef86ea21f8ba8805d936e8f98fae0867b91 | 184fc7f91b0186cd57f6c79d0effad0a7f0e0b79 | refs/heads/master | 2022-12-03T03:27:40.396419 | 2020-08-17T13:36:03 | 2020-08-17T13:36:03 | 278,713,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,537 | cc | #include <iostream>
#include <filesystem>
#include <cstring>
#include <cassert>
static auto print_help() -> void {
std::cerr << "Usage: swap [file1] [file2]\n";
std::cerr << "Swaps the contents of file1 and file2\n";
std::cerr << "Use swap to print this message\n";
}
static auto validate_files(const std::filesystem::path& file1_path, const std::filesystem::path& file2_path) -> void {
{
/* check if the files exists */
const auto file1_exists = std::filesystem::exists(file1_path);
const auto file2_exists = std::filesystem::exists(file2_path);
const auto exists = file1_exists && file2_exists;
if (!exists) {
if (!file1_exists) std::cerr << "cannot find file " << file1_path << '\n';
if (!file2_exists) std::cerr << "cannot find file " << file2_path << '\n';
exit(EXIT_FAILURE);
}
}
{
if (std::filesystem::absolute(file1_path) == std::filesystem::absolute(file2_path)) {
std::cerr << "swaping the same two files does nothing\n";
exit(EXIT_SUCCESS);
}
}
}
static auto get_temp_filename(char* template_name) -> void {
/* tmpnam_s does not work on linux */
#if defined(WIN32) || defined(_WIN32)
errno_t err = tmpnam_s(template_name, L_tmpnam);
if (!err) exit(err); /* if we failed exit */
#else
int err = mkstemp(template_name);
if (err == -1) exit(err); /* if we failed exit */
#endif
}
int main(int argc, char** argv) {
std::ios::sync_with_stdio(false);
if (argc != 3) {
print_help();
return EXIT_FAILURE;
}
const auto file1_path = std::filesystem::path{ argv[1] };
const auto file2_path = std::filesystem::path{ argv[2] };
validate_files(file1_path, file2_path);
char temp_filename[L_tmpnam] = "XXXXXX";
get_temp_filename(temp_filename);
const auto temp_filepath = std::filesystem::path{ temp_filename };
/* move-swap the files instead of copy-swaping */
/* renaming a file is the same as moving it */
const auto rename_file = [](const auto& old_file, const auto& new_file) {
std::error_code error;
std::filesystem::rename(old_file, new_file, error);
if (error) {
std::cerr << error.message() << '\n';
exit(EXIT_FAILURE);
}
};
rename_file(file1_path, temp_filepath);
rename_file(file2_path, file1_path);
rename_file(temp_filepath, file2_path);
} | [
"noreply@github.com"
] | qwertybomb.noreply@github.com |
d3bd9db65e2c325ba54a66351af98dcb1e53c5c1 | 6bd0b2a34bd546e9371c38103a281ce78575e6b6 | /src/engine/file_system.cpp | 2a791942d0abf606be129b7350ba5bdf92754e7a | [
"MIT"
] | permissive | khyveasna/LumixEngine | efe131faa31b69bdf9173339e69dae46ad9606dd | b32bbc4558978dcc0eb73d48a63ac545418ccaab | refs/heads/master | 2022-01-20T21:27:20.364696 | 2019-07-19T19:28:07 | 2019-07-19T19:28:07 | 197,835,659 | 1 | 0 | null | 2019-07-19T20:10:05 | 2019-07-19T20:10:05 | null | UTF-8 | C++ | false | false | 9,477 | cpp | #include "engine/file_system.h"
#include "engine/allocator.h"
#include "engine/array.h"
#include "engine/crc32.h"
#include "engine/delegate_list.h"
#include "engine/flag_set.h"
#include "engine/hash_map.h"
#include "engine/log.h"
#include "engine/mt/sync.h"
#include "engine/mt/task.h"
#include "engine/os.h"
#include "engine/path.h"
#include "engine/path_utils.h"
#include "engine/profiler.h"
#include "engine/queue.h"
#include "engine/stream.h"
#include "engine/string.h"
#ifdef _WIN32
#include <Windows.h>
#endif
namespace Lumix
{
struct TarHeader {
char name[100];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char chksum[8];
char typeflag;
char linkname[100];
char magic[6];
char version[2];
char uname[32];
char gname[32];
char devmajor[8];
char devminor[8];
char prefix[155];
};
struct AsyncItem
{
enum class Flags : u32 {
FAILED = 1 << 0,
CANCELED = 1 << 1,
};
AsyncItem(IAllocator& allocator) : data(allocator) {}
bool isFailed() const { return flags.isSet(Flags::FAILED); }
bool isCanceled() const { return flags.isSet(Flags::CANCELED); }
FileSystem::ContentCallback callback;
Array<u8> data;
StaticString<MAX_PATH_LENGTH> path;
u32 id = 0;
FlagSet<Flags, u32> flags;
};
struct FileSystemImpl;
class FSTask final : public MT::Task
{
public:
FSTask(FileSystemImpl& fs, IAllocator& allocator)
: MT::Task(allocator)
, m_fs(fs)
{
}
~FSTask() = default;
void stop();
int task() override;
private:
FileSystemImpl& m_fs;
bool m_finish = false;
};
struct FileSystemImpl final : public FileSystem
{
explicit FileSystemImpl(const char* base_path, IAllocator& allocator)
: m_allocator(allocator)
, m_queue(allocator)
, m_finished(allocator)
, m_last_id(0)
, m_semaphore(0, 0xffFF)
, m_bundled(allocator)
, m_bundled_map(allocator)
{
setBasePath(base_path);
loadBundled();
m_task = LUMIX_NEW(m_allocator, FSTask)(*this, m_allocator);
m_task->create("Filesystem", true);
}
~FileSystemImpl()
{
m_task->stop();
m_task->destroy();
LUMIX_DELETE(m_allocator, m_task);
}
void loadBundled() {
#ifdef _WIN32
HRSRC hrsrc = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(102), "TAR");
if (!hrsrc) return;
HGLOBAL hglobal = LoadResource(GetModuleHandle(NULL), hrsrc);
if (!hglobal) return;
const DWORD size = SizeofResource(GetModuleHandle(NULL), hrsrc);
if (size == 0) return;
const void* res_mem = LockResource(hglobal);
if (!res_mem) return;
TCHAR exe_path[MAX_PATH_LENGTH];
GetModuleFileName(NULL, exe_path, MAX_PATH_LENGTH);
m_bundled_last_modified = OS::getLastModified(exe_path);
m_bundled.resize((int)size);
memcpy(m_bundled.begin(), res_mem, m_bundled.byte_size());
InputMemoryStream str(m_bundled.begin(), m_bundled.byte_size());
UnlockResource(res_mem);
TarHeader header;
while (str.getPosition() < str.size()) {
const u8* ptr = (const u8*)str.getData() + str.getPosition();
str.read(&header, sizeof(header));
u32 size;
fromCStringOctal(header.size, sizeof(header.size), &size);
if (header.name[0] && header.typeflag == 0 || header.typeflag == '0') {
Path path(header.name);
m_bundled_map.insert(path.getHash(), ptr);
}
str.setPosition(str.getPosition() + (512 - str.getPosition() % 512) % 512);
str.setPosition(str.getPosition() + size + (512 - size % 512) % 512);
}
#endif
}
bool hasWork() override
{
MT::CriticalSectionLock lock(m_mutex);
return !m_queue.empty();
}
const char* getBasePath() const override { return m_base_path; }
void setBasePath(const char* dir) override
{
PathUtils::normalize(dir, m_base_path.data, lengthOf(m_base_path.data));
if (!endsWith(m_base_path, "/") && !endsWith(m_base_path, "\\")) {
m_base_path << '/';
}
}
bool getContentSync(const Path& path, Array<u8>* content) override {
OS::InputFile file;
StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path.c_str());
if (!file.open(full_path)) {
auto iter = m_bundled_map.find(path.getHash());
if (iter.isValid()) {
const TarHeader* header = (const TarHeader*)iter.value();
u32 size;
fromCStringOctal(header->size, sizeof(header->size), &size);
content->resize(size);
copyMemory(content->begin(), iter.value() + 512, content->byte_size());
return true;
}
return false;
}
content->resize((int)file.size());
if (!file.read(content->begin(), content->byte_size())) {
file.close();
return false;
}
file.close();
return true;
}
AsyncHandle getContent(const Path& file, const ContentCallback& callback) override
{
if (!file.isValid()) return AsyncHandle::invalid();
MT::CriticalSectionLock lock(m_mutex);
AsyncItem& item = m_queue.emplace(m_allocator);
++m_last_id;
if (m_last_id == 0) ++m_last_id;
item.id = m_last_id;
item.path = file.c_str();
item.callback = callback;
m_semaphore.signal();
return AsyncHandle(item.id);
}
void cancel(AsyncHandle async) override
{
MT::CriticalSectionLock lock(m_mutex);
for (AsyncItem& item : m_queue) {
if (item.id == async.value) {
item.flags.set(AsyncItem::Flags::CANCELED);
return;
}
}
for (AsyncItem& item : m_finished) {
if (item.id == async.value) {
item.flags.set(AsyncItem::Flags::CANCELED);
return;
}
}
}
bool open(const char* path, OS::InputFile* file) override
{
ASSERT(file);
StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path);
return file->open(full_path);
}
bool open(const char* path, OS::OutputFile* file) override
{
ASSERT(file);
StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path);
return file->open(full_path);
}
bool copyFile(const char* from, const char* to) override
{
StaticString<MAX_PATH_LENGTH> full_path_from(m_base_path, from);
StaticString<MAX_PATH_LENGTH> full_path_to(m_base_path, to);
if (OS::copyFile(full_path_from, full_path_to)) return true;
auto iter = m_bundled_map.find(crc32(from));
if(!iter.isValid()) return false;
OS::OutputFile file;
if(!file.open(full_path_to)) return false;
u32 size;
TarHeader* header = (TarHeader*)iter.value();
fromCStringOctal(header->size, sizeof(header->size), &size);
const bool res = file.write(iter.value() + 512, size);
file.close();
return res;
}
bool fileExists(const char* path) override
{
StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path);
if (!OS::fileExists(full_path)) {
return (m_bundled_map.find(crc32(path)).isValid());
}
return true;
}
u64 getLastModified(const char* path) override
{
StaticString<MAX_PATH_LENGTH> full_path(m_base_path, path);
const u64 res = OS::getLastModified(full_path);
if (!res && m_bundled_map.find(crc32(path)).isValid()) {
return m_bundled_last_modified;
}
return res;
}
OS::FileIterator* createFileIterator(const char* dir) override
{
StaticString<MAX_PATH_LENGTH> path(m_base_path, dir);
return OS::createFileIterator(path, m_allocator);
}
void updateAsyncTransactions() override
{
PROFILE_FUNCTION();
for(;;) {
m_mutex.enter();
if (m_finished.empty()) {
m_mutex.exit();
break;
}
AsyncItem item = static_cast<AsyncItem&&>(m_finished[0]);
m_finished.erase(0);
m_mutex.exit();
if(!item.isCanceled()) {
item.callback.invoke(item.data.size(), item.data.begin(), !item.isFailed());
}
}
}
IAllocator& m_allocator;
FSTask* m_task;
StaticString<MAX_PATH_LENGTH> m_base_path;
Array<AsyncItem> m_queue;
Array<AsyncItem> m_finished;
Array<u8> m_bundled;
HashMap<u32, const u8*> m_bundled_map;
u64 m_bundled_last_modified;
MT::CriticalSection m_mutex;
MT::Semaphore m_semaphore;
u32 m_last_id;
};
int FSTask::task()
{
while (!m_finish) {
m_fs.m_semaphore.wait();
if (m_finish) break;
StaticString<MAX_PATH_LENGTH> path;
{
MT::CriticalSectionLock lock(m_fs.m_mutex);
ASSERT(!m_fs.m_queue.empty());
path = m_fs.m_queue[0].path;
if (m_fs.m_queue[0].isCanceled()) {
m_fs.m_queue.erase(0);
continue;
}
}
bool success = true;
Array<u8> data(m_fs.m_allocator);
OS::InputFile file;
StaticString<MAX_PATH_LENGTH> full_path(m_fs.m_base_path, path);
if (file.open(full_path)) {
data.resize((int)file.size());
if (!file.read(data.begin(), data.byte_size())) {
success = false;
}
file.close();
}
else {
auto iter = m_fs.m_bundled_map.find(crc32(path));
if (iter.isValid()) {
const TarHeader* header = (const TarHeader*)iter.value();
u32 size;
fromCStringOctal(header->size, sizeof(header->size), &size);
data.resize(size);
copyMemory(data.begin(), iter.value() + 512, data.byte_size());
success = true;
}
else {
success = false;
}
}
{
MT::CriticalSectionLock lock(m_fs.m_mutex);
if (!m_fs.m_queue[0].isCanceled()) {
m_fs.m_finished.emplace(static_cast<AsyncItem&&>(m_fs.m_queue[0]));
m_fs.m_finished.back().data = static_cast<Array<u8>&&>(data);
if(!success) {
m_fs.m_finished.back().flags.set(AsyncItem::Flags::FAILED);
}
m_fs.m_queue.erase(0);
}
}
}
return 0;
}
void FSTask::stop()
{
m_finish = true;
m_fs.m_semaphore.signal();
}
FileSystem* FileSystem::create(const char* base_path, IAllocator& allocator)
{
return LUMIX_NEW(allocator, FileSystemImpl)(base_path, allocator);
}
void FileSystem::destroy(FileSystem* fs)
{
LUMIX_DELETE(static_cast<FileSystemImpl*>(fs)->m_allocator, fs);
}
} // namespace Lumix
| [
"mikulas.florek@gamedev.sk"
] | mikulas.florek@gamedev.sk |
fc05f8608621834c8f82cf368cdfad4a7c98ea70 | 8ce5e9545ee0556df943ce5733aee737024555a2 | /template/template/p9.cpp | b179d9f3e095e72ce9f474735e9c2a15441b40f3 | [] | no_license | irenelee5645/C-_Programs | fb86ba0f4da7ce3ce9cfc4f9a058c4d2533285b9 | c092f05b64bc3789db408bcf8781fc5c479de93d | refs/heads/master | 2020-07-25T04:55:29.785185 | 2019-12-16T00:20:13 | 2019-12-16T00:20:13 | 208,172,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp | //
// p9.cpp
// template
//
// Created by Irene Lee on 6/5/19.
// Copyright © 2019 Irene Lee. All rights reserved.
//
#include <iostream>
using namespace std;
template <typename T>
T* concat(T a[], int n1, T b[],int n2)
{
T *rvalue=new T[n1+n2];
int i=0;
for( i=0;i<n1;i++)
rvalue[i]=a[i];
for( int j=0;j<n2;j++)
rvalue[i+j]=b[j];
return rvalue;
}
int main(){
int x[]={1,2,3};
int y[]={6,7,8,9};
int *p=concat(x,3,y,4);
for(int i=0;i<7;i++)
cout<<p[i]<<" ";
cout<<endl;
char a[]={'l','o','v','e'};
char b[]={'y','o','u'};
char *q=concat(a,4,b,3);
for(int i=0;i<7;i++)
cout<<q[i]<<" ";
cout<<endl;
}
| [
"noreply@github.com"
] | irenelee5645.noreply@github.com |
af7eab081e8ec9c4a82d4aebf4c590e4d5f82f86 | 8b29d172daa0adf10150bff5791723c787bf4874 | /include/FeatureDetect.h | eb615b878adfcc53ed17ddda1b31a0065b4f5e93 | [] | no_license | bazinga-IIIIII/slam | b2b1c55ef926a518f09626e9b552c76be780a2eb | 45b3c77a93ad2ebd841a021ddc10267c97f08c1e | refs/heads/master | 2021-01-21T04:42:28.457018 | 2016-05-24T06:42:49 | 2016-05-24T06:42:49 | 54,100,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,138 | h | /*
* FeatureDetect.h
*
* Created on: Mar 30, 2016
* Author: wei
*/
#ifndef FEATUREDETECT_H_
#define FEATUREDETECT_H_
#include "rgbdframe.h"
using namespace rgbd_tutor;
using namespace cv;
class FeatureDetect {
public:
FeatureDetect();
virtual ~FeatureDetect();
public:
OrbFeatureDetector feature_detector;
OrbDescriptorExtractor feature_extractor;
double good_match_threshold;
int min_inliers;
double keyframe_threshold;
double max_norm;
public:
void Detect_orb(RGBDFrame::Ptr& frame);
void Detect_sift(RGBDFrame::Ptr& frame);
void Detect_surf(RGBDFrame::Ptr& frame);
RESULT_OF_PNP Match_orb(RGBDFrame::Ptr& src, RGBDFrame::Ptr& dst, CAMERA_INTRINSIC_PARAMETERS cam);
RESULT_OF_PNP Match_sift(RGBDFrame::Ptr& src, RGBDFrame::Ptr& dst, CAMERA_INTRINSIC_PARAMETERS cam);
RESULT_OF_PNP Match_surf(RGBDFrame::Ptr& src, RGBDFrame::Ptr& dst, CAMERA_INTRINSIC_PARAMETERS cam);
int Key_Frame_Judge(RESULT_OF_PNP result_of_pnp);
public:
double normofTransform(cv::Mat rvec, cv::Mat tvec) {
return fabs(min(cv::norm(rvec), 2 * M_PI - cv::norm(rvec))) + fabs(cv::norm(tvec));
}
};
#endif /* FEATUREDETECT_H_ */
| [
"liuwei.unique@gmail.com"
] | liuwei.unique@gmail.com |
98edbff16d5af4310e6ce0018e66c872f22d0e20 | cf1911723d07048c4180ace63afbd6ae60727eb0 | /nnnUtilLib/wavemusic.cpp | d5a012d1329c22ec463f620504ea8ef825c93c38 | [] | no_license | tinyan/SystemNNN | 57490606973d95aa1e65d6090957b0e25c5b89f8 | 07e18ded880a0998bf5560c05c112b5520653e19 | refs/heads/master | 2023-05-04T17:30:42.406037 | 2023-04-16T03:38:40 | 2023-04-16T03:38:40 | 7,564,789 | 13 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 28,717 | cpp | //
//
//
#include <windows.h>
#include <stdio.h>
#include <mmSystem.h>
#include <dsound.h>
#include "..\nyanLib\include\commonMacro.h"
#include "..\nyanLib\include\myFile.h"
#include "..\nyanDirectXLib\myDirectSound.h"
#include "oggStreamDecoder.h"
//#include "oggDecoder.h"
#include "mmlControl.h"
#include "waveMusic.h"
//CWaveMusic* CWaveMusic::m_this = NULL;
//HANDLE CWaveMusic::m_hEvent[12];
//BOOL CWaveMusic::m_dataEndFlag = FALSE;
//LPSTR CWaveMusic::m_filename = NULL;
//COggStreamDecoder* CWaveMusic::m_oggStreamDecoder = NULL;
//char CWaveMusic::m_blockBuffer[44100*2*2 *2];
//FILE* CWaveMusic::m_filePointer = NULL;
//int CWaveMusic::m_musicLoopCount = 0;
//int CWaveMusic::m_nokoriDataSize = 0;
//int CWaveMusic::m_waveTime = 0;
//int CWaveMusic::m_waveTime0 = 0;
//int CWaveMusic::m_playFlag0 = 0;
//int CWaveMusic::m_playFlag = 0;
#define STARTBGM_COMMAND 3
#define STOPBGM_COMMAND 4
#define THREADEND_COMMAND 5
#define GETMUSICTIME_COMMAND 7
#define PAUSEBGM_COMMAND 8
#define RESUMEBGM_COMMAND 9
#define CHECKPLAYING_COMMAND 10
#define SETVOLUME_COMMAND 11
#define FADEOUT_COMMAND 12
//#define RETURNEVENT_STATUS 13
#define GETFFT_COMMAND 13
#define FADEVOLUME_COMMAND 14
short convBuffer[4096];
short convBuffer2[4096];
//
// multiThreadOnly
//
CWaveMusic::CWaveMusic(LPVOID myDirectSound, int number)
{
m_myDirectSound = myDirectSound;
m_bufferNumber = number;
m_directSoundBuffer = NULL;
m_directSoundBuffer8 = NULL;
m_filePointer = NULL;
// m_fileHandle = INVALID_HANDLE_VALUE;
m_spectrumCalcuMode = 0;
//create second buffer 2sec
WAVEFORMATEX pcmwf;
ZeroMemory(&pcmwf, sizeof(pcmwf));
pcmwf.cbSize = sizeof(pcmwf);
pcmwf.wBitsPerSample = 16;
pcmwf.wFormatTag = WAVE_FORMAT_PCM;
pcmwf.nChannels = 2;
pcmwf.nSamplesPerSec = 44100;
pcmwf.nBlockAlign = 4;
pcmwf.nAvgBytesPerSec = pcmwf.nSamplesPerSec * pcmwf.nBlockAlign;
DSBUFFERDESC dsbdesc;
ZeroMemory(&dsbdesc, sizeof(dsbdesc));
dsbdesc.dwSize = sizeof(dsbdesc);
dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCSOFTWARE | DSBCAPS_CTRLPOSITIONNOTIFY;
// dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_LOCDEFER | DSBCAPS_CTRLPOSITIONNOTIFY;
dsbdesc.dwBufferBytes = pcmwf.nAvgBytesPerSec * 2;
dsbdesc.lpwfxFormat = &pcmwf;
LPDIRECTSOUND8 directSound8 = (LPDIRECTSOUND8)m_myDirectSound;
LPDIRECTSOUNDBUFFER lp = NULL;
if (directSound8)
{
HRESULT hr = directSound8->CreateSoundBuffer(&dsbdesc, &lp, NULL);
m_directSoundBuffer = lp;
lp->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*)&m_directSoundBuffer8);
}
//refget
// if (hr != DS_OK) return FALSE;
// if (lp == NULL) return FALSE;
m_startVolumeFlag = FALSE;
// char m_blockBuffer[44100*2*2 *2];
// char m_fftBuffer[4096];
// char m_fftBuffer0[44100*2*2 ];
// char m_fftBuffer00[44100*2*2 ];
m_blockBuffer = NULL;
m_fftBuffer = NULL;
m_fftBuffer0 = NULL;
m_fftBuffer00 = NULL;
m_blockBuffer = new char[44100*2*2 *2];
if (number < 2)
{
m_fftBuffer = new char[4096];
m_fftBuffer0 = new char[44100*2*2];
m_fftBuffer00 = new char[44100*2*2];
}
m_convBuffer = NULL;
//#if !defined __USE_XAUDIO2__
m_oggStreamDecoder = NULL;
if (CMyDirectSound::m_xAudioFlag == 0)
{
if (number == 0)
{
m_oggStreamDecoder = new COggStreamDecoder(convBuffer);
}
else if (number == 1)
{
m_oggStreamDecoder = new COggStreamDecoder(convBuffer2);
}
else
{
m_convBuffer = new short[4096];
m_oggStreamDecoder = new COggStreamDecoder(m_convBuffer);
}
}
//#endif
m_mmlControl = new CMMLControl();
for (int i=0;i<16;i++)
{
m_hEvent[i] = NULL;
m_hReturnEvent[i] = NULL;
}
//event
m_hEvent[0] = CreateEvent(NULL,FALSE,FALSE,NULL); //first point
m_hEvent[1] = CreateEvent(NULL,FALSE,FALSE,NULL); //centerpoint
m_hEvent[2] = CreateEvent(NULL,FALSE,FALSE,NULL); //end
m_hEvent[3] = CreateEvent(NULL,FALSE,FALSE,NULL); //start bgm command
m_hEvent[4] = CreateEvent(NULL,FALSE,FALSE,NULL); //stop bgm command
m_hEvent[5] = CreateEvent(NULL,FALSE,FALSE,NULL); //thread end command
m_hEvent[6] = CreateEvent(NULL,FALSE,FALSE,NULL); //bgm stopped
m_hEvent[7] = CreateEvent(NULL,FALSE,FALSE,NULL); //gettime event
m_hEvent[8] = CreateEvent(NULL,FALSE,FALSE,NULL); //pause event
m_hEvent[9] = CreateEvent(NULL,FALSE,FALSE,NULL); //resume event
m_hEvent[10] = CreateEvent(NULL,FALSE,FALSE,NULL); //checkplaying
m_hEvent[11] = CreateEvent(NULL,FALSE,FALSE,NULL); //setvolume
m_hEvent[12] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeout
//m_hEvent[13] = CreateEvent(NULL,FALSE,FALSE,NULL); //return event
m_hEvent[13] = CreateEvent(NULL,FALSE,FALSE,NULL); //getfftbuffer
m_hEvent[14] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeVolume
m_hReturnEvent[3] = CreateEvent(NULL,FALSE,FALSE,NULL); //start bgm command
m_hReturnEvent[4] = CreateEvent(NULL,FALSE,FALSE,NULL); //stop bgm command
m_hReturnEvent[5] = CreateEvent(NULL,FALSE,FALSE,NULL); //thread end command
m_hReturnEvent[6] = CreateEvent(NULL,FALSE,FALSE,NULL); //bgm stopped
m_hReturnEvent[7] = CreateEvent(NULL,FALSE,FALSE,NULL); //gettime event
m_hReturnEvent[8] = CreateEvent(NULL,FALSE,FALSE,NULL); //pause event
m_hReturnEvent[9] = CreateEvent(NULL,FALSE,FALSE,NULL); //resume event
m_hReturnEvent[10] = CreateEvent(NULL,FALSE,FALSE,NULL); //checkplaying
m_hReturnEvent[11] = CreateEvent(NULL,FALSE,FALSE,NULL); //setvolume
m_hReturnEvent[12] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeout
m_hReturnEvent[13] = CreateEvent(NULL,FALSE,FALSE,NULL); //getfftbuffer
m_hReturnEvent[14] = CreateEvent(NULL,FALSE,FALSE,NULL); //fadeVolume
DSBPOSITIONNOTIFY pn[3];
pn[0].dwOffset = 0;
pn[0].hEventNotify = m_hEvent[0];
pn[1].dwOffset = 1*(44100*2*2);
pn[1].hEventNotify = m_hEvent[1];
pn[2].dwOffset = DSBPN_OFFSETSTOP;
pn[2].hEventNotify = m_hEvent[2];
m_directSoundNotify = NULL;
if (m_myDirectSound)
{
LPDIRECTSOUNDNOTIFY pNotify;
HRESULT hr2 = lp->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&pNotify);
m_directSoundNotify = lp;
HRESULT hr3 = pNotify->SetNotificationPositions(3, pn);
}
m_fadeInFlag = FALSE;
m_fadeOutFlag = FALSE;
m_volume = 100;
m_fadeInCount = 0;
m_fadeOutCount = 0;
m_fadeInTime0 = 20;
m_fadeInTime = 20;
m_fadeOutTime0 = 30;
m_fadeOutTime = 30;
ZeroMemory(m_fftBuffer,4096);
ZeroMemory(m_fftBuffer0,40960);
ZeroMemory(m_fftBuffer00,40960);
m_fadeTime = 0;
m_fadeTime0 = 0;
m_fadeCount = 0;
m_fadeVolumeStart = 0;
m_fadeVolumeEnd = 0;
m_fadeVolumeEnd0 = 0;
// m_this = this;
//thread
m_threadHandle = NULL;
if (m_myDirectSound)
{
m_threadHandle = CreateThread(NULL, 0, staticMyThread, (LPVOID)this, 0, &m_threadID);
if (m_threadHandle == NULL)
{
//error
}
}
}
CWaveMusic::~CWaveMusic()
{
End();
}
void CWaveMusic::End(void)
{
//threadが存在すれば停止終了させる
if (m_threadHandle != NULL)
{
SetEvent(m_hEvent[THREADEND_COMMAND]);
WaitForSingleObject(m_threadHandle,5*1000);
// if (m_hEvent[RETURNEVENT_STATUS] != NULL)
// {
// WaitForSingleObject(m_hEvent[RETURNEVENT_STATUS],2*1000);
// }
Sleep(100);
CloseHandle(m_threadHandle);
m_threadHandle = NULL;
}
int i = 0;
for (i=0;i<16;i++)
{
if (m_hEvent[i] != NULL)
{
CloseHandle(m_hEvent[i]);
m_hEvent[i] = NULL;
}
}
for (i=0;i<16;i++)
{
if (m_hReturnEvent[i] != NULL)
{
CloseHandle(m_hReturnEvent[i]);
m_hReturnEvent[i] = NULL;
}
}
if (m_directSoundNotify != NULL)
{
LPDIRECTSOUNDNOTIFY lp = (LPDIRECTSOUNDNOTIFY)m_directSoundNotify;
lp->Release();
m_directSoundNotify = NULL;
}
//release second buffer
if (m_directSoundBuffer8 != NULL)
{
LPDIRECTSOUNDBUFFER8 lp8 = (LPDIRECTSOUNDBUFFER8)m_directSoundBuffer8;
lp8->Release();
m_directSoundBuffer8 = NULL;
}
if (m_directSoundBuffer != NULL)
{
LPDIRECTSOUNDBUFFER lp = (LPDIRECTSOUNDBUFFER)m_directSoundBuffer;
lp->Release();
m_directSoundBuffer = NULL;
}
//用心
if (m_filePointer != NULL)
{
fclose(m_filePointer);
m_filePointer = NULL;
}
// if (m_fileHandle != INVALID_HANDLE_VALUE)
// {
// CloseHandle(m_fileHandle);
// m_fileHandle = INVALID_HANDLE_VALUE;
// }
//
DELETEARRAY(m_convBuffer);
DELETEARRAY(m_fftBuffer00);
DELETEARRAY(m_fftBuffer0);
DELETEARRAY(m_fftBuffer);
DELETEARRAY(m_blockBuffer);
ENDDELETECLASS(m_mmlControl);
ENDDELETECLASS(m_oggStreamDecoder);
}
BOOL CWaveMusic::PlayBGM(LPSTR filename,int loop,BOOL fadeinFlag,int fadeinTime)
{
if (m_threadHandle == NULL) return FALSE;
//stop in playing
StopBGM();
if (m_mmlControl->LoadMML(filename) == FALSE) return FALSE;
//
m_musicLoopCount0 = loop;
m_filename = filename;
if (fadeinFlag)
{
m_fadeInTime0 = fadeinTime;
// char mes[256];
// sprintf(mes,"[PlayWithFadeIn %d]",fadeinTime);
// OutputDebugString(mes);
}
else
{
m_fadeInTime0 = 0;
}
m_fadeInFlag0 = fadeinFlag;
SetEvent(m_hEvent[STARTBGM_COMMAND]);
WaitForSingleObject(m_hReturnEvent[STARTBGM_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[STARTBGM_COMMAND]);
return TRUE;
}
//PlayVoice pack voice
//PlaySound plain wave
BOOL CWaveMusic::StopBGM(BOOL fadeOutFlag,int fadeOutTime)
{
if (m_threadHandle == NULL) return FALSE;
if (fadeOutFlag == FALSE)
{
SetEvent(m_hEvent[STOPBGM_COMMAND]);
WaitForSingleObject(m_hReturnEvent[STOPBGM_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[STOPBGM_COMMAND]);
//if (m_bufferNumber == 1)
//{
OutputDebugString("[stopbgm command]");
//}
m_fadeInFlag = FALSE;
m_fadeFlag = FALSE;
}
else
{
if (fadeOutTime > 0)
{
m_fadeOutTime0 = fadeOutTime;
}
m_fadeOutFlag0 = fadeOutFlag;
SetEvent(m_hEvent[FADEOUT_COMMAND]);
WaitForSingleObject(m_hReturnEvent[FADEOUT_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[FADEOUT_COMMAND]);
OutputDebugString("bgm(FADEOUT) command");
}
return TRUE;
}
void CWaveMusic::SetStartVolume(int vol)
{
m_startVolume = vol;
m_startVolumeFlag = TRUE;
}
void CWaveMusic::SetVolumeRoutine(int vol)
{
if (m_directSoundBuffer != NULL)
{
long vol2 = (vol-100)*20;
if (vol == 0) vol2 = -10000;
if (vol2>0) vol2 = 0;
if (vol2<-10000) vol2 = -10000;
LPDIRECTSOUNDBUFFER8 lp = (LPDIRECTSOUNDBUFFER8)m_directSoundBuffer8;
lp->SetVolume(vol2);
}
}
DWORD WINAPI CWaveMusic::staticMyThread(LPVOID param)
{
CWaveMusic* thisObject = (CWaveMusic*)param;
int rt = thisObject->MyThread(param);
ExitThread(0);
return rt;
}
DWORD WINAPI CWaveMusic::MyThread(LPVOID param)
{
BOOL bgmPlayingFlag = FALSE;
int loopCount = 0;
// LPDIRECTSOUND directSound = (LPDIRECTSOUND)m_myDirectSound;
LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
// static int debugCount = 0;
m_oldTime = timeGetTime();
m_amari = 0;
m_bufferTimeAmari = 0;
while(TRUE)
{
DWORD en = WaitForMultipleObjects(15,m_hEvent,FALSE,100);
switch (en)
{
case WAIT_OBJECT_0: //first
//OutputDebugString("[F]");
case WAIT_OBJECT_0+1: //center
//OutputDebugString("[C]");
//OutputDebugString("[1sec]");
m_waveTime0++;
int n;
n = 0;
if (en == WAIT_OBJECT_0) n = 1;
if (m_dataEndFlag)
{
directSoundBuffer->Stop();
//OutputDebugString("[data end stop]");
m_playFlag0 = FALSE;
}
else
{
if (GetBlock(n) == 0)
{
m_dataEndFlag = TRUE;
}
}
OnWaveTime();
break;
case WAIT_OBJECT_0+2: //end dummy
break;
case WAIT_OBJECT_0+3: //play command
m_waveTime0 = 0;
LPSTR filename;
filename = m_mmlControl->Kaiseki();
if (filename == NULL)
{
m_mmlControl->RestartMML();
filename = m_mmlControl->Kaiseki();
}
#if defined _DEBUG
char mes[256];
wsprintf(mes,"PLAY ch=%d 曲【%s】\n",m_bufferNumber,filename);
OutputDebugString(mes);
#endif
OpenNewFile(filename);
m_dataEndFlag = FALSE;
m_nokoriDataSize = 0;
if (m_filePointer != NULL)
// if (m_fileHandle != INVALID_HANDLE_VALUE)
{
if (GetBlock(0) == 0) m_dataEndFlag = TRUE;//???
}
directSoundBuffer->SetCurrentPosition(0);
m_fadeInFlag = m_fadeInFlag0;
m_fadeInCount = 0;
m_fadeInTime = m_fadeInTime0;
m_fadeOutFlag = FALSE;
m_fadeOutCount = 0;
m_musicLoopCount = m_musicLoopCount0;
if (m_startVolumeFlag)
{
m_volume = m_startVolume;
m_startVolumeFlag = FALSE;
}
//set start volume
if (m_fadeInFlag)
{
//if (m_bufferNumber == 1)
//{
//OutputDebugString("[o]");
//}
SetFadeInVolume();
}
else
{
SetNormalVolume();
}
// ResetEvent(m_hEvent[0]);
// ResetEvent(m_hEvent[1]);
int hr;
hr = directSoundBuffer->Play(0,0,DSBPLAY_LOOPING);
// if FAILED(hr)
// {
// OutputDebugString("DirectSoundBuffer::Play Error");
// }
m_playTime = 0;
m_bufferTime = 0;
m_playFlag0 = TRUE;
m_amari = 0;
m_bufferTimeAmari = 0;
m_oldTime = timeGetTime();
SetEvent(m_hReturnEvent[STARTBGM_COMMAND]);
break;
case WAIT_OBJECT_0+4: //stop command
directSoundBuffer->Stop();
if (m_filePointer != NULL)
{
fclose(m_filePointer);
m_filePointer = NULL;
}
// m_oggStreamDecoder->EndDecode();
// if (m_fileHandle != INVALID_HANDLE_VALUE)
// {
// CloseHandle(m_fileHandle);
// m_fileHandle = INVALID_HANDLE_VALUE;
// }
m_playFlag0 = FALSE;
SetEvent(m_hReturnEvent[STOPBGM_COMMAND]);
break;
case WAIT_OBJECT_0+5: //exit command
if (directSoundBuffer != NULL)
{
directSoundBuffer->Stop();
}
// SetEvent(m_hEvent[RETURNEVENT_STATUS]);
ExitThread(0);
return 0;
break;
case WAIT_OBJECT_0+7: //getmusictime
m_waveTime = m_waveTime0;
SetEvent(m_hReturnEvent[GETMUSICTIME_COMMAND]);
break;
case WAIT_OBJECT_0+8: //pause
directSoundBuffer->Stop();
m_playFlag0 = FALSE;
SetEvent(m_hReturnEvent[PAUSEBGM_COMMAND]);
break;
case WAIT_OBJECT_0+9: //resume
directSoundBuffer->Play(0,0,DSBPLAY_LOOPING);
m_playFlag0 = TRUE;
SetEvent(m_hReturnEvent[RESUMEBGM_COMMAND]);
break;
case WAIT_OBJECT_0+10: //checkplaying
m_playFlag = m_playFlag0;
SetEvent(m_hReturnEvent[CHECKPLAYING_COMMAND]);
break;
case WAIT_OBJECT_0+11: //setvolume
m_volume = m_volume0;
if (m_fadeOutFlag)
{
SetFadeOutVolume();
}
else if (m_fadeInFlag)
{
SetFadeInVolume();
}
else if (m_fadeFlag)
{
SetFadeVolume();
}
else
{
SetNormalVolume();
}
SetEvent(m_hReturnEvent[SETVOLUME_COMMAND]);
break;
case WAIT_OBJECT_0+12: //fadeout
if (m_fadeInFlag)
{
//けいさん
m_fadeOutCount = m_fadeInTime - m_fadeInCount;
if (m_fadeOutCount < 0) m_fadeOutCount = 0;
if (m_fadeOutCount > m_fadeInTime) m_fadeOutCount = m_fadeInTime;
if (m_fadeInTime > 0)
{
m_fadeOutCount *= m_fadeOutTime;
m_fadeOutCount /= m_fadeInTime;
}
// OutputDebugString("特殊");
}
else if (m_fadeOutFlag == FALSE)
{
m_fadeOutCount = 0;
}
else
{
//そのまま?
}
m_fadeOutFlag = TRUE;
m_fadeOutTime = m_fadeOutTime0;
//if (m_bufferNumber == 1)
//{
//OutputDebugString("[x]");
//}
m_fadeInFlag = FALSE;
SetEvent(m_hReturnEvent[FADEOUT_COMMAND]);
break;
case WAIT_OBJECT_0+13: //getfftbuffer
OnWaveTime();
if (m_fftBuffer != NULL)
{
DWORD playPtr;
if (directSoundBuffer->GetCurrentPosition(&playPtr,NULL) == DS_OK)
{
playPtr %= (44100*2*2 * 2);
int n2 = playPtr / (44100*2*2);
int n3 = playPtr % (44100*2*2);
n3 &= ~3;
if (n3>4408*39) n3 = 4408*39;
if (n2 == 0)
{
memcpy(m_fftBuffer,m_fftBuffer00+n3,4096);
}
else
{
memcpy(m_fftBuffer,m_fftBuffer0+n3,4096);
}
}
else
{
if (m_bufferBlockNumber == 1)
{
memcpy(m_fftBuffer,m_fftBuffer00+4408*(m_bufferTime % 40),4096);//4410は4の倍数じゃないのでごまかす
}
else
{
memcpy(m_fftBuffer,m_fftBuffer0+4408*(m_bufferTime % 40),4096);
}
}
}
// memcpy(m_fftBuffer,m_fftBuffer0+4096*(rand() % 10),4096);
SetEvent(m_hReturnEvent[GETFFT_COMMAND]);
break;
case WAIT_OBJECT_0+14://fadevolume
FadeVolumeMain();
SetEvent(m_hReturnEvent[FADEVOLUME_COMMAND]);
break;
case WAIT_TIMEOUT:
OnWaveTime();
break;
}
}
return 0;
}
void CWaveMusic::OnWaveTime(void)
{
int newTime;
newTime = timeGetTime();
int deltaTime = newTime - m_oldTime + m_amari;
int dms;
dms = deltaTime / 100;
m_amari = deltaTime - dms * 100;
int deltaBufferTime = newTime - m_oldTime + m_bufferTimeAmari;
int dms2;
dms2 = deltaBufferTime / 25;
m_bufferTimeAmari = deltaBufferTime - dms2*25;
m_oldTime = newTime;
if (dms<=0) return;
m_playTime += dms;
m_bufferTime += dms2;
//if (m_bufferNumber == 1)
//{
//OutputDebugString(".");
//}
if (m_fadeInFlag)
{
//OutputDebugString("+");
if (m_fadeInCount <= m_fadeInTime)
{
m_fadeInCount += dms;
if (dms>0)
{
// OutputDebugString("+");
}
else
{
// OutputDebugString(",");
}
if (m_fadeInCount >= m_fadeInTime)
{
m_fadeInCount = m_fadeInTime;
m_fadeInFlag = FALSE;
// OutputDebugString("[fadein終了にゃ]");
}
//set volume
if (m_playFlag0)
{
SetFadeInVolume();
}
}
}
else if (m_fadeOutFlag)
{
m_fadeOutCount += dms;
if (dms>0)
{
// OutputDebugString("-");
}
else
{
// OutputDebugString(".");
}
if (m_fadeOutCount >= m_fadeOutTime)
{
//stop bgm
if (m_playFlag0)
{
LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
directSoundBuffer->Stop();
// m_oggStreamDecoder->EndDecode();
// if (m_fileHandle != INVALID_HANDLE_VALUE)
// {
// CloseHandle(m_fileHandle);
// m_fileHandle = INVALID_HANDLE_VALUE;
// }
if (m_filePointer != NULL)
{
fclose(m_filePointer);
m_filePointer = NULL;
}
}
m_playFlag0 = FALSE;
m_fadeOutFlag = FALSE;
//if (m_bufferNumber == 1)
//{
//OutputDebugString("[xx]");
//}
m_fadeInFlag = FALSE;
}
else
{
//set volume
SetFadeOutVolume();
}
}
else if (m_fadeFlag)
{
if (m_fadeCount <= m_fadeTime)
{
m_fadeCount += dms;
if (dms>0)
{
// OutputDebugString("+");
}
else
{
// OutputDebugString(",");
}
if (m_fadeCount >= m_fadeTime)
{
m_fadeCount = m_fadeTime;
m_fadeFlag = FALSE;
// OutputDebugString("[fadein終了にゃ]");
}
//set volume
if (m_playFlag0)
{
SetFadeVolume();
}
}
}
}
//もどり:有効データサイズ
int CWaveMusic::GetBlock(int n)
{
if (m_filePointer == NULL)
// if (m_fileHandle == INVALID_HANDLE_VALUE)
{
ZeroMemory(m_blockBuffer,44100*2*2);
return 0;
}
BOOL f = TRUE;
while(f)
{
//OutputDebugString("[decode]");
int sz = m_oggStreamDecoder->Decode();
if (sz>0)
{
if (m_bufferNumber == 0)
{
memcpy(m_blockBuffer + m_nokoriDataSize,convBuffer,sz);
}
else
{
memcpy(m_blockBuffer + m_nokoriDataSize,convBuffer2,sz);
}
m_nokoriDataSize += sz;
if (m_nokoriDataSize >= 44100*2*2) f = FALSE;
//char mes[256];
//sprintf(mes,"[decode=%d nokori=%d]",sz,m_nokoriDataSize);
//OutputDebugString(mes);
}
else
{
//char mes[256];
//sprintf(mes,"[nokori=%d]",m_nokoriDataSize);
//OutputDebugString(mes);
m_oggStreamDecoder->EndDecode();
BOOL flg = TRUE;
if (m_filePointer != NULL)
{
fclose(m_filePointer);
m_filePointer = NULL;
}
// if (m_fileHandle != INVALID_HANDLE_VALUE)
// {
// CloseHandle(m_fileHandle);
// m_fileHandle = INVALID_HANDLE_VALUE;
// }
//nextdecode?
LPSTR filename;
filename = m_mmlControl->Kaiseki();
if (filename == NULL)
{
if (m_musicLoopCount == 0)
{
m_mmlControl->RestartMML();
filename = m_mmlControl->Kaiseki();
}
else
{
m_musicLoopCount--;
if (m_musicLoopCount > 0)
{
m_mmlControl->RestartMML();
filename = m_mmlControl->Kaiseki();
}
}
}
if (filename == NULL)
{
f = FALSE;
}
else
{
#if defined _DEBUG
OutputDebugString("- 曲【");
OutputDebugString(filename);
OutputDebugString("】");
#endif
OpenNewFile(filename);
}
}
}
int dataSize = m_nokoriDataSize;
if (dataSize > 44100*2*2) dataSize = 44100*2*2;
#if defined _DEBUG
//char mes2[256];
//sprintf(mes2,"[dataSize=%d]",dataSize);
//OutputDebugString(mes2);
#endif
//あきをうめる
if (m_nokoriDataSize < 44100*2*2)
{
ZeroMemory(m_blockBuffer+m_nokoriDataSize,44100*2*2-m_nokoriDataSize);
}
//転送
LPBYTE lpBlockAdd1;
LPBYTE lpBlockAdd2;
DWORD blockSize1;
DWORD blockSize2;
LPDIRECTSOUNDBUFFER8 lpDSBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
int dsize = (44100*2*2*2)/2;
HRESULT hr = lpDSBuffer->Lock(dsize*n,dsize,(LPVOID*)&lpBlockAdd1,&blockSize1,(LPVOID*)&lpBlockAdd2,&blockSize2,0);
//error check
if (blockSize1>0)
{
memcpy(lpBlockAdd1,m_blockBuffer,blockSize1);
}
if (blockSize2>0)
{
memcpy(lpBlockAdd2,m_blockBuffer+blockSize1,blockSize2);
}
lpDSBuffer->Unlock(lpBlockAdd1,blockSize1,lpBlockAdd2,blockSize2);
if (m_spectrumCalcuMode == 1)
{
//4096byte to fft buffer
if (n == 0)
{
memcpy(m_fftBuffer00,m_blockBuffer,4408*40);
}
else
{
memcpy(m_fftBuffer0,m_blockBuffer,4408*40);
}
}
//のこりをずらす
m_nokoriDataSize -= 44100*2*2;
if (m_nokoriDataSize < 0) m_nokoriDataSize = 0;
if (m_nokoriDataSize > 0)
{
memmove(m_blockBuffer,m_blockBuffer+44100*2*2,m_nokoriDataSize);
}
m_bufferBlockNumber = n;
return dataSize;
}
void CWaveMusic::Pause(void)
{
SetEvent(m_hEvent[PAUSEBGM_COMMAND]);
WaitForSingleObject(m_hReturnEvent[PAUSEBGM_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[PAUSEBGM_COMMAND]);
}
void CWaveMusic::Resume(void)
{
//OutputDebugString("resumeCommand");
SetEvent(m_hEvent[RESUMEBGM_COMMAND]);
WaitForSingleObject(m_hReturnEvent[RESUMEBGM_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[RESUMEBGM_COMMAND]);
}
BOOL CWaveMusic::CheckPlaying(void)
{
SetEvent(m_hEvent[CHECKPLAYING_COMMAND]);
WaitForSingleObject(m_hReturnEvent[CHECKPLAYING_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[CHECKPLAYING_COMMAND]);
return m_playFlag;
}
int CWaveMusic::GetMusicTime(void)
{
SetEvent(m_hEvent[GETMUSICTIME_COMMAND]);
WaitForSingleObject(m_hReturnEvent[GETMUSICTIME_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[GETMUSICTIME_COMMAND]);
return m_waveTime;
}
void CWaveMusic::SetNormalVolume(void)
{
LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
int vol = m_volume*100;
m_nowVolume = m_volume;
vol -= 10000;
if (directSoundBuffer != nullptr)
{
directSoundBuffer->SetVolume(vol);
}
//char mes[256];
//sprintf(mes,"[ch=%d VOL=%d]",m_bufferNumber,m_volume);
//OutputDebugString(mes);
}
void CWaveMusic::SetFadeVolume(void)
{
LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
int dv = m_fadeTime;
if (dv<1) dv = 1;
int count = m_fadeCount;
if (m_fadeTime == 0) count = 1;
if (count>dv) count = dv;
int vol = ((m_fadeVolumeEnd - m_fadeVolumeStart)*100 * count) / dv;
vol += m_fadeVolumeStart * 100;
if (vol < 0) vol = 0;
if (vol > 10000) vol = 10000;
vol -= 10000;
if (directSoundBuffer != nullptr)
{
directSoundBuffer->SetVolume(vol);
}
}
void CWaveMusic::SetFadeInVolume(void)
{
LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
int dv = m_fadeInTime;
if (dv<1) dv = 1;
int count = m_fadeInCount;
if (m_fadeInTime == 0) count = 1;
if (count>dv) count = dv;
if (m_fadeInFlag == FALSE)
{
count = dv;
}
m_nowVolume = (m_volume * count) / dv;
int vol = (m_volume*100 * count) / dv;
//char mes[256];
//sprintf(mes,"[ch=%d FadeInVol=%d]",m_bufferNumber,vol/100);
//OutputDebugString(mes);
vol -= 10000;
if (directSoundBuffer != nullptr)
{
directSoundBuffer->SetVolume(vol);
}
}
void CWaveMusic::SetFadeOutVolume(void)
{
LPDIRECTSOUNDBUFFER8 directSoundBuffer = (LPDIRECTSOUNDBUFFER8)(m_directSoundBuffer8);
int dv = m_fadeOutTime;
if (dv<1) dv = 1;
int count = m_fadeOutCount;
if (m_fadeOutTime == 0) count = 1;
if (count>dv) count = dv;
m_nowVolume = (m_volume * count) / dv;
int vol = (m_volume*100 * (dv-count)) / dv;
//char mes[256];
//sprintf(mes,"[ch=%d FadeOutVol=%d]",m_bufferNumber,vol/100);
//OutputDebugString(mes);
vol -= 10000;
if (directSoundBuffer != nullptr)
{
directSoundBuffer->SetVolume(vol);
}
}
BOOL CWaveMusic::OpenNewFile(LPSTR filename)
{
char allfilename[256];
wsprintf(allfilename,"wgq\\%s.wgq",filename);
// memcpy(allfilename,"wgq\\",4);
// int ln = strlen(filename);
// memcpy(allfilename+4,filename,ln);
// memcpy(allfilename+4+ln,".wgq",5);
m_filePointer = CMyFile::Open(allfilename,"rb");
// m_fileHandle = CreateFile(allfilename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (m_filePointer != NULL)
// if (m_fileHandle != INVALID_HANDLE_VALUE)
{
//packtypeでわける
char header[64];
DWORD readed = 0;
//ReadFile(m_fileHandle,header,64,&readed,NULL);
fread(header,sizeof(char),64,m_filePointer);
if (header[57] == '2')
{
char waveheader[20];
// ReadFile(m_fileHandle,waveheader,20,&readed,NULL);
fread(waveheader,sizeof(char),20,m_filePointer);
int* ptr = (int*)waveheader;
ptr += 4;
int skp = *ptr;
// SetFilePointer(m_fileHandle,skp,NULL,FILE_CURRENT);
fpos_t nowPos;
fgetpos(m_filePointer,&nowPos);
nowPos += skp;
fsetpos(m_filePointer,&nowPos);
}
// SetFilePointer(m_fileHandle,64,NULL,FILE_BEGIN);
m_dataEndFlag = FALSE;
m_oggStreamDecoder->StartDecode2(m_filePointer);
// m_oggStreamDecoder->StartDecode2(m_fileHandle);
return TRUE;
}
return FALSE;
}
void CWaveMusic::FadeVolume(int vol,int fadeTime)
{
m_fadeVolumeEnd0 = vol;
m_fadeTime0 = fadeTime;
SetEvent(m_hEvent[FADEVOLUME_COMMAND]);
WaitForSingleObject(m_hReturnEvent[FADEVOLUME_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[FADEVOLUME_COMMAND]);
}
void CWaveMusic::ChangeVolume(int vol)
{
m_volume0 = vol;
// char mes[256];
// sprintf(mes,"[COMMAND SETVOLUME %d]",m_volume);
// OutputDebugString(mes);
SetEvent(m_hEvent[SETVOLUME_COMMAND]);
WaitForSingleObject(m_hReturnEvent[SETVOLUME_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[SETVOLUME_COMMAND]);
// sprintf(mes,"[RETURN SETVOLUME %d]",m_volume);
// OutputDebugString(mes);
}
BOOL CWaveMusic::GetWaveCut(float* wave,int n,int rightChannel)
{
if ((m_threadHandle == NULL) || (m_playFlag0 == FALSE) || (m_spectrumCalcuMode == 0))
{
for (int i=0;i<n;i++)
{
*(wave) = 0.0f;
}
return FALSE;
}
SetEvent(m_hEvent[GETFFT_COMMAND]);
WaitForSingleObject(m_hReturnEvent[GETFFT_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[GETFFT_COMMAND]);
short* ptr = (short*)m_fftBuffer;
ptr += rightChannel;
float dv = 1.0f / 32768.0f;
for (int i=0;i<n;i++)
{
*(wave+i) = ((float)(ptr[2*i])) * dv;
}
return TRUE;
}
BOOL CWaveMusic::GetWavePlainData(int* wave,int block)
{
if ((m_threadHandle == NULL) || (m_playFlag0 == FALSE) || (m_spectrumCalcuMode == 0))
{
for (int i=0;i<block;i++)
{
*(wave) = 0;
}
return FALSE;
}
SetEvent(m_hEvent[GETFFT_COMMAND]);
WaitForSingleObject(m_hReturnEvent[GETFFT_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[GETFFT_COMMAND]);
short* ptr = (short*)m_fftBuffer;
for (int i=0;i<block;i++)
{
*(wave+i) = (int)(ptr[2*i * (1024/block)]);
}
return TRUE;
}
BOOL CWaveMusic::GetFFT(int* fft,int point,int block)
{
if ((m_threadHandle == NULL) || (m_playFlag0 == FALSE) || (m_spectrumCalcuMode == 0))
{
for (int i=0;i<block;i++)
{
*(fft+i) = 0;
}
return FALSE;
}
SetEvent(m_hEvent[GETFFT_COMMAND]);
WaitForSingleObject(m_hReturnEvent[GETFFT_COMMAND],10*1000);
ResetEvent(m_hReturnEvent[GETFFT_COMMAND]);
// int tm = GetMusicTime();
// tm %= 10;
//fft計算は最大1024pointまで
//volumeも考慮すべきか→FFTに専念
//dummy routine stereo 44 16bit
short* ptr = (short*)m_fftBuffer;
// ptr += 44100*2*2/2/10*tm;
for (int i=0;i<block;i++)
{
*(fft+i) = (int)(ptr[2*i * (1024/block)]);
}
// memcpy(buffer,m_fftBuffer,4096);
return TRUE;
}
//handleで同期とらなくてもだいじょうぶかな
void CWaveMusic::StartSpectrum(void)
{
m_spectrumCalcuMode = 1;
}
void CWaveMusic::StopSpectrum(void)
{
m_spectrumCalcuMode = 0;
}
void CWaveMusic::FadeVolumeMain(void)
{
int vol = m_volume;
if (m_fadeInFlag)
{
vol = m_nowVolume;
}
else if (m_fadeOutFlag)
{
vol = m_nowVolume;
}
else
{
//
}
m_fadeVolumeStart = vol;
m_fadeVolumeEnd = m_fadeVolumeEnd0;
m_fadeInFlag = FALSE;
m_fadeOutFlag = FALSE;
m_fadeFlag = TRUE;
m_fadeTime = m_fadeTime0;
m_fadeCount = 0;
m_volume = m_fadeVolumeEnd;
}
| [
"tinyan@mri.biglobe.ne.jp"
] | tinyan@mri.biglobe.ne.jp |
acfcaa2f81ead05b6b9f3d44b8934892a8ba114d | 9ab722e6b9e4ce741cc6f865ba97e0fdc0ad14e5 | /library/ui_base/win/shell.cpp | af883c2997b62ef7fd4ff4bffa44042ad9b3e5cf | [
"MIT"
] | permissive | csjy309450/PuTTY-ng | b892c6474c8ff797f1d0bf555b08351da4fe617b | 0af73729d45d51936810f675d481c47e5588407b | refs/heads/master | 2022-12-24T13:31:22.786842 | 2020-03-08T16:53:51 | 2020-03-08T16:53:51 | 296,880,184 | 1 | 0 | MIT | 2020-09-19T13:54:25 | 2020-09-19T13:54:24 | null | UTF-8 | C++ | false | false | 4,144 | cpp |
#include "shell.h"
#include <shellapi.h>
#include <shlobj.h>
#include "base/file_path.h"
#include "base/native_library.h"
#include "base/win/scoped_comptr.h"
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
namespace ui
{
namespace win
{
namespace
{
const wchar_t kShell32[] = L"shell32.dll";
const char kSHGetPropertyStoreForWindow[] = "SHGetPropertyStoreForWindow";
// Define the type of SHGetPropertyStoreForWindow is SHGPSFW.
typedef DECLSPEC_IMPORT HRESULT (STDAPICALLTYPE *SHGPSFW)(HWND hwnd,
REFIID riid, void** ppv);
}
// Open an item via a shell execute command. Error code checking and casting
// explanation: http://msdn2.microsoft.com/en-us/library/ms647732.aspx
bool OpenItemViaShell(const FilePath& full_path)
{
HINSTANCE h = ::ShellExecuteW(
NULL, NULL, full_path.value().c_str(), NULL,
full_path.DirName().value().c_str(), SW_SHOWNORMAL);
LONG_PTR error = reinterpret_cast<LONG_PTR>(h);
if(error > 32)
{
return true;
}
if((error == SE_ERR_NOASSOC))
{
return OpenItemWithExternalApp(full_path.value());
}
return false;
}
bool OpenItemViaShellNoZoneCheck(const FilePath& full_path)
{
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.fMask = SEE_MASK_NOZONECHECKS | SEE_MASK_FLAG_DDEWAIT;
sei.nShow = SW_SHOWNORMAL;
sei.lpVerb = NULL;
sei.lpFile = full_path.value().c_str();
if(::ShellExecuteExW(&sei))
{
return true;
}
LONG_PTR error = reinterpret_cast<LONG_PTR>(sei.hInstApp);
if((error == SE_ERR_NOASSOC))
{
return OpenItemWithExternalApp(full_path.value());
}
return false;
}
// Show the Windows "Open With" dialog box to ask the user to pick an app to
// open the file with.
bool OpenItemWithExternalApp(const string16& full_path)
{
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.fMask = SEE_MASK_FLAG_DDEWAIT;
sei.nShow = SW_SHOWNORMAL;
sei.lpVerb = L"openas";
sei.lpFile = full_path.c_str();
return (TRUE == ::ShellExecuteExW(&sei));
}
void SetAppIdForWindow(const string16& app_id, HWND hwnd)
{
// This functionality is only available on Win7+.
if(base::win::GetVersion() < base::win::VERSION_WIN7)
{
return;
}
// Load Shell32.dll into memory.
// TODO(brg): Remove this mechanism when the Win7 SDK is available in trunk.
std::wstring shell32_filename(kShell32);
FilePath shell32_filepath(shell32_filename);
base::NativeLibrary shell32_library = base::LoadNativeLibrary(shell32_filepath);
if(!shell32_library)
{
return;
}
// Get the function pointer for SHGetPropertyStoreForWindow.
void* function = base::GetFunctionPointerFromNativeLibrary(
shell32_library,
kSHGetPropertyStoreForWindow);
if(!function)
{
base::UnloadNativeLibrary(shell32_library);
return;
}
// Set the application's name.
base::win::ScopedComPtr<IPropertyStore> pps;
SHGPSFW SHGetPropertyStoreForWindow = static_cast<SHGPSFW>(function);
HRESULT result = SHGetPropertyStoreForWindow(
hwnd, __uuidof(*pps), reinterpret_cast<void**>(pps.Receive()));
if(S_OK == result)
{
base::win::SetAppIdForPropertyStore(pps, app_id.c_str());
}
// Cleanup.
base::UnloadNativeLibrary(shell32_library);
}
} //namespace win
} //namespace ui | [
"wlwlxj@gmail.com@b2b8c3b8-ce47-b78c-ec54-380d862a5473"
] | wlwlxj@gmail.com@b2b8c3b8-ce47-b78c-ec54-380d862a5473 |
cd0bf51f186ccf0db1712b0624e0dbc238afbaed | cbfd948b53734a5a22993dc3e8b82d86d3807548 | /GtkMouse201608311200/Program.cpp | 8ab0f0b8567f4aafbe3678c3924f0041288c3220 | [
"CC0-1.0"
] | permissive | ytyaru/GtkMouse201608311200 | bf33a0604ee4accda3eeffa12f9e3a52efed6b37 | 2f1c957f7698a163165bc431a34d8a3c261419f5 | refs/heads/master | 2020-09-16T21:52:26.739256 | 2016-08-31T22:36:55 | 2016-08-31T22:36:55 | 67,078,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,277 | cpp | #include <gtk-2.0/gtk/gtk.h>
#include <cairo.h>
#include <glib.h>
#include <glib/gprintf.h> // g_sprintf
int g_mouseX = 0;
int g_mouseY = 0;
GtkWidget *drawing_area = NULL;
gboolean Draw(GtkWidget *widget, GdkEventExpose *event, gpointer data)
{
cairo_t *cr;
cr = gdk_cairo_create(widget->window);
cairo_select_font_face (cr, "Serif", CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 24);
gchar posStr[256] = "";
g_sprintf(posStr, "(%d,%d)", (int)g_mouseX, (int)g_mouseY);
cairo_set_source_rgba(cr, 1, 0, 0, 1);
cairo_move_to(cr, (int)g_mouseX, (int)g_mouseY);
cairo_show_text(cr, posStr);
cairo_destroy(cr);
return FALSE;
}
gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
{
g_print ("delete_event\n");
return FALSE; // windowが"delete_event"により破棄される
//return TRUE; // windowが"delete_event"により破棄されない
}
void destroy(GtkWidget *widget, gpointer data)
{
g_print ("destroy\n");
gtk_main_quit ();
}
gint motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
{
g_mouseX = (int)event->x;
g_mouseY = (int)event->y;
g_print("motion_notify_event (%f,%f)\n", event->x, event->y);
gtk_widget_queue_draw_area(
drawing_area,
0,
0,
400,
300);
return TRUE;
}
int main(int argc, char* argv[])
{
gtk_set_locale();
gtk_init(&argc, &argv);
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Mouse Point Draw");
gtk_window_set_default_size(GTK_WINDOW(window), 400, 300);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_signal_connect (GTK_OBJECT (window), "delete_event",
GTK_SIGNAL_FUNC (delete_event), NULL);
gtk_signal_connect (GTK_OBJECT (window), "destroy",
GTK_SIGNAL_FUNC (destroy), NULL);
drawing_area = gtk_drawing_area_new();
gtk_widget_set_size_request (drawing_area, 400, 300);
gtk_container_add(GTK_CONTAINER(window), drawing_area);
g_signal_connect(G_OBJECT(drawing_area), "expose_event", G_CALLBACK(Draw), NULL);
gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
(GtkSignalFunc) motion_notify_event, NULL);
gtk_widget_set_events(drawing_area,
GDK_POINTER_MOTION_MASK
);
gtk_widget_show_all(window);
gtk_main();
return 0;
} | [
"ytyaru@outlook.jp"
] | ytyaru@outlook.jp |
0acff8625d077189314db75bd0be6539d7c10415 | a8fc76656166b3ccd46a0c276febb1a31bb71cc3 | /mgmt.cpp | bc6677df88fe4cd19236285c69d57deb3b0f1e2c | [] | no_license | benwu232/agre | 7693cb0ab89d13e0af92d3b1d49f1ca65cb24437 | b7ea96319893e4bc05ac2e733a4fba3ccf6856c7 | refs/heads/master | 2016-09-06T02:21:19.202674 | 2013-04-20T12:48:55 | 2013-04-20T12:48:55 | 9,562,356 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,248 | cpp | #include <QString>
#include <QMessageBox>
#include <QtDebug>
#include <QDir>
#include "mgmt.h"
#include <qdatetime.h>
extern void WiimoteRun();
CMgmt::CMgmt(QString HomeDir)
{
//CMgmt();
TrIdx = 0;
UserDirName = "user/";
UserDirPath = HomeDir + UserDirName;
UserDir = QDir(UserDirPath);
if (!UserDir.exists())
UserDir.mkpath(UserDir.absolutePath());
TemplateDir = QDir(HomeDir + "template");
if (!TemplateDir.exists())
TemplateDir.mkpath(TemplateDir.absolutePath());
ImageDir = QDir(HomeDir + "image");
if (!ImageDir.exists())
ImageDir.mkpath(ImageDir.absolutePath());
GestureDir = QDir(HomeDir + "gesture");
if (!GestureDir.exists())
GestureDir.mkpath(GestureDir.absolutePath());
}
void CMgmt::GenUserList()
{
//qDebug("into GenUserList");
//if (!UserDir.exists())
//UserDir.mkpath(UserDir.absolutePath());
if (!UserDir.cd(UserDir.absolutePath()))
qDebug("Error: Can't go into UserDir!");
UserList = UserDir.entryList(QDir::Dirs);
// Remove '.' and '..'
UserList.removeAt(0);
UserList.removeAt(0);
//return UserList;
//UserDir =
//qDebug("UserDirName = %s", UserDirName);
//qDebug()<<"UserDirName ="<<UserDirName;
/*
QMessageBox::warning(this, "Message!",
UserDirName,
QMessageBox::Ok,
QMessageBox::Ok);*/
//QMessageBox::information(this,"Quit...","Really Quit?",QMessageBox::Ok,QMessageBox::Cancel);
}
QStringList& CMgmt::GetUserList()
{
return UserList;
}
void CMgmt::AddUser(const QString& UserName)
{
UserDir.cd(UserDir.absolutePath());
UserDir.mkdir(UserName);
UserDir.cd(UserName);
UserDir.mkdir("training");
UserDir.mkdir("recognizing");
UserDir.cdUp();
}
void CMgmt::SetCurUser(QString User)
{
CurUser = User;
}
QString& CMgmt::GetCurUser()
{
return CurUser;
}
QDir& CMgmt::GetUserDir()
{
return UserDir;
}
QDir& CMgmt::GetTemplateDir()
{
return TemplateDir;
}
QDir& CMgmt::GetImageDir()
{
return ImageDir;
}
QDir& CMgmt::GetGestureDir()
{
return GestureDir;
}
void CDataPro::run()
{
WiimoteRun();
}
| [
"benwu232@gmail.com"
] | benwu232@gmail.com |
b8f50d1f3caf751f93ceab44d568def8af44d7e0 | 939543a016b324fc6b273a4c0f3ed462f2a4eb3c | /SampleBaseStation/SampleBaseStation/UdpSocket.cpp | 3474429367d5cae6897b9fe3b555b64174c8918f | [] | no_license | BadgerRoboticMiningTeam/Comms | 51cf15753fbc0581749d1043dabb3c848b564b7f | e80f7d9939eab519b534c808eee74a8f9a3bb1a3 | refs/heads/master | 2021-01-12T17:08:18.909329 | 2017-03-28T14:11:30 | 2017-03-28T14:11:30 | 71,515,535 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,096 | cpp | #include "UdpSocket.hpp"
#include <cstring>
constexpr _socket_t INVALID_SOCKET_HANDLE = ((_socket_t)(-1));
UdpSocket::UdpSocket(int port)
{
this->port = port;
this->isOpen = false;
}
UdpSocket::~UdpSocket()
{
if (this->isOpen)
this->Close();
}
bool UdpSocket::Open()
{
_socket_t sock_handle;
struct sockaddr_in socket_addr;
#ifdef _WIN32
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
return false;
#endif
#ifdef _WIN32
#define OPEN_FAIL() { WSACleanup(); return false; }
#else
#define OPEN_FAIL() { return false; }
#endif
sock_handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock_handle == INVALID_SOCKET_HANDLE)
OPEN_FAIL();
std::memset(&socket_addr, 0, sizeof(struct sockaddr_in));
socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons(port);
if (bind(sock_handle, (struct sockaddr *) &socket_addr, sizeof(struct sockaddr)) != 0)
OPEN_FAIL();
this->handle = sock_handle;
this->isOpen = true;
return true;
#undef OPEN_FAIL
}
void UdpSocket::Close()
{
if (!this->isOpen)
return;
this->isOpen = false;
#ifdef _WIN32
closesocket(handle);
#else
close(handle);
#endif
}
int UdpSocket::Write(const void *buffer, unsigned int size, struct sockaddr *dest_addr)
{
if (buffer == nullptr || dest_addr == nullptr)
return -1;
return sendto(handle, (const char *)buffer, size, 0, dest_addr, sizeof(struct sockaddr));
}
int UdpSocket::Read(void *buffer, unsigned int size, struct sockaddr *source_addr)
{
socklen_t source_addr_size;
if (buffer == nullptr)
return -1;
source_addr_size = sizeof(struct sockaddr);
if (source_addr)
return recvfrom(handle, (char *)buffer, size, 0, source_addr, &source_addr_size);
else
return recvfrom(handle, (char *)buffer, size, 0, nullptr, nullptr);
}
int UdpSocket::GetPort() const
{
return port;
}
bool UdpSocket::IsOpen() const
{
return this->isOpen;
} | [
"wjen@wisc.edu"
] | wjen@wisc.edu |
f3df8ae5374e585b9c217824dddbb9069e0b7839 | 569ae08ce03206bc7afcf8e48b0c74d89525735e | /lib/skia/type_converters.h | 36b98228c9b702e3ce0cf6e70b0a0edbb4f14b5b | [
"BSD-3-Clause"
] | permissive | rzel/mozart | 77ef8bc73697a19a9c2296950fe64ad4fb3d7552 | f97aaccd05f79f115e85ca47330452e485623357 | refs/heads/master | 2021-01-12T14:09:48.789400 | 2016-09-30T23:43:54 | 2016-09-30T23:43:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,613 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef APPS_MOZART_LIB_SKIA_TYPE_CONVERTERS_H_
#define APPS_MOZART_LIB_SKIA_TYPE_CONVERTERS_H_
#include "mojo/public/cpp/bindings/type_converter.h"
#include "mojo/services/geometry/interfaces/geometry.mojom.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkMatrix44.h"
#include "third_party/skia/include/core/SkPoint.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
// The TypeConverter template is defined in the mojo namespace.
namespace mojo {
template <>
struct TypeConverter<SkIPoint, mojo::Point> {
static SkIPoint Convert(const mojo::Point& input);
};
template <>
struct TypeConverter<mojo::Point, SkIPoint> {
static mojo::Point Convert(const SkIPoint& input);
};
template <>
struct TypeConverter<SkPoint, mojo::PointF> {
static SkPoint Convert(const mojo::PointF& input);
};
template <>
struct TypeConverter<mojo::PointF, SkPoint> {
static mojo::PointF Convert(const SkPoint& input);
};
template <>
struct TypeConverter<SkIRect, mojo::Rect> {
static SkIRect Convert(const mojo::Rect& input);
};
template <>
struct TypeConverter<mojo::Rect, SkIRect> {
static mojo::Rect Convert(const SkIRect& input);
};
template <>
struct TypeConverter<SkRect, mojo::RectF> {
static SkRect Convert(const mojo::RectF& input);
};
template <>
struct TypeConverter<mojo::RectF, SkRect> {
static mojo::RectF Convert(const SkRect& input);
};
template <>
struct TypeConverter<SkRRect, mojo::RRectF> {
static SkRRect Convert(const mojo::RRectF& input);
};
template <>
struct TypeConverter<mojo::RRectF, SkRRect> {
static mojo::RRectF Convert(const SkRRect& input);
};
// Note: This transformation is lossy since Transform is 4x4 whereas
// SkMatrix is only 3x3 so we drop the 3rd row and column.
template <>
struct TypeConverter<SkMatrix, mojo::TransformPtr> {
static SkMatrix Convert(const mojo::TransformPtr& input);
};
template <>
struct TypeConverter<mojo::TransformPtr, SkMatrix> {
static mojo::TransformPtr Convert(const SkMatrix& input);
};
// Note: This transformation is lossless.
template <>
struct TypeConverter<SkMatrix44, mojo::TransformPtr> {
static SkMatrix44 Convert(const mojo::TransformPtr& input);
};
template <>
struct TypeConverter<mojo::TransformPtr, SkMatrix44> {
static mojo::TransformPtr Convert(const SkMatrix44& input);
};
} // namespace mojo
#endif // APPS_MOZART_LIB_SKIA_TYPE_CONVERTERS_H_
| [
"jeffbrown@google.com"
] | jeffbrown@google.com |
5bdbc0640801ba3f34800dcc5bc09169d3a72865 | 8ff320e31e8ad83c75c93cd8f71347a38e718e71 | /src/lib/Basic/status.cpp | b3d6bb4a40fb037cd741cd0d1417cc857561493d | [] | no_license | tavu/karakaxa | 60ff6e3e79196f5a3e079c5dc1cc1c430d9ff1be | 03f3df0f22a6a001438589d72c42c34a3f3dd519 | refs/heads/master | 2021-01-01T18:22:49.392260 | 2013-09-04T13:42:02 | 2013-09-04T13:42:02 | 4,357,814 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | cpp | #include"status.h"
#include<QDebug>
Basic::status::status()
{
}
void Basic::status::error(const QString& s)
{
emit errorMessage(s);
}
void Basic::status::logErr(const QString& s)
{
qDebug()<<"[ERR] "<<s;
}
void Basic::status::info(const QString& s)
{
emit infoMessage(s);
}
void Basic::status::logInfo(const QString& s)
{
qDebug()<<"[INF] "<<s;
}
void Basic::status::init()
{
if(_instance==0)
{
_instance=new status();
}
}
void Basic::status::cleanUp()
{
if(_instance!=0)
{
delete _instance;
}
_instance=0;
}
Basic::status* Basic::status::instance()
{
return _instance;
}
Basic::status* Basic::status::_instance=0;
Basic::status* Basic::msg()
{
return status::instance();
}
| [
"tavu@linux-t06i.site"
] | tavu@linux-t06i.site |
6f09f5635be528d9f1e704524abb734a49da8932 | f1aaed1e27416025659317d1f679f7b3b14d654e | /MenuMate/MenuMate/Source/SmartCards/SmartCardAPI.h | 2933cb71dd8198a534fc1cc6187b506f1979dd1f | [] | no_license | radtek/Pos | cee37166f89a7fcac61de9febb3760d12b823ce5 | f117845e83b41d65f18a4635a98659144d66f435 | refs/heads/master | 2020-11-25T19:49:37.755286 | 2016-09-16T14:55:17 | 2016-09-16T14:55:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,528 | h | // ---------------------------------------------------------------------------
#ifndef SmartCardAPIH
#define SmartCardAPIH
#include "MM_DBCore.h"
#include "Contact.h"
#include "SystemEvents.h"
#include "ContactPoints.h"
#include "SmartCardDefs.h"
#include "ManagerSyndCode.h"
#include "SmartCardVer2API.h"
#include "SmartCardVer3API.h"
#include "SmartCardVer5API.h"
#include "SmartCardVer6API.h"
#include "SmartCardException.h"
#include "MMMessageBox.h"
/*
Packet Block on card.
1 ) A block Length includes the CRC for corruption.
2 ) Data in brackets ()is encrypted.
3 ) ... Is padding out to Block Length - 2.
.Card Ver Block.
[Card Ver]
.Customer Info Block.
([Customer Data][SYND CRC]...)[Coruption CRC]
.Customer Points.
([Points][SYND CRC]...)[Coruption CRC]
*/
// ---------------------------------------------------------------------------
class TManagerSmartCard
{
private:
SCARDCONTEXT hCardContext;
SCARDHANDLE hCard;
BYTE VerificationCode[3];
std::map <int, TSyndCode> SyndCodes;
AnsiString fCardReader;
UnicodeString LastErrorMessage;
int LastErrorCode;
TSmartCardGUID TransactionCardGuid;
void StartMonitoringThread();
void StopMonitoringThread();
bool VerifyFactoryCard();
bool VerifySyndicateCard();
void FormatCard();
LONG CardConnect();
void CardDisconnect();
LONG CardReadMainMemory(int BlockStart, int BlockEnd, TMemoryStream &Stream);
LONG CardReadProtectedMemory(TMemoryStream &Stream);
LONG CardReadSecurityMemory(TMemoryStream &Stream);
bool CheckStreamCRC(TMemoryStream *Stream);
// void Encrypt(TMemoryStream &InData);
void Decrypt(TMemoryStream &InData, AnsiString SyndicateCode);
void StreamGetVersion(TSmartCardBlock &CardBlock, TMemoryStream &Stream);
void LoadCardBlock(TSmartCardBlock &CardBlock);
std::auto_ptr <TSmartCard> SmartCard;
bool CardReaderEventsActive;
void Reset();
public:
void Initialise(bool inUserEnabled , std::map <int, TSyndCode> inSyndCodes);
UnicodeString LoadCardGUID();
bool CheckCorrectCard(TSmartCardGUID &SmartCardGUID);
bool ContactInfoMatches(TMMContactInfo &inContactInfo);
void SaveContactInfo(TMMContactInfo &inContactInfo);
void SaveContactPoints(TContactPoints Points);
void SaveCardGUID(TSmartCardGUID &CardGuid);
int GetCardBlockVersion(TSmartCardBlock &CardBlock);
void GetReaders(TStringList *ReaderList);
void SetReader(UnicodeString inReaderName);
bool CardInserted;
bool CardBlank;
bool CardOk;
bool CardUnknown;
bool CardCorrupt;
bool CardSyndicate;
bool CardFactory;
bool CardUnreadable;
bool Registered;
bool Enabled;
void SmartCardRemoved();
void SmartCardInserted();
void FormatCardToNewUser();
bool FormatCardToFactory();
void CardReaderEventsOn();
void CardReaderEventsOff();
// Card Reader Events
TSystemEvents OnCardInserted;
TSystemEvents OnCardRemoved;
// Card Events.
TSystemEvents OnNewCardInserted;
TSystemEvents OnUnknownCardInserted;
TSystemEvents OnUnableToDecodeCard;
TSystemEvents OnCardUpdated;
TSystemEvents OnCardCorrupt;
TSystemEvents OnCardUnreadable;
TSmartCardBlock *GetRestorePoint();
void GetSyndCodeInfo(TSyndCode &SyndCode);
bool GetSyndCodeValid();
TSyndCode GetDefaultSyndCode();
const TSmartCardGUID *GetCardGUID();
void RestoreToRestorePoint(TSmartCardBlock &RestorePoint);
void UpdateViewers();
TManagerSmartCard();
virtual ~TManagerSmartCard();
class TMonitoringThread : public TThread
{
public:
TMonitoringThread(SCARDCONTEXT &hCardContext, UnicodeString infCardReader /* , TCardStatusChangedEvent OnCardStatusChanged */ );
void Cancel();
// Call if terminating the application while running!
UnicodeString ErrorMsg;
private:
SCARDCONTEXT hCardContext;
SCARD_READERSTATE fReaderState;
UnicodeString fCardReader;
void __fastcall Execute();
void __fastcall SetStatus();
};
TMonitoringThread *fMonitoringThread;
/* Used be the Calling programs to "lock in a card".
If the card changes between transaction calls any writes to the card fails.
*/
void BeginTransaction();
void EndTransaction();
GetContactInfo(TMMContactInfo & ContactInfo);
// void __fastcall fMonitoringThreadTerminate(TObject *Sender);
bool UpgradeCardToVersion(int version, int newVersion, std::map <int, TSyndCode> SyndCodes, bool cardUnlocked = false);
int GetCurrentCardVersion();
TSyndCode GetCurrentSyndicateCode();
};
#endif
| [
"ravish.sharma@menumate.com"
] | ravish.sharma@menumate.com |
663e83919d360dad9de88c94859264d7856bfcd0 | 57ed0d32c96ee0e1adf0f1dedfb0a1a782cccd21 | /lib/Target/DCPU16/DCPU16ISelLowering.cpp | 00fc5e877bd150206950e6e35462ace6d3844be8 | [
"NCSA"
] | permissive | Blei/llvm-dcpu16 | 61fe3af6de3fedd10bcb84b68ef5d337ba27627c | d9995cc702576cc489c6ac1bcdbcd3b01f351038 | refs/heads/main | 2021-01-17T16:25:32.596393 | 2012-04-07T18:14:25 | 2012-04-07T18:14:25 | 3,963,745 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,661 | cpp | //===-- DCPU16ISelLowering.cpp - DCPU16 DAG Lowering Implementation ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the DCPU16TargetLowering class.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "dcpu16-lower"
#include "DCPU16ISelLowering.h"
#include "DCPU16.h"
#include "DCPU16MachineFunctionInfo.h"
#include "DCPU16TargetMachine.h"
#include "DCPU16Subtarget.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Intrinsics.h"
#include "llvm/CallingConv.h"
#include "llvm/GlobalVariable.h"
#include "llvm/GlobalAlias.h"
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
typedef enum {
NoHWMult,
HWMultIntr,
HWMultNoIntr
} HWMultUseMode;
static cl::opt<HWMultUseMode>
HWMultMode("dcpu16-hwmult-mode",
cl::desc("Hardware multiplier use mode"),
cl::init(HWMultNoIntr),
cl::values(
clEnumValN(NoHWMult, "no",
"Do not use hardware multiplier"),
clEnumValN(HWMultIntr, "interrupts",
"Assume hardware multiplier can be used inside interrupts"),
clEnumValN(HWMultNoIntr, "use",
"Assume hardware multiplier cannot be used inside interrupts"),
clEnumValEnd));
DCPU16TargetLowering::DCPU16TargetLowering(DCPU16TargetMachine &tm) :
TargetLowering(tm, new TargetLoweringObjectFileELF()),
Subtarget(*tm.getSubtargetImpl()), TM(tm) {
TD = getTargetData();
// Set up the register classes.
addRegisterClass(MVT::i8, DCPU16::GR8RegisterClass);
addRegisterClass(MVT::i16, DCPU16::GR16RegisterClass);
// Compute derived properties from the register classes
computeRegisterProperties();
// Provide all sorts of operation actions
// Division is expensive
setIntDivIsCheap(false);
setStackPointerRegisterToSaveRestore(DCPU16::SPW);
setBooleanContents(ZeroOrOneBooleanContent);
setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
// We have post-incremented loads / stores.
setIndexedLoadAction(ISD::POST_INC, MVT::i8, Legal);
setIndexedLoadAction(ISD::POST_INC, MVT::i16, Legal);
setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Expand);
// We don't have any truncstores
setTruncStoreAction(MVT::i16, MVT::i8, Expand);
setOperationAction(ISD::SRA, MVT::i8, Custom);
setOperationAction(ISD::SHL, MVT::i8, Custom);
setOperationAction(ISD::SRL, MVT::i8, Custom);
setOperationAction(ISD::SRA, MVT::i16, Custom);
setOperationAction(ISD::SHL, MVT::i16, Custom);
setOperationAction(ISD::SRL, MVT::i16, Custom);
setOperationAction(ISD::ROTL, MVT::i8, Expand);
setOperationAction(ISD::ROTR, MVT::i8, Expand);
setOperationAction(ISD::ROTL, MVT::i16, Expand);
setOperationAction(ISD::ROTR, MVT::i16, Expand);
setOperationAction(ISD::GlobalAddress, MVT::i16, Custom);
setOperationAction(ISD::ExternalSymbol, MVT::i16, Custom);
setOperationAction(ISD::BlockAddress, MVT::i16, Custom);
setOperationAction(ISD::BR_JT, MVT::Other, Expand);
setOperationAction(ISD::BR_CC, MVT::i8, Custom);
setOperationAction(ISD::BR_CC, MVT::i16, Custom);
setOperationAction(ISD::BRCOND, MVT::Other, Expand);
setOperationAction(ISD::SETCC, MVT::i8, Custom);
setOperationAction(ISD::SETCC, MVT::i16, Custom);
setOperationAction(ISD::SELECT, MVT::i8, Expand);
setOperationAction(ISD::SELECT, MVT::i16, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i8, Custom);
setOperationAction(ISD::SELECT_CC, MVT::i16, Custom);
setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Custom);
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i8, Expand);
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i16, Expand);
setOperationAction(ISD::CTTZ, MVT::i8, Expand);
setOperationAction(ISD::CTTZ, MVT::i16, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i8, Expand);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Expand);
setOperationAction(ISD::CTLZ, MVT::i8, Expand);
setOperationAction(ISD::CTLZ, MVT::i16, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8, Expand);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Expand);
setOperationAction(ISD::CTPOP, MVT::i8, Expand);
setOperationAction(ISD::CTPOP, MVT::i16, Expand);
setOperationAction(ISD::SHL_PARTS, MVT::i8, Expand);
setOperationAction(ISD::SHL_PARTS, MVT::i16, Expand);
setOperationAction(ISD::SRL_PARTS, MVT::i8, Expand);
setOperationAction(ISD::SRL_PARTS, MVT::i16, Expand);
setOperationAction(ISD::SRA_PARTS, MVT::i8, Expand);
setOperationAction(ISD::SRA_PARTS, MVT::i16, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
// FIXME: Implement efficiently multiplication by a constant
setOperationAction(ISD::MUL, MVT::i8, Expand);
setOperationAction(ISD::MULHS, MVT::i8, Expand);
setOperationAction(ISD::MULHU, MVT::i8, Expand);
setOperationAction(ISD::SMUL_LOHI, MVT::i8, Expand);
setOperationAction(ISD::UMUL_LOHI, MVT::i8, Expand);
setOperationAction(ISD::MUL, MVT::i16, Expand);
setOperationAction(ISD::MULHS, MVT::i16, Expand);
setOperationAction(ISD::MULHU, MVT::i16, Expand);
setOperationAction(ISD::SMUL_LOHI, MVT::i16, Expand);
setOperationAction(ISD::UMUL_LOHI, MVT::i16, Expand);
setOperationAction(ISD::UDIV, MVT::i8, Expand);
setOperationAction(ISD::UDIVREM, MVT::i8, Expand);
setOperationAction(ISD::UREM, MVT::i8, Expand);
setOperationAction(ISD::SDIV, MVT::i8, Expand);
setOperationAction(ISD::SDIVREM, MVT::i8, Expand);
setOperationAction(ISD::SREM, MVT::i8, Expand);
setOperationAction(ISD::UDIV, MVT::i16, Expand);
setOperationAction(ISD::UDIVREM, MVT::i16, Expand);
setOperationAction(ISD::UREM, MVT::i16, Expand);
setOperationAction(ISD::SDIV, MVT::i16, Expand);
setOperationAction(ISD::SDIVREM, MVT::i16, Expand);
setOperationAction(ISD::SREM, MVT::i16, Expand);
// Libcalls names.
if (HWMultMode == HWMultIntr) {
setLibcallName(RTLIB::MUL_I8, "__mulqi3hw");
setLibcallName(RTLIB::MUL_I16, "__mulhi3hw");
} else if (HWMultMode == HWMultNoIntr) {
setLibcallName(RTLIB::MUL_I8, "__mulqi3hw_noint");
setLibcallName(RTLIB::MUL_I16, "__mulhi3hw_noint");
}
setMinFunctionAlignment(1);
setPrefFunctionAlignment(2);
}
SDValue DCPU16TargetLowering::LowerOperation(SDValue Op,
SelectionDAG &DAG) const {
switch (Op.getOpcode()) {
case ISD::SHL: // FALLTHROUGH
case ISD::SRL:
case ISD::SRA: return LowerShifts(Op, DAG);
case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
case ISD::SETCC: return LowerSETCC(Op, DAG);
case ISD::BR_CC: return LowerBR_CC(Op, DAG);
case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
default:
llvm_unreachable("unimplemented operand");
}
}
//===----------------------------------------------------------------------===//
// DCPU16 Inline Assembly Support
//===----------------------------------------------------------------------===//
/// getConstraintType - Given a constraint letter, return the type of
/// constraint it is for this target.
TargetLowering::ConstraintType
DCPU16TargetLowering::getConstraintType(const std::string &Constraint) const {
if (Constraint.size() == 1) {
switch (Constraint[0]) {
case 'r':
return C_RegisterClass;
default:
break;
}
}
return TargetLowering::getConstraintType(Constraint);
}
std::pair<unsigned, const TargetRegisterClass*>
DCPU16TargetLowering::
getRegForInlineAsmConstraint(const std::string &Constraint,
EVT VT) const {
if (Constraint.size() == 1) {
// GCC Constraint Letters
switch (Constraint[0]) {
default: break;
case 'r': // GENERAL_REGS
if (VT == MVT::i8)
return std::make_pair(0U, DCPU16::GR8RegisterClass);
return std::make_pair(0U, DCPU16::GR16RegisterClass);
}
}
return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
}
//===----------------------------------------------------------------------===//
// Calling Convention Implementation
//===----------------------------------------------------------------------===//
#include "DCPU16GenCallingConv.inc"
SDValue
DCPU16TargetLowering::LowerFormalArguments(SDValue Chain,
CallingConv::ID CallConv,
bool isVarArg,
const SmallVectorImpl<ISD::InputArg>
&Ins,
DebugLoc dl,
SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals)
const {
switch (CallConv) {
default:
llvm_unreachable("Unsupported calling convention");
case CallingConv::C:
case CallingConv::Fast:
return LowerCCCArguments(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals);
case CallingConv::DCPU16_INTR:
if (Ins.empty())
return Chain;
report_fatal_error("ISRs cannot have arguments");
}
}
SDValue
DCPU16TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
CallingConv::ID CallConv, bool isVarArg,
bool doesNotRet, bool &isTailCall,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const {
// DCPU16 target does not yet support tail call optimization.
isTailCall = false;
switch (CallConv) {
default:
llvm_unreachable("Unsupported calling convention");
case CallingConv::Fast:
case CallingConv::C:
return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
Outs, OutVals, Ins, dl, DAG, InVals);
case CallingConv::DCPU16_INTR:
report_fatal_error("ISRs cannot be called directly");
}
}
/// LowerCCCArguments - transform physical registers into virtual registers and
/// generate load operations for arguments places on the stack.
// FIXME: struct return stuff
// FIXME: varargs
SDValue
DCPU16TargetLowering::LowerCCCArguments(SDValue Chain,
CallingConv::ID CallConv,
bool isVarArg,
const SmallVectorImpl<ISD::InputArg>
&Ins,
DebugLoc dl,
SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals)
const {
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo *MFI = MF.getFrameInfo();
MachineRegisterInfo &RegInfo = MF.getRegInfo();
// Assign locations to all of the incoming arguments.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
getTargetMachine(), ArgLocs, *DAG.getContext());
CCInfo.AnalyzeFormalArguments(Ins, CC_DCPU16);
assert(!isVarArg && "Varargs not supported yet");
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
CCValAssign &VA = ArgLocs[i];
if (VA.isRegLoc()) {
// Arguments passed in registers
EVT RegVT = VA.getLocVT();
switch (RegVT.getSimpleVT().SimpleTy) {
default:
{
#ifndef NDEBUG
errs() << "LowerFormalArguments Unhandled argument type: "
<< RegVT.getSimpleVT().SimpleTy << "\n";
#endif
llvm_unreachable(0);
}
case MVT::i16:
unsigned VReg =
RegInfo.createVirtualRegister(DCPU16::GR16RegisterClass);
RegInfo.addLiveIn(VA.getLocReg(), VReg);
SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, RegVT);
// If this is an 8-bit value, it is really passed promoted to 16
// bits. Insert an assert[sz]ext to capture this, then truncate to the
// right size.
if (VA.getLocInfo() == CCValAssign::SExt)
ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
DAG.getValueType(VA.getValVT()));
else if (VA.getLocInfo() == CCValAssign::ZExt)
ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
DAG.getValueType(VA.getValVT()));
if (VA.getLocInfo() != CCValAssign::Full)
ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
InVals.push_back(ArgValue);
}
} else {
// Sanity check
assert(VA.isMemLoc());
// Load the argument to a virtual register
unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
if (ObjSize > 2) {
errs() << "LowerFormalArguments Unhandled argument type: "
<< EVT(VA.getLocVT()).getEVTString()
<< "\n";
}
// Create the frame index object for this incoming parameter...
int FI = MFI->CreateFixedObject(ObjSize, VA.getLocMemOffset(), true);
// Create the SelectionDAG nodes corresponding to a load
//from this parameter
SDValue FIN = DAG.getFrameIndex(FI, MVT::i16);
InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
MachinePointerInfo::getFixedStack(FI),
false, false, false, 0));
}
}
return Chain;
}
SDValue
DCPU16TargetLowering::LowerReturn(SDValue Chain,
CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
DebugLoc dl, SelectionDAG &DAG) const {
// CCValAssign - represent the assignment of the return value to a location
SmallVector<CCValAssign, 16> RVLocs;
// ISRs cannot return any value.
if (CallConv == CallingConv::DCPU16_INTR && !Outs.empty())
report_fatal_error("ISRs cannot return any value");
// CCState - Info about the registers and stack slot.
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
getTargetMachine(), RVLocs, *DAG.getContext());
// Analize return values.
CCInfo.AnalyzeReturn(Outs, RetCC_DCPU16);
// If this is the first return lowered for this function, add the regs to the
// liveout set for the function.
if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
for (unsigned i = 0; i != RVLocs.size(); ++i)
if (RVLocs[i].isRegLoc())
DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
}
SDValue Flag;
// Copy the result values into the output registers.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
CCValAssign &VA = RVLocs[i];
assert(VA.isRegLoc() && "Can only return in registers!");
Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
OutVals[i], Flag);
// Guarantee that all emitted copies are stuck together,
// avoiding something bad.
Flag = Chain.getValue(1);
}
unsigned Opc = (CallConv == CallingConv::DCPU16_INTR ?
DCPU16ISD::RETI_FLAG : DCPU16ISD::RET_FLAG);
if (Flag.getNode())
return DAG.getNode(Opc, dl, MVT::Other, Chain, Flag);
// Return Void
return DAG.getNode(Opc, dl, MVT::Other, Chain);
}
/// LowerCCCCallTo - functions arguments are copied from virtual regs to
/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
/// TODO: sret.
SDValue
DCPU16TargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
CallingConv::ID CallConv, bool isVarArg,
bool isTailCall,
const SmallVectorImpl<ISD::OutputArg>
&Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const {
// Analyze operands of the call, assigning locations to each operand.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
getTargetMachine(), ArgLocs, *DAG.getContext());
CCInfo.AnalyzeCallOperands(Outs, CC_DCPU16);
// Get a count of how many bytes are to be pushed on the stack.
unsigned NumBytes = CCInfo.getNextStackOffset();
Chain = DAG.getCALLSEQ_START(Chain ,DAG.getConstant(NumBytes,
getPointerTy(), true));
SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
SmallVector<SDValue, 12> MemOpChains;
SDValue StackPtr;
// Walk the register/memloc assignments, inserting copies/loads.
for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
CCValAssign &VA = ArgLocs[i];
SDValue Arg = OutVals[i];
// Promote the value if needed.
switch (VA.getLocInfo()) {
default: llvm_unreachable("Unknown loc info!");
case CCValAssign::Full: break;
case CCValAssign::SExt:
Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
break;
case CCValAssign::ZExt:
Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
break;
case CCValAssign::AExt:
Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
break;
}
// Arguments that can be passed on register must be kept at RegsToPass
// vector
if (VA.isRegLoc()) {
RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
} else {
assert(VA.isMemLoc());
if (StackPtr.getNode() == 0)
StackPtr = DAG.getCopyFromReg(Chain, dl, DCPU16::SPW, getPointerTy());
SDValue PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(),
StackPtr,
DAG.getIntPtrConstant(VA.getLocMemOffset()));
MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
MachinePointerInfo(),false, false, 0));
}
}
// Transform all store nodes into one single node because all store nodes are
// independent of each other.
if (!MemOpChains.empty())
Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
&MemOpChains[0], MemOpChains.size());
// Build a sequence of copy-to-reg nodes chained together with token chain and
// flag operands which copy the outgoing args into registers. The InFlag in
// necessary since all emitted instructions must be stuck together.
SDValue InFlag;
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
RegsToPass[i].second, InFlag);
InFlag = Chain.getValue(1);
}
// If the callee is a GlobalAddress node (quite common, every direct call is)
// turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
// Likewise ExternalSymbol -> TargetExternalSymbol.
if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i16);
else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i16);
// Returns a chain & a flag for retval copy to use.
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
SmallVector<SDValue, 8> Ops;
Ops.push_back(Chain);
Ops.push_back(Callee);
// Add argument registers to the end of the list so that they are
// known live into the call.
for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
Ops.push_back(DAG.getRegister(RegsToPass[i].first,
RegsToPass[i].second.getValueType()));
if (InFlag.getNode())
Ops.push_back(InFlag);
Chain = DAG.getNode(DCPU16ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
InFlag = Chain.getValue(1);
// Create the CALLSEQ_END node.
Chain = DAG.getCALLSEQ_END(Chain,
DAG.getConstant(NumBytes, getPointerTy(), true),
DAG.getConstant(0, getPointerTy(), true),
InFlag);
InFlag = Chain.getValue(1);
// Handle result values, copying them out of physregs into vregs that we
// return.
return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl,
DAG, InVals);
}
/// LowerCallResult - Lower the result values of a call into the
/// appropriate copies out of appropriate physical registers.
///
SDValue
DCPU16TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins,
DebugLoc dl, SelectionDAG &DAG,
SmallVectorImpl<SDValue> &InVals) const {
// Assign locations to each value returned by this call.
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
getTargetMachine(), RVLocs, *DAG.getContext());
CCInfo.AnalyzeCallResult(Ins, RetCC_DCPU16);
// Copy all of the result registers out of their specified physreg.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
RVLocs[i].getValVT(), InFlag).getValue(1);
InFlag = Chain.getValue(2);
InVals.push_back(Chain.getValue(0));
}
return Chain;
}
SDValue DCPU16TargetLowering::LowerShifts(SDValue Op,
SelectionDAG &DAG) const {
unsigned Opc = Op.getOpcode();
SDNode* N = Op.getNode();
EVT VT = Op.getValueType();
DebugLoc dl = N->getDebugLoc();
// Expand non-constant shifts to loops:
if (!isa<ConstantSDNode>(N->getOperand(1)))
switch (Opc) {
default: llvm_unreachable("Invalid shift opcode!");
case ISD::SHL:
return DAG.getNode(DCPU16ISD::SHL, dl,
VT, N->getOperand(0), N->getOperand(1));
case ISD::SRA:
return DAG.getNode(DCPU16ISD::SRA, dl,
VT, N->getOperand(0), N->getOperand(1));
case ISD::SRL:
return DAG.getNode(DCPU16ISD::SRL, dl,
VT, N->getOperand(0), N->getOperand(1));
}
uint64_t ShiftAmount = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
// Expand the stuff into sequence of shifts.
// FIXME: for some shift amounts this might be done better!
// E.g.: foo >> (8 + N) => sxt(swpb(foo)) >> N
SDValue Victim = N->getOperand(0);
if (Opc == ISD::SRL && ShiftAmount) {
// Emit a special goodness here:
// srl A, 1 => clrc; rrc A
Victim = DAG.getNode(DCPU16ISD::RRC, dl, VT, Victim);
ShiftAmount -= 1;
}
while (ShiftAmount--)
Victim = DAG.getNode((Opc == ISD::SHL ? DCPU16ISD::RLA : DCPU16ISD::RRA),
dl, VT, Victim);
return Victim;
}
SDValue DCPU16TargetLowering::LowerGlobalAddress(SDValue Op,
SelectionDAG &DAG) const {
const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
// Create the TargetGlobalAddress node, folding in the constant offset.
SDValue Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
getPointerTy(), Offset);
return DAG.getNode(DCPU16ISD::Wrapper, Op.getDebugLoc(),
getPointerTy(), Result);
}
SDValue DCPU16TargetLowering::LowerExternalSymbol(SDValue Op,
SelectionDAG &DAG) const {
DebugLoc dl = Op.getDebugLoc();
const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
return DAG.getNode(DCPU16ISD::Wrapper, dl, getPointerTy(), Result);
}
SDValue DCPU16TargetLowering::LowerBlockAddress(SDValue Op,
SelectionDAG &DAG) const {
DebugLoc dl = Op.getDebugLoc();
const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
SDValue Result = DAG.getBlockAddress(BA, getPointerTy(), /*isTarget=*/true);
return DAG.getNode(DCPU16ISD::Wrapper, dl, getPointerTy(), Result);
}
static SDValue EmitCMP(SDValue &LHS, SDValue &RHS, SDValue &TargetCC,
ISD::CondCode CC,
DebugLoc dl, SelectionDAG &DAG) {
// FIXME: Handle bittests someday
assert(!LHS.getValueType().isFloatingPoint() && "We don't handle FP yet");
// FIXME: Handle jump negative someday
DCPU16CC::CondCodes TCC = DCPU16CC::COND_INVALID;
switch (CC) {
default: llvm_unreachable("Invalid integer condition!");
case ISD::SETEQ:
TCC = DCPU16CC::COND_E; // aka COND_Z
// Minor optimization: if LHS is a constant, swap operands, then the
// constant can be folded into comparison.
if (LHS.getOpcode() == ISD::Constant)
std::swap(LHS, RHS);
break;
case ISD::SETNE:
TCC = DCPU16CC::COND_NE; // aka COND_NZ
// Minor optimization: if LHS is a constant, swap operands, then the
// constant can be folded into comparison.
if (LHS.getOpcode() == ISD::Constant)
std::swap(LHS, RHS);
break;
case ISD::SETULE:
std::swap(LHS, RHS); // FALLTHROUGH
case ISD::SETUGE:
// Turn lhs u>= rhs with lhs constant into rhs u< lhs+1, this allows us to
// fold constant into instruction.
if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
LHS = RHS;
RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
TCC = DCPU16CC::COND_LO;
break;
}
TCC = DCPU16CC::COND_HS; // aka COND_C
break;
case ISD::SETUGT:
std::swap(LHS, RHS); // FALLTHROUGH
case ISD::SETULT:
// Turn lhs u< rhs with lhs constant into rhs u>= lhs+1, this allows us to
// fold constant into instruction.
if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
LHS = RHS;
RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
TCC = DCPU16CC::COND_HS;
break;
}
TCC = DCPU16CC::COND_LO; // aka COND_NC
break;
case ISD::SETLE:
std::swap(LHS, RHS); // FALLTHROUGH
case ISD::SETGE:
// Turn lhs >= rhs with lhs constant into rhs < lhs+1, this allows us to
// fold constant into instruction.
if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
LHS = RHS;
RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
TCC = DCPU16CC::COND_L;
break;
}
TCC = DCPU16CC::COND_GE;
break;
case ISD::SETGT:
std::swap(LHS, RHS); // FALLTHROUGH
case ISD::SETLT:
// Turn lhs < rhs with lhs constant into rhs >= lhs+1, this allows us to
// fold constant into instruction.
if (const ConstantSDNode * C = dyn_cast<ConstantSDNode>(LHS)) {
LHS = RHS;
RHS = DAG.getConstant(C->getSExtValue() + 1, C->getValueType(0));
TCC = DCPU16CC::COND_GE;
break;
}
TCC = DCPU16CC::COND_L;
break;
}
TargetCC = DAG.getConstant(TCC, MVT::i8);
return DAG.getNode(DCPU16ISD::CMP, dl, MVT::Glue, LHS, RHS);
}
SDValue DCPU16TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
SDValue Chain = Op.getOperand(0);
ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
SDValue LHS = Op.getOperand(2);
SDValue RHS = Op.getOperand(3);
SDValue Dest = Op.getOperand(4);
DebugLoc dl = Op.getDebugLoc();
SDValue TargetCC;
SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
return DAG.getNode(DCPU16ISD::BR_CC, dl, Op.getValueType(),
Chain, Dest, TargetCC, Flag);
}
SDValue DCPU16TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
DebugLoc dl = Op.getDebugLoc();
// If we are doing an AND and testing against zero, then the CMP
// will not be generated. The AND (or BIT) will generate the condition codes,
// but they are different from CMP.
// FIXME: since we're doing a post-processing, use a pseudoinstr here, so
// lowering & isel wouldn't diverge.
bool andCC = false;
if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
if (RHSC->isNullValue() && LHS.hasOneUse() &&
(LHS.getOpcode() == ISD::AND ||
(LHS.getOpcode() == ISD::TRUNCATE &&
LHS.getOperand(0).getOpcode() == ISD::AND))) {
andCC = true;
}
}
ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
SDValue TargetCC;
SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
// Get the condition codes directly from the status register, if its easy.
// Otherwise a branch will be generated. Note that the AND and BIT
// instructions generate different flags than CMP, the carry bit can be used
// for NE/EQ.
bool Invert = false;
bool Shift = false;
bool Convert = true;
switch (cast<ConstantSDNode>(TargetCC)->getZExtValue()) {
default:
Convert = false;
break;
case DCPU16CC::COND_HS:
// Res = SRW & 1, no processing is required
break;
case DCPU16CC::COND_LO:
// Res = ~(SRW & 1)
Invert = true;
break;
case DCPU16CC::COND_NE:
if (andCC) {
// C = ~Z, thus Res = SRW & 1, no processing is required
} else {
// Res = ~((SRW >> 1) & 1)
Shift = true;
Invert = true;
}
break;
case DCPU16CC::COND_E:
Shift = true;
// C = ~Z for AND instruction, thus we can put Res = ~(SRW & 1), however,
// Res = (SRW >> 1) & 1 is 1 word shorter.
break;
}
EVT VT = Op.getValueType();
SDValue One = DAG.getConstant(1, VT);
if (Convert) {
SDValue SR = DAG.getCopyFromReg(DAG.getEntryNode(), dl, DCPU16::SRW,
MVT::i16, Flag);
if (Shift)
// FIXME: somewhere this is turned into a SRL, lower it MSP specific?
SR = DAG.getNode(ISD::SRA, dl, MVT::i16, SR, One);
SR = DAG.getNode(ISD::AND, dl, MVT::i16, SR, One);
if (Invert)
SR = DAG.getNode(ISD::XOR, dl, MVT::i16, SR, One);
return SR;
} else {
SDValue Zero = DAG.getConstant(0, VT);
SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
SmallVector<SDValue, 4> Ops;
Ops.push_back(One);
Ops.push_back(Zero);
Ops.push_back(TargetCC);
Ops.push_back(Flag);
return DAG.getNode(DCPU16ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
}
}
SDValue DCPU16TargetLowering::LowerSELECT_CC(SDValue Op,
SelectionDAG &DAG) const {
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
SDValue TrueV = Op.getOperand(2);
SDValue FalseV = Op.getOperand(3);
ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
DebugLoc dl = Op.getDebugLoc();
SDValue TargetCC;
SDValue Flag = EmitCMP(LHS, RHS, TargetCC, CC, dl, DAG);
SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
SmallVector<SDValue, 4> Ops;
Ops.push_back(TrueV);
Ops.push_back(FalseV);
Ops.push_back(TargetCC);
Ops.push_back(Flag);
return DAG.getNode(DCPU16ISD::SELECT_CC, dl, VTs, &Ops[0], Ops.size());
}
SDValue DCPU16TargetLowering::LowerSIGN_EXTEND(SDValue Op,
SelectionDAG &DAG) const {
SDValue Val = Op.getOperand(0);
EVT VT = Op.getValueType();
DebugLoc dl = Op.getDebugLoc();
assert(VT == MVT::i16 && "Only support i16 for now!");
return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
DAG.getNode(ISD::ANY_EXTEND, dl, VT, Val),
DAG.getValueType(Val.getValueType()));
}
SDValue
DCPU16TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
DCPU16MachineFunctionInfo *FuncInfo = MF.getInfo<DCPU16MachineFunctionInfo>();
int ReturnAddrIndex = FuncInfo->getRAIndex();
if (ReturnAddrIndex == 0) {
// Set up a frame object for the return address.
uint64_t SlotSize = TD->getPointerSize();
ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
true);
FuncInfo->setRAIndex(ReturnAddrIndex);
}
return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
}
SDValue DCPU16TargetLowering::LowerRETURNADDR(SDValue Op,
SelectionDAG &DAG) const {
MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
MFI->setReturnAddressIsTaken(true);
unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
DebugLoc dl = Op.getDebugLoc();
if (Depth > 0) {
SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
SDValue Offset =
DAG.getConstant(TD->getPointerSize(), MVT::i16);
return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
DAG.getNode(ISD::ADD, dl, getPointerTy(),
FrameAddr, Offset),
MachinePointerInfo(), false, false, false, 0);
}
// Just load the return address.
SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
RetAddrFI, MachinePointerInfo(), false, false, false, 0);
}
SDValue DCPU16TargetLowering::LowerFRAMEADDR(SDValue Op,
SelectionDAG &DAG) const {
MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
MFI->setFrameAddressIsTaken(true);
EVT VT = Op.getValueType();
DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
DCPU16::FPW, VT);
while (Depth--)
FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
MachinePointerInfo(),
false, false, false, 0);
return FrameAddr;
}
/// getPostIndexedAddressParts - returns true by value, base pointer and
/// offset pointer and addressing mode by reference if this node can be
/// combined with a load / store to form a post-indexed load / store.
bool DCPU16TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
SDValue &Base,
SDValue &Offset,
ISD::MemIndexedMode &AM,
SelectionDAG &DAG) const {
LoadSDNode *LD = cast<LoadSDNode>(N);
if (LD->getExtensionType() != ISD::NON_EXTLOAD)
return false;
EVT VT = LD->getMemoryVT();
if (VT != MVT::i8 && VT != MVT::i16)
return false;
if (Op->getOpcode() != ISD::ADD)
return false;
if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
uint64_t RHSC = RHS->getZExtValue();
if ((VT == MVT::i16 && RHSC != 2) ||
(VT == MVT::i8 && RHSC != 1))
return false;
Base = Op->getOperand(0);
Offset = DAG.getConstant(RHSC, VT);
AM = ISD::POST_INC;
return true;
}
return false;
}
const char *DCPU16TargetLowering::getTargetNodeName(unsigned Opcode) const {
switch (Opcode) {
default: return NULL;
case DCPU16ISD::RET_FLAG: return "DCPU16ISD::RET_FLAG";
case DCPU16ISD::RETI_FLAG: return "DCPU16ISD::RETI_FLAG";
case DCPU16ISD::RRA: return "DCPU16ISD::RRA";
case DCPU16ISD::RLA: return "DCPU16ISD::RLA";
case DCPU16ISD::RRC: return "DCPU16ISD::RRC";
case DCPU16ISD::CALL: return "DCPU16ISD::CALL";
case DCPU16ISD::Wrapper: return "DCPU16ISD::Wrapper";
case DCPU16ISD::BR_CC: return "DCPU16ISD::BR_CC";
case DCPU16ISD::CMP: return "DCPU16ISD::CMP";
case DCPU16ISD::SELECT_CC: return "DCPU16ISD::SELECT_CC";
case DCPU16ISD::SHL: return "DCPU16ISD::SHL";
case DCPU16ISD::SRA: return "DCPU16ISD::SRA";
}
}
bool DCPU16TargetLowering::isTruncateFree(Type *Ty1,
Type *Ty2) const {
if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
return false;
return (Ty1->getPrimitiveSizeInBits() > Ty2->getPrimitiveSizeInBits());
}
bool DCPU16TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
if (!VT1.isInteger() || !VT2.isInteger())
return false;
return (VT1.getSizeInBits() > VT2.getSizeInBits());
}
bool DCPU16TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
// DCPU16 implicitly zero-extends 8-bit results in 16-bit registers.
return 0 && Ty1->isIntegerTy(8) && Ty2->isIntegerTy(16);
}
bool DCPU16TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
// DCPU16 implicitly zero-extends 8-bit results in 16-bit registers.
return 0 && VT1 == MVT::i8 && VT2 == MVT::i16;
}
//===----------------------------------------------------------------------===//
// Other Lowering Code
//===----------------------------------------------------------------------===//
MachineBasicBlock*
DCPU16TargetLowering::EmitShiftInstr(MachineInstr *MI,
MachineBasicBlock *BB) const {
MachineFunction *F = BB->getParent();
MachineRegisterInfo &RI = F->getRegInfo();
DebugLoc dl = MI->getDebugLoc();
const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
unsigned Opc;
const TargetRegisterClass * RC;
switch (MI->getOpcode()) {
default: llvm_unreachable("Invalid shift opcode!");
case DCPU16::Shl8:
Opc = DCPU16::SHL8r1;
RC = DCPU16::GR8RegisterClass;
break;
case DCPU16::Shl16:
Opc = DCPU16::SHL16r1;
RC = DCPU16::GR16RegisterClass;
break;
case DCPU16::Sra8:
Opc = DCPU16::SAR8r1;
RC = DCPU16::GR8RegisterClass;
break;
case DCPU16::Sra16:
Opc = DCPU16::SAR16r1;
RC = DCPU16::GR16RegisterClass;
break;
case DCPU16::Srl8:
Opc = DCPU16::SAR8r1c;
RC = DCPU16::GR8RegisterClass;
break;
case DCPU16::Srl16:
Opc = DCPU16::SAR16r1c;
RC = DCPU16::GR16RegisterClass;
break;
}
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineFunction::iterator I = BB;
++I;
// Create loop block
MachineBasicBlock *LoopBB = F->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *RemBB = F->CreateMachineBasicBlock(LLVM_BB);
F->insert(I, LoopBB);
F->insert(I, RemBB);
// Update machine-CFG edges by transferring all successors of the current
// block to the block containing instructions after shift.
RemBB->splice(RemBB->begin(), BB,
llvm::next(MachineBasicBlock::iterator(MI)),
BB->end());
RemBB->transferSuccessorsAndUpdatePHIs(BB);
// Add adges BB => LoopBB => RemBB, BB => RemBB, LoopBB => LoopBB
BB->addSuccessor(LoopBB);
BB->addSuccessor(RemBB);
LoopBB->addSuccessor(RemBB);
LoopBB->addSuccessor(LoopBB);
unsigned ShiftAmtReg = RI.createVirtualRegister(DCPU16::GR8RegisterClass);
unsigned ShiftAmtReg2 = RI.createVirtualRegister(DCPU16::GR8RegisterClass);
unsigned ShiftReg = RI.createVirtualRegister(RC);
unsigned ShiftReg2 = RI.createVirtualRegister(RC);
unsigned ShiftAmtSrcReg = MI->getOperand(2).getReg();
unsigned SrcReg = MI->getOperand(1).getReg();
unsigned DstReg = MI->getOperand(0).getReg();
// BB:
// cmp 0, N
// je RemBB
BuildMI(BB, dl, TII.get(DCPU16::CMP8ri))
.addReg(ShiftAmtSrcReg).addImm(0);
BuildMI(BB, dl, TII.get(DCPU16::JCC))
.addMBB(RemBB)
.addImm(DCPU16CC::COND_E);
// LoopBB:
// ShiftReg = phi [%SrcReg, BB], [%ShiftReg2, LoopBB]
// ShiftAmt = phi [%N, BB], [%ShiftAmt2, LoopBB]
// ShiftReg2 = shift ShiftReg
// ShiftAmt2 = ShiftAmt - 1;
BuildMI(LoopBB, dl, TII.get(DCPU16::PHI), ShiftReg)
.addReg(SrcReg).addMBB(BB)
.addReg(ShiftReg2).addMBB(LoopBB);
BuildMI(LoopBB, dl, TII.get(DCPU16::PHI), ShiftAmtReg)
.addReg(ShiftAmtSrcReg).addMBB(BB)
.addReg(ShiftAmtReg2).addMBB(LoopBB);
BuildMI(LoopBB, dl, TII.get(Opc), ShiftReg2)
.addReg(ShiftReg);
BuildMI(LoopBB, dl, TII.get(DCPU16::SUB8ri), ShiftAmtReg2)
.addReg(ShiftAmtReg).addImm(1);
BuildMI(LoopBB, dl, TII.get(DCPU16::JCC))
.addMBB(LoopBB)
.addImm(DCPU16CC::COND_NE);
// RemBB:
// DestReg = phi [%SrcReg, BB], [%ShiftReg, LoopBB]
BuildMI(*RemBB, RemBB->begin(), dl, TII.get(DCPU16::PHI), DstReg)
.addReg(SrcReg).addMBB(BB)
.addReg(ShiftReg2).addMBB(LoopBB);
MI->eraseFromParent(); // The pseudo instruction is gone now.
return RemBB;
}
MachineBasicBlock*
DCPU16TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
MachineBasicBlock *BB) const {
unsigned Opc = MI->getOpcode();
if (Opc == DCPU16::Shl8 || Opc == DCPU16::Shl16 ||
Opc == DCPU16::Sra8 || Opc == DCPU16::Sra16 ||
Opc == DCPU16::Srl8 || Opc == DCPU16::Srl16)
return EmitShiftInstr(MI, BB);
const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
DebugLoc dl = MI->getDebugLoc();
assert((Opc == DCPU16::Select16 || Opc == DCPU16::Select8) &&
"Unexpected instr type to insert");
// To "insert" a SELECT instruction, we actually have to insert the diamond
// control-flow pattern. The incoming instruction knows the destination vreg
// to set, the condition code register to branch on, the true/false values to
// select between, and a branch opcode to use.
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineFunction::iterator I = BB;
++I;
// thisMBB:
// ...
// TrueVal = ...
// cmpTY ccX, r1, r2
// jCC copy1MBB
// fallthrough --> copy0MBB
MachineBasicBlock *thisMBB = BB;
MachineFunction *F = BB->getParent();
MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
F->insert(I, copy0MBB);
F->insert(I, copy1MBB);
// Update machine-CFG edges by transferring all successors of the current
// block to the new block which will contain the Phi node for the select.
copy1MBB->splice(copy1MBB->begin(), BB,
llvm::next(MachineBasicBlock::iterator(MI)),
BB->end());
copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
// Next, add the true and fallthrough blocks as its successors.
BB->addSuccessor(copy0MBB);
BB->addSuccessor(copy1MBB);
BuildMI(BB, dl, TII.get(DCPU16::JCC))
.addMBB(copy1MBB)
.addImm(MI->getOperand(3).getImm());
// copy0MBB:
// %FalseValue = ...
// # fallthrough to copy1MBB
BB = copy0MBB;
// Update machine-CFG edges
BB->addSuccessor(copy1MBB);
// copy1MBB:
// %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
// ...
BB = copy1MBB;
BuildMI(*BB, BB->begin(), dl, TII.get(DCPU16::PHI),
MI->getOperand(0).getReg())
.addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
.addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
MI->eraseFromParent(); // The pseudo instruction is gone now.
return BB;
}
| [
"imkrasin@gmail.com"
] | imkrasin@gmail.com |
406912235a33cc2dc15f265c6cceb001312713de | f3e6fa8f406e57726b511540a64b4863228833ca | /segmentation/Caffe_Segmentation/src/caffe/layers/image_data_layer.cpp | 214d8192566564c473f585ef106213e70735057a | [
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | USCDataScience/cmu-fg-bg-similarity | acb2336db015d195e8db0eb80f30be080a59d1d8 | d8fc9a53937551f7a052bc2c6f442bcc29ea2615 | refs/heads/master | 2023-09-04T07:30:56.714233 | 2020-04-20T04:40:15 | 2020-04-20T04:40:15 | 255,199,739 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,332 | cpp | #include <fstream> // NOLINT(readability/streams)
#include <iostream> // NOLINT(readability/streams)
#include <string>
#include <utility>
#include <vector>
#include "caffe/data_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/util/io.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/rng.hpp"
namespace caffe {
template <typename Dtype>
ImageDataLayer<Dtype>::~ImageDataLayer<Dtype>() {
this->JoinPrefetchThread();
}
template <typename Dtype>
void ImageDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
const int new_height = this->layer_param_.image_data_param().new_height();
const int new_width = this->layer_param_.image_data_param().new_width();
CHECK((new_height == 0 && new_width == 0) ||
(new_height > 0 && new_width > 0)) << "Current implementation requires "
"new_height and new_width to be set at the same time.";
// Read the file with filenames and labels
const string& source = this->layer_param_.image_data_param().source();
LOG(INFO) << "Opening file " << source;
std::ifstream infile(source.c_str());
string filename;
int label;
while (infile >> filename >> label) {
lines_.push_back(std::make_pair(filename, label));
}
if (this->layer_param_.image_data_param().shuffle()) {
// randomly shuffle data
LOG(INFO) << "Shuffling data";
const unsigned int prefetch_rng_seed = caffe_rng_rand();
prefetch_rng_.reset(new Caffe::RNG(prefetch_rng_seed));
ShuffleImages();
}
LOG(INFO) << "A total of " << lines_.size() << " images.";
lines_id_ = 0;
// Check if we would need to randomly skip a few data points
if (this->layer_param_.image_data_param().rand_skip()) {
unsigned int skip = caffe_rng_rand() %
this->layer_param_.image_data_param().rand_skip();
LOG(INFO) << "Skipping first " << skip << " data points.";
CHECK_GT(lines_.size(), skip) << "Not enough points to skip";
lines_id_ = skip;
}
// Read a data point, and use it to initialize the top blob.
Datum datum;
CHECK(ReadImageToDatum(lines_[lines_id_].first, lines_[lines_id_].second,
new_height, new_width, &datum));
// image
const int crop_size = this->layer_param_.transform_param().crop_size();
const int batch_size = this->layer_param_.image_data_param().batch_size();
if (crop_size > 0) {
(*top)[0]->Reshape(batch_size, datum.channels(), crop_size, crop_size);
this->prefetch_data_.Reshape(batch_size, datum.channels(), crop_size,
crop_size);
} else {
(*top)[0]->Reshape(batch_size, datum.channels(), datum.height(),
datum.width());
this->prefetch_data_.Reshape(batch_size, datum.channels(), datum.height(),
datum.width());
}
LOG(INFO) << "output data size: " << (*top)[0]->num() << ","
<< (*top)[0]->channels() << "," << (*top)[0]->height() << ","
<< (*top)[0]->width();
// label
(*top)[1]->Reshape(batch_size, 1, 1, 1);
this->prefetch_label_.Reshape(batch_size, 1, 1, 1);
// datum size
this->datum_channels_ = datum.channels();
this->datum_height_ = datum.height();
this->datum_width_ = datum.width();
this->datum_size_ = datum.channels() * datum.height() * datum.width();
}
template <typename Dtype>
void ImageDataLayer<Dtype>::ShuffleImages() {
caffe::rng_t* prefetch_rng =
static_cast<caffe::rng_t*>(prefetch_rng_->generator());
shuffle(lines_.begin(), lines_.end(), prefetch_rng);
}
// This function is used to create a thread that prefetches the data.
template <typename Dtype>
void ImageDataLayer<Dtype>::InternalThreadEntry() {
Datum datum;
CHECK(this->prefetch_data_.count());
Dtype* top_data = this->prefetch_data_.mutable_cpu_data();
Dtype* top_label = this->prefetch_label_.mutable_cpu_data();
ImageDataParameter image_data_param = this->layer_param_.image_data_param();
const int batch_size = image_data_param.batch_size();
const int new_height = image_data_param.new_height();
const int new_width = image_data_param.new_width();
// datum scales
const int lines_size = lines_.size();
for (int item_id = 0; item_id < batch_size; ++item_id) {
// get a blob
CHECK_GT(lines_size, lines_id_);
if (!ReadImageToDatum(lines_[lines_id_].first,
lines_[lines_id_].second,
new_height, new_width, &datum)) {
continue;
}
if (this->layer_param_.transform_param().is_seg()) {
this->data_transformer_.Transform(lines_id_, item_id, datum, this->mean_, top_data, /* resetLocData= */ false);
// resetLocData is not required here because this layer is mostly used in training, where new images are
// not being provided at the real time
} else {
// Apply transformations (mirror, crop...) to the data
this->data_transformer_.Transform(item_id, datum, this->mean_, top_data);
}
top_label[item_id] = datum.label().Get(0);
// go to the next iter
lines_id_++;
if (lines_id_ >= lines_size) {
// We have reached the end. Restart from the first.
DLOG(INFO) << "Restarting data prefetching from start.";
lines_id_ = 0;
if (this->layer_param_.image_data_param().shuffle()) {
ShuffleImages();
}
}
}
}
INSTANTIATE_CLASS(ImageDataLayer);
} // namespace caffe
| [
"chris.a.mattmann@jpl.nasa.gov"
] | chris.a.mattmann@jpl.nasa.gov |
14a85419e2473f2ea38bc6223477cc2570726f8a | 0b4dbb9ae315adfa91b047fbc616884276d1a97d | /build-supervisor-Desktop_Qt_6_1_2_MinGW_64_bit-Debug/debug/moc_mainwindow.cpp | 920c2d4d4b79e5ff81e7e8e87c25316e5b32424e | [] | no_license | JoaoPauloPrata/supervisor | fcb28aed0ab6d5ae7527f5ed80b2f8242fb26601 | 618e9ccaa3b6ce8da252d950c06658717e0ef9eb | refs/heads/master | 2023-07-18T13:08:50.655007 | 2021-08-26T15:08:10 | 2021-08-26T15:08:10 | 392,493,109 | 0 | 1 | null | 2021-08-19T02:22:14 | 2021-08-04T00:14:52 | C++ | UTF-8 | C++ | false | false | 3,634 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 68 (Qt 6.1.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../supervisor/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 68
#error "This file was generated using the moc from 6.1.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
const uint offsetsAndSize[6];
char stringdata0[36];
};
#define QT_MOC_LITERAL(ofs, len) \
uint(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs), len
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 10), // "MainWindow"
QT_MOC_LITERAL(11, 23), // "on_button_login_clicked"
QT_MOC_LITERAL(35, 0) // ""
},
"MainWindow\0on_button_login_clicked\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
9, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags, initial metatype offsets
1, 0, 20, 2, 0x08, 0 /* Private */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<MainWindow *>(_o);
(void)_t;
switch (_id) {
case 0: _t->on_button_login_clicked(); break;
default: ;
}
}
(void)_a;
}
const QMetaObject MainWindow::staticMetaObject = { {
QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(),
qt_meta_stringdata_MainWindow.offsetsAndSize,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
qt_incomplete_metaTypeArray<qt_meta_stringdata_MainWindow_t
, QtPrivate::TypeAndForceComplete<void, std::false_type>
>,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<QMetaType *>(_a[0]) = QMetaType();
_id -= 1;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"joaoppcosta@hotmail.com.br"
] | joaoppcosta@hotmail.com.br |
78892b817dce2eda9aa709c78090e1a2c23dd348 | 1331d6a97ca637306c233c07351e9f941ac2832b | /Gateway_Test/src/main.cpp | dc1a5cc2da5f4e802f231488262bb453d18b77f5 | [] | no_license | christiamrojas/OI_MeasureTemperature | c45c5dbe1427450c507717663069a1588d3ad1c1 | d38b611d0b9df18443d038884e92164e332e8f54 | refs/heads/master | 2023-06-12T08:22:51.822581 | 2021-07-05T15:09:21 | 2021-07-05T15:09:21 | 377,896,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,334 | cpp | //-----------------------------------------------
// Libraries
//-----------------------------------------------
#include "Global.h"
#include "Task_ModBus.h"
#include "Task_LoRa.h"
#include "Task_Rtc.h"
#include "Task_Serial.h"
uint8_t Register[64];
uint8_t DevSamp[8];
char* ssid = "";
char* password = "Diacsa4723128";
WiFiServer server(80);
IPAddress ip(192, 168, 10, 10);
IPAddress gateway(192, 168, 10, 1);
IPAddress subnet(255, 255, 255, 0);
Rtc_struct Rtc;
//-----------------------------------------------
// Main Program
//-----------------------------------------------
void setup()
{
Serial.begin(115200);
delay(100);
pinMode(PinLed,OUTPUT);
digitalWrite(PinLed,LOW);
xTaskCreate(ModTcp_Task,"Task_ModbusTcp",20480,NULL,2,NULL);
xTaskCreate(LoRa_Task,"Task_LoRaReception",10240,NULL,2,NULL);
xTaskCreate(Rtc_Task,"Task_Rtc",4096,NULL,2,NULL);
xTaskCreate(Serial_Task,"Task_Serial",4096,NULL,2,NULL);
}
void loop() {}
//------------------------------------------------------------------------
// Modbus TCP Task
//------------------------------------------------------------------------
void ModTcp_Task(void *pvParameters)
{
uint8_t cad[128];
uint8_t b,start,idx;
WiFiClient client;
unsigned long tini;
long t;
start = idx = 0;
ModTcp_WiFiConn(&server,ssid,password,&ip,&gateway,&subnet);
while(1)
{
vTaskDelay(0);
client=server.available();
if(!client) continue;
Serial.println("Client connected");
while(client.connected())
{
vTaskDelay(0);
if(client.available()==0) continue;
b = client.read();
#ifdef Modbus_Debug
Serial.print(b,HEX);
Serial.print(" ");
#endif
if(start==0)
{ tini = millis();
start=1;
}
t = millis()-tini;
if((t<0)||(t>5000))
{
idx=0;
start=0;
}
if( (b==0xff) && (idx==0) ) continue;
cad[idx++] = b;
if(idx<12) continue;
idx = 0;
if(ModTcp_RxTx(&client,cad,Register)==0)
Serial.println("Request: Incorrect format");
else
Serial.println("Request: Responded");
}
Serial.println("Client disconnected");
}
}
//------------------------------------------------------------------------
// Lora task
//------------------------------------------------------------------------
void LoRa_Task(void *pvParameters)
{
int packetLen;
uint8_t data[256],i,d;
DevSamp[1] = DevSamp[3] = 0xff;
for(uint8_t d=0;d<64;d++) Register[d] = 0xff;
LoRa_Init();
LoRa.receive();
while(1)
{
delay(10);
Lora_CheckTxConfig(DevSamp);
packetLen = LoRa.parsePacket();
if(packetLen==0) continue;
if(packetLen!=10){
Serial.println("LoRa: Packet length error");
while(LoRa.available())
d = LoRa.read();
continue;
}
#ifdef Lora_Debug
Serial.print("LoRa Debug: ");
#endif
digitalWrite(PinLed,HIGH);
while(LoRa.available()){
data[i]= LoRa.read();
#ifdef Lora_Debug
Serial.print(data[i],HEX);
Serial.print(" ");
#endif
i++;
}
i=0;
#ifdef Lora_Debug
Serial.println("");
#endif
uint8_t node;
if(Lora_ParseNodePacket(data,Register,&Rtc,&node)==true)
{
Serial.print("Node-");
Serial.print(node);
Serial.print(" ");
Serial.print(Register[node*16]);Serial.print(":");Serial.print(Register[node*16+1]);Serial.print(":");Serial.print(Register[node*16+2]);Serial.print(" ");
Serial.print(Register[node*16+3]);Serial.print("/");Serial.print(Register[node*16+4]);Serial.print("/");Serial.print(Register[node*16+5]);
Serial.print(" - ");
for(uint8_t j=0;j<10;j++)
{
Serial.print(Register[16*node+2*j+6],HEX); Serial.print(Register[16*node+2*j+7],HEX);
Serial.print(" ");
}
Serial.println("");
}
digitalWrite(PinLed,LOW);
}
}
void Rtc_Task(void *pvParameters)
{
Rtc.day = 3;
Rtc.month = 5;
Rtc.year = 21;
Rtc.hour = 1;
Rtc.minute = 20;
Rtc.second = 03;
while(1)
{
vTaskDelay(105);
Rtc_UpdateRtc(&Rtc);
}
}
void Serial_Task(void *pvParameters)
{
uint8_t cadRx[50],i;
while(1)
{
vTaskDelay(100);
if(Serial.available()==0) continue;
while(Serial.available()!=0)
{
if(i>=50) i=0;
cadRx[i++] = Serial.read();
if( (cadRx[i-1]==10) ) break;
}
i=0;
if(Serial_UpdateTime(cadRx, &Rtc)==true) continue;
if(Serial_UpdateDeviceSampling(cadRx,DevSamp)==true) continue;
Serial.println("Unknow command");
}
} | [
"crojas@diacsa.com"
] | crojas@diacsa.com |
b2c484b1bdc99e7ba796228d13fb7de5c8578973 | 6abb92d99ff4218866eafab64390653addbf0d64 | /AtCoder/arc/arc014/c.cpp | 1f64aa8e573b6c3bb1feeda1921dee47f7beff79 | [] | no_license | Johannyjm/c-pro | 38a7b81aff872b2246e5c63d6e49ef3dfb0789ae | 770f2ac419b31bb0d47c4ee93c717c0c98c1d97d | refs/heads/main | 2023-08-18T01:02:23.761499 | 2023-08-07T15:13:58 | 2023-08-07T15:13:58 | 217,938,272 | 0 | 0 | null | 2023-06-25T15:11:37 | 2019-10-28T00:51:09 | C++ | UTF-8 | C++ | false | false | 431 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n;
cin >> n;
string s;
cin >> s;
vector<int> cnt(3, 0);
for(int i = 0; i < n; ++i){
if(s[i] == 'R') ++cnt[0];
else if(s[i] == 'G') ++cnt[1];
else ++cnt[2];
}
cout << cnt[0]%2 + cnt[1]%2 + cnt[2]%2 << endl;
return 0;
}
| [
"meetpastarts@gmail.com"
] | meetpastarts@gmail.com |
493de0a723ac475da7c19be0fe37e1a146d77614 | 55edaf5a0d891beebe11cd36c21bddf3b70f97e4 | /Schul_ubungSeptember23-2019.ino | ba8dc2faea1813e90ca186f752e6b3a27867591b | [] | no_license | toalba/NWES-anti-button-bounce | 8061694a3f2e61b13dd7caf915937133cf6ddb81 | 17d7791b41de64d63f2a74c47d213dc1e2b86963 | refs/heads/master | 2020-08-13T12:41:19.841274 | 2019-10-14T06:44:56 | 2019-10-14T06:44:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,601 | ino | class LED{
private:
int led;
int anzahl;
int intervall = 0;
int counter=0;
long int letzteZeit=0;
bool blinkForEver=false;
public:
LED(int a){
pinMode(a, OUTPUT);
this->led=a;
}
void aus(){
digitalWrite(led, LOW);
resetLED();
}
void ein(){
digitalWrite(led, HIGH);
resetLED();
}
void resetLED(){
blinkForEver = false;
intervall=0;
counter=0;
}
void blinken(int i, int u){
counter=0;
intervall=u;
anzahl=i;
}
void blinken(int i){
intervall=i;
blinkForEver=true;
}
void check(){
if(intervall == 0) return;
if(counter<anzahl*2 || blinkForEver){
if(millis()>=letzteZeit+intervall){
digitalWrite(led, !digitalRead(led));
counter++;
letzteZeit=millis();
}
}
}
};
class CButton{
private:
bool rising = false;
bool falling = false;
bool pressed = false;
int pin;
long int prellZeit=50;
public:
CButton(int pin_, long int prellZeit_){
this->pin = pin_;
pinMode(pin_, INPUT);
this->prellZeit=prellZeit_;
}
boolean ispressed(){
return pressed;
}
boolean isRising(){
return rising;
}
boolean isFalling(){
return falling;
}
void check(){
static bool oldState=false;
bool currentState;
static long int risingTime=0;
static long int fallingTime=0;
static int oldPressed=false;
currentState = digitalRead(pin);
if(!oldState && currentState){
risingTime = millis();
}
if((millis() >= risingTime + prellZeit)&¤tState)
{
pressed = currentState;
}
if(oldState && !currentState){
fallingTime = millis();
}
if((millis() >= fallingTime + prellZeit)&&!currentState)
{
pressed = currentState;
}
oldState = currentState;
rising = pressed && !oldPressed;
falling = !pressed && oldPressed;
oldPressed=pressed;
}
};
LED led1(5);
LED led2(10);
LED led3(13);
CButton but1(2, 500);
void setup() {
Serial.begin(9600);
led1.blinken(2000);
led2.blinken(1000);
}
void loop() {
static int z=0;
static int k=0;
led1.check();
led2.check();
led3.check();
but1.check();
if(but1.isRising()){
led3.blinken(500);
}
if(but1.isRising()) z++;
Serial.print(z);
Serial.print(" | ");
if(but1.isFalling()) k++;
Serial.println(k);
}
| [
"noreply@github.com"
] | toalba.noreply@github.com |
a4cf85022bc103078155da64a732582b7e86ce1a | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /extensions/browser/image_sanitizer.cc | 861355aa8e5daf3b66a2e3ab1cb8ba9e8b06fe12 | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 8,866 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "extensions/browser/image_sanitizer.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/task_runner_util.h"
#include "extensions/browser/extension_file_task_runner.h"
#include "extensions/common/extension_resource_path_normalizer.h"
#include "services/service_manager/public/cpp/connector.h"
#include "ui/gfx/codec/png_codec.h"
namespace extensions {
namespace {
// We don't expect icons and other extension's images to be big.
// We use this limit to prevent from opening too large images.
const int kMaxImageCanvas = 4096 * 4096; // 16MB
// Reads the file in |path| and then deletes it.
// Returns a tuple containing: the file content, whether the read was
// successful, whether the delete was successful.
std::tuple<std::vector<uint8_t>, bool, bool> ReadAndDeleteBinaryFile(
const base::FilePath& path) {
std::vector<uint8_t> contents;
bool read_success = false;
int64_t file_size;
if (base::GetFileSize(path, &file_size)) {
contents.resize(file_size);
read_success =
base::ReadFile(path, reinterpret_cast<char*>(contents.data()),
file_size) == file_size;
}
bool delete_success = base::DeleteFile(path, /*recursive=*/false);
return std::make_tuple(std::move(contents), read_success, delete_success);
}
std::pair<bool, std::vector<unsigned char>> EncodeImage(const SkBitmap& image) {
std::vector<unsigned char> image_data;
bool success = gfx::PNGCodec::EncodeBGRASkBitmap(
image,
/*discard_transparency=*/false, &image_data);
return std::make_pair(success, std::move(image_data));
}
int WriteFile(const base::FilePath& path,
const std::vector<unsigned char>& data) {
return base::WriteFile(path, reinterpret_cast<const char*>(data.data()),
base::checked_cast<int>(data.size()));
}
} // namespace
// static
std::unique_ptr<ImageSanitizer> ImageSanitizer::CreateAndStart(
service_manager::Connector* connector,
const service_manager::ServiceFilter& service_filter,
const base::FilePath& image_dir,
const std::set<base::FilePath>& image_paths,
ImageDecodedCallback image_decoded_callback,
SanitizationDoneCallback done_callback) {
std::unique_ptr<ImageSanitizer> sanitizer(new ImageSanitizer(
image_dir, image_paths, std::move(image_decoded_callback),
std::move(done_callback)));
sanitizer->Start(connector, service_filter);
return sanitizer;
}
ImageSanitizer::ImageSanitizer(
const base::FilePath& image_dir,
const std::set<base::FilePath>& image_relative_paths,
ImageDecodedCallback image_decoded_callback,
SanitizationDoneCallback done_callback)
: image_dir_(image_dir),
image_paths_(image_relative_paths),
image_decoded_callback_(std::move(image_decoded_callback)),
done_callback_(std::move(done_callback)) {}
ImageSanitizer::~ImageSanitizer() = default;
void ImageSanitizer::Start(
service_manager::Connector* connector,
const service_manager::ServiceFilter& service_filter) {
if (image_paths_.empty()) {
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&ImageSanitizer::ReportSuccess,
weak_factory_.GetWeakPtr()));
return;
}
connector->Connect(service_filter,
image_decoder_.BindNewPipeAndPassReceiver());
image_decoder_.set_disconnect_handler(
base::BindOnce(&ImageSanitizer::ReportError, weak_factory_.GetWeakPtr(),
Status::kServiceError, base::FilePath()));
std::set<base::FilePath> normalized_image_paths;
for (const base::FilePath& path : image_paths_) {
// Normalize paths as |image_paths_| can contain duplicates like "icon.png"
// and "./icon.png" to avoid unpacking the same image twice.
base::FilePath normalized_path;
if (path.IsAbsolute() || path.ReferencesParent() ||
!NormalizeExtensionResourcePath(path, &normalized_path)) {
// Report the error asynchronously so the caller stack has chance to
// unwind.
base::SequencedTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&ImageSanitizer::ReportError,
weak_factory_.GetWeakPtr(),
Status::kImagePathError, path));
return;
}
normalized_image_paths.insert(normalized_path);
}
// Update |image_paths_| as some of the path might have been changed by
// normalization.
image_paths_ = std::move(normalized_image_paths);
// Note that we use 2 for loops instead of one to prevent a race and flakyness
// in tests: if |image_paths_| contains 2 paths, a valid one that points to a
// file that does not exist and an invalid one, there is a race that can cause
// either error to be reported (kImagePathError or kFileReadError).
for (const base::FilePath& path : image_paths_) {
base::FilePath full_image_path = image_dir_.Append(path);
base::PostTaskAndReplyWithResult(
extensions::GetExtensionFileTaskRunner().get(), FROM_HERE,
base::BindOnce(&ReadAndDeleteBinaryFile, full_image_path),
base::BindOnce(&ImageSanitizer::ImageFileRead,
weak_factory_.GetWeakPtr(), path));
}
}
void ImageSanitizer::ImageFileRead(
const base::FilePath& image_path,
std::tuple<std::vector<uint8_t>, bool, bool> read_and_delete_result) {
if (!std::get<1>(read_and_delete_result)) {
ReportError(Status::kFileReadError, image_path);
return;
}
if (!std::get<2>(read_and_delete_result)) {
ReportError(Status::kFileDeleteError, image_path);
return;
}
const std::vector<uint8_t>& image_data = std::get<0>(read_and_delete_result);
image_decoder_->DecodeImage(
image_data, data_decoder::mojom::ImageCodec::DEFAULT,
/*shrink_to_fit=*/false, kMaxImageCanvas, gfx::Size(),
base::BindOnce(&ImageSanitizer::ImageDecoded, weak_factory_.GetWeakPtr(),
image_path));
}
void ImageSanitizer::ImageDecoded(const base::FilePath& image_path,
const SkBitmap& decoded_image) {
if (decoded_image.isNull()) {
ReportError(Status::kDecodingError, image_path);
return;
}
if (image_decoded_callback_)
image_decoded_callback_.Run(image_path, decoded_image);
// TODO(mpcomplete): It's lame that we're encoding all images as PNG, even
// though they may originally be .jpg, etc. Figure something out.
// http://code.google.com/p/chromium/issues/detail?id=12459
base::PostTaskAndReplyWithResult(
extensions::GetExtensionFileTaskRunner().get(), FROM_HERE,
base::BindOnce(&EncodeImage, decoded_image),
base::BindOnce(&ImageSanitizer::ImageReencoded,
weak_factory_.GetWeakPtr(), image_path));
}
void ImageSanitizer::ImageReencoded(
const base::FilePath& image_path,
std::pair<bool, std::vector<unsigned char>> result) {
bool success = result.first;
std::vector<unsigned char> image_data = std::move(result.second);
if (!success) {
ReportError(Status::kEncodingError, image_path);
return;
}
int size = base::checked_cast<int>(image_data.size());
base::PostTaskAndReplyWithResult(
extensions::GetExtensionFileTaskRunner().get(), FROM_HERE,
base::BindOnce(&WriteFile, image_dir_.Append(image_path),
std::move(image_data)),
base::BindOnce(&ImageSanitizer::ImageWritten, weak_factory_.GetWeakPtr(),
image_path, size));
}
void ImageSanitizer::ImageWritten(const base::FilePath& image_path,
int expected_size,
int actual_size) {
if (expected_size != actual_size) {
ReportError(Status::kFileWriteError, image_path);
return;
}
// We have finished with this path.
size_t removed_count = image_paths_.erase(image_path);
DCHECK_EQ(1U, removed_count);
if (image_paths_.empty()) {
// This was the last path, we are done.
ReportSuccess();
}
}
void ImageSanitizer::ReportSuccess() {
CleanUp();
std::move(done_callback_).Run(Status::kSuccess, base::FilePath());
}
void ImageSanitizer::ReportError(Status status, const base::FilePath& path) {
CleanUp();
// Prevent any other task from reporting, we want to notify only once.
weak_factory_.InvalidateWeakPtrs();
std::move(done_callback_).Run(status, path);
}
void ImageSanitizer::CleanUp() {
image_decoder_.reset();
// It's important to clear the repeating callback as it may cause a circular
// reference (the callback holds a ref to an object that has a ref to |this|)
// that would cause a leak.
image_decoded_callback_.Reset();
}
} // namespace extensions
| [
"rjkroege@chromium.org"
] | rjkroege@chromium.org |
b3e8432d6c2255ea3b003c12643069d0abf5fc95 | 6d56b944956ef43477ff2399a0d56d96aa507ed7 | /Source/Main/Main/T_pool.cpp | 89d8e3f6cd22f765b4fd0e1bf89ff3a96ebfeb05 | [] | no_license | koe22kr/T_Pool | 7decc0dd6cf52e11350469591a8e716868dd4c51 | d3b5cefb51f7b55147d5cdc5dca71c0115c14e0f | refs/heads/master | 2022-07-25T18:38:35.931987 | 2020-05-20T10:25:59 | 2020-05-20T10:25:59 | 260,671,888 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 20 | cpp | #include "T_pool.h"
| [
"50091267+seoaplo@users.noreply.github.com"
] | 50091267+seoaplo@users.noreply.github.com |
31faf293cc4c27fef775c3a92141c43e30b2a0c7 | ed2be5ce5b5a66f32f36a0b5d2f6b38644efa90a | /test/TestThreadData.cpp | 239411899742aeb07bdb8e85b207d61c48681dbd | [] | no_license | skyformat99/ccinfra | 0784cf7cf1091e40799fc3d3e4916944fc68520a | 07071aa91eb00f5ee2526e6e9c5e989621e01f0f | refs/heads/master | 2021-01-21T00:05:18.692068 | 2016-06-11T04:18:16 | 2016-06-11T04:18:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 894 | cpp | #include "gtest/gtest.h"
#include <ccinfra/sched/ThreadData.h>
namespace
{
struct ThreadInfo
{
static unsigned int getCurrentId()
{
return index;
}
static void setCurrentId(unsigned int id)
{
index = id;
}
const static unsigned int MAX_THREAD_NUM = 2;
private:
static unsigned int index;
};
unsigned int ThreadInfo::index = 0;
}
struct ThreadDataTest : testing::Test
{
protected:
ThreadData<int, ThreadInfo> data;
};
TEST_F(ThreadDataTest, should_write_the_correct_thread_data_when_default_thread_id)
{
*data = 2;
ASSERT_EQ(2, *data);
ASSERT_EQ(2, data[0]);
}
TEST_F(ThreadDataTest, should_write_the_correct_thread_data_when_change_the_current_thread_id)
{
ThreadInfo::setCurrentId(1);
*data = 5;
ASSERT_EQ(5, *data);
ASSERT_EQ(5, data[1]);
}
| [
"wang.bo123@zte.com.cn"
] | wang.bo123@zte.com.cn |
b431cb6f46bc3cc2df0aa3a461f5505695056892 | 4f27d12349224583c24f8941d2561684ee4f48de | /Source/Lastim/Public/Pickups/DroppedPickup.h | b774e87fedad28dae017245653ce3d9c4caf39c9 | [] | no_license | nik3122/SolUnderSiege | 5002af1e182ebb9a8e1616458a8b84e926c5b71b | 167ce5cbafc29ef6ee33f160179eb6ca2b8f39f6 | refs/heads/master | 2023-08-26T03:46:40.485253 | 2021-10-20T06:49:37 | 2021-10-20T06:49:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | h | // Copyright Kyle Taylor Lange
#pragma once
#include "SpecificPickup.h"
#include "DroppedPickup.generated.h"
/**
* CAN PROBABLY DELETE THIS CLASS LATER (parent class has lifespan functionality), BUT LET'S KEEP IT FOR NOW.
*/
UCLASS()
class LASTIM_API ADroppedPickup : public ASpecificPickup
{
GENERATED_BODY()
public:
ADroppedPickup(const FObjectInitializer& ObjectInitializer);
// Currently overridden to set a 60 second lifetime.
//Todo?: maybe only set a life span if there are too many pickups in the level?
//Also todo: check the game mode for a proper life span; we probably don't want to delete pickups on singleplayer/cooperative/etc gametypes.
virtual void BeginPlay() override;
};
| [
"dakatsu@gmail.com"
] | dakatsu@gmail.com |
3e867f84cf3f9caac1bfea889ddacee91860d7f5 | 7c3793fc4a1896efbcce2d9d871dccebf7150e6c | /cpp/1d_to_2d.cpp | 25fcd447576fdd86749d1b6e3eb92afc1e4da846 | [] | no_license | LePtC/Backup | b4d4d95d237936debbce2e139486d083a4fe6e8b | 92272ef0ffc885c1799a1db53c5eb6168ea1eac3 | refs/heads/master | 2023-02-23T10:52:28.175549 | 2023-02-08T14:28:29 | 2023-02-08T14:28:29 | 17,785,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 910 | cpp | #include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> fill_square(vector<vector<int>>& arr) {
int rows = arr.size();
int cols = arr[0].size();
int size = max(rows, cols);
vector<vector<int>> result(size, vector<int>(size, 0));
if (rows < size) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < size; ++j) {
result[j][i] = arr[i][0];
}
}
}
else {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < cols; ++j) {
result[i][j] = arr[0][j];
}
}
}
return result;
}
int main() {
vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}};
auto result = fill_square(arr);
for (const auto& row : result) {
for (const auto& col : row) {
cout << col << " ";
}
cout << endl;
}
return 0;
}
| [
"alileptc@gmail.com"
] | alileptc@gmail.com |
0f6ded5402d78168e28705bc636185c9e402f7d1 | 9eb9796d34f587b02672d98a9e9dbda1cd7af3e6 | /CS/1/C++PrimerPlus/unit4/programList/7strtype1.cpp | fa4aec632f253577808f7a31fdd3f761149ed761 | [] | no_license | eternity6666/university | ef0b902158917d7c70287eaa1207ee28d9d98c20 | 953188832fd174270c43c584fc8c4beda297d95d | refs/heads/master | 2021-07-15T04:16:50.128943 | 2020-05-15T02:34:17 | 2020-05-15T02:34:17 | 141,017,995 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 673 | cpp | // strtype1.cpp -- using the C++ string class
#include <iostream>
#include <string>
#include <cstring>
int main()
{
using namespace std;
char charr1[20];
char charr2[20] = "jaguar";
string str1;
string str2 = "panther";
cout << "Enter a kind of feline: ";
cin >> charr1;
cout << "Enter another kind of feline: ";
cin >> str1;
cout << "Here some felines: \n";
cout << charr1 << " " << charr2 << " "
<< str1 << " " << str2 << " " << endl;
cout << "The third letter in " << charr2 << " is "
<< charr2[2] << endl;
cout << "The third letter in " << str2 << " is "
<< str2[2] << endl;
return 0;
} | [
"eternity6666@qq.com"
] | eternity6666@qq.com |
79492de6b19f35d48a1d5cffc4c81377d89ac360 | c86ef1757d6598225c5162032b41628f221e02e1 | /main.cpp | 2e0b712d878a15d144ece08b2610a46e451a7d8a | [] | no_license | deknapp/mtg-sim | 77f42f83a8fc0569917e6c96a6858c26abdf5230 | 6cb625e8a279ffd8165d45b74bf10240473180c7 | refs/heads/master | 2020-04-03T18:29:35.598213 | 2018-11-09T06:05:56 | 2018-11-09T06:05:56 | 155,486,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | cpp | #include "include/run.h"
#include <cstdlib>
#include <iostream>
int main( int argc, char* argv[] ){
if ( argc == 1 or argc > 2 ){
std::cout << argv[0] << " " << argv[1] << std::endl;
std::cout << argc << std::endl;
std::cout << "Invalid arguments. Requires one text file argument." << std::endl;
return 0;
}
run( argv[1] );
return 1;
}
| [
"nathaniel.knapp@gmail.com"
] | nathaniel.knapp@gmail.com |
4bcc12311816942f3f3339421aa79ed7d2bf8315 | cb0963eeedf5d15a5364891e2690eda75dcdba8b | /Source/DigitViewer2/DigitReaders/BasicTextReader.h | 25c35e7b89345fd65dddcd8399370d1a45511ad5 | [
"BSD-3-Clause"
] | permissive | Mysticial/DigitViewer | ed17e786f6850555a4cd384a153c192e021d82b1 | 369d4bd94729712fb770100a9bec904071fd9bf9 | refs/heads/master | 2021-05-02T08:35:14.078443 | 2021-03-25T05:10:27 | 2021-03-25T05:10:27 | 13,462,178 | 45 | 13 | BSD-3-Clause | 2023-09-05T05:19:08 | 2013-10-10T04:42:48 | C++ | UTF-8 | C++ | false | false | 3,754 | h | /* BasicTextReader.h
*
* Author : Alexander J. Yee
* Date Created : 01/14/2018
* Last Modified : 03/20/2018
*
* This reader uses raw (unbuffered) I/O.
*
* The advantages of raw disk I/O are:
* - Faster for bulk transfers because it eliminates the OS memcpy().
* - Saves memory since the OS doesn't need to allocate a buffer.
* - Prevents the OS from doing any stupid caching that may lead to
* the pagefile Thrash of Death.
*
* The disadvantage is that the buffer needs to be larger and must satisfy
* stricter alignment requirements. It is also more difficult to implement.
*
*/
#pragma once
#ifndef ydv_DigitViewer_BasicTextReader_H
#define ydv_DigitViewer_BasicTextReader_H
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Dependencies
#include <mutex>
#include "PublicLibs/SystemLibs/FileIO/RawFile/RawFile.h"
#include "BasicDigitReader.h"
namespace DigitViewer2{
using namespace ymp;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class BasicTextReader : public BasicDigitReader{
public:
static const upL_t FILE_ALIGNMENT = FileIO::DEFAULT_FILE_ALIGNMENT;
BasicTextReader(const std::string& path, char radix = 0);
virtual std::string first_digits () override;
virtual uiL_t stream_end () const override{ return m_total_digits; }
virtual bool range_is_available (uiL_t offset, uiL_t digits) override;
virtual upL_t recommend_buffer_size (uiL_t digits, upL_t limit) const override;
virtual void load_stats(
DigitStats& stats,
uiL_t offset, uiL_t digits,
const AlignedBufferC<BUFFER_ALIGNMENT>& buffer,
BasicParallelizer& parallelizer, upL_t tds
) override;
virtual void load_digits(
char* output,
DigitStats* stats,
uiL_t offset, upL_t digits,
const AlignedBufferC<BUFFER_ALIGNMENT>& buffer,
BasicParallelizer& parallelizer, upL_t tds
) override;
private:
static const upL_t CACHE_BLOCK = 8192;
void process(
DigitStats* stats, char* output, const char* txt_digits, upL_t digits
) const;
void process(
DigitStats* stats, char* output, const char* txt_digits, upL_t digits,
BasicParallelizer& parallelizer, upL_t tds
) const;
class Action_process;
private:
using ConvertFunction = bool (*)(char* raw_digits, const char* buffer, upL_t digits);
std::mutex m_lock;
FileIO::RawFile m_file; // File handle
ConvertFunction m_fp_convert;
ufL_t m_data_offset; // Offset in the file of the first digit after the decimal place.
ufL_t m_total_digits; // Digits after the decimal place.
std::string m_first_digits;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
}
#endif
| [
"a-yee@u.northwestern.edu"
] | a-yee@u.northwestern.edu |
5dfecab5457f081b9618bf420bebb38f58e44b05 | cfceffb372a31d6bec816857d4310c4224543995 | /Übung 8/src/math/Matrix.cpp | 314aef933722a4ac5145f1daa5a4c2716859cd0c | [] | no_license | themightyoarfish/intro-to-c | f7ad417f3b30413caace0324430577f8d297b106 | 27bdd1f69a7f6919c780a325c311cc6776736ca6 | refs/heads/master | 2021-01-10T02:28:47.859425 | 2015-01-18T12:05:56 | 2015-01-18T12:05:56 | 47,020,894 | 0 | 1 | null | 2018-11-14T17:06:29 | 2015-11-28T11:31:28 | C++ | UTF-8 | C++ | false | false | 11,658 | cpp | /*
* Matrix.hpp
*
* @date 26.08.2008
* @author Thomas Wiemann (twiemann@uos.de)
*/
#include "Matrix.hpp"
namespace asteroids
{
Matrix::Matrix()
{
for(int i = 0; i < 16; i++) m[i] = 0;
m[0] = m[5] = m[10] = m[15] = 1;
}
Matrix::Matrix(float* matrix)
{
for(int i = 0; i < 16; i++) m[i] = matrix[i];
}
Matrix::Matrix(const Matrix& other)
{
for(int i = 0; i < 16; i++) m[i] = other[i];
}
Matrix::Matrix(Vertex axis, float angle)
{
// Check for gimbal lock
if(fabs(angle) < 0.0001)
{
bool invert_z = axis.z < 0;
//Angle to yz-plane
float pitch = atan2(axis.z, axis.x) - M_PI_2;
if(pitch < 0.0f) pitch += 2.0f * M_PI;
if(axis.x == 0.0f && axis.z == 0.0) pitch = 0.0f;
//Transform axis into yz-plane
axis.x = axis.x * cos(pitch) + axis.z * sin(pitch);
axis.z = -axis.x * sin(pitch) + axis.z * cos(pitch);
//Angle to y-Axis
float yaw = atan2(axis.y, axis.z);
if(yaw < 0) yaw += 2 * M_PI;
Matrix m1, m2, m3;
if(invert_z) yaw = -yaw;
cout << "YAW: " << yaw << " PITCH: " << pitch << endl;
if(fabs(yaw) > 0.0001){
m2 = Matrix(Vertex(1.0, 0.0, 0.0), yaw);
m3 = m3 * m2;
}
if(fabs(pitch) > 0.0001){
m1 = Matrix(Vertex(0.0, 1.0, 0.0), pitch);
m3 = m3 * m1;
}
for(int i = 0; i < 16; i++) m[i] = m3[i];
} else {
float c = cos(angle);
float s = sin(angle);
float t = 1.0f - c;
float tmp1, tmp2;
// Normalize axis
Vertex a(axis);
a.normalize();
m[ 0] = c + a.x * a.x * t;
m[ 5] = c + a.y * a.y * t;
m[10] = c + a.z * a.z * t;
tmp1 = a.x * a.y * t;
tmp2 = a.z * s;
m[ 4] = tmp1 + tmp2;
m[ 1] = tmp1 - tmp2;
tmp1 = a.x * a.z * t;
tmp2 = a.y * s;
m[ 8] = tmp1 - tmp2;
m[ 2] = tmp1 + tmp2;
tmp1 = a.y * a.z * t;
tmp2 = a.x * s;
m[ 9] = tmp1 + tmp2;
m[ 6] = tmp1 - tmp2;
m[ 3] = m[ 7] = m[11] = 0.0;
m[12] = m[13] = m[14] = 0.0;
m[15] = 1.0;
}
}
Matrix::Matrix(const Vertex &position, const Vertex &angles)
{
float sx = sin(angles[0]);
float cx = cos(angles[0]);
float sy = sin(angles[1]);
float cy = cos(angles[1]);
float sz = sin(angles[2]);
float cz = cos(angles[2]);
m[0] = cy*cz;
m[1] = sx*sy*cz + cx*sz;
m[2] = -cx*sy*cz + sx*sz;
m[3] = 0.0;
m[4] = -cy*sz;
m[5] = -sx*sy*sz + cx*cz;
m[6] = cx*sy*sz + sx*cz;
m[7] = 0.0;
m[8] = sy;
m[9] = -sx*cy;
m[10] = cx*cy;
m[11] = 0.0;
m[12] = position[0];
m[13] = position[1];
m[14] = position[2];
m[15] = 1;
}
Matrix::~Matrix()
{
}
Matrix Matrix::operator*(const float &scale) const
{
float new_matrix[16];
for(int i = 0; i < 16; i++){
new_matrix[i] = m[i] * scale;
}
return Matrix(new_matrix);
}
Matrix Matrix::operator*(const Matrix &other) const
{
float new_matrix[16];
new_matrix[ 0] = m[ 0] * other[ 0] + m[ 4] * other[ 1] + m[ 8] * other[ 2] + m[12] * other[ 3];
new_matrix[ 1] = m[ 1] * other[ 0] + m[ 5] * other[ 1] + m[ 9] * other[ 2] + m[13] * other[ 3];
new_matrix[ 2] = m[ 2] * other[ 0] + m[ 6] * other[ 1] + m[10] * other[ 2] + m[14] * other[ 3];
new_matrix[ 3] = m[ 3] * other[ 0] + m[ 7] * other[ 1] + m[11] * other[ 2] + m[15] * other[ 3];
new_matrix[ 4] = m[ 0] * other[ 4] + m[ 4] * other[ 5] + m[ 8] * other[ 6] + m[12] * other[ 7];
new_matrix[ 5] = m[ 1] * other[ 4] + m[ 5] * other[ 5] + m[ 9] * other[ 6] + m[13] * other[ 7];
new_matrix[ 6] = m[ 2] * other[ 4] + m[ 6] * other[ 5] + m[10] * other[ 6] + m[14] * other[ 7];
new_matrix[ 7] = m[ 3] * other[ 4] + m[ 7] * other[ 5] + m[11] * other[ 6] + m[15] * other[ 7];
new_matrix[ 8] = m[ 0] * other[ 8] + m[ 4] * other[ 9] + m[ 8] * other[10] + m[12] * other[11];
new_matrix[ 9] = m[ 1] * other[ 8] + m[ 5] * other[ 9] + m[ 9] * other[10] + m[13] * other[11];
new_matrix[10] = m[ 2] * other[ 8] + m[ 6] * other[ 9] + m[10] * other[10] + m[14] * other[11];
new_matrix[11] = m[ 3] * other[ 8] + m[ 7] * other[ 9] + m[11] * other[10] + m[15] * other[11];
new_matrix[12] = m[ 0] * other[12] + m[ 4] * other[13] + m[ 8] * other[14] + m[12] * other[15];
new_matrix[13] = m[ 1] * other[12] + m[ 5] * other[13] + m[ 9] * other[14] + m[13] * other[15];
new_matrix[14] = m[ 2] * other[12] + m[ 6] * other[13] + m[10] * other[14] + m[14] * other[15];
new_matrix[15] = m[ 3] * other[12] + m[ 7] * other[13] + m[11] * other[14] + m[15] * other[15];
return Matrix(new_matrix);
}
/**
* @brief Matrix addition operator. Returns a new matrix
*
*/
Matrix Matrix::operator+(const Matrix &other) const
{
float new_matrix[16];
for(int i = 0; i < 16; i++)
{
new_matrix[i] = m[i] + other[i];
}
return Matrix(new_matrix);
}
Matrix Matrix::operator+=(const Matrix &other)
{
return *this + other;
}
Matrix Matrix::operator*(const float* &other) const
{
float new_matrix[16];
new_matrix[ 0] = m[ 0] * other[ 0] + m[ 4] * other[ 1] + m[ 8] * other[ 2] + m[12] * other[ 3];
new_matrix[ 1] = m[ 1] * other[ 0] + m[ 5] * other[ 1] + m[ 9] * other[ 2] + m[13] * other[ 3];
new_matrix[ 2] = m[ 2] * other[ 0] + m[ 6] * other[ 1] + m[10] * other[ 2] + m[14] * other[ 3];
new_matrix[ 3] = m[ 3] * other[ 0] + m[ 7] * other[ 1] + m[11] * other[ 2] + m[15] * other[ 3];
new_matrix[ 4] = m[ 0] * other[ 4] + m[ 4] * other[ 5] + m[ 8] * other[ 6] + m[12] * other[ 7];
new_matrix[ 5] = m[ 1] * other[ 4] + m[ 5] * other[ 5] + m[ 9] * other[ 6] + m[13] * other[ 7];
new_matrix[ 6] = m[ 2] * other[ 4] + m[ 6] * other[ 5] + m[10] * other[ 6] + m[14] * other[ 7];
new_matrix[ 7] = m[ 3] * other[ 4] + m[ 7] * other[ 5] + m[11] * other[ 6] + m[15] * other[ 7];
new_matrix[ 8] = m[ 0] * other[ 8] + m[ 4] * other[ 9] + m[ 8] * other[10] + m[12] * other[11];
new_matrix[ 9] = m[ 1] * other[ 8] + m[ 5] * other[ 9] + m[ 9] * other[10] + m[13] * other[11];
new_matrix[10] = m[ 2] * other[ 8] + m[ 6] * other[ 9] + m[10] * other[10] + m[14] * other[11];
new_matrix[11] = m[ 3] * other[ 8] + m[ 7] * other[ 9] + m[11] * other[10] + m[15] * other[11];
new_matrix[12] = m[ 0] * other[12] + m[ 4] * other[13] + m[ 8] * other[14] + m[12] * other[15];
new_matrix[13] = m[ 1] * other[12] + m[ 5] * other[13] + m[ 9] * other[14] + m[13] * other[15];
new_matrix[14] = m[ 2] * other[12] + m[ 6] * other[13] + m[10] * other[14] + m[14] * other[15];
new_matrix[15] = m[ 3] * other[12] + m[ 7] * other[13] + m[11] * other[14] + m[15] * other[15];
return Matrix(new_matrix);
}
Vertex Matrix::operator*(const Vertex &v) const
{
float x = m[ 0] * v.x + m[ 4] * v.y + m[8 ] * v.z;
float y = m[ 1] * v.x + m[ 5] * v.y + m[9 ] * v.z;
float z = m[ 2] * v.x + m[ 6] * v.y + m[10] * v.z;
x = x + m[12];
y = y + m[13];
z = z + m[14];
return Vertex(x, y, z);
}
/**
* @brief Transposes the current matrix
*/
void Matrix::transpose()
{
float m_tmp[16];
m_tmp[0] = m[0];
m_tmp[4] = m[1];
m_tmp[8] = m[2];
m_tmp[12] = m[3];
m_tmp[1] = m[4];
m_tmp[5] = m[5];
m_tmp[9] = m[6];
m_tmp[13] = m[7];
m_tmp[2] = m[8];
m_tmp[6] = m[9];
m_tmp[10] = m[10];
m_tmp[14] = m[11];
m_tmp[3] = m[12];
m_tmp[7] = m[13];
m_tmp[11] = m[14];
m_tmp[15] = m[15];
for(int i = 0; i < 16; i++) m[i] = m_tmp[i];
}
/**
* @brief Computes an Euler representation (x, y, z) plus three
* rotation values in rad. Rotations are with respect to
* the x, y, z axes.
*/
void Matrix::toPostionAngle(float pose[6])
{
if(pose != 0){
float _trX, _trY;
if(m[0] > 0.0) {
pose[4] = asin(m[8]);
} else {
pose[4] = (float)M_PI - asin(m[8]);
}
// rPosTheta[1] = asin( m[8]); // Calculate Y-axis angle
float C = cos( pose[4] );
if ( fabs( C ) > 0.005 ) { // Gimball lock?
_trX = m[10] / C; // No, so get X-axis angle
_trY = -m[9] / C;
pose[3] = atan2( _trY, _trX );
_trX = m[0] / C; // Get Z-axis angle
_trY = -m[4] / C;
pose[5] = atan2( _trY, _trX );
} else { // Gimball lock has occurred
pose[3] = 0.0; // Set X-axis angle to zero
_trX = m[5]; //1 // And calculate Z-axis angle
_trY = m[1]; //2
pose[5] = atan2( _trY, _trX );
}
pose[0] = m[12];
pose[1] = m[13];
pose[2] = m[14];
}
}
/**
* @brief Matrix scaling with self assignment.
*/
void Matrix::operator*=(const float scale)
{
*this = *this * scale;
}
/**
* @brief Matrix-Matrix multiplication with self assigment.
*/
void Matrix::operator*=(const Matrix& other)
{
*this = *this * other;
}
/**
* @brief Matrix-Matrix multiplication (array based). See \ref{operator*}.
*/
void Matrix::operator*=(const float* other)
{
*this = *this * other;
}
/**
* @brief Returns the internal data array. Unsafe. Will probably
* removed in one of the next versions.
*/
float* Matrix::getData(){ return m;};
/**
* @brief Indexed element (reading) access.
*/
float Matrix::operator[](const int index) const
{
/// TODO: Boundary check
return m[index];
}
/**
* @brief Writeable index access
*/
float& Matrix::operator[](const int index)
{
return m[index];
}
/**
* @brief Returns the matrix's determinant
*/
float Matrix::det()
{
float det, result = 0, i = 1.0;
float Msub3[9];
int n;
for ( n = 0; n < 4; n++, i *= -1.0 ) {
submat( Msub3, 0, n );
det = det3( Msub3 );
result += m[n] * det * i;
}
return( result );
}
Matrix Matrix::inv(bool& success)
{
Matrix Mout;
float mdet = det();
if ( fabs( mdet ) < 0.00000000000005 ) {
cout << "Error matrix inverting! " << mdet << endl;
return Mout;
}
float mtemp[9];
int i, j, sign;
for ( i = 0; i < 4; i++ ) {
for ( j = 0; j < 4; j++ ) {
sign = 1 - ( (i +j) % 2 ) * 2;
submat( mtemp, i, j );
Mout[i+j*4] = ( det3( mtemp ) * sign ) / mdet;
}
}
return Mout;
}
/**
* @brief Returns a sub matrix without row \ref i and column \ref j.
*/
void Matrix::submat(float* submat, int i, int j)
{
int di, dj, si, sj;
// loop through 3x3 submatrix
for( di = 0; di < 3; di ++ ) {
for( dj = 0; dj < 3; dj ++ ) {
// map 3x3 element (destination) to 4x4 element (source)
si = di + ( ( di >= i ) ? 1 : 0 );
sj = dj + ( ( dj >= j ) ? 1 : 0 );
// copy element
submat[di * 3 + dj] = m[si * 4 + sj];
}
}
}
/**
* @brief Calculates the determinant of a 3x3 matrix
*
* @param M input 3x3 matrix
* @return determinant of input matrix
*/
float Matrix::det3( const float *M )
{
float det;
det = (double)( M[0] * ( M[4]*M[8] - M[7]*M[5] )
- M[1] * ( M[3]*M[8] - M[6]*M[5] )
+ M[2] * ( M[3]*M[7] - M[6]*M[4] ));
return ( det );
}
} // namespace cpp2014
| [
"themightyoarfish@users.noreply.github.com"
] | themightyoarfish@users.noreply.github.com |
180b2b2824a445efc72de2663bcdcada8142b615 | d3723ce7b88292110120460e538692995c50b426 | /4-( Object Oriented Design and Programming)/2-PointRectangle(public).cpp | d163c03f71df290422e62792bd730dae9ed40873 | [] | no_license | BackTo2012/CPP-OOP | abf68a7ae72a99b13c59fc3dcdfc98686eabeb3e | 59569687a4fa7fd085ed4fac6303d84845c0470e | refs/heads/main | 2023-06-16T19:03:51.500525 | 2021-07-04T07:35:58 | 2021-07-04T07:35:58 | 382,268,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include <iostream>
using namespace std;
class Point
{
double x, y;
public:
void SetPoint(double x = 0, double y = 0) {
this->x = x, this->y = y;
}
double GetX() const {return x;}
double GetY() const {return y;}
void Move(double xOff, double yOff) {
x += xOff, y += yOff;
}
};
class Rectangle: public Point
{
private:
double w, h;
public:
void SetRect(double x, double y, double w, double h) {
SetPoint(x, y); this->w = w; this->h = h;
}
double GetW() const {
return w;
}
double GetH() const {
return h;
}
};
//StudybarCommentBegin
int main()
{
Rectangle rect;
rect.SetRect(0, 0, 1, 1);
rect.Move(3, 2);
cout << "sizeof(Point):" << sizeof(Point) << " and sizeof(rect):"
<< sizeof(rect) << ", (x,y,w,h) is (" << rect.GetX() << ","
<< rect.GetY() << "," << rect.GetW() << "," << rect.GetH() << ")";
return 0;
}
//StudybarCommentEnd | [
"1742331636@qq.com"
] | 1742331636@qq.com |
b59006eb8c9e5ea3553ee4b89e25a133595d5f9e | 6466da0d6adc644d11c39046583ef3ae0a8bffd1 | /insert_element_inarry.cpp | 436e3af38eb633102237a3788a66522e37bc5765 | [] | no_license | Solayman-Emon/Hackerrank_Practise | 319cdec530d5925741ff778b178ab2557fb13006 | c25c412a749250f27f2366e96f3bd415b2ad1ae6 | refs/heads/master | 2020-05-17T00:58:57.584639 | 2019-04-25T10:37:58 | 2019-04-25T10:37:58 | 183,413,200 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,arr[100];
cout<<"How many number do you want to enter : "<<endl;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int location,num;
cout<<"In what location you want to entered the element : "<<endl;
cin>>location;
cout<<"Enter your number : "<<endl;
cin>>num;
for(int i=n-1; i>=location-1; i--)
{
arr[i+1]=arr[i];
}
arr[location-1]=num;
for(int i=0; i<=n; i++)
{
cout<<arr[i]<<"\t";
}
return 0;
}
| [
"emonqt19@gmail.com"
] | emonqt19@gmail.com |
2d960eacc4404f926f7bb7c4cd7bcd4354c9ec6f | b97faacb3d682883ef5b35c2a872a204e9604129 | /serverGUI/ClientManager/sotadb.cpp | 4a87fef9db44011f2e47b0a1fc61d324b41817d4 | [] | no_license | garrettharvey/sota-server | 7a0f1f5ee824bd3ab602064143dfa3025b954bdb | 500452ec1ec49e3df4bfa7b62deeec4dd33350e8 | refs/heads/master | 2022-07-01T17:18:15.609883 | 2020-05-05T07:10:27 | 2020-05-05T07:10:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,386 | cpp | #include <QString>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <QQuickView>
#include <QQmlContext>
#include "sotadb.h"
QSqlDatabase db;
const QString DRIVER("QSQLITE");
const QString dbName("/home/" + qgetenv("USER") + "/sota-server/db/sotaserver.db");
QVariantList clientList;
int numclients = 0;
SOTAdb::SOTAdb(QObject *parent) : QObject(parent)
{
numclients = 0;
qDebug() << "creating db object";
if(QSqlDatabase::isDriverAvailable(DRIVER)){ //check for database driver
db = QSqlDatabase::addDatabase(DRIVER);
db.setDatabaseName(dbName);
if(!db.open()){ //db didn't open
qWarning() << "ERROR: " << db.lastError();
//emit openFailed();
}else{//opened db
open = true;
qDebug() << "opened/created database";
//need set initialized after checking if tabels exist
if(!initialized){ //db tables haven't been created
initDB(); //will either create tables, or they already exist
//successfully created tables
initialized = true;
queryAllClients();
}else{
//db tables exist
queryAllClients();
}//end check initialized
}//end try open
}else{
//driver not available
qWarning() << "QSQLITE database driver unavailable";
}//end check driver
}
int SOTAdb::initDB()
{
if(!open || initialized){//db didn't open on object creation OR tables already created
qWarning() << "ERROR: " << db.lastError();
return 0;
}
QSqlQuery sqlClientsTable("CREATE TABLE CLIENTS (" \
"unique_id CHAR(16) NOT NULL PRIMARY KEY," \
"init_id CHAR(22)," \
"software_id CHAR(16)," \
"last_seen INTEGER," \
"last_ip TEXT," \
"status TEXT," \
"group_id CHAR(16)," \
"last_sw_id CHAR(16)," \
"active TEXT," \
"FOREIGN KEY(software_id) REFERENCES SOFTWARE(id)" \
");");
QSqlQuery sqlSoftwareTable("CREATE TABLE SOFTWARE (" \
"id CHAR(16) NOT NULL PRIMARY KEY," \
"name TEXT," \
"version TEXT," \
"num_users INTEGER," \
"size INTEGER," \
"location TEXT" \
");");
if(!sqlClientsTable.isActive()){ //something went wrong creating Clients table
qWarning() << "ERROR: " << sqlClientsTable.lastError().text();
return 0;
}
if(!sqlSoftwareTable.isActive()){ //something went wrong creating Software table
qWarning() << "ERROR: " << sqlSoftwareTable.lastError().text();
return 0;
}
return 1; //success
}// end initDB
void SOTAdb::createClient(QString rand)
{
// init-12345-abcde-123ab
QString initID(rand.left(15));
initID.prepend("init-");
initID.insert(16, "-");
initID.insert(10, "-");
QString uniqueID(rand.right(16));
if(!db.open()){ // can't open db
qWarning() << "ERROR: " << db.lastError();
return;
}
QSqlQuery query;
query.prepare("INSERT INTO CLIENTS (unique_id, init_id) "
"VALUES (:unique_id, :init_id)");
query.bindValue(":unique_id", uniqueID);
query.bindValue(":init_id", initID);
query.exec();
if(!query.isActive()){
qWarning() << "ERROR: " << query.lastError().text();
return;
}else{ //insert successful
// emit newdata();
ClientModel tempclient;
tempclient.setUnique_id(uniqueID);
tempclient.setInit_id(initID);
tempclient.setSoftware_id("");
tempclient.setLast_seen("");
tempclient.setLast_ip("");
tempclient.setStatus("");
tempclient.setGroup_id("");
tempclient.setLast_sw_id("");
tempclient.setActive("");
cList.append(tempclient);
}
}
int SOTAdb::queryAllClients() // get all info for many clients
{
qDebug() << "starting loadAllClients()";
if (!open){ //db isn't open, try to open
if(!db.open()){ // can't open db
qWarning() << "ERROR opening db in SOTAdb::loadAllClients: " << db.lastError();
return 0;
}
}
QSqlQuery query;
query.prepare("SELECT * FROM CLIENTS");
if(!query.exec()){ //error executing query
qWarning() << "ERROR executing query in SOTAdb::loadAllClients: " << query.lastError().text();
return 0;
}
qDebug() << "successfully ran select * from clients";
while (query.next()){
//create new ClientEntity type and set values
// ClientEntity dbclient =
// {
// query.value(0).toString(),
// query.value(1).toString(),
// query.value(2).toString(),
// query.value(3).toString(),
// query.value(4).toString(),
// query.value(5).toString(),
// query.value(6).toString(),
// query.value(7).toString(),
// query.value(8).toString()
// };
QString uniqueid = query.value(0).toString();
QString initid = query.value(1).toString();
QString softwareid = query.value(2).toString();
QString lastseen = query.value(3).toString();
QString lastip = query.value(4).toString();
QString status = query.value(5).toString();
QString groupid = query.value(6).toString();
QString lastswid = query.value(7).toString();
QString active = query.value(8).toString();
ClientModel tempclient;
tempclient.setUnique_id(uniqueid);
tempclient.setInit_id(initid);
tempclient.setSoftware_id(softwareid);
tempclient.setLast_seen(lastseen);
tempclient.setLast_ip(lastip);
tempclient.setStatus(status);
tempclient.setGroup_id(groupid);
tempclient.setLast_sw_id(lastswid);
tempclient.setActive(active);
cList.append(tempclient);
// dbclient << query.value(0).toString();
// dbclient << query.value(1).toString();
// dbclient << query.value(2).toString();
// dbclient << query.value(3).toString();
// dbclient << query.value(4).toString();
// dbclient << query.value(5).toString();
// dbclient << query.value(6).toString();
// dbclient << query.value(7).toString();
// dbclient << query.value(8).toString();
//conver client to QVariant
//QVariant qclient;
//qclient.setValue(dbclient);
//qclient.setValue(tempclient);
//clientList.append(qclient);
qDebug() << "loaded client uniqueid: " + query.value(0).toString();
}
numclients = cList.size();
qDebug() << "loaded All clients";
qDebug() << "Num clients: " << numclients;
return 1;
}//end constructor
/*
int SOTAdb::getnumclients() //might only return number of columns - fix
{
if(!db.open()){ // can't open db
qWarning() << "ERROR: " << db.lastError();
}
QSqlQuery query;
query.prepare("SELECT * FROM CLIENTS");
if(!query.exec()){
qWarning() << "ERROR: " << query.lastError().text();
return 0;
}
int numclients = query.size();
return numclients;
}
*/
//QString SOTAdb::updateClient()
//{
// return QString("not done");
//}
//QString SOTAdb::deleteClient()
//{
// return QString("not done");
//}
//QString SOTAdb::numActive()
//{
//}
//QString SOTAdb::numInactive()
//{
//}
| [
"glharvey@go.olemiss.edu"
] | glharvey@go.olemiss.edu |
558ebc504ddf4a8251f30ef9d8a1ef4c08727c92 | 237313342e4ab6d924855072dbe506ecdac0ef37 | /Cipher.cpp | d8960050a876c6f007b3df2dc64ff8592f0e955a | [
"OpenSSL",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSD-3-Clause"
] | permissive | tresorit/ZeroKit-Client-Native-Crypto | b1473383340ff10164289e77d128190e8058aaf3 | 02af3e54dcd557dc8f93913cd2137382992e7db2 | refs/heads/master | 2021-01-20T14:39:29.123247 | 2018-06-19T07:34:03 | 2018-06-19T07:34:03 | 90,640,581 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,629 | cpp | /**
* Copyright (c) 2017, Tresorit Kft.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Cipher.hpp"
#include <limits>
#include <openssl/evp.h>
#include "OpenSSLException.hpp"
const EVP_CIPHER* getCipher(CipherType cipherType)
{
switch (cipherType) {
case CipherType::AES128GCM:
return EVP_aes_128_gcm();
case CipherType::AES256GCM:
return EVP_aes_256_gcm();
default:
throw OpenSSLException();
}
}
CipherCtx::CipherCtx()
: ctx(nullptr)
{
OPENSSL_THROW_IF_NULL(this->ctx = EVP_CIPHER_CTX_new());
}
CipherCtx::CipherCtx(CipherCtx&& other)
: ctx(other.ctx)
{
other.ctx = nullptr;
}
CipherCtx& CipherCtx::operator=(CipherCtx&& other)
{
if (this != &other) {
if (this->ctx != nullptr) {
EVP_CIPHER_CTX_free(this->ctx);
}
this->ctx = other.ctx;
other.ctx = nullptr;
}
return *this;
}
CipherCtx::~CipherCtx()
{
if (this->ctx != nullptr) {
EVP_CIPHER_CTX_free(this->ctx);
}
}
EVP_CIPHER_CTX* CipherCtx::get()
{
return this->ctx;
}
void CipherCtx::setType(const EVP_CIPHER* cipher, CipherOperation operation)
{
OPENSSL_THROW_IF_ERROR(EVP_CipherInit_ex(
this->get(), cipher, nullptr, nullptr, nullptr, static_cast<int>(operation)));
}
void CipherCtx::setPadding(bool enable)
{
OPENSSL_THROW_IF_ERROR(EVP_CIPHER_CTX_set_padding(this->get(), enable));
}
void CipherCtx::setKey(const uint8_t* key, size_t len)
{
OPENSSL_THROW_IF(len > std::numeric_limits<int>::max())
int keyLen = EVP_CIPHER_CTX_key_length(this->get());
OPENSSL_THROW_IF(keyLen < 0);
OPENSSL_THROW_IF(len != static_cast<size_t>(keyLen));
OPENSSL_THROW_IF_ERROR(EVP_CipherInit_ex(this->get(), nullptr, nullptr, key, nullptr, -1));
}
void CipherCtx::setIV(const uint8_t* iv, size_t len)
{
if (EVP_CIPHER_CTX_cipher(this->get()) == getCipher(CipherType::AES128GCM)
|| EVP_CIPHER_CTX_cipher(this->get()) == getCipher(CipherType::AES256GCM)) {
OPENSSL_THROW_IF(len > std::numeric_limits<int>::max())
OPENSSL_THROW_IF_ERROR(EVP_CIPHER_CTX_ctrl(
this->get(), EVP_CTRL_AEAD_SET_IVLEN, static_cast<int>(len), nullptr));
}
OPENSSL_THROW_IF_ERROR(EVP_CipherInit_ex(this->get(), nullptr, nullptr, nullptr, iv, -1));
}
void CipherCtx::updateAAD(const uint8_t* aad, size_t len)
{
OPENSSL_THROW_IF(len > std::numeric_limits<int>::max())
if (aad == nullptr || len == 0) {
return;
}
int outl = 0;
OPENSSL_THROW_IF_ERROR(
EVP_CipherUpdate(this->get(), nullptr, &outl, aad, static_cast<int>(len)));
}
SecureVector CipherCtx::update(const uint8_t* data, size_t len)
{
OPENSSL_THROW_IF(len > std::numeric_limits<int>::max())
if (data == nullptr || len == 0) {
return SecureVector();
}
int blockSize = EVP_CIPHER_CTX_block_size(this->get());
OPENSSL_THROW_IF(blockSize < 1);
SecureVector res(len + static_cast<size_t>(blockSize) - 1);
int outl = 0;
OPENSSL_THROW_IF_ERROR(
EVP_CipherUpdate(this->get(), res.data(), &outl, data, static_cast<int>(len)));
OPENSSL_THROW_IF(outl < 0);
res.resize(static_cast<size_t>(outl));
return res;
}
SecureVector CipherCtx::finalize()
{
int blockSize = EVP_CIPHER_CTX_block_size(this->get());
OPENSSL_THROW_IF(blockSize < 1);
SecureVector res(static_cast<size_t>(blockSize));
int outl = 0;
OPENSSL_THROW_IF_ERROR(EVP_CipherFinal_ex(this->get(), res.data(), &outl));
OPENSSL_THROW_IF(outl < 0);
res.resize(static_cast<size_t>(outl));
return res;
}
SecureVector CipherCtx::getTag(size_t len)
{
OPENSSL_THROW_IF(len > std::numeric_limits<int>::max())
SecureVector tag(len);
OPENSSL_THROW_IF_ERROR(
EVP_CIPHER_CTX_ctrl(this->get(), EVP_CTRL_AEAD_GET_TAG, static_cast<int>(len), tag.data()));
return tag;
}
void CipherCtx::setTag(const uint8_t* tag, size_t len)
{
OPENSSL_THROW_IF(len > std::numeric_limits<int>::max())
OPENSSL_THROW_IF_ERROR(EVP_CIPHER_CTX_ctrl(this->get(), EVP_CTRL_AEAD_SET_TAG,
static_cast<int>(len), static_cast<void*>(const_cast<uint8_t*>(tag))));
}
| [
"daniel.bakai@tresorit.com"
] | daniel.bakai@tresorit.com |
8b8cd9d2dda01ce529cee7a048abccc877844530 | 3fc7cfc6a2e2cddcd685620b9ad5b6e8745b9a04 | /include/libtorrent/aux_/torrent_list.hpp | dd003fd268f85f28191cf5827579fa03f4b766cb | [
"BSD-3-Clause",
"BSL-1.0",
"Zlib"
] | permissive | jriker1/libtorrent | e8663a19a0dd58fe50ee9651f272fb7f84b33c5a | a53e19d16b49d0d725f184dd8c332263feb9ea52 | refs/heads/master | 2020-07-02T14:18:58.912154 | 2019-08-06T23:19:52 | 2019-08-07T04:19:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,854 | hpp | /*
Copyright (c) 2019, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author 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.
*/
#ifndef TORRENT_TORRENT_LIST_HPP_INCLUDED
#define TORRENT_TORRENT_LIST_HPP_INCLUDED
#include "libtorrent/config.hpp"
#include "libtorrent/sha1_hash.hpp"
#if !defined TORRENT_DISABLE_ENCRYPTION
#include "libtorrent/hasher.hpp"
#endif
#include <memory> // for shared_ptr
#include <vector>
#include <unordered_map>
namespace libtorrent {
namespace aux {
template <typename T>
struct torrent_list
{
// These are non-owning pointers. Lifetime is managed by the `torrent_array`
using torrent_map = std::unordered_map<sha1_hash, T*>;
using torrent_array = std::vector<std::shared_ptr<T>>;
using iterator = typename torrent_array::iterator;
using const_iterator = typename torrent_array::const_iterator;
using value_type = typename torrent_array::value_type;
bool empty() const { return m_array.empty(); }
iterator begin() { return m_array.begin(); }
iterator end() { return m_array.end(); }
const_iterator begin() const { return m_array.begin(); }
const_iterator end() const { return m_array.end(); }
std::size_t size() const { return m_array.size(); }
T* operator[](std::size_t const idx)
{
TORRENT_ASSERT(idx < m_array.size());
return m_array[idx].get();
}
T const* operator[](std::size_t const idx) const
{
TORRENT_ASSERT(idx < m_array.size());
return m_array[idx].get();
}
bool insert(sha1_hash const& ih, std::shared_ptr<T> t)
{
TORRENT_ASSERT(t);
bool const added = m_index.insert({ih, t.get()}).second;
// if we already have a torrent with this hash, don't do anything
if (!added) return false;
#if !defined TORRENT_DISABLE_ENCRYPTION
static char const req2[4] = {'r', 'e', 'q', '2'};
hasher h(req2);
h.update(ih);
// this is SHA1("req2" + info-hash), used for
// encrypted hand shakes
m_obfuscated_index.emplace(h.final(), t.get());
#endif
m_array.emplace_back(std::move(t));
return true;
}
#if !defined TORRENT_DISABLE_ENCRYPTION
T* find_obfuscated(sha1_hash const& ih)
{
auto const i = m_obfuscated_index.find(ih);
if (i == m_obfuscated_index.end()) return nullptr;
return i->second;
}
#endif
T* find(sha1_hash const& ih) const
{
auto const i = m_index.find(ih);
if (i == m_index.end()) return nullptr;
return i->second;
}
bool erase(sha1_hash const& ih)
{
auto const i = m_index.find(ih);
if (i == m_index.end()) return false;
auto const array_iter = std::find_if(m_array.begin(), m_array.end()
, [&](std::shared_ptr<T> const& p) { return p.get() == i->second; });
TORRENT_ASSERT(array_iter != m_array.end());
m_index.erase(i);
#if !defined TORRENT_DISABLE_ENCRYPTION
static char const req2[4] = {'r', 'e', 'q', '2'};
hasher h(req2);
h.update(ih);
m_obfuscated_index.erase(h.final());
#endif
TORRENT_ASSERT(m_index.find(ih) == m_index.end());
if (array_iter != m_array.end() - 1)
std::swap(*array_iter, m_array.back());
// This is where we, potentially, remove the last reference
m_array.pop_back();
return true;
}
void clear()
{
m_array.clear();
m_index.clear();
#if !defined TORRENT_DISABLE_ENCRYPTION
m_obfuscated_index.clear();
#endif
}
private:
torrent_array m_array;
torrent_map m_index;
#if !defined TORRENT_DISABLE_ENCRYPTION
// this maps obfuscated hashes to torrents. It's only
// used when encryption is enabled
torrent_map m_obfuscated_index;
#endif
};
}
}
#endif
| [
"arvid.norberg@gmail.com"
] | arvid.norberg@gmail.com |
df91068c0db0e72bbb753d7831a339d881ea0c22 | cc57145c6aaed587aae05fe5f7e586f1032409ba | /gui/output/Outputs.h | c2d0a98d60fcef9486ff1db43093ab2c7f1e25d6 | [] | no_license | andygarcia/denmod | f12fb8e0a2691228ce99f0c93c2f3cd318deac86 | 01f85e803ff8f90f121f1070f194d3f297d93842 | refs/heads/master | 2020-04-15T14:39:46.321111 | 2015-06-05T20:29:42 | 2015-06-05T20:29:42 | 9,421,998 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,780 | h | #pragma once
#include "Enums.h"
using namespace System;
using namespace System::Collections::Generic;
namespace gui {
namespace output {
public interface class IOutput
{
public:
property String ^ Name;
property Collections::IList ^ Data;
};
generic<class T>
public ref class Output : public IOutput
{
public:
Output( String ^ name, array<T> ^ data )
: _name(name),
_data(gcnew List<T>())
{
for each( T t in data ) {
_data->Add( t );
}
}
public:
property String ^ Name {
virtual String ^ get(void) {
return _name;
}
virtual void set(String ^ s) {
_name = s;
}
}
property Collections::IList ^ Data {
virtual Collections::IList ^ get(void) {
return _data;
}
virtual void set(Collections::IList ^ il) {
throw gcnew InvalidOperationException( "not implemented" );
}
}
protected:
String ^ _name;
List<T> ^ _data;
};
typedef Collections::Generic::List<IOutput^> OutputCollection;
public ref class DatedOutput : public Output<double>
{
public:
DatedOutput( String ^ name, DateTime startDate, DateTime stopDate, array<double> ^ data )
: Output(name,data),
_startDate(startDate),
_stopDate(stopDate)
{}
public:
List<DateTime> ^ GetDates(void);
List<DateTime> ^ GetWeeks(void);
List<DateTime> ^ GetMonths(void);
List<double> ^ GetWeeklyData( TimePeriodFunction function );
List<double> ^ GetMonthlyData( TimePeriodFunction function );
private:
DateTime _startDate;
DateTime _stopDate;
};
public ref class ClassOutput : public Output<double>
{
public:
ClassOutput( String ^ name, array<double> ^ data )
: Output( name, data )
{}
virtual ~ClassOutput(void) {}
};
ref class CimsimOutput;
ref class DensimOutput;
public ref class SimOutput abstract
{
public:
SimOutput( String ^ name, DateTime startDate, DateTime stopDate );
virtual ~SimOutput(void);
public:
virtual void SaveToDisk( IO::DirectoryInfo ^ di ) abstract;
void WriteDailyWorksheet( IO::StreamWriter ^ sw, String ^ worksheetName, List<String^> ^ headers, List<DateTime> ^ dates, List<array<double>^> ^ columns );
void WriteClassWorksheet( IO::StreamWriter ^ sw, String ^ worksheetName, List<String^> ^ headers, List<String^> ^ indices, List<array<double>^> ^ columns );
protected:
void GenerateWeeks(void);
void GenerateMonths(void);
void WriteWorkbookOpen( IO::StreamWriter ^ sw );
void WriteWorkbookStyles( IO::StreamWriter ^ sw );
void WriteWorkbookClose( IO::StreamWriter ^ sw );
public:
property String ^ Name {
String ^ get(void) {
return _name;
}
}
property DateTime StartDate {
DateTime get(void) {
return _startDate;
}
}
property DateTime StopDate {
DateTime get(void) {
return _stopDate;
}
}
property int NumberOfDays {
int get(void) {
return _numberOfDays;
}
}
property List<DateTime> ^ Dates {
List<DateTime> ^ get(void) {
return _dates;
}
}
property List<DateTime> ^ Weeks {
List<DateTime> ^ get(void) {
if( _weeks == nullptr ) {
GenerateWeeks();
}
return _weeks;
}
}
property List<DateTime> ^ Months {
List<DateTime> ^ get(void) {
if( _months == nullptr ) {
GenerateMonths();
}
return _months;
}
}
protected:
String ^ _name;
DateTime _startDate;
DateTime _stopDate;
int _numberOfDays;
List<DateTime> ^ _dates;
List<DateTime> ^ _weeks;
List<DateTime> ^ _months;
Dictionary<Type^,String^> ^ _typeToStyle;
Dictionary<Type^,String^> ^ _typeToCellType;
};
};
};
| [
"andygarcia@gmail.com"
] | andygarcia@gmail.com |
d5e3793eb93e0b079340d1610813ba71a684ff68 | b4408fe55dcd6173aab67f96b7f804eb500dfd66 | /Monk and Prispner of Azkaban.cpp | 877b91cec29cc49a918dbab3a82152195f89a488 | [] | no_license | sripadhse/Stack-and-Queues | d368342a71e6c9e2f0b30f99ccf7ad8636e7abca | 704b2cac8cb494c660d4c85ee57e26bdc0be0be3 | refs/heads/main | 2023-04-26T12:04:53.885476 | 2021-05-25T17:39:46 | 2021-05-25T17:39:46 | 370,778,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | cpp | #include <bits/stdc++.h>
using namespace std;
#define mkp make_pair
#define pb push_back
#define scan(x) scanf("%lld", &x)
#define ll long long int
#define MOD 1000000007
#define pii pair<int, int>
stack <ll> st;
ll front[1000001], back[1000001], arr[1000001];
int main()
{
ll n, i, x;
scan(n);
for (i = 1; i <= n; ++i) {
scan(arr[i]);
}
for (i = 1; i <= n; ++i) {
if (st.empty() || arr[st.top()] >= arr[i]) {
st.push(i);
} else {
while (!st.empty() && arr[st.top()] < arr[i]) {
front[st.top()] = i;
st.pop();
}
st.push(i);
}
}
while (!st.empty()) {
front[st.top()] = -1;
st.pop();
}
for (i = n; i > 0; --i) {
if (st.empty() || arr[st.top()] >= arr[i]) {
st.push(i);
} else {
while (!st.empty() && arr[st.top()] < arr[i]) {
back[st.top()] = i;
st.pop();
}
st.push(i);
}
}
while (!st.empty()) {
back[st.top()] = -1;
st.pop();
}
for (i = 1; i <= n; ++i) {
printf("%lld ", front[i] + back[i]);
}
puts("");
return 0;
} | [
"noreply@github.com"
] | sripadhse.noreply@github.com |
b092a6266a302c5d495ecca8003b6680604f04f3 | 438f884b4b69a8ec50edac904cee9ab4f274d9ca | /GradTeme/GameThings/Door.h | d4e5f19a2c8cb1b32f5eb1ccf26e11d0cffe8e70 | [] | no_license | Zeepooh1/RG_Seminar | 66e1a5171cbfda95763e735ee12f834e65d50066 | 24d09522ed4ea882ad28fbd4e91681ad38f20c9a | refs/heads/master | 2020-04-11T09:36:41.080332 | 2019-03-10T20:18:32 | 2019-03-10T20:18:32 | 161,684,510 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | h | #pragma once
#include <GL\glew.h>
#include <glm\glm.hpp>
#include <PlayingGround\SpriteBatch.h>
class Door
{
public:
Door();
~Door();
void init(GLint pID);
void update();
void draw(PlayingGround::SpriteBatch&);
private:
glm::mat4 m_projection;
glm::mat4 m_model;
glm::mat4 m_view;
float m_speed = 0.1f;
bool m_isOpen = false;
GLfloat m_viewLoc;
GLfloat m_modelLoc;
GLfloat m_projectionLoc;
glm::vec3 m_position;
};
| [
"zb0382@student.uni-lj.si"
] | zb0382@student.uni-lj.si |
43b54cd30f3e64cb3d2864118d1f417be6c3ffdb | 1d5dfe11d0bf4cb628cafafbc5c3660fee065397 | /9.cpp | 309f2910ee534d987e0ea2e64844d52778778a5f | [] | no_license | Eberty/ProgrammingSkillsAndSQL | 955d42ed164ccf24b2aba6e9313d11093c60a006 | 311fde2a36892dd4d03533868be45d0de2de2ec5 | refs/heads/main | 2023-07-15T01:05:21.275945 | 2021-08-19T03:31:28 | 2021-08-19T03:31:28 | 397,298,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | /*
* Copyright 2021 Eberty Alves
*
* 9. Make a program in C/C++ or Java language that calculates the length of a string informed by the user (do not use
* any pre-existing function or method for this, such as len(), count(), strlen() or length());
*
* How to compile and run:
* g++ 9.cpp -o StringLength
* ./StringLength
*/
#include <bits/stdc++.h>
int main(int argc, char** argv) {
std::string str;
std::getline(std::cin, str);
size_t i = 0;
while (str[i] != '\0') {
i++;
}
std::cout << i << std::endl;
return 0;
}
| [
"eberty.silva@hotmail.com"
] | eberty.silva@hotmail.com |
0e320c93d7ea521caaed1c45a597ebfe89104f47 | 8d01f870a612201c61bfa42068e2d40b7ae58675 | /src/momentum.cpp | e158ac56d7df05fac563cbccf39379cf73052045 | [] | no_license | hsitaram/nadi | 0808779ce585b5f07325bc6bee2eb25746e32aa9 | a02cb06900eb5be789cf724249f3dbec40f50bde | refs/heads/main | 2023-03-16T12:35:05.280608 | 2021-03-05T21:04:58 | 2021-03-05T21:04:58 | 326,523,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,222 | cpp | #include<solve_manager.H>
#include<global_defines.H>
//=======================================================================
void solveManager::vel_solve(Real time,Real dt)
{
const auto dx = m_geom.CellSizeArray();
Real visc=m_visc;
Real delt=dt;
for(MFIter mfi(*m_cc_flow_vars); mfi.isValid(); ++mfi)
{
const Box& bx = mfi.validbox();
auto vx=(*m_vx)[mfi].array();
auto vy=(*m_vy)[mfi].array();
auto vz=(*m_vz)[mfi].array();
Box x_bx=convert(bx, {1,0,0});
Box y_bx=convert(bx, {0,1,0});
Box z_bx=convert(bx, {0,0,1});
FArrayBox vx_src(x_bx, 1);
Elixir vx_src_eli = vx_src.elixir();
Array4<Real> const& vx_src_arr = vx_src.array();
FArrayBox vy_src(y_bx, 1);
Elixir vy_src_eli = vy_src.elixir();
Array4<Real> const& vy_src_arr = vy_src.array();
FArrayBox vz_src(z_bx, 1);
Elixir vz_src_eli = vz_src.elixir();
Array4<Real> const& vz_src_arr = vz_src.array();
amrex::ParallelFor(x_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k)
{
Real vmid;
vx_src_arr(i,j,k)=0.0;
//left face
vmid=0.5*(vx(i,j,k)+vx(i-1,j,k));
if(vmid > 0)
vx_src_arr(i,j,k) -= vmid*vx(i-1,j,k)/dx[0];
else
vx_src_arr(i,j,k) -= vmid*vx(i,j,k)/dx[0];
//right face
vmid=0.5*(vx(i,j,k)+vx(i+1,j,k));
if(vmid > 0)
vx_src_arr(i,j,k) += vmid*vx(i,j,k)/dx[0];
else
vx_src_arr(i,j,k) += vmid*vx(i+1,j,k)/dx[0];
//bottom face
vmid=0.5*(vy(i-1,j,k)+vy(i,j,k));
if(vmid > 0)
vx_src_arr(i,j,k) -= vmid*vx(i,j-1,k)/dx[1];
else
vx_src_arr(i,j,k) -= vmid*vx(i,j,k)/dx[1];
//top face
vmid=0.5*(vy(i-1,j+1,k)+vy(i,j+1,k));
if(vmid > 0)
vx_src_arr(i,j,k) += vmid*vx(i,j,k)/dx[1];
else
vx_src_arr(i,j,k) += vmid*vx(i,j+1,k)/dx[1];
//back face
vmid=0.5*(vz(i-1,j,k)+vz(i,j,k));
if(vmid > 0)
vx_src_arr(i,j,k) -= vmid*vx(i,j,k-1)/dx[2];
else
vx_src_arr(i,j,k) -= vmid*vx(i,j,k)/dx[2];
//front face
vmid=0.5*(vz(i-1,j,k+1)+vz(i,j,k+1));
if(vmid > 0)
vx_src_arr(i,j,k) += vmid*vx(i,j,k)/dx[2];
else
vx_src_arr(i,j,k) += vmid*vx(i,j,k+1)/dx[2];
//diffusion
vx_src_arr(i,j,k) -= visc*(vx(i+1,j,k)+vx(i-1,j,k)-2.0*vx(i,j,k))/(dx[0]*dx[0]);
vx_src_arr(i,j,k) -= visc*(vx(i,j+1,k)+vx(i,j-1,k)-2.0*vx(i,j,k))/(dx[1]*dx[1]);
vx_src_arr(i,j,k) -= visc*(vx(i,j,k+1)+vx(i,j,k-1)-2.0*vx(i,j,k))/(dx[2]*dx[2]);
});
amrex::ParallelFor(y_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k)
{
Real vmid;
vy_src_arr(i,j,k)=0.0;
//left face
vmid=0.5*(vx(i,j,k)+vx(i,j-1,k));
if(vmid > 0)
vy_src_arr(i,j,k) -= vmid*vy(i-1,j,k)/dx[0];
else
vy_src_arr(i,j,k) -= vmid*vy(i,j,k)/dx[0];
//right face
vmid=0.5*(vx(i+1,j-1,k)+vx(i+1,j,k));
if(vmid > 0)
vy_src_arr(i,j,k) += vmid*vy(i,j,k)/dx[0];
else
vy_src_arr(i,j,k) += vmid*vy(i+1,j,k)/dx[0];
//bottom face
vmid=0.5*(vy(i,j,k)+vy(i,j-1,k));
if(vmid > 0)
vy_src_arr(i,j,k) -= vmid*vy(i,j-1,k)/dx[1];
else
vy_src_arr(i,j,k) -= vmid*vy(i,j,k)/dx[1];
//top face
vmid=0.5*(vy(i,j+1,k)+vy(i,j,k));
if(vmid > 0)
vy_src_arr(i,j,k) += vmid*vy(i,j,k)/dx[1];
else
vy_src_arr(i,j,k) += vmid*vy(i,j+1,k)/dx[1];
//back face
vmid=0.5*(vz(i,j,k)+vz(i,j-1,k));
if(vmid > 0)
vy_src_arr(i,j,k) -= vmid*vy(i,j,k-1)/dx[2];
else
vy_src_arr(i,j,k) -= vmid*vy(i,j,k)/dx[2];
//front face
vmid=0.5*(vz(i,j-1,k+1)+vz(i,j,k+1));
if(vmid > 0)
vy_src_arr(i,j,k) += vmid*vy(i,j,k)/dx[2];
else
vy_src_arr(i,j,k) += vmid*vy(i,j,k+1)/dx[2];
//diffusion
vy_src_arr(i,j,k) -= visc*(vy(i+1,j,k)+vy(i-1,j,k)-2.0*vy(i,j,k))/(dx[0]*dx[0]);
vy_src_arr(i,j,k) -= visc*(vy(i,j+1,k)+vy(i,j-1,k)-2.0*vy(i,j,k))/(dx[1]*dx[1]);
vy_src_arr(i,j,k) -= visc*(vy(i,j,k+1)+vy(i,j,k-1)-2.0*vy(i,j,k))/(dx[2]*dx[2]);
});
amrex::ParallelFor(z_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k)
{
Real vmid;
vz_src_arr(i,j,k)=0.0;
//left face
vmid=0.5*(vx(i,j,k)+vx(i,j,k-1));
if(vmid > 0)
vz_src_arr(i,j,k) -= vmid*vz(i-1,j,k)/dx[0];
else
vz_src_arr(i,j,k) -= vmid*vz(i,j,k)/dx[0];
//right face
vmid=0.5*(vx(i+1,j,k-1)+vx(i+1,j,k));
if(vmid > 0)
vz_src_arr(i,j,k) += vmid*vz(i,j,k)/dx[0];
else
vz_src_arr(i,j,k) += vmid*vz(i+1,j,k)/dx[0];
//bottom face
vmid=0.5*(vy(i,j,k)+vy(i,j,k-1));
if(vmid > 0)
vz_src_arr(i,j,k) -= vmid*vz(i,j-1,k)/dx[1];
else
vz_src_arr(i,j,k) -= vmid*vz(i,j,k)/dx[1];
//top face
vmid=0.5*(vy(i,j+1,k-1)+vy(i,j,k));
if(vmid > 0)
vz_src_arr(i,j,k) += vmid*vz(i,j,k)/dx[1];
else
vz_src_arr(i,j,k) += vmid*vz(i,j+1,k)/dx[1];
//back face
vmid=0.5*(vz(i,j,k)+vz(i,j,k-1));
if(vmid > 0)
vz_src_arr(i,j,k) -= vmid*vz(i,j,k-1)/dx[2];
else
vz_src_arr(i,j,k) -= vmid*vz(i,j,k)/dx[2];
//front face
vmid=0.5*(vz(i,j,k)+vz(i,j,k+1));
if(vmid > 0)
vz_src_arr(i,j,k) += vmid*vz(i,j,k)/dx[2];
else
vz_src_arr(i,j,k) += vmid*vz(i,j,k+1)/dx[2];
//diffusion
vz_src_arr(i,j,k) -= visc*(vz(i+1,j,k)+vz(i-1,j,k)-2.0*vz(i,j,k))/(dx[0]*dx[0]);
vz_src_arr(i,j,k) -= visc*(vz(i,j+1,k)+vz(i,j-1,k)-2.0*vz(i,j,k))/(dx[1]*dx[1]);
vz_src_arr(i,j,k) -= visc*(vz(i,j,k+1)+vz(i,j,k-1)-2.0*vz(i,j,k))/(dx[2]*dx[2]);
});
amrex::ParallelFor(x_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k)
{
vx(i,j,k) += -vx_src_arr(i,j,k)*delt;
});
amrex::ParallelFor(y_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k)
{
vy(i,j,k) += -vy_src_arr(i,j,k)*delt;
});
amrex::ParallelFor(z_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k)
{
vz(i,j,k) += -vz_src_arr(i,j,k)*delt;
});
}
}
| [
"hariswaran.sitaraman@nrel.gov"
] | hariswaran.sitaraman@nrel.gov |
fbec0425d6894b8b5503d9fdb9f601a69460a2b9 | 642ce02205385799aec1521ea53dd59beff87c32 | /LAB/Primera Tarea/main.cpp | fd5780afa88e53574b712ead0f4c27330403531b | [] | no_license | RubenJTL/Computacion-Grafica | 6e270208aae7fa859f7f519580c3c80e4ef85576 | 8da579930e01dce8b2675b9eaf1ba6a97c7ca142 | refs/heads/master | 2020-03-28T02:27:00.462237 | 2018-11-28T16:11:21 | 2018-11-28T16:11:21 | 147,571,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,633 | cpp | #include <GL/glut.h>
#include <stdlib.h>
#include <iostream>
#include <tuple>
#include <cmath>
using namespace std;
typedef tuple<float,float> Point;
int tam =50;
int midx=50;
int midy=50;
void init(void){
glClearColor(1.0,1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,200.0,0.0,150.0);
}
void drawLine(Point a, Point b){
float x1;
float x2;
float y1;
float y2;
tie(x1,y1) = a;
tie(x2,y2) = b;
glBegin(GL_LINES);
glVertex2i(x1,y1);
glVertex2i(x2,y2);
glEnd();
}
void drawLinePM(Point a, Point b){
float x,y;
float x1=get<0> (a);
float y1=get<1> (a);
float x2=get<0> (b);
float y2=get<1> (b);
if (x1==x2 and y1>y2)
{
swap(y1,y2);
}
else if (y1==y2 and x1>x2)
{
swap(x1,x2);
}
//Point d=make_tuple((x2-x1)/2,(y2-y1)/2);
float dx=x2-x1;
float dy=y2-y1;
float d=dy-dx;
float incE=dy;
float incNE=(dy-dx);
x=x1;
y=y1;
cout<<incE<<endl;
cout<<incNE<<endl;
float cambio=0.01;
glBegin(GL_POINTS);
glVertex2i(x,y);
cout<<x<<" "<<y<<endl;
if(x==x2){
while(y<y2){
//cout<<x<<" "<<y<<endl;
d=d+incE;
y=y+cambio;
glVertex2i(x,y);
}
}else{
while(x<x2){
//cout<<x<<" "<<y<<endl;
if(d<=0){
d=d+incE;
x=x+cambio;
if(y>y2){
y=y-cambio;
}
}else{
d=d+incNE;
x=x+cambio;
if(y>y2){
y=y-cambio;
}else{
y=y+cambio;
}
}
glVertex2i(x,y);
}
}
glEnd();
}
void drawPolygon(float distance,int lade){
float angle=360/lade;
float theta,theta1;
float x,y,x1,y1;
glBegin(GL_LINES);
for (int i = 0; i < lade; ++i)
{
theta=i*angle*M_PI/180;
theta1=(i+1)*angle*M_PI/180;
x=cos(theta)*distance+midx;
y=sin(theta)*distance+midy;
x1=cos(theta1)*distance+midx;
y1=sin(theta1)*distance+midy;
drawLine(make_tuple(x,y),make_tuple(x1,y1));
}
theta1=(0)*angle*M_PI/180;
x1=cos(theta)*distance+midx;
y1=sin(theta)*distance+midy;
drawLine(make_tuple(x,y),make_tuple(x1,y1));
glEnd();
}
void display(void){
//drawPolygon(40,360);
//drawPolygon(40,4);
drawLinePM(make_tuple(0,0),make_tuple(400,300));
glFlush();
}
void lineSegment(void){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2i(180,15);
glVertex2i(10,145);
glEnd();
glFlush();
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(midx,midy);
glutInitWindowSize(400,300);
glutCreateWindow("Ejemplo");
init();
glutDisplayFunc(display);
glutMainLoop();
} | [
"noreply@github.com"
] | RubenJTL.noreply@github.com |
36eeca246bd05d2293ddce2748bffa0798be8126 | c76adc973e5251452e1beb3de7776d0a2b709fce | /submissions/c3.s822.ncu100502028.Group1B.cpp.0.100502028.cpp | fee75edb4ea92af8ff6234fdb113e49cc0b34adf | [] | no_license | ncuoolab/domjudge | 779a167f695f45a6a33437996ec5ad0f9d01c563 | bda18c69d418c829ff653f9183b3244520139f8a | refs/heads/master | 2020-05-19T08:10:39.974107 | 2015-03-10T19:35:03 | 2015-03-10T19:43:26 | 31,972,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,120 | cpp | #include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
int main () {
string line = "";
int outCount = 0;
bool flag[2] = {true, true};
string temp[2] = {};
while (true) {
getline(cin, line);
istringstream in(line);
string input[3];
int count = 0;
while(in >> input[count])
count++;
if (count == 3) {
if (input[0][0] == 'l' || input[0][0] == 'b') {
int sizeOfFirstName = input[1].length();
for (int i = 1; i < sizeOfFirstName - 1; i++){
if ((input[1][i] >= 'a' && input[1][i] <= 'z') && (input[1][0] >= 'A' && input[1][0] <= 'Z')) {
flag[outCount] = true;
int sizeOfLastName = input[2].length();
for (int i = 0; i < sizeOfLastName - 1; i++){
if ((input[2][i] == 'a'|| (input[2][i] >= 'c' && input[2][i] <= 'z'))) {
flag[outCount] = true;
}
else {
flag[outCount] = false;
}
}
}
else {
flag[outCount] = false;
}
}
if (flag[outCount] == true) {
if (input[0][0] == 'l')
temp[outCount] += "level " + input[0] + "\n";
else
temp[outCount] += "battle " + input[0] + "\n";
temp[outCount] += "FirstName " + input[1] + "\n";
temp[outCount] += "LastName " + input[2] + "\n";
}
}
else {
flag[outCount] = false;
}
}
else if (count == 2) {
if (input[0][0] == 'b') {
int sizeOfID = input[1].length();
for (int i = 0; i < sizeOfID - 1; i++){
if ((input[1][i] >= '0' && input[1][i] <= '9')) {
flag[outCount] = true;
}
else {
flag[outCount] = false;
}
}
if (flag[outCount] == true) {
temp[outCount] += "battle " + input[0] + "\n";
temp[outCount] += "cid " + input[1] + "\n";
}
}
else {
flag[outCount] = false;
}
}
else {
flag[outCount] = false;
}
outCount++;
}
if(flag[0] == true && flag[1] == true) {
cout << temp[0];
cout << temp[1];
}
else
cout << "invalid input" << endl;
system("pause");
return 0;
} | [
"fntsrlike@gmail.com"
] | fntsrlike@gmail.com |
7a6f1a058397aeb54e45554597fe217d6eebb4a6 | 7481cd579dbd72999141a2533cfab5414a9af059 | /src/training/agents/nn_agent.h | e371df73619be7afec648665cc76b9cfedb972e6 | [] | no_license | Omegastick/bots | 36d9c99ede06aed54fc66b6a8bc0b493924e3c34 | 25342bbeec18c228bd1ec5350573a1e4bee11337 | refs/heads/master | 2022-04-13T20:36:46.847747 | 2020-04-14T12:09:07 | 2020-04-14T12:09:07 | 150,558,810 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 710 | h | #pragma once
#include <cpprl/model/policy.h>
#include <nlohmann/json_fwd.hpp>
#include "iagent.h"
namespace ai
{
class NNAgent : public IAgent
{
private:
mutable cpprl::Policy policy;
public:
NNAgent(cpprl::Policy policy, const nlohmann::json &body_spec, const std::string &name);
ActResult act(torch::Tensor observations,
torch::Tensor hidden_states,
torch::Tensor masks) const;
virtual std::unique_ptr<IAgent> clone() const;
inline int get_hidden_state_size() const { return policy->get_hidden_size(); }
inline cpprl::Policy &get_policy() { return policy; }
inline void set_policy(cpprl::Policy policy) { this->policy = policy; }
};
} | [
"omegastick@hotmail.co.uk"
] | omegastick@hotmail.co.uk |
243937977692893fc4f713d14d750fca71e41bce | 9d94929753208f65f3789b9ae454a225c344d9c0 | /SuperTagEditor/SuperTagEditorDoc.cpp | 211ae120762cdf9ff228b21d446cd389fbd27ebc | [] | no_license | de-ataka/mm_STEP_M | 7c68cc4033428a67b19e8308cd01b4bfe285bdae | d85179c370dc56aa709cc3494a8e89e8e7b44f5d | refs/heads/master | 2021-09-14T09:41:55.798522 | 2011-07-19T13:29:56 | 2011-07-19T13:29:56 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 30,013 | cpp | // SuperTagEditorDoc.cpp : CSuperTagEditorDoc クラスの動作の定義を行います。
//
#include "stdafx.h"
#include "Shlwapi.h"
#include "FileMP3.h"
#include "SuperTagEditor.h"
#include "DlgCommonProg.h"
#include "DlgEnvSheet.h"
#include "SHBrowseForFolder.h"
#include "SuperTagEditorView.h"
#include "SuperTagEditorDoc.h"
#include "DlgPluginSetup.h"
#include "INI/Profile.h"
//#include "NewAPIs.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//////////////////////////////////////////////////////////////////////////////
//GetLongPathName
//短いファイル名を長いファイル名に変換
//////////////////////////////////////////////////////////////////////////////
/*
引数:
LPSTR lpszLongFileName 長いファイル名を受け取るバッファへのポインタ
LPSTR lpszShortPathName 短いファイル名を含むパス名へのポインタ
DWORD dwSize バッファサイズ
戻り値:
DWORD バッファにコピーした文字列の長さ
0のとき異常終了
*/
DWORD GetLongPathName(LPSTR lpszLongFileName, LPSTR lpszShortPathName, DWORD dwSize)
{
WIN32_FIND_DATA fd;
HANDLE hFind;
//短いファイル名でファイルを検索
if((hFind = FindFirstFile(lpszShortPathName,&fd)) != INVALID_HANDLE_VALUE) {
FindClose(hFind);
if((DWORD)lstrlen(fd.cFileName) <= dwSize) {
//長いファイル名をバッファにコピー
lstrcpy(lpszLongFileName,fd.cFileName);
//バッファにコピーした文字列を返す
return lstrlen(lpszLongFileName);
}
}
lstrcpy(lpszLongFileName, "");
//バッファのサイズを超えたかファイルが見つからなかったときは異常終了
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// CSuperTagEditorDoc
IMPLEMENT_DYNCREATE(CSuperTagEditorDoc, CDocument)
BEGIN_MESSAGE_MAP(CSuperTagEditorDoc, CDocument)
//{{AFX_MSG_MAP(CSuperTagEditorDoc)
ON_UPDATE_COMMAND_UI(ID_OPEN_FOLDER, OnUpdateOpenFolder)
ON_COMMAND(ID_OPEN_FOLDER, OnOpenFolder)
ON_UPDATE_COMMAND_UI(ID_SAVE_ALL_TAG, OnUpdateSaveAllTag)
ON_COMMAND(ID_SAVE_ALL_TAG, OnSaveAllTag)
ON_UPDATE_COMMAND_UI(ID_FILE_OPEN, OnUpdateFileOpen)
ON_UPDATE_COMMAND_UI(ID_EDIT_FIELD_SI, OnUpdateEditFieldSi)
ON_COMMAND(ID_EDIT_FIELD_SI, OnEditFieldSi)
ON_UPDATE_COMMAND_UI(ID_EDIT_TD3_TAG, OnUpdateEditTd3Tag)
ON_COMMAND(ID_EDIT_TD3_TAG, OnEditTd3Tag)
ON_UPDATE_COMMAND_UI(ID_EDIT_CHANGE_FIELD, OnUpdateEditChangeField)
ON_COMMAND(ID_EDIT_CHANGE_FIELD, OnEditChangeField)
ON_UPDATE_COMMAND_UI(ID_EXEC_CLASSIFICATION, OnUpdateExecClassification)
ON_COMMAND(ID_EXEC_CLASSIFICATION, OnExecClassification)
ON_COMMAND(ID_DLG_SETUP_PLUGIN, OnDlgSetupPlugin)
ON_UPDATE_COMMAND_UI(ID_DLG_SETUP_PLUGIN, OnUpdateDlgSetupPlugin)
ON_COMMAND(ID_DLG_ENVIRONMENT, OnDlgEnvironment)
ON_UPDATE_COMMAND_UI(ID_DLG_ENVIRONMENT, OnUpdateDlgEnvironment)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CSuperTagEditorDoc クラスの構築/消滅
CSuperTagEditorDoc::CSuperTagEditorDoc()
{
// TODO: この位置に1度だけ呼ばれる構築用のコードを追加してください。
m_dlgLoadProgress = new CDlgCommonProgress;
m_nArrayFileCount = 0;
m_nArrayRequestFileCount = 0;
m_StartLoadFileCount = 0;//追加 by Kobarin
m_TagUpdatingCount = 0;//追加 by Kobarin
m_bInitialized = false; /* StartInaction2 055 */
}
CSuperTagEditorDoc::~CSuperTagEditorDoc()
{
delete m_dlgLoadProgress;
m_dlgLoadProgress = NULL;
}
BOOL CSuperTagEditorDoc::OnNewDocument()
{
// 保存確認
if (m_nArrayFileCount && CanCloseFrame((CFrameWnd *)AfxGetMainWnd()) == FALSE) {
return FALSE;
}
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: この位置に再初期化処理を追加してください。
// (SDI ドキュメントはこのドキュメントを再利用します。)
InitFileList(); // ファイルリストの初期化
ClearRequestFiles(); // 追加リクエストファイルリストの初期化
if (!m_bInitialized) {
InitPlugin(); // プラグインのロード
// 初期化処理
GetView()->m_List.InitializeGrid();
// フォントの設定
GetView()->UpdateFontListView();
}
InitGridList(); // グリッドを初期化
m_bInitialized = true;
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CSuperTagEditorDoc シリアライゼーション
void CSuperTagEditorDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring()) {
} else {
}
}
/////////////////////////////////////////////////////////////////////////////
// CSuperTagEditorDoc クラスの診断
#ifdef _DEBUG
void CSuperTagEditorDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CSuperTagEditorDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CSuperTagEditorDoc コマンド
//****************************************************************************
// ファイル検索処理関連
//****************************************************************************
// =============================================
// CSuperTagEditorDoc::GetFileTime
// 概要 : ファイルのタイムスタンプを取得
// 引数 : sFileName = ファイル名
// 戻り値: CTime = タイムスタンプ(CTime(0):エラー)
// =============================================
CTime CSuperTagEditorDoc::GetFileTime(const char *sFileName)
{
CFileStatus status;
if (sFileName == NULL
|| CFile::GetStatus(sFileName, status) == FALSE) {
return(CTime(0));
}
if (status.m_mtime == -1) return(CTime(0));
if (status.m_mtime.GetTime() == -1) return(CTime(0));
return(status.m_mtime);
}
// =============================================
// CSuperTagEditorDoc::AddRequestFile
// 概要 : ファイル追加リクエストリストにファイルを追加する
// 引数 : sFillPath = フルパス名
// : pParent = 親アイテム(NULLも可)
// 戻り値: int = インデックス(追加しなかった場合は-1を返す)
// =============================================
int CSuperTagEditorDoc::AddRequestFile(const char *sFillPath, CSuperGridCtrl::CTreeItem *pParent)
{
//追加 by Kobarin
if(IsTagUpdating())//タグを更新中は追加しない
return -1;
if(m_dlgLoadProgress->IsCanceled()){
//キャンセルボタンが押されている
return -1;
}
FILE_STATE stat;
stat.strFullPathName = sFillPath;
stat.pParent = pParent;
// 配列に追加
if (m_nArrayRequestFileCount > m_arrayRequestFiles.GetUpperBound()) {
// 配列が足りない場合は、確保サイズを増加させる
m_arrayRequestFiles.SetSize(m_arrayRequestFiles.GetUpperBound() + ADD_ARRAY_SIZE);
}
m_arrayRequestFiles[m_nArrayRequestFileCount] = stat;
m_nArrayRequestFileCount++;
return(m_nArrayRequestFileCount);
}
void CSuperTagEditorDoc::StartLoadFile(const char *sTitle)
{
if (m_dlgLoadProgress->GetSafeHwnd() == NULL) {
// プログレスバーを生成
// m_dlgLoadProgress = new CDlgCommonProgress;
m_dlgLoadProgress->Create(AfxGetMainWnd());
m_dlgLoadProgress->SetWindowText(sTitle);
UpdateAllViews(NULL);
}
m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "ファイル検索中...");
m_StartLoadFileCount++;//追加 by Kobarin
}
void CSuperTagEditorDoc::EndLoadFile(void)
{
if(--m_StartLoadFileCount != 0)return;//追加 by Kobarin
if (m_dlgLoadProgress->GetSafeHwnd() != NULL) {
m_dlgLoadProgress->DestroyWindow();
m_dlgLoadProgress->SetCanceled(FALSE);//追加 by Kobarin
// delete m_dlgLoadProgress;
// m_dlgLoadProgress = NULL;
}
}
// =============================================
// CSuperTagEditorDoc::ExecRequestFiles
// 概要 : 追加リクエストリストのファイルを処理する
// 引数 : bListClear = 追加処理終了後に追加リクエストのリストをクリアするか?
// : bCheck = チェックマークを付けるかどうか
// 戻り値: none
// =============================================
void CSuperTagEditorDoc::ExecRequestFiles(bool bListClear, bool bCheck)
{
m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "タグ情報の読み込み中...");
// CMySuperGrid &listCtrl = GetListCtrl();
// listCtrl.SetRedraw(FALSE);
//int nFileCount = m_nArrayFileCount; /* STEP 015 */
for (int no = 0; no < m_nArrayRequestFileCount; no++) {
int nFileCount = m_nArrayFileCount; /* STEP 015 */
// プログレスバー更新
if (m_nArrayRequestFileCount > 1) {
m_dlgLoadProgress->SetPos(no * 100 / (m_nArrayRequestFileCount-1));
}
// 追加 by Kobarin
if(m_dlgLoadProgress->IsCanceled()){
//キャンセルボタンが押されていた
break;
}
// 多重登録チェック
if (nFileCount > 0) {
bool bFound = false;
CString *strFileName = &m_arrayRequestFiles[no].strFullPathName;
int i; for (i = 0; i < nFileCount; i++) {
if (GetListMP3(i)->strFullPathName == *strFileName) {
bFound = true;
break;
}
}
if (bFound == false) {
// MP3ファイル情報の取得
FoundFile(*strFileName, m_arrayRequestFiles[no].pParent, bCheck);
}
} else {
// MP3ファイル情報の取得
FoundFile(m_arrayRequestFiles[no].strFullPathName, m_arrayRequestFiles[no].pParent, bCheck);
}
}
// listCtrl.SetRedraw(TRUE);
if (bListClear) {
ClearRequestFiles();
}
if (g_bOptShowTotalParent) {
CMySuperGrid &listCtrl = GetListCtrl();
listCtrl.CalcSum(0);
}
// カラム幅の自動調整
if (g_bOptLoadFileAdjustColumn) {
CMySuperGrid &listCtrl = GetListCtrl();
listCtrl.AutoSizeColumns(-1);
}
}
// =============================================
// CSuperTagEditorDoc::ClearRequestFiles
// 概要 : 追加リクエストファイルリストの初期化
// 引数 : none
// 戻り値: none
// =============================================
void CSuperTagEditorDoc::ClearRequestFiles(void)
{
m_arrayRequestFiles.RemoveAll();
m_arrayRequestFiles.SetSize(INIT_ARRAY_SIZE);
m_nArrayRequestFileCount = 0;
}
// =============================================
// CSuperTagEditorDoc::LoadPlayList
// 概要 : プレイリストを読みこみます
// 引数 : sPlayList = プレイリストファイル名(絶対パスで指定)
// 戻り値: bool = true:正常終了 / false:エラー
// =============================================
bool CSuperTagEditorDoc::LoadPlayList(const char *sPlayList)
{
TRY {
CFile file;
// プレイリストファイルのカレントディレクトリを取得
TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR];
_tsplitpath(sPlayList, drive, dir, NULL, NULL);
if (file.Open(sPlayList, CFile::modeRead)) {
CString strLine;
CArchive ar(&file, CArchive::load);
while(ar.ReadString(strLine)) {
if (strLine.GetLength() >= 3) {
if (strLine[0] != '#') {
// リストに追加
if ((strLine[0] == '\\' && strLine[1] == '\\')
|| strLine[1] == ':') {
// 絶対パス
AddRequestFile(strLine, NULL);
} else {
// 相対パス
CString strName;
if (strLine[0] == '\\') {
// ドライブ名無しのルート指定
strName.Format("%s%s", drive, strLine);
} else {
// ルート以外
strName.Format("%s%s%s", drive, dir, strLine);
}
AddRequestFile(strName, NULL);
}
}
}
}
}
}
CATCH( CFileException, e) {
CString str;
str.Format("%s の読み込みに失敗しました", sPlayList);
MessageBox(NULL, str, "ファイルエラー", MB_ICONSTOP|MB_OK|MB_TOPMOST);
}
END_CATCH
return(true);
}
// =============================================
// CSuperTagEditorDoc::FoundFile
// 概要 : ファイル検索:ファイルを発見
// 引数 : sFileName = ファイル名
// : pItemParent = 親アイテム(NULL=ルート)
// : bCheck = チェックマークを付けるかどうか
// 戻り値: bool = true:正常終了 / false:異常終了
// =============================================
bool CSuperTagEditorDoc::FoundFile(const char *sFileName, CSuperGridCtrl::CTreeItem *pItemParent, bool bCheck)
{
// MP3ファイル情報の取得
CFileMP3 fileMP3;
if (fileMP3.Attach(sFileName)) {
int nIndex = m_nArrayFileCount;
// 配列に追加
if (m_nArrayFileCount > m_arrayFiles.GetUpperBound()) {
// 配列が足りない場合は、確保サイズを増加させる
m_arrayFiles.SetSize(m_arrayFiles.GetUpperBound() + ADD_ARRAY_SIZE);
}
m_arrayFiles[m_nArrayFileCount] = fileMP3.m_fileMP3;
m_nArrayFileCount++;
// リストコントロールを取得
CMySuperGrid &listCtrl = GetListCtrl();
if (g_classInfo.nType == 0) {
// フォルダで分類
listCtrl.AddFile(GetListMP3(nIndex), pItemParent, (LPARAM)nIndex, bCheck);
} else {
// タグ情報で分類
listCtrl.AddFile2(GetListMP3(nIndex), pItemParent, (LPARAM)nIndex, bCheck);
}
return(true);
} else {
CString strMessage;
strMessage.Format("%s の読み込みに失敗しました", sFileName);
//MessageBox(NULL, strMessage, "ファイル読み込みエラー", MB_ICONSTOP|MB_OK|MB_TOPMOST);
((CMainFrame *)AfxGetMainWnd())->SetStatusBarText(strMessage); // ステータスバーにエラーを表示
}
return(false);
}
// =============================================
// CSuperTagEditorDoc::SearchFileReent
// 概要 : ファイル検索:検索処理
// 引数 : sDir = 検索するディレクトリ
// : pItemDir = ディレクトリアイテム(NULL=ルート)
// 戻り値: bool = true:正常終了 / false:異常終了
// =============================================
bool CSuperTagEditorDoc::SearchFileReent(const char *sDir, CSuperGridCtrl::CTreeItem *pItemDir)
{
//追加 by Kobarin
if(m_dlgLoadProgress->IsCanceled()){
return true;
}
HANDLE hFindFile;
WIN32_FIND_DATA data;
char *sCurFile = new char [MAX_PATH + 1];
if (sCurFile == NULL) return(false); // 割り当て失敗
// 検索開始ディレクトリの場合の処理
if (pItemDir == NULL) {
// ルートにディレクトリアイテム追加
if (g_classInfo.nType == 0) {
// フォルダで分類
CMySuperGrid &listCtrl = GetListCtrl();
// pItemDir = listCtrl.AddDirectory(sDir, listCtrl.m_itemClassOK, 0);
pItemDir = listCtrl.m_pItemRoot;
}
}
// 同一ディレクトリの全てのファイルを検索
// サブディレクトリの検索は行わない
//static char *sFindPattern[] = {
// "*.rmp", "*.mp3", "*.ape", "*.wma", "*.wmv", "*.asf", "*.ogg"/* Conspiracy 196 */, "*.wav"/* Conspiracy 197 */, "*.avi"/* Conspiracy 197 */, NULL,
//};
extern void GetFileExtList(CStringArray& arExt);
CStringArray arExt;
GetFileExtList(arExt);
for (int nType = 0; nType < arExt.GetSize() ; nType++) {
// 検索ファイルのパターンを設定
sprintf(sCurFile, "%s%s", sDir, "*." + arExt[nType]);
// ファイル検索
if ((hFindFile = FindFirstFile(sCurFile, &data)) != INVALID_HANDLE_VALUE) {
do {
m_dlgLoadProgress->SetPos(0);//追加 by Kobarin
if(m_dlgLoadProgress->IsCanceled()){
break;
}
if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
// ディレクトリ付きファイル名作成
strcpy(sCurFile, sDir);
strcat(sCurFile, data.cFileName);
m_sTargetFile = sCurFile;
// ファイル発見処理
AddRequestFile(m_sTargetFile, pItemDir);
}
} while(FindNextFile(hFindFile, &data) == TRUE);
}
if (hFindFile != INVALID_HANDLE_VALUE) FindClose(hFindFile);
}
if (g_bEnableSearchSubDir) { // サブディレクトリの検索
sprintf(sCurFile, "%s*.*", sDir);
if ((hFindFile = FindFirstFile(sCurFile, &data)) != INVALID_HANDLE_VALUE) {
do {
m_dlgLoadProgress->SetPos(0);//追加 by Kobarin
if(m_dlgLoadProgress->IsCanceled()){
break;
}
if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
if (strcmp(data.cFileName, "." ) != 0 // カレントディレクトリ以外
&& strcmp(data.cFileName, "..") != 0 // 親ディレクトリ以外
&& (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0/* STEP 032 */) { // 隠しフォルダ以外
// ディレクトリ付きファイル名作成
strcpy(sCurFile, sDir);
strcat(sCurFile, data.cFileName);
m_sTargetFile = sCurFile;
// ツリーにディレクトリアイテム追加
CSuperGridCtrl::CTreeItem *pItemSubDir = NULL;
if (g_classInfo.nType == 0) {
// フォルダで分類
CMySuperGrid &listCtrl = GetListCtrl();
pItemSubDir = listCtrl.AddDirectory(data.cFileName, pItemDir);
}
// サブディレクトリ突入処理
strcat(sCurFile, "\\");
if (!SearchFileReent(sCurFile, pItemSubDir)) {
break; // サブディレクトリ検索エラー
}
sCurFile[strlen(sCurFile)-1] = NULL;
m_sTargetFile = sCurFile; // サブディレクトリの処理が入るので再設定
}
}
} while(FindNextFile(hFindFile, &data) == TRUE);
}
if (hFindFile != INVALID_HANDLE_VALUE) FindClose(hFindFile); /* 2004.02.18 こっちに移動 */
}
delete[] sCurFile;
return(true);
}
// =============================================
// CSenkyokuMeijinDoc::SelectDirectory
// 概要 : フォルダ参照ダイアログ処理
// 引数 : sLocal = パス(入出力)
// 戻り値: bool
// =============================================
BOOL CSuperTagEditorDoc::SelectDirectory(char *sLocal)
{
bool bResult;
CSHBrowseForFolder browse(true, g_bEnableSearchSubDir);
bResult = browse.Exec(sLocal);
g_bEnableSearchSubDir = browse.GetSearchSubDirState();
return(bResult);
}
void CSuperTagEditorDoc::OpenFolder(const char *sOpenDir)
{
//追加 by Kobarin
if(IsTagUpdating())//タグを更新中は追加しない
return;
if(m_dlgLoadProgress->IsCanceled()){
//キャンセルボタンが押されている
return ;
}
((CSuperTagEditorApp *)AfxGetApp())->AddToRecentFileList (sOpenDir); /* StartInaction 053 */
// ディレクトリのファイルを読み込む
char sFolderName[_MAX_PATH] = {'\0'};
strcpy(sFolderName, sOpenDir);
int nLen;
nLen = strlen(sFolderName);
if (nLen > 0) {
if (IsFolderName(sFolderName) == false) {
// 最後は '\\' である事
strcat(sFolderName, "\\");
}
// プログレスバー初期化
BOOL bIsOpen = (m_dlgLoadProgress->GetSafeHwnd() == NULL) ? TRUE : FALSE;
if (bIsOpen) StartLoadFile("MP3ファイル読み込み中...");
// フォルダ読み込み
if (g_classInfo.nType == 0) {
// フォルダで分類
CMySuperGrid &listCtrl = GetListCtrl();
TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR];
_tsplitpath(sFolderName, drive, dir, NULL, NULL);
CString str;
str.Format("%s%s", drive, dir);
SearchFileReent(sFolderName, listCtrl.AddDirectory(str, listCtrl.m_pItemRoot, 2));
} else {
// タグ情報で分類
SearchFileReent(sFolderName);
}
// 追加リクエストのあったファイルのタグ情報を読み込む
#ifdef FLICKERFREE
//CMySuperGrid &listCtrl = GetListCtrl();
//listCtrl.SetRedraw(FALSE);
//GetView()->SetRedraw(FALSE);
#endif
ExecRequestFiles(true, g_bOptLoadFileChecked);
#ifdef FLICKERFREE
//listCtrl.SetRedraw(TRUE);
//GetView()->SetRedraw(TRUE);
#endif
// プログレスバー終了
if (bIsOpen) EndLoadFile();
UpdateAllViews(NULL);
}
}
void CSuperTagEditorDoc::OnUpdateOpenFolder(CCmdUI* pCmdUI)
{
pCmdUI->Enable(TRUE);
}
void CSuperTagEditorDoc::OnOpenFolder()
{
char sFolderName[_MAX_PATH] = {'\0'};
// フォルダ選択ダイアログを開く
strcpy(sFolderName, g_strCurrentDirectory);
if (SelectDirectory(sFolderName) == TRUE) {
g_strCurrentDirectory = sFolderName;
OpenFolder(g_strCurrentDirectory);
}
}
BOOL CSuperTagEditorDoc::CanCloseFrame(CFrameWnd* pFrame)
{
if (CheckFileModified()) {
int nResult;
nResult = MessageBox(AfxGetMainWnd()->GetSafeHwnd(), "タグ情報が変更されています。\n"
"変更されているファイルを更新してもよろしいですか?",
"保存確認", MB_YESNOCANCEL);
switch(nResult) {
case IDYES:
//OnSaveAllTag();
SaveAllTag(TRUE);
if (m_bSaveAllTagResult == false) {
return(FALSE);
}
break;
case IDNO:
break;
case IDCANCEL:
return(FALSE);
}
}
InitFileList(); /* Conspiracy 196 */
return CDocument::CanCloseFrame(pFrame);
}
void CSuperTagEditorDoc::OnUpdateSaveAllTag(CCmdUI* pCmdUI)
{
pCmdUI->Enable(TRUE);
}
void CSuperTagEditorDoc::OnSaveAllTag()
{
SaveAllTag(FALSE);
}
void CSuperTagEditorDoc::OnUpdateFileOpen(CCmdUI* pCmdUI)
{
pCmdUI->Enable(FALSE);
}
// [オプション設定]-[全部]
void CSuperTagEditorDoc::OnUpdateDlgEnvironment(CCmdUI* pCmdUI)
{
pCmdUI->Enable(TRUE);
}
void CSuperTagEditorDoc::OnDlgEnvironment()
{
CDlgEnvSheet dialog("オプション設定");
bool bKeepTimeStamp = g_bOptKeepTimeStamp;
bool bHideMP3ListFile = g_bOptHideMP3ListFile;
bool bFileNameMaxCellColor = g_bFileNameMaxCellColor; /* SeaKnows 036 */
dialog.m_pDoc = this;
dialog.DoModal(CDlgEnvSheet::ENV_ALL);
CMySuperGrid &listCtrl = GetListCtrl();
// タイムスタンプ保持の設定項目が変更された
// MP3 List のファイル名表示の有無が変更された
if (bKeepTimeStamp != g_bOptKeepTimeStamp
|| bHideMP3ListFile != g_bOptHideMP3ListFile) {
// 表示を更新させる
listCtrl.UpdateAllFiles();
// カラム幅の自動調整
if (g_bOptLoadFileAdjustColumn) listCtrl.AutoSizeColumns(-1);
}
if (bFileNameMaxCellColor != g_bFileNameMaxCellColor) { /* SeaKnows 036 */
// 表示を更新させる
listCtrl.UpdateAllFiles();
}
// 分類済みフォルダの名称を更新する
listCtrl.UpdateSyncFolderItemName();
// ジャンルリストを更新させる
listCtrl.MakeStrListGenre();
}
BOOL CSuperTagEditorDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
// if (!CDocument::OnOpenDocument(lpszPathName))
// return FALSE;
char sFileName[FILENAME_MAX];
strcpy(sFileName, lpszPathName);
// 初期化処理
if (m_bInitialized == false) { /* StartInaction2 055 */
InitFileList(); // ファイルリストの初期化
ClearRequestFiles(); // 追加リクエストファイルリストの初期化
m_bInitialized = true;
InitPlugin(); // プラグインのロード
// 初期化処理
GetView()->m_List.InitializeGrid();
// フォントの設定
GetView()->UpdateFontListView();
InitGridList(); // グリッドを初期化
}
// プレイリストか?
CString strFileName = sFileName;
strFileName.MakeLower();
if (strFileName.Find(".m3u") != -1) {
// プレイリスト追加
GetView()->LoadPlayList(sFileName);
return(TRUE);
}
// プログレスバー初期化
StartLoadFile("MP3ファイル読み込み中...");
CFileStatus status;
if (CFile::GetStatus(sFileName, status) == TRUE && status.m_mtime != -1) {
if (status.m_attribute & CFile::directory) {
// ディレクトリの場合
// 最後の '\\' は必要
if (IsFolderName(sFileName) == false) {
strcat(sFileName, "\\");
}
bool bEnableSearchSubDir = g_bEnableSearchSubDir; /* TyphoonSwell 026 */
if (g_bOptDropSearchSubFolder) {
g_bEnableSearchSubDir = true;
}
/* WildCherry2 078 */
//SearchFileReent(sFileName);
OpenFolder(sFileName);
g_bEnableSearchSubDir = bEnableSearchSubDir;
} else {
// ファイルの場合(ロングファイル名に変換してから処理する)
if (GetLongPathName(sFileName, status.m_szFullName, FILENAME_MAX) != 0) {
CString strLongFileName;
TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR];
_tsplitpath(status.m_szFullName, drive, dir, NULL, NULL);
strLongFileName.Format("%s%s%s", drive, dir, sFileName);
AddRequestFile(strLongFileName, NULL);
}
}
} else if (strlen(sFileName) == 3 && sFileName[1] == ':' && sFileName[2] == '\\') { /* STEP 027 */
// ドライブの場合
// 下位階層を検索
bool bEnableSearchSubDir = g_bEnableSearchSubDir;
if (g_bOptDropSearchSubFolder) {
g_bEnableSearchSubDir = true;
}
OpenFolder(sFileName);
g_bEnableSearchSubDir = bEnableSearchSubDir;
}
// 追加リクエストのあったファイルのタグ情報を読み込む
#ifdef FLICKERFREE
//GetView()->SetRedraw(FALSE);
#endif
ExecRequestFiles(true, g_bOptLoadFileChecked);
#ifdef FLICKERFREE
//GetView()->SetRedraw(TRUE);
#endif
// プログレスバー終了
EndLoadFile();
UpdateAllViews(NULL);
return(TRUE);
}
// SI フィールドを表示/編集
void CSuperTagEditorDoc::OnUpdateEditFieldSi(CCmdUI* pCmdUI)
{
pCmdUI->Enable(TRUE);
pCmdUI->SetCheck(g_bOptEditFieldSIF ? TRUE : FALSE);
}
void CSuperTagEditorDoc::OnEditFieldSi()
{
if (g_bOptEditFieldSIF != true) {
g_bOptEditFieldSIF = true;
// 情報を更新
UpdateAllFiles(true);
}
}
// ID3 tag 情報を表示/編集
void CSuperTagEditorDoc::OnUpdateEditTd3Tag(CCmdUI* pCmdUI)
{
pCmdUI->Enable(TRUE);
pCmdUI->SetCheck(g_bOptEditFieldSIF ? FALSE : TRUE);
}
void CSuperTagEditorDoc::OnEditTd3Tag()
{
if (g_bOptEditFieldSIF != false) {
g_bOptEditFieldSIF = false;
// 情報を更新
UpdateAllFiles(true);
}
}
// [ID3 tag] <=> [SIフィールド]を切替
void CSuperTagEditorDoc::OnUpdateEditChangeField(CCmdUI* pCmdUI)
{
pCmdUI->Enable(TRUE);
}
void CSuperTagEditorDoc::OnEditChangeField()
{
g_bOptEditFieldSIF = g_bOptEditFieldSIF ? false : true;
// 情報を更新
UpdateAllFiles(true);
}
// 分類表示の更新
void CSuperTagEditorDoc::OnUpdateExecClassification(CCmdUI* pCmdUI)
{
pCmdUI->Enable((m_nArrayFileCount > 0 && g_classInfo.nType) ? TRUE : FALSE);
}
void CSuperTagEditorDoc::OnExecClassification()
{
// プレイリスト読みこみ
StartLoadFile("分類表示を更新中...");
m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "処理中...");
m_dlgLoadProgress->EnableCancelButton(FALSE);
// グリッドに再登録
CMySuperGrid &listCtrl = GetListCtrl();
listCtrl.DeleteAllEx(); // グリッドを初期化
for (int no = 0; no < m_nArrayFileCount; no++) {
// プログレスバー更新
if (m_nArrayFileCount > 1) {
m_dlgLoadProgress->SetPos(no * 100 / (m_nArrayFileCount-1));
}
// フォルダで分類
if (GetListMP3(no)->nFormat != FILE_FORMAT_UNKNOWN) {
listCtrl.AddFile2(GetListMP3(no), NULL, (LPARAM)no, g_bOptLoadFileChecked);
}
}
// ファイルのタグ情報を読み込む
EndLoadFile();
UpdateAllViews(NULL);
}
#include "DlgFileOverWrite.h"
bool CSuperTagEditorDoc::CheckFileAttribute(FILE_MP3 *fileMP3)
{
extern int g_nWriteTagProcFlag;
if (g_nWriteTagProcFlag == 3) {
return(false); // 以降中止
}
// ファイル情報を取得
CFileStatus fileStatus;
if (CFile::GetStatus(fileMP3->strFullPathName, fileStatus) == FALSE) {
return(false);
}
// 読み出し専用ファイルは、上書き確認を行う
if (fileStatus.m_attribute & CFile::readOnly) {
if (g_nWriteTagProcFlag != 1) {
// 上書き確認ダイアログを開く
CDlgFileOverWrite dialog;
dialog.m_strFileName = fileMP3->strFullPathName;
dialog.m_strSize.Format("%ld byte", fileStatus.m_size);
if (fileStatus.m_mtime.GetTime() < 0) {
dialog.m_strTimeStamp.Format("----/--/-- --:--:--");
} else {
dialog.m_strTimeStamp.Format("%04d/%02d/%02d %02d:%02d:%02d",
fileStatus.m_mtime.GetYear(),
fileStatus.m_mtime.GetMonth(),
fileStatus.m_mtime.GetDay(),
fileStatus.m_mtime.GetHour(),
fileStatus.m_mtime.GetMinute(),
fileStatus.m_mtime.GetSecond());
}
dialog.DoModal();
g_nWriteTagProcFlag = dialog.m_nResult;
switch(dialog.m_nResult) {
case 0: // このファイルを上書き
case 1: // 以降全て上書き
break;
case 2: // スキップ
case 3: // 中止
default:
return(false);
}
}
// 読み込み専用属性を解除
SetFileAttributes(fileMP3->strFullPathName, CFile::normal);
}
return(true);
}
void CSuperTagEditorDoc::OnDlgSetupPlugin()
{
// TODO: この位置にコマンド ハンドラ用のコードを追加してください
CDlgPluginSetup dialog;
if (dialog.DoModal() == IDOK) {
((CSuperTagEditorApp *)AfxGetApp())->UpdateAccelerator(); /* STEP 030 */
}
}
void CSuperTagEditorDoc::OnUpdateDlgSetupPlugin(CCmdUI* pCmdUI)
{
// TODO: この位置に command update UI ハンドラ用のコードを追加してください
pCmdUI->Enable(TRUE);
}
void CSuperTagEditorDoc::SaveAllTag(BOOL bSaveOnly)
{
m_bSaveAllTagResult = true;
extern int g_nWriteTagProcFlag;
// プログレスバー表示
StartLoadFile("タグ情報を更新中...");
m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "処理中...");
// 更新ファイルのタグ情報更新
g_nWriteTagProcFlag = 0;
for (int no = 0; no < m_nArrayFileCount; no++) {
FILE_MP3 *fileMP3 = GetListMP3(no);
if (m_nArrayFileCount != 1) {
// プログレスバー更新
m_dlgLoadProgress->SetPos(no * 100 / (m_nArrayFileCount-1));
// 追加 by Kobarin
if(m_dlgLoadProgress->IsCanceled()){
m_bSaveAllTagResult = false;
break;
}
}
if (fileMP3->nFormat != FILE_FORMAT_UNKNOWN && fileMP3->bModifyFlag) {
if (CFileMP3::WriteTag(fileMP3, g_bOptKeepTimeStamp)) {
fileMP3->bModifyFlag = FALSE;
} else {
MessageBox(NULL, "タグ情報をファイルを更新できませんでした", fileMP3->strFullPathName, MB_ICONSTOP|MB_OK|MB_TOPMOST);
m_bSaveAllTagResult = false;
}
}
}
// プログレスバー終了
EndLoadFile();
if (bSaveOnly) return;
// 情報を更新
CMySuperGrid &listCtrl = GetListCtrl();
#ifdef FLICKERFREE
//listCtrl.SetRedraw(FALSE);
#endif
listCtrl.UpdateAllFiles();
UpdateAllFiles(true);
if (g_bOptLoadFileAdjustColumn) listCtrl.AutoSizeColumns(-1); /* 2003.06.26 */
#ifdef FLICKERFREE
//listCtrl.SetRedraw(TRUE);
#endif
}
| [
"mimura1133@yahoo.co.jp"
] | mimura1133@yahoo.co.jp |
87d1637e4a0df057a6e8f5950f07b11f9830d693 | 65e3391b6afbef10ec9429ca4b43a26b5cf480af | /PHOS/macros/Trigger/raw/AliTRUPedestalAnalysis.h | 45236bd1bb6e26669e1cc3babb4b4eafa60b0df9 | [] | permissive | alisw/AliRoot | c0976f7105ae1e3d107dfe93578f819473b2b83f | d3f86386afbaac9f8b8658da6710eed2bdee977f | refs/heads/master | 2023-08-03T11:15:54.211198 | 2023-07-28T12:39:57 | 2023-07-28T12:39:57 | 53,312,169 | 61 | 299 | BSD-3-Clause | 2023-07-28T13:19:50 | 2016-03-07T09:20:12 | C++ | UTF-8 | C++ | false | false | 1,436 | h | /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// Author: Henrik Qvigstad <henrik.qvigstad@cern.ch>
/* $Id$ */
#ifndef ALITRUPEDESTALANALYSIS_H
#define ALITRUPEDESTALANALYSIS_H
#include <Rtypes.h>
class AliCaloRawStreamV3;
class AliTRUPedestalOutput;
class AliPHOSTriggerRawReader;
class AliTRUPedestalAnalysis
{
public:
AliTRUPedestalAnalysis();
virtual ~AliTRUPedestalAnalysis();
void ProcessEvent(AliCaloRawStreamV3* );
AliTRUPedestalOutput* GetOutput() { return fOutput; }
static UInt_t Get2x2Max(AliPHOSTriggerRawReader* reader, int mod, int row, int branch, int x, int z);
// Constants
const static UInt_t kNMods = 5;
const static UInt_t kNTRURows = 4;
const static UInt_t kNBranches = 2;
const static UInt_t kN2x2X = 64/2;
const static UInt_t kN2x2Z = 56/2;
const static UInt_t kN2x2XPrTRURow = kN2x2X / kNTRURows;
const static UInt_t kN2x2ZPrBranch = kN2x2Z / kNBranches;
const static UInt_t kNTRUTimeBins = 128;
const static UInt_t kNEMCTimeBins = 62;
private:
AliTRUPedestalAnalysis ( const AliTRUPedestalAnalysis& other ); // not impl.
AliTRUPedestalAnalysis& operator= ( const AliTRUPedestalAnalysis& other ); // not impl.
AliTRUPedestalOutput* fOutput;
AliPHOSTriggerRawReader* fTriggerReader;
};
#endif // ALITRUPEDESTALANALYSIS_H
| [
"hqvigsta@f7af4fe6-9843-0410-8265-dc069ae4e863"
] | hqvigsta@f7af4fe6-9843-0410-8265-dc069ae4e863 |
5820f160b3afabc47c2fa60ee76523fee14bacc2 | 17f5ceec908be809e16e201856140ce9c11cd37a | /ABGameMode.h | 2fb2b383972ff114f3ef7866376e923f74b0ea67 | [] | no_license | kojea0919/UE4_BookCode | cd27ceedb14af51641de955a7bde6f54f1981b2d | 3ce9b42b1773e24f5c94d57eb55fe2e8f3e78439 | refs/heads/master | 2020-07-07T11:14:49.929238 | 2019-08-20T08:29:30 | 2019-08-20T08:29:30 | 203,333,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "ArenaBattle.h"
#include "GameFramework/GameModeBase.h"
#include "ABGameMode.generated.h"
/**
*
*/
UCLASS()
class ARENABATTLE_API AABGameMode : public AGameModeBase
{
GENERATED_BODY()
AABGameMode();
public:
virtual void PostLogin(APlayerController * NewPlayer) override;
};
| [
"gottkf0919@naver.com"
] | gottkf0919@naver.com |
1be87b75c9cbf4a266a03b0f66087b7c618af7cd | b7f1758aa724c14248e3dd426417c7b861c03df0 | /libraries/microLED/examples/other_func/other_func.ino | 644b01a107413105c9062734d7581206b5d365e2 | [
"MIT"
] | permissive | AlexGyver/GyverDrink | 9ce774b99d12d7543f3242e9b3d06be4417bc4ad | 78e83d8fb7ab93b2ba84f5721c5fd36c8b0a47a6 | refs/heads/master | 2022-03-08T10:48:35.548930 | 2021-09-09T16:11:03 | 2021-09-09T16:11:03 | 217,405,392 | 32 | 23 | MIT | 2022-02-25T21:42:05 | 2019-10-24T22:21:42 | C++ | UTF-8 | C++ | false | false | 1,706 | ino | // пример работы с лентой
#define LED_PIN 6 // пин ленты
#define NUMLEDS 64 // кол-во светодиодов
#define ORDER_GRB // порядок цветов ORDER_GRB / ORDER_RGB / ORDER_BRG
#define MAX_DATA_SPEED // разогнанный протокол связи (на 40% быстрее). Работает на ws2812/13. На 2811 не работает
#define COLOR_DEBTH 2 // цветовая глубина: 1, 2, 3 (в байтах)
// на меньшем цветовом разрешении скетч будет занимать в разы меньше места,
// но уменьшится и количество оттенков и уровней яркости!
// ВНИМАНИЕ! define настройки (ORDER_GRB и COLOR_DEBTH) делаются до подключения библиотеки!
#include <microLED.h>
LEDdata leds[NUMLEDS]; // буфер ленты типа LEDdata (размер зависит от COLOR_DEBTH)
microLED strip(leds, NUMLEDS, LED_PIN); // объект лента
void setup() {
strip.setBrightness(30); // яркость (0-255)
// яркость применяется при выводе .show() !
strip.setVoltage(4500); // установить напряжение питания в мв, по умолч. 5000 (для расчёта тока)
strip.setMaxCurrent(700); // установить максимальный ток (автокоррекция яркости). 0 - выключено
// при .show() яркость будет скорректирована, чтобы ток не превышал установленный
}
void loop() {
}
| [
"victor.glekler@gmail.com"
] | victor.glekler@gmail.com |
0af3244911f3596061df2f84decb9cbd8709c4ea | db628fea8fef4587a806c38e1f4cb0b45616005e | /Source/Spriter/Public/SpriterImportData.h | 62a8d420fe05f78fc47811d0a4dd99f7dc12f5d6 | [] | no_license | FashGek/Spriter-1 | a1dd0a9546aa41c6311e96acca1b1c8cf78c8eef | 5a625a65e366f2d27de6936fec1eb18eb928d090 | refs/heads/master | 2021-06-01T05:07:40.233449 | 2016-05-29T10:43:59 | 2016-05-29T10:43:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "SpriterDataModel.h" //@TODO: For debug only
#include "SpriterImportData.generated.h"
// This is the 'hub' asset that tracks other imported assets for a rigged sprite character exported from Spriter
UCLASS(BlueprintType)
class SPRITER_API USpriterImportData : public UObject
{
GENERATED_UCLASS_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spriter")
FSpriterSCON ImportedData;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spriter")
float PixelsPerUnrealUnit;
// Import data for this
UPROPERTY(EditAnywhere, Instanced, Category=ImportSettings)
class UAssetImportData* AssetImportData;
/** Override to ensure we write out the asset import data */
virtual void GetAssetRegistryTags(TArray<FAssetRegistryTag>& OutTags) const override;
};
| [
"jacobmaley@yahoo.com"
] | jacobmaley@yahoo.com |
a4b8aa2b754d907b2fff02dfbcf60412ceed77eb | 3279a02a10e0ddda4029d0db9c538dfb0014aa31 | /Towers/Towers/towers.cpp | 8c27958b16e636916de3d09634152ca2556f505d | [] | no_license | chengjieyun59/UCLA_CS32_projects | 02089f968205b2ae544118cd29393456efabc98b | 6320db86896538d09e1098f52f9201ac56803d40 | refs/heads/master | 2021-05-05T15:25:13.871335 | 2020-05-02T06:20:30 | 2020-05-02T06:20:30 | 117,296,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,476 | cpp | #include <stack>
#include <iostream>
using namespace std;
#include "towers.h"
TowersOfHanoi::TowersOfHanoi() {
num_disks = 3;
for (int i = num_disks - 1; i >= 0; --i) {
m_towers[0].push(i);
}
printGameState();
}
TowersOfHanoi::TowersOfHanoi(int n) {
this->num_disks = n;
for (int i = n - 1; i >= 0; --i) {
m_towers[0].push(i);
}
printGameState();
}
// function that doesn't return, but prints some result
// you can move a disk from one tower to any other tower
// as long as you obey the rule that a larger disk (larger
// int) can never be place on top of a smaller disk
void TowersOfHanoi::moveDisk(int fromTower, int toTower) {
cout << "\n\n\n";
if (fromTower == toTower) {
cout << "No point in moving a disk to the same tower!\n";
}
else if (m_towers[fromTower].empty()) {
cout << "Nothing on that tower to move!\n";
}
else if (m_towers[toTower].empty()) {
int fromDisk = m_towers[fromTower].top();
cout << "Moved " << fromDisk << " from tower " << fromTower
<< " to tower " << toTower << " which was empty\n";
m_towers[fromTower].pop();
m_towers[toTower].push(fromDisk);
}
else {
int fromDisk = m_towers[fromTower].top();
int toDisk = m_towers[toTower].top();
if (toDisk < fromDisk) {
cout << "Can't place a larger disk on a smaller disk!\n";
return;
}
else {
cout << "Moved disk sized " << fromDisk << " from tower "
<< fromTower << " to tower " << toTower << " which had "
<< toDisk << " at the top." << endl;
m_towers[fromTower].pop();
m_towers[toTower].push(fromDisk);
}
}
printGameState();
}
void TowersOfHanoi::printGameState() {
// print out each of the towers
for (int i = 0; i < 3; ++i) {
cout << i << endl;
stack<int> temp = m_towers[i];
while (!temp.empty()) {
int disk_size = temp.top() + 1;
temp.pop();
// print disk_size X's
for (int j = 0; j < disk_size; ++j) {
cout << 'X';
}
cout << endl;
}
cout << endl;
}
checkWonState();
}
void TowersOfHanoi::checkWonState() {
// won state
if (m_towers[0].empty() && m_towers[2].empty()) {
stack<int> temp = m_towers[1];
bool won = true;
while (temp.size() > 1) {
int top = temp.top();
temp.pop();
int next = temp.top();
if (top > next) {
won = false;
}
}
if (won) {
cout << "CONGRATULATIONS YOU WON!!!\n";
}
}
}
int main() {
TowersOfHanoi toh;
toh.moveDisk(0, 1);
toh.moveDisk(0, 2);
toh.moveDisk(1, 2);
toh.moveDisk(0, 1);
toh.moveDisk(0, 2);
toh.moveDisk(2, 0);
toh.moveDisk(2, 1);
toh.moveDisk(0, 1);
return 0;
}
#include <stack>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
//
//
// STACK STUFF
//
//
// correctParens - takes in a stack of chars that (from the bottom up)
// is a string of parens, valid or not
// this function should return true if it's a valid parenthesis string
// and false if not
bool correctParens(stack<char>& s) {
stack<char> temp;
while (!s.empty()) {
if (s.top() == ')') {
// put all preceding closed parens in stack
while (s.top() == ')' && !s.empty()) {
temp.push(s.top());
s.pop();
}
// pop one off of temp for each subsequent open you get
while (!s.empty() && s.top() == '(') {
temp.pop();
s.pop();
}
}
// if you're ever looking at an open paren
// without having seen an closed one, it's no good
else {
return false;
}
}
return temp.empty();
}
// binarytoDecimal
// if you wanna read binary right to left,
// push everything into a stack (right goes in last) and
// pop out one at a time, adding in accordingly
// BUT if you wanna read left to right ... you can use a
// queue and read the front then pop
// little endian: least significant value is stored first
// so you read it left to right -- QUEUE
// big endian: most significant value is stored first
// so you read it right to left -- STACK
int binaryToDecimal(string s) {
// need to convert string to stack of 1's and 0's
// push all of the bits into a stack so that you
// can easily read them backwards and add in 2^pos
// or not
stack<int> binary; // change to queue if little endian
for (int i = 0; i < s.size(); ++i) {
binary.push(int(s[i]) - 48);
}
int pos = 0;
int ret = 0;
// run through the stack, adding in 2^pos if 1 or not
while (!binary.empty()) {
if (binary.top() == 1) { // change to front if little endian
ret += pow(2, pos);
}
binary.pop();
++pos;
}
return ret;
}
//
//
// QUEUE STUFF
//
//
// this function takes in n, a number of people
// and m, meaning each mth person will be killed
// until there is just one person left
void dontGetKilled(int m, int n) {
queue<int> s;
// push all of the people into a queue
for (int i = 0; i < n; ++i) {
s.push(i);
}
// you know all of the positions that are going to be killed
// by printing and popping every m people until the queue is empty
// the last person's position to be printed is not going to die
while (!s.empty()) {
// to avoid modulus, we can keep a countdown of people
// to not kill and once that's 0, kill that person
int betweeners = m - 1;
while (betweeners != 0) {
// every
s.push(s.front());
s.pop();
--betweeners;
}
// kill the mth person - print them out and
// take them out of the queue
cout << s.front() << " " ;
s.pop();
}
cout << endl;
}
| [
"chengjieyun59@gmail.com"
] | chengjieyun59@gmail.com |
158bd88e06fd85fe2d19f1e100a1c1311c73e663 | 46811b2012137ff6daaf22385d78c4aa0f6a5880 | /SourceCode/ModelClass.h | bb95a0cf09fdd23f3d15cf01eae1a713e52250b7 | [] | no_license | maggyo07/SelfMadeLibrary | e8ae444abcfa63dd80c7ab033ab359d8ac2b4cd0 | d5ebe4b2bd48751f5a7782f3368b89194a4392dc | refs/heads/master | 2020-06-09T12:01:15.025097 | 2019-06-24T05:31:36 | 2019-06-24T05:31:36 | 193,434,327 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,380 | h | #pragma once
//システム系のヘッダーインクルード
#include <d3d11.h>
#include <D3DX10math.h>
#include <fstream>
//Gameシステム用ヘッダー(自作)インクルード
#include "TextureArrayClass.h"
using namespace std;
//3Dモデルのジオメトリをカプセル化
class ModelClass
{
private:
//頂点情報(シェーダーのものと同じになければならない)
struct VertexType
{
D3DXVECTOR3 position;
D3DXVECTOR2 texture;
D3DXVECTOR3 normal;
D3DXVECTOR3 tangent;
D3DXVECTOR3 binormal;
};
struct ModelType
{
float x, y, z; //位置
float tu, tv; //テクスチャ座標
float nx, ny, nz; //法線
float tx, ty, tz; //
float bx, by, bz; //
};
//タンジェントとバイノーマルの計算に使う
struct TempVertexType
{
float x, y, z;
float tu, tv;
float nx, ny, nz;
};
public:
ModelClass();
ModelClass(const ModelClass&);
~ModelClass();
//初期化関数
bool Initialize(WCHAR* modelFilename);
//シャットダウン関数
void Shutdown();
//ファイル名からテクスチャを読み込む
bool LoadTexture(WCHAR*);
//描画関数
void Render(ID3D11DeviceContext*);
//モデルの接線ベクトルと二値ベクトルを計算用
void CalculateModelVectors();
void CalculateTangentBinormal(TempVertexType, TempVertexType, TempVertexType,D3DXVECTOR3&,D3DXVECTOR3&);
void CalculateNormal(D3DXVECTOR3, D3DXVECTOR3, D3DXVECTOR3&);
int GetIndexCount();
ID3D11ShaderResourceView** GetTextureArray();
private:
//初期化関数(モデルの読み込み、バッファを作成)
bool InitalizeBuffers(const WCHAR* modelFilename);
//シャットダウン関数(バッファ専用)
void ShutdownBuffers();
//描画関数(GPUの入力アセンブラで頂点、インデックスバッファをアクティブに設定する)
void RenderBuffers(ID3D11DeviceContext*);
void ReleaseTexture();
//ファイルからモデル情報を読み込む
bool LoadModel(const WCHAR* filename, VertexType*& vertexs, unsigned long*& indices);
void ReleaseModel();
private:
ID3D11Buffer* m_vertex_buffer; //頂点バッファ
ID3D11Buffer* m_index_buffer; //インデックスバッファ
int m_vertex_count; //頂点の数
int m_index_count; //インデックスの数
TextureArrayClass* m_texture_array; //テクスチャデータ
ModelType* m_model; //モデル情報
}; | [
"h1201619006@hiratagakuen.onmicrosoft.com"
] | h1201619006@hiratagakuen.onmicrosoft.com |
01fd5618f36525edee24474e7ce0c5b91bf29e7e | 23513134b9a28be57b9bb325a4873174df3008d8 | /src/system/modules/ext2/Ext2Node.h | aefce54ca5348c0b047551e0b7c7c75dc28b806c | [] | no_license | berkus/pedigree | 1012c29e78acb17c3696dcb2061a07f0515c88b7 | 9e2af017526a91566cc9560f9bb31b1cac784a3f | refs/heads/master | 2023-09-01T21:28:46.221619 | 2009-04-13T16:40:11 | 2009-04-13T16:40:11 | 32,474,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,364 | h | /*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef EXT2_NODE_H
#define EXT2_NODE_H
#include "ext2.h"
#include <utilities/Vector.h>
#include "Ext2Filesystem.h"
/** A node in an ext2 filesystem. */
class Ext2Node
{
private:
/** Copy constructors are hidden - unused! */
Ext2Node(const Ext2Node &file);
Ext2Node& operator =(const Ext2Node&);
public:
/** Constructor, should be called only by a Filesystem. */
Ext2Node(uintptr_t inode_num, Inode inode, class Ext2Filesystem *pFs);
/** Destructor */
virtual ~Ext2Node();
Inode *getInode()
{return &m_Inode;}
uint32_t getInodeNumber()
{return m_InodeNumber;}
/** Updates inode attributes. */
void fileAttributeChanged(size_t size, size_t atime, size_t mtime, size_t ctime);
uint64_t read(uint64_t location, uint64_t size, uintptr_t buffer);
uint64_t write(uint64_t location, uint64_t size, uintptr_t buffer);
void truncate();
protected:
/** Ensures the inode is at least 'size' big. */
bool ensureLargeEnough(size_t size);
bool addBlock(uint32_t blockValue);
bool ensureBlockLoaded(size_t nBlock);
bool getBlockNumber(size_t nBlock);
bool getBlockNumberIndirect(uint32_t inode_block, size_t nBlocks, size_t nBlock);
bool getBlockNumberBiindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock);
bool getBlockNumberTriindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock);
bool setBlockNumber(size_t blockNum, uint32_t blockValue);
Inode m_Inode;
uint32_t m_InodeNumber;
class Ext2Filesystem *m_pExt2Fs;
uint32_t *m_pBlocks;
uint32_t m_nBlocks;
size_t m_nSize;
};
#endif
| [
"mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d"
] | mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d |
57c4a1b988cbf9d3f59bc38076d83bba8b55f2f4 | 4bd36dae2e4e69e9d04438b9197ae23bbab255e1 | /Status/GeneratedFiles/ui_s_functionButtonWidget.h | e24a5f17dca915fb3cbf3c78b0053079d7c2f5bb | [] | no_license | StatusOnIineEducationDev/status-desktop | 6b40704a25b8082a22bb16ea923dacd2f20e6938 | f8632fa835306a8ec34d5324cd1f44406b1dcdb5 | refs/heads/master | 2020-07-30T19:29:04.119987 | 2019-12-30T11:22:54 | 2019-12-30T11:22:54 | 210,332,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,571 | h | /********************************************************************************
** Form generated from reading UI file 's_functionButtonWidget.ui'
**
** Created by: Qt User Interface Compiler version 5.13.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_S_FUNCTIONBUTTONWIDGET_H
#define UI_S_FUNCTIONBUTTONWIDGET_H
#include <QtCore/QVariant>
#include <QtGui/QIcon>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFrame>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_StudentFunctionButtonWidget
{
public:
QVBoxLayout *verticalLayout;
QLabel *function_navigation_text;
QPushButton *course_management_btn;
QPushButton *online_classroom_btn;
QPushButton *history_btn;
QFrame *line_2;
QLabel *other_navigation_text;
QPushButton *setting_btn;
QPushButton *document_btn;
QButtonGroup *buttonGroup;
void setupUi(QWidget *StudentFunctionButtonWidget)
{
if (StudentFunctionButtonWidget->objectName().isEmpty())
StudentFunctionButtonWidget->setObjectName(QString::fromUtf8("StudentFunctionButtonWidget"));
StudentFunctionButtonWidget->resize(155, 248);
StudentFunctionButtonWidget->setStyleSheet(QString::fromUtf8("QPushButton { \n"
" text-align: left;\n"
" padding-left: 15px;\n"
" border: none;\n"
" color: #79A0BA;;\n"
" background-color: none;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
" background-color: #385368;\n"
"}\n"
"\n"
"QPushButton:checked {\n"
" background-color: #537b9b;\n"
" border-left: 5px solid #699BC3;\n"
"}"));
verticalLayout = new QVBoxLayout(StudentFunctionButtonWidget);
verticalLayout->setSpacing(5);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
function_navigation_text = new QLabel(StudentFunctionButtonWidget);
function_navigation_text->setObjectName(QString::fromUtf8("function_navigation_text"));
function_navigation_text->setMinimumSize(QSize(155, 30));
function_navigation_text->setMaximumSize(QSize(155, 30));
QFont font;
font.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221"));
font.setPointSize(10);
function_navigation_text->setFont(font);
function_navigation_text->setStyleSheet(QString::fromUtf8("QLabel {\n"
" color: #5b788c;\n"
"}"));
function_navigation_text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
verticalLayout->addWidget(function_navigation_text);
course_management_btn = new QPushButton(StudentFunctionButtonWidget);
buttonGroup = new QButtonGroup(StudentFunctionButtonWidget);
buttonGroup->setObjectName(QString::fromUtf8("buttonGroup"));
buttonGroup->addButton(course_management_btn);
course_management_btn->setObjectName(QString::fromUtf8("course_management_btn"));
course_management_btn->setMinimumSize(QSize(155, 30));
course_management_btn->setMaximumSize(QSize(155, 30));
course_management_btn->setFont(font);
course_management_btn->setCursor(QCursor(Qt::PointingHandCursor));
course_management_btn->setStyleSheet(QString::fromUtf8(""));
QIcon icon;
icon.addFile(QString::fromUtf8(":/button/Resources/material/button/course.png"), QSize(), QIcon::Normal, QIcon::Off);
course_management_btn->setIcon(icon);
course_management_btn->setIconSize(QSize(18, 18));
course_management_btn->setCheckable(true);
course_management_btn->setChecked(true);
verticalLayout->addWidget(course_management_btn);
online_classroom_btn = new QPushButton(StudentFunctionButtonWidget);
buttonGroup->addButton(online_classroom_btn);
online_classroom_btn->setObjectName(QString::fromUtf8("online_classroom_btn"));
online_classroom_btn->setMinimumSize(QSize(155, 30));
online_classroom_btn->setMaximumSize(QSize(155, 30));
online_classroom_btn->setFont(font);
online_classroom_btn->setCursor(QCursor(Qt::PointingHandCursor));
online_classroom_btn->setStyleSheet(QString::fromUtf8(""));
QIcon icon1;
icon1.addFile(QString::fromUtf8(":/button/Resources/material/button/interaction.png"), QSize(), QIcon::Normal, QIcon::Off);
online_classroom_btn->setIcon(icon1);
online_classroom_btn->setIconSize(QSize(18, 18));
online_classroom_btn->setCheckable(true);
verticalLayout->addWidget(online_classroom_btn);
history_btn = new QPushButton(StudentFunctionButtonWidget);
buttonGroup->addButton(history_btn);
history_btn->setObjectName(QString::fromUtf8("history_btn"));
history_btn->setMinimumSize(QSize(155, 30));
history_btn->setMaximumSize(QSize(155, 30));
history_btn->setFont(font);
history_btn->setCursor(QCursor(Qt::PointingHandCursor));
history_btn->setStyleSheet(QString::fromUtf8(""));
QIcon icon2;
icon2.addFile(QString::fromUtf8(":/button/Resources/material/button/history.png"), QSize(), QIcon::Normal, QIcon::Off);
history_btn->setIcon(icon2);
history_btn->setIconSize(QSize(18, 18));
history_btn->setCheckable(true);
verticalLayout->addWidget(history_btn);
line_2 = new QFrame(StudentFunctionButtonWidget);
line_2->setObjectName(QString::fromUtf8("line_2"));
line_2->setFrameShape(QFrame::HLine);
line_2->setFrameShadow(QFrame::Sunken);
verticalLayout->addWidget(line_2);
other_navigation_text = new QLabel(StudentFunctionButtonWidget);
other_navigation_text->setObjectName(QString::fromUtf8("other_navigation_text"));
other_navigation_text->setMinimumSize(QSize(155, 30));
other_navigation_text->setMaximumSize(QSize(155, 30));
other_navigation_text->setFont(font);
other_navigation_text->setStyleSheet(QString::fromUtf8("QLabel {\n"
" color: #5b788c;\n"
"}"));
other_navigation_text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
verticalLayout->addWidget(other_navigation_text);
setting_btn = new QPushButton(StudentFunctionButtonWidget);
buttonGroup->addButton(setting_btn);
setting_btn->setObjectName(QString::fromUtf8("setting_btn"));
setting_btn->setMinimumSize(QSize(155, 30));
setting_btn->setMaximumSize(QSize(155, 30));
setting_btn->setFont(font);
setting_btn->setCursor(QCursor(Qt::PointingHandCursor));
setting_btn->setStyleSheet(QString::fromUtf8(""));
QIcon icon3;
icon3.addFile(QString::fromUtf8(":/button/Resources/material/button/setting.png"), QSize(), QIcon::Normal, QIcon::Off);
setting_btn->setIcon(icon3);
setting_btn->setIconSize(QSize(18, 18));
setting_btn->setCheckable(true);
verticalLayout->addWidget(setting_btn);
document_btn = new QPushButton(StudentFunctionButtonWidget);
buttonGroup->addButton(document_btn);
document_btn->setObjectName(QString::fromUtf8("document_btn"));
document_btn->setMinimumSize(QSize(155, 30));
document_btn->setMaximumSize(QSize(155, 30));
document_btn->setFont(font);
document_btn->setCursor(QCursor(Qt::PointingHandCursor));
document_btn->setStyleSheet(QString::fromUtf8(""));
QIcon icon4;
icon4.addFile(QString::fromUtf8(":/button/Resources/material/button/document.png"), QSize(), QIcon::Normal, QIcon::Off);
document_btn->setIcon(icon4);
document_btn->setIconSize(QSize(18, 18));
document_btn->setCheckable(true);
verticalLayout->addWidget(document_btn);
retranslateUi(StudentFunctionButtonWidget);
QMetaObject::connectSlotsByName(StudentFunctionButtonWidget);
} // setupUi
void retranslateUi(QWidget *StudentFunctionButtonWidget)
{
StudentFunctionButtonWidget->setWindowTitle(QCoreApplication::translate("StudentFunctionButtonWidget", "Form", nullptr));
function_navigation_text->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\212\237\350\203\275\350\217\234\345\215\225", nullptr));
course_management_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \350\257\276\347\250\213\347\256\241\347\220\206", nullptr));
online_classroom_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\234\250\347\272\277\346\225\231\345\256\244", nullptr));
history_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\216\206\345\217\262\350\256\260\345\275\225", nullptr));
other_navigation_text->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\205\266\344\273\226", nullptr));
setting_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \350\256\276\347\275\256", nullptr));
document_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \344\275\277\347\224\250\345\270\256\345\212\251", nullptr));
} // retranslateUi
};
namespace Ui {
class StudentFunctionButtonWidget: public Ui_StudentFunctionButtonWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_S_FUNCTIONBUTTONWIDGET_H
| [
"lanyangbo@foxmail.com"
] | lanyangbo@foxmail.com |
ca03f5c263c449a259def270f1e820f29e150b49 | f6f1053bc63911d671c5699dbf304e245ae646e4 | /control_system/control_system/tests/SIL_sysMSD.cpp | b9dfdba1347e07e0857f803e39e48a998d6616c8 | [] | no_license | gordon1258/control_system | 635bb76486d322609cc2a97ac326534e7849029a | 04c435fa3f90163994d5e8395f241020084890f3 | refs/heads/master | 2020-11-25T05:14:42.896164 | 2020-02-02T01:11:27 | 2020-02-02T01:11:27 | 228,512,930 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,092 | cpp | //
// SIL_sysMSD.cpp
// control_systemUT
//
// Created by Li-Cheng Hsu on 1/31/20.
// Copyright © 2020 Li-Cheng Hsu. All rights reserved.
//
#include <stdio.h>
#include "gtest/gtest.h"
// GNUplot headers
#include "gnuplot-iostream.h"
#include <map>
#include <vector>
#include <boost/tuple/tuple.hpp>
#include "mass_spring_damper.hpp"
#include "pid.hpp"
TEST(SIL_sysMSD_pid, SIL_test_sysMSD_pid)
{
// Mass-spring-damper system with PID controller
sysMSD* sys;
pid* pidCtrl;
sys = new sysMSD;
pidCtrl = new pid;
// Parameters
double t0 = 0;
double dt_plant = 0.1; // sec
double tFinal = 10; // sec
double x_init = 0; // m
double v_init = 0; // m/s
double m = 1; // kg
double b = 10; // N s/m
double k = 20; // N/m
double kp = 3;
double ki = 0.01;
double kd = 0;
double dt_C = 0.01;
std::vector<std::pair<double,double>> x_t;
std::vector<std::pair<double,double>> v_t;
std::vector<std::pair<double,double>> y_t;
std::vector<std::pair<double,double>> err_t;
std::vector<std::pair<double,double>> F_t;
std::vector<std::pair<double,double>> xDes_t;
// Init
sys->setInitTime(t0);
sys->setSampleTime(dt_plant);
sys->setInitState(x_init, v_init);
sys->setMass(m);
sys->setDamper(b);
sys->setSpring(k);
std::cout << "t = " << sys->getCurTime() << std::endl;
std::cout << "x = " << sys->getState().x1 << std::endl;
x_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x1));
v_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x2));
y_t.push_back(std::make_pair(sys->getCurTime(), sys->getY()));
// PID control
double x_des = 1;
xDes_t.push_back(std::make_pair(sys->getCurTime(), x_des));
err_t.push_back(std::make_pair(sys->getCurTime(), x_des - sys->getState().x1));
pidCtrl->setDt(dt_C);
pidCtrl->setGains(kp, ki, kd);
double F = pidCtrl->getCmdCtrl().cmdCtrl;
F_t.push_back(std::make_pair(sys->getCurTime(), F));
// Simulation starts
while(sys->getCurTime() < tFinal)
{
sys->dynSys(F);
// Update F with PID controller
double err = x_des - sys->getState().x1;
pidCtrl->pidCalculate(err);
if(pidCtrl->getCmdCtrl().isValid)
F = pidCtrl->getCmdCtrl().cmdCtrl;
// Push the states, outputs, and errors for plotting
std::cout << "t = " << sys->getCurTime() << ", ";
std::cout << "x = " << sys->getState().x1 << std::endl;
x_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x1));
v_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x2));
y_t.push_back(std::make_pair(sys->getCurTime(), sys->getY()));
F_t.push_back(std::make_pair(sys->getCurTime(), F));
xDes_t.push_back(std::make_pair(sys->getCurTime(), x_des));
err_t.push_back(std::make_pair(sys->getCurTime(), err));
}
// Plot : gnuplot
Gnuplot gp;
//gp << "set xrange [0:3]\n";
gp << "set multiplot layout 3, 1 title 'Mass-Spring-Damper with PID controller'"
<< "font ',15'" << std::endl;
// plot 1: Pos
gp << "set title 'Position'" << "font ',11'" << std::endl;
gp << "set xlabel 'time [sec]'" << std::endl;
gp << "set ylabel 'position [m]'" << std::endl;
gp << "plot '-' with lines title 'position', '-' with lines title 'pos_{des}'"<<std::endl;
gp.send1d(x_t);
gp.send1d(xDes_t);
// plot 2: Err
gp << "set title 'Error'" << "font ',11'" << std::endl;
gp << "set xlabel 'time [sec]'" << std::endl;
gp << "set ylabel 'err [m]'" << std::endl;
gp << "plot '-' with lines title 'err'"<<std::endl;
gp.send1d(err_t);
// plot 3: Force
gp << "set title 'Force'" << "font ',11'" << std::endl;
gp << "set xlabel 'time [sec]'" << std::endl;
gp << "set ylabel 'force [N]'" << std::endl;
gp << "plot '-' with lines title 'force'"<<std::endl;
gp.send1d(F_t);
}
| [
"gordon1258@gmail.com"
] | gordon1258@gmail.com |
8910e016c4afcdb35801a692b82f42443a3c5d59 | 438e67f05d962053e400d6417249c116d2a6954b | /StringToInteger.cpp | 301477c39afd40e30fba29626a937dc5e75e4374 | [] | no_license | alexandersdickinson/LeetCode | c09e8f0e70fe714b4d285812692e74ad4f3d75c6 | d381b1e603beeb31aa9ac38085e887874852152c | refs/heads/master | 2020-12-02T21:04:18.426840 | 2017-09-13T21:09:04 | 2017-09-13T21:09:04 | 96,253,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cpp | class Solution {
public:
int myAtoi(string str) {
int signs = int();
long converted = 0;
bool negative = false;
if(str.find_first_of("1234567890") == string::npos || str.length() == 0){
return 0;
}
str = str.substr(str.find_first_not_of(" \t"), str.length());
str = str.substr(0, str.find_first_not_of("+-1234567890"));
for(int i = str.length() - 1, j = 0; i >= 0; --i, ++j){
if(str.at(i) == '+' || str.at(i) == '-'){
break;
}
else{
converted += ((long)str.at(i) - 48) * (long)pow(10, j);
if(j >= 9 && converted > INT_MAX){
if(str.find_first_of("1234567890") > 1){
return 0;
}
else if(str.at(0) == '-'){
return INT_MIN;
}
else{
return INT_MAX;
}
}
}
}
if(str.find_first_of("1234567890") > 1){
return 0;
}
else if(str.at(0) == '-'){
negative = true;
}
if(negative){
return (int)converted * -1;
}
else{
return converted;
}
}
};
| [
"alexandersdickinson@gmail.com"
] | alexandersdickinson@gmail.com |
7c853f110c1b4af4b04129942b69339d89dbae5c | 44ea78720cf1fbbbb57a204d462f08ef8ccb7c42 | /Others/diverta-2019/B/main.cpp | a36e8a2b0bbc116bae96a67b40e40d46caf1c333 | [] | no_license | kironbot/AtCoder | 854a85d55e2d3c0c8ef76589ad905af20d9c567d | 4c05bf806413f5c601baa7432b9d85b102ba34b7 | refs/heads/master | 2021-06-29T16:14:47.667960 | 2020-09-27T06:17:02 | 2020-09-27T06:17:02 | 138,470,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 642 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1e9 + 7;
const ll INF = 1LL << 60;
#define rep(i, a, n) for (ll i = (a); i < (n); i++)
#define debug(x) cerr << #x << ": " << x << endl;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
int main() {
ll r, g, b, n;
cin >> r >> g >> b >> n;
ll ans = 0;
rep(i, 0, n+1) {
rep(j, 0, n+1) {
if ((n - i*r - j*g) % b == 0 && n - i*r - j*g >= 0) ans++;
else continue;
}
}
cout << ans << endl;
}
| [
"sgr.araki@gmail.com"
] | sgr.araki@gmail.com |
be4bfdaf30f91d99fb8c8651fe083e0e03136ee0 | 2f6b17aa5911b83e27f365a28ad09ee74e0d63f9 | /source/organizer/organizercore.cpp | 19c55e8df71df6ad654236383e71d747820af82b | [] | no_license | GrantSP/OriginalMO | afcc7b9bc8225db36216fe963c162696193e4b74 | 7935114fa2bbc6e38ad7a7b485754d20ee9bec23 | refs/heads/master | 2021-09-02T06:20:13.207699 | 2017-12-31T00:44:07 | 2017-12-31T00:44:07 | 115,833,608 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 54,237 | cpp | #include "organizercore.h"
#include "mainwindow.h"
#include "gameinfoimpl.h"
#include "messagedialog.h"
#include "logbuffer.h"
#include "credentialsdialog.h"
#include "filedialogmemory.h"
#include "lockeddialog.h"
#include "modinfodialog.h"
#include "spawn.h"
#include "safewritefile.h"
#include "syncoverwritedialog.h"
#include "nxmaccessmanager.h"
#include <ipluginmodpage.h>
#include <dataarchives.h>
#include <directoryentry.h>
#include <scopeguard.h>
#include <utility.h>
#include <appconfig.h>
#include <report.h>
#include <questionboxmemory.h>
#include <QNetworkInterface>
#include <QMessageBox>
#include <QDialogButtonBox>
#include <QApplication>
#include <Psapi.h>
#include <functional>
using namespace MOShared;
using namespace MOBase;
static bool isOnline()
{
QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
bool connected = false;
for (auto iter = interfaces.begin(); iter != interfaces.end() && !connected; ++iter) {
if ( (iter->flags() & QNetworkInterface::IsUp) &&
(iter->flags() & QNetworkInterface::IsRunning) &&
!(iter->flags() & QNetworkInterface::IsLoopBack)) {
auto addresses = iter->addressEntries();
if (addresses.count() == 0) {
continue;
}
qDebug("interface %s seems to be up (address: %s)",
qPrintable(iter->humanReadableName()),
qPrintable(addresses[0].ip().toString()));
connected = true;
}
}
return connected;
}
static bool renameFile(const QString &oldName, const QString &newName, bool overwrite = true)
{
if (overwrite && QFile::exists(newName)) {
QFile::remove(newName);
}
return QFile::rename(oldName, newName);
}
static std::wstring getProcessName(DWORD processId)
{
HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION, false, processId);
wchar_t buffer[MAX_PATH];
if (::GetProcessImageFileNameW(process, buffer, MAX_PATH) != 0) {
wchar_t *fileName = wcsrchr(buffer, L'\\');
if (fileName == nullptr) {
fileName = buffer;
} else {
fileName += 1;
}
return fileName;
} else {
return std::wstring(L"unknown");
}
}
static void startSteam(QWidget *widget)
{
QSettings steamSettings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", QSettings::NativeFormat);
QString exe = steamSettings.value("SteamExe", "").toString();
if (!exe.isEmpty()) {
exe = QString("\"%1\"").arg(exe);
//See if username and password supplied. If so, pass them into steam.
QStringList args;
QString username;
QString password;
if (Settings::instance().getSteamLogin(username, password)) {
args << "-login";
args << username;
if (password != "") {
args << password;
}
}
if (!QProcess::startDetached(exe, args)) {
reportError(QObject::tr("Failed to start \"%1\"").arg(exe));
} else {
QMessageBox::information(widget, QObject::tr("Waiting"),
QObject::tr("Please press OK once you're logged into steam."));
}
}
}
template <typename InputIterator>
QStringList toStringList(InputIterator current, InputIterator end)
{
QStringList result;
for (; current != end; ++current) {
result.append(*current);
}
return result;
}
OrganizerCore::OrganizerCore(const QSettings &initSettings)
: m_GameInfo(new GameInfoImpl())
, m_UserInterface(nullptr)
, m_PluginContainer(nullptr)
, m_GameName()
, m_CurrentProfile(nullptr)
, m_Settings(initSettings)
, m_Updater(NexusInterface::instance())
, m_AboutToRun()
, m_FinishedRun()
, m_ModInstalled()
, m_ModList(this)
, m_PluginList(this)
, m_DirectoryRefresher()
, m_DirectoryStructure(new DirectoryEntry(L"data", nullptr, 0))
, m_DownloadManager(NexusInterface::instance(), this)
, m_InstallationManager()
, m_RefresherThread()
, m_AskForNexusPW(false)
, m_DirectoryUpdate(false)
, m_ArchivesInit(false)
, m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this))
{
m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory());
m_DownloadManager.setPreferredServers(m_Settings.getPreferredServers());
NexusInterface::instance()->setCacheDirectory(m_Settings.getCacheDirectory());
NexusInterface::instance()->setNMMVersion(m_Settings.getNMMVersion());
MOBase::QuestionBoxMemory::init(initSettings.fileName());
m_InstallationManager.setModsDirectory(m_Settings.getModDirectory());
m_InstallationManager.setDownloadDirectory(m_Settings.getDownloadDirectory());
connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString,int)), this, SLOT(downloadSpeed(QString,int)));
connect(&m_DirectoryRefresher, SIGNAL(refreshed()), this, SLOT(directory_refreshed()));
connect(&m_ModList, SIGNAL(removeOrigin(QString)), this, SLOT(removeOrigin(QString)));
connect(NexusInterface::instance()->getAccessManager(), SIGNAL(loginSuccessful(bool)), this, SLOT(loginSuccessful(bool)));
connect(NexusInterface::instance()->getAccessManager(), SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString)));
connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame*)), &m_Settings, SLOT(managedGameChanged(MOBase::IPluginGame*)));
connect(&m_PluginList, &PluginList::writePluginsList, &m_PluginListsWriter, &DelayedFileWriterBase::write);
// make directory refresher run in a separate thread
m_RefresherThread.start();
m_DirectoryRefresher.moveToThread(&m_RefresherThread);
m_AskForNexusPW = initSettings.value("ask_for_nexuspw", true).toBool();
}
OrganizerCore::~OrganizerCore()
{
m_RefresherThread.exit();
m_RefresherThread.wait();
prepareStart();
// profile has to be cleaned up before the modinfo-buffer is cleared
delete m_CurrentProfile;
m_CurrentProfile = nullptr;
ModInfo::clear();
LogBuffer::cleanQuit();
m_ModList.setProfile(nullptr);
NexusInterface::instance()->cleanup();
delete m_GameInfo;
delete m_DirectoryStructure;
}
QString OrganizerCore::commitSettings(const QString &iniFile)
{
if (!shellRename(iniFile + ".new", iniFile, true, qApp->activeWindow())) {
DWORD err = ::GetLastError();
// make a second attempt using qt functions but if that fails print the error from the first attempt
if (!renameFile(iniFile + ".new", iniFile)) {
return windowsErrorString(err);
}
}
return QString();
}
QSettings::Status OrganizerCore::storeSettings(const QString &fileName)
{
QSettings settings(fileName, QSettings::IniFormat);
if (m_UserInterface != nullptr) {
m_UserInterface->storeSettings(settings);
}
if (m_CurrentProfile != nullptr) {
settings.setValue("selected_profile", m_CurrentProfile->name().toUtf8().constData());
}
settings.setValue("ask_for_nexuspw", m_AskForNexusPW);
settings.remove("customExecutables");
settings.beginWriteArray("customExecutables");
std::vector<Executable>::const_iterator current, end;
m_ExecutablesList.getExecutables(current, end);
int count = 0;
for (; current != end; ++current) {
const Executable &item = *current;
settings.setArrayIndex(count++);
settings.setValue("title", item.m_Title);
settings.setValue("custom", item.isCustom());
settings.setValue("toolbar", item.isShownOnToolbar());
settings.setValue("ownicon", item.usesOwnIcon());
if (item.isCustom()) {
settings.setValue("binary", item.m_BinaryInfo.absoluteFilePath());
settings.setValue("arguments", item.m_Arguments);
settings.setValue("workingDirectory", item.m_WorkingDirectory);
settings.setValue("closeOnStart", item.m_CloseMO == ExecutableInfo::CloseMOStyle::DEFAULT_CLOSE);
settings.setValue("steamAppID", item.m_SteamAppID);
}
}
settings.endArray();
FileDialogMemory::save(settings);
settings.sync();
return settings.status();
}
void OrganizerCore::storeSettings()
{
QString iniFile = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName());
if (QFileInfo(iniFile).exists()) {
if (!shellCopy(iniFile, iniFile + ".new", true, qApp->activeWindow())) {
QMessageBox::critical(qApp->activeWindow(), tr("Failed to write settings"),
tr("An error occured trying to update MO settings to %1: %2").arg(
iniFile, windowsErrorString(::GetLastError())));
return;
}
}
QSettings::Status result = storeSettings(iniFile + ".new");
if (result == QSettings::NoError) {
QString errMsg = commitSettings(iniFile);
if (!errMsg.isEmpty()) {
qWarning("settings file not writable, may be locked by another application, trying direct write");
result = storeSettings(iniFile);
}
}
if (result != QSettings::NoError) {
QString reason = result == QSettings::AccessError ? tr("File is write protected")
: result == QSettings::FormatError ? tr("Invalid file format (probably a bug)")
: tr("Unknown error %1").arg(result);
QMessageBox::critical(qApp->activeWindow(), tr("Failed to write settings"),
tr("An error occured trying to write back MO settings to %1: %2").arg(iniFile + ".new", reason));
}
}
bool OrganizerCore::testForSteam()
{
size_t currentSize = 1024;
std::unique_ptr<DWORD[]> processIDs;
DWORD bytesReturned;
bool success = false;
while (!success) {
processIDs.reset(new DWORD[currentSize]);
if (!::EnumProcesses(processIDs.get(), currentSize * sizeof(DWORD), &bytesReturned)) {
qWarning("failed to determine if steam is running");
return true;
}
if (bytesReturned == (currentSize * sizeof(DWORD))) {
// maximum size used, list probably truncated
currentSize *= 2;
} else {
success = true;
}
}
TCHAR processName[MAX_PATH];
for (unsigned int i = 0; i < bytesReturned / sizeof(DWORD); ++i) {
memset(processName, '\0', sizeof(TCHAR) * MAX_PATH);
if (processIDs[i] != 0) {
HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIDs[i]);
if (process != nullptr) {
HMODULE module;
DWORD ignore;
// first module in a process is always the binary
if (EnumProcessModules(process, &module, sizeof(HMODULE) * 1, &ignore)) {
::GetModuleBaseName(process, module, processName, MAX_PATH);
if ((_tcsicmp(processName, TEXT("steam.exe")) == 0) ||
(_tcsicmp(processName, TEXT("steamservice.exe")) == 0)) {
return true;
}
}
}
}
}
return false;
}
void OrganizerCore::updateExecutablesList(QSettings &settings)
{
if (m_PluginContainer == nullptr) {
qCritical("can't update executables list now");
return;
}
m_ExecutablesList.init(m_PluginContainer->managedGame(ToQString(GameInfo::instance().getGameName())));
qDebug("setting up configured executables");
int numCustomExecutables = settings.beginReadArray("customExecutables");
for (int i = 0; i < numCustomExecutables; ++i) {
settings.setArrayIndex(i);
ExecutableInfo::CloseMOStyle closeMO =
settings.value("closeOnStart").toBool() ? ExecutableInfo::CloseMOStyle::DEFAULT_CLOSE
: ExecutableInfo::CloseMOStyle::DEFAULT_STAY;
Executable::Flags flags;
if (settings.value("custom", true).toBool()) flags |= Executable::CustomExecutable;
if (settings.value("toolbar", false).toBool()) flags |= Executable::ShowInToolbar;
if (settings.value("ownicon", false).toBool()) flags |= Executable::UseApplicationIcon;
m_ExecutablesList.addExecutable(settings.value("title").toString(),
settings.value("binary").toString(),
settings.value("arguments").toString(),
settings.value("workingDirectory", "").toString(),
closeMO,
settings.value("steamAppID", "").toString(),
flags);
}
settings.endArray();
// TODO this has nothing to do with executables list move to an appropriate function!
ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, m_Settings.displayForeign());
}
void OrganizerCore::setUserInterface(IUserInterface *userInterface, QWidget *widget)
{
storeSettings();
m_UserInterface = userInterface;
if (widget != nullptr) {
connect(&m_ModList, SIGNAL(modlist_changed(QModelIndex, int)), widget, SLOT(modlistChanged(QModelIndex, int)));
connect(&m_ModList, SIGNAL(showMessage(QString)), widget, SLOT(showMessage(QString)));
connect(&m_ModList, SIGNAL(modRenamed(QString,QString)), widget, SLOT(modRenamed(QString,QString)));
connect(&m_ModList, SIGNAL(modUninstalled(QString)), widget, SLOT(modRemoved(QString)));
connect(&m_ModList, SIGNAL(removeSelectedMods()), widget, SLOT(removeMod_clicked()));
connect(&m_ModList, SIGNAL(requestColumnSelect(QPoint)), widget, SLOT(displayColumnSelection(QPoint)));
connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), widget, SLOT(fileMoved(QString, QString, QString)));
connect(&m_ModList, SIGNAL(modorder_changed()), widget, SLOT(modorder_changed()));
connect(&m_DownloadManager, SIGNAL(showMessage(QString)), widget, SLOT(showMessage(QString)));
}
m_InstallationManager.setParentWidget(widget);
m_Updater.setUserInterface(widget);
if (userInterface != nullptr) {
// this currently wouldn't work reliably if the ui isn't initialized yet to display the result
if (isOnline() && !m_Settings.offlineMode()) {
m_Updater.testForUpdate();
} else {
qDebug("user doesn't seem to be connected to the internet");
}
}
}
void OrganizerCore::connectPlugins(PluginContainer *container)
{
m_DownloadManager.setSupportedExtensions(m_InstallationManager.getSupportedExtensions());
m_PluginContainer = container;
if (!m_GameName.isEmpty()) {
m_GamePlugin = m_PluginContainer->managedGame(m_GameName);
emit managedGameChanged(m_GamePlugin);
}
}
void OrganizerCore::disconnectPlugins()
{
m_AboutToRun.disconnect_all_slots();
m_FinishedRun.disconnect_all_slots();
m_ModInstalled.disconnect_all_slots();
m_ModList.disconnectSlots();
m_PluginList.disconnectSlots();
m_Settings.clearPlugins();
m_GamePlugin = nullptr;
m_PluginContainer = nullptr;
}
void OrganizerCore::setManagedGame(const QString &gameName, const QString &gamePath)
{
m_GameName = gameName;
if (m_PluginContainer != nullptr) {
m_GamePlugin = m_PluginContainer->managedGame(m_GameName);
m_GamePlugin->setGamePath(gamePath);
qApp->setProperty("managed_game", QVariant::fromValue(m_GamePlugin));
emit managedGameChanged(m_GamePlugin);
}
}
Settings &OrganizerCore::settings()
{
return m_Settings;
}
bool OrganizerCore::nexusLogin(bool retry)
{
NXMAccessManager *accessManager = NexusInterface::instance()->getAccessManager();
if ((accessManager->loginAttempted()
|| accessManager->loggedIn())
&& !retry) {
// previous attempt, maybe even successful
return false;
} else {
QString username, password;
if ((!retry && m_Settings.getNexusLogin(username, password))
|| (m_AskForNexusPW && queryLogin(username, password))) {
// credentials stored or user entered them manually
qDebug("attempt login with username %s", qPrintable(username));
accessManager->login(username, password);
return true;
} else {
// no credentials stored and user didn't enter them
accessManager->refuseLogin();
return false;
}
}
}
bool OrganizerCore::queryLogin(QString &username, QString &password)
{
CredentialsDialog dialog(qApp->activeWindow());
int res = dialog.exec();
if (dialog.neverAsk()) {
m_AskForNexusPW = false;
}
if (res == QDialog::Accepted) {
username = dialog.username();
password = dialog.password();
if (dialog.store()) {
m_Settings.setNexusLogin(username, password);
}
return true;
} else {
return false;
}
}
void OrganizerCore::startMOUpdate()
{
if (nexusLogin()) {
m_PostLoginTasks.append([&]() { m_Updater.startUpdate(); });
} else {
m_Updater.startUpdate();
}
}
void OrganizerCore::downloadRequestedNXM(const QString &url)
{
qDebug("download requested: %s", qPrintable(url));
if (nexusLogin()) {
m_PendingDownloads.append(url);
} else {
m_DownloadManager.addNXMDownload(url);
}
}
void OrganizerCore::externalMessage(const QString &message)
{
if (message.left(6).toLower() == "nxm://") {
MessageDialog::showMessage(tr("Download started"), qApp->activeWindow());
downloadRequestedNXM(message);
}
}
void OrganizerCore::downloadRequested(QNetworkReply *reply, int modID, const QString &fileName)
{
try {
if (m_DownloadManager.addDownload(reply, QStringList(), fileName, modID, 0, new ModRepositoryFileInfo(modID))) {
MessageDialog::showMessage(tr("Download started"), qApp->activeWindow());
}
} catch (const std::exception &e) {
MessageDialog::showMessage(tr("Download failed"), qApp->activeWindow());
qCritical("exception starting download: %s", e.what());
}
}
void OrganizerCore::removeOrigin(const QString &name)
{
FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(name));
origin.enable(false);
refreshLists();
}
void OrganizerCore::downloadSpeed(const QString &serverName, int bytesPerSecond)
{
m_Settings.setDownloadSpeed(serverName, bytesPerSecond);
}
InstallationManager *OrganizerCore::installationManager()
{
return &m_InstallationManager;
}
void OrganizerCore::createDefaultProfile()
{
QString profilesPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::profilesPath());
if (QDir(profilesPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot).size() == 0) {
Profile newProf("Default", managedGame(), false);
}
}
void OrganizerCore::setCurrentProfile(const QString &profileName)
{
if ((m_CurrentProfile != nullptr) &&
(profileName == m_CurrentProfile->name())) {
return;
}
QString profileDir = qApp->property("dataPath").toString() + "/" + ToQString(AppConfig::profilesPath()) + "/" + profileName;
Profile *newProfile = new Profile(QDir(profileDir), managedGame());
delete m_CurrentProfile;
m_CurrentProfile = newProfile;
m_ModList.setProfile(newProfile);
if (m_CurrentProfile->invalidationActive(nullptr)) {
m_CurrentProfile->activateInvalidation();
} else {
m_CurrentProfile->deactivateInvalidation();
}
connect(m_CurrentProfile, SIGNAL(modStatusChanged(uint)), this, SLOT(modStatusChanged(uint)));
refreshDirectoryStructure();
}
MOBase::IGameInfo &OrganizerCore::gameInfo() const
{
return *m_GameInfo;
}
MOBase::IModRepositoryBridge *OrganizerCore::createNexusBridge() const
{
return new NexusBridge();
}
QString OrganizerCore::profileName() const
{
if (m_CurrentProfile != nullptr) {
return m_CurrentProfile->name();
} else {
return "";
}
}
QString OrganizerCore::profilePath() const
{
if (m_CurrentProfile != nullptr) {
return m_CurrentProfile->absolutePath();
} else {
return "";
}
}
QString OrganizerCore::downloadsPath() const
{
return QDir::fromNativeSeparators(m_Settings.getDownloadDirectory());
}
MOBase::VersionInfo OrganizerCore::appVersion() const
{
return m_Updater.getVersion();
}
MOBase::IModInterface *OrganizerCore::getMod(const QString &name)
{
unsigned int index = ModInfo::getIndex(name);
if (index == UINT_MAX) {
return nullptr;
} else {
return ModInfo::getByIndex(index).data();
}
}
MOBase::IModInterface *OrganizerCore::createMod(GuessedValue<QString> &name)
{
bool merge = false;
if (!m_InstallationManager.testOverwrite(name, &merge)) {
return nullptr;
}
m_InstallationManager.setModsDirectory(m_Settings.getModDirectory());
QString targetDirectory = QDir::fromNativeSeparators(m_Settings.getModDirectory()).append("/").append(name);
QSettings settingsFile(targetDirectory + "/meta.ini", QSettings::IniFormat);
if (!merge) {
settingsFile.setValue("modid", 0);
settingsFile.setValue("version", "");
settingsFile.setValue("newestVersion", "");
settingsFile.setValue("category", 0);
settingsFile.setValue("installationFile", "");
settingsFile.beginWriteArray("installedFiles", 0);
settingsFile.endArray();
}
return ModInfo::createFrom(QDir(targetDirectory), &m_DirectoryStructure).data();
}
bool OrganizerCore::removeMod(MOBase::IModInterface *mod)
{
unsigned int index = ModInfo::getIndex(mod->name());
if (index == UINT_MAX) {
return mod->remove();
} else {
return ModInfo::removeMod(index);
}
}
void OrganizerCore::modDataChanged(MOBase::IModInterface*)
{
refreshModList(false);
}
QVariant OrganizerCore::pluginSetting(const QString &pluginName, const QString &key) const
{
return m_Settings.pluginSetting(pluginName, key);
}
void OrganizerCore::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value)
{
m_Settings.setPluginSetting(pluginName, key, value);
}
QVariant OrganizerCore::persistent(const QString &pluginName, const QString &key, const QVariant &def) const
{
return m_Settings.pluginPersistent(pluginName, key, def);
}
void OrganizerCore::setPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync)
{
m_Settings.setPluginPersistent(pluginName, key, value, sync);
}
QString OrganizerCore::pluginDataPath() const
{
return qApp->applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()) + "/data";
}
MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName, const QString &initModName)
{
if (m_CurrentProfile == nullptr) {
return nullptr;
}
bool hasIniTweaks = false;
GuessedValue<QString> modName;
if (!initModName.isEmpty()) {
modName.update(initModName, GUESS_USER);
}
m_CurrentProfile->writeModlistNow();
m_InstallationManager.setModsDirectory(m_Settings.getModDirectory());
if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) {
MessageDialog::showMessage(tr("Installation successful"), qApp->activeWindow());
refreshModList();
int modIndex = ModInfo::getIndex(modName);
if (modIndex != UINT_MAX) {
ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex);
if (hasIniTweaks
&& (m_UserInterface != nullptr)
&& (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"),
tr("This mod contains ini tweaks. Do you want to configure them now?"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) {
m_UserInterface->displayModInformation(modInfo, modIndex, ModInfoDialog::TAB_INIFILES);
}
m_ModInstalled(modName);
return modInfo.data();
} else {
reportError(tr("mod \"%1\" not found").arg(modName));
}
} else if (m_InstallationManager.wasCancelled()) {
QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"),
tr("The mod was not installed completely."), QMessageBox::Ok);
}
return nullptr;
}
void OrganizerCore::installDownload(int index)
{
try {
QString fileName = m_DownloadManager.getFilePath(index);
int modID = m_DownloadManager.getModID(index);
int fileID = m_DownloadManager.getFileInfo(index)->fileID;
GuessedValue<QString> modName;
// see if there already are mods with the specified mod id
if (modID != 0) {
std::vector<ModInfo::Ptr> modInfo = ModInfo::getByModID(modID);
for (auto iter = modInfo.begin(); iter != modInfo.end(); ++iter) {
std::vector<ModInfo::EFlag> flags = (*iter)->getFlags();
if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) == flags.end()) {
modName.update((*iter)->name(), GUESS_PRESET);
(*iter)->saveMeta();
}
}
}
m_CurrentProfile->writeModlistNow();
bool hasIniTweaks = false;
m_InstallationManager.setModsDirectory(m_Settings.getModDirectory());
if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) {
MessageDialog::showMessage(tr("Installation successful"), qApp->activeWindow());
refreshModList();
int modIndex = ModInfo::getIndex(modName);
if (modIndex != UINT_MAX) {
ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex);
modInfo->addInstalledFile(modID, fileID);
if (hasIniTweaks
&& m_UserInterface != nullptr
&& (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"),
tr("This mod contains ini tweaks. Do you want to configure them now?"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) {
m_UserInterface->displayModInformation(modInfo, modIndex, ModInfoDialog::TAB_INIFILES);
}
m_ModInstalled(modName);
} else {
reportError(tr("mod \"%1\" not found").arg(modName));
}
m_DownloadManager.markInstalled(index);
emit modInstalled(modName);
} else if (m_InstallationManager.wasCancelled()) {
QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"),
tr("The mod was not installed completely."), QMessageBox::Ok);
}
} catch (const std::exception &e) {
reportError(e.what());
}
}
QString OrganizerCore::resolvePath(const QString &fileName) const
{
if (m_DirectoryStructure == nullptr) {
return QString();
}
const FileEntry::Ptr file = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr);
if (file.get() != nullptr) {
return ToQString(file->getFullPath());
} else {
return QString();
}
}
QStringList OrganizerCore::listDirectories(const QString &directoryName) const
{
QStringList result;
DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(ToWString(directoryName));
if (dir != nullptr) {
std::vector<DirectoryEntry*>::iterator current, end;
dir->getSubDirectories(current, end);
for (; current != end; ++current) {
result.append(ToQString((*current)->getName()));
}
}
return result;
}
QStringList OrganizerCore::findFiles(const QString &path, const std::function<bool (const QString &)> &filter) const
{
QStringList result;
DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(ToWString(path));
if (dir != nullptr) {
std::vector<FileEntry::Ptr> files = dir->getFiles();
foreach (FileEntry::Ptr file, files) {
if (filter(ToQString(file->getFullPath()))) {
result.append(ToQString(file->getFullPath()));
}
}
} else {
qWarning("directory %s not found", qPrintable(path));
}
return result;
}
QStringList OrganizerCore::getFileOrigins(const QString &fileName) const
{
QStringList result;
const FileEntry::Ptr file = m_DirectoryStructure->searchFile(ToWString(QFileInfo(fileName).fileName()), nullptr);
if (file.get() != nullptr) {
result.append(ToQString(m_DirectoryStructure->getOriginByID(file->getOrigin()).getName()));
foreach (int i, file->getAlternatives()) {
result.append(ToQString(m_DirectoryStructure->getOriginByID(i).getName()));
}
} else {
qDebug("%s not found", qPrintable(fileName));
}
return result;
}
QList<MOBase::IOrganizer::FileInfo> OrganizerCore::findFileInfos(const QString &path, const std::function<bool (const MOBase::IOrganizer::FileInfo &)> &filter) const
{
QList<IOrganizer::FileInfo> result;
DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(ToWString(path));
if (dir != nullptr) {
std::vector<FileEntry::Ptr> files = dir->getFiles();
foreach (FileEntry::Ptr file, files) {
IOrganizer::FileInfo info;
info.filePath = ToQString(file->getFullPath());
bool fromArchive = false;
info.origins.append(ToQString(m_DirectoryStructure->getOriginByID(file->getOrigin(fromArchive)).getName()));
info.archive = fromArchive ? ToQString(file->getArchive()) : "";
foreach (int idx, file->getAlternatives()) {
info.origins.append(ToQString(m_DirectoryStructure->getOriginByID(idx).getName()));
}
if (filter(info)) {
result.append(info);
}
}
}
return result;
}
DownloadManager *OrganizerCore::downloadManager()
{
return &m_DownloadManager;
}
PluginList *OrganizerCore::pluginList()
{
return &m_PluginList;
}
ModList *OrganizerCore::modList()
{
return &m_ModList;
}
void OrganizerCore::spawnBinary(const QFileInfo &binary, const QString &arguments, const QDir ¤tDirectory, bool closeAfterStart, const QString &steamAppID)
{
LockedDialog *dialog = new LockedDialog(qApp->activeWindow());
dialog->show();
ON_BLOCK_EXIT([&] () { dialog->hide(); dialog->deleteLater(); });
HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID);
if (processHandle != INVALID_HANDLE_VALUE) {
if (closeAfterStart && (m_UserInterface != nullptr)) {
m_UserInterface->closeWindow();
} else {
if (m_UserInterface != nullptr) {
m_UserInterface->setWindowEnabled(false);
}
// re-enable the locked dialog because what'd be the point otherwise?
dialog->setEnabled(true);
QCoreApplication::processEvents();
DWORD processExitCode;
DWORD retLen;
JOBOBJECT_BASIC_PROCESS_ID_LIST info;
{
DWORD currentProcess = 0UL;
bool isJobHandle = true;
DWORD res = ::MsgWaitForMultipleObjects(1, &processHandle, false, 1000, QS_KEY | QS_MOUSE);
while ((res != WAIT_FAILED) && (res != WAIT_OBJECT_0) && !dialog->unlockClicked()) {
if (isJobHandle) {
if (::QueryInformationJobObject(processHandle, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) {
if (info.NumberOfProcessIdsInList == 0) {
break;
} else {
if (info.ProcessIdList[0] != currentProcess) {
currentProcess = info.ProcessIdList[0];
dialog->setProcessName(ToQString(getProcessName(currentProcess)));
}
}
} else {
// the info-object I passed only provides space for 1 process id. but since this code only cares about whether there
// is more than one that's good enough. ERROR_MORE_DATA simply signals there are at least two processes running.
// any other error probably means the handle is a regular process handle, probably caused by running MO in a job without
// the right to break out.
if (::GetLastError() != ERROR_MORE_DATA) {
isJobHandle = false;
}
}
}
// keep processing events so the app doesn't appear dead
QCoreApplication::processEvents();
res = ::MsgWaitForMultipleObjects(1, &processHandle, false, 1000, QS_KEY | QS_MOUSE);
}
::GetExitCodeProcess(processHandle, &processExitCode);
}
::CloseHandle(processHandle);
if (m_UserInterface != nullptr) {
m_UserInterface->setWindowEnabled(true);
}
refreshDirectoryStructure();
// need to remove our stored load order because it may be outdated if a foreign tool changed the
// file time. After removing that file, refreshESPList will use the file time as the order
if (GameInfo::instance().getLoadOrderMechanism() == GameInfo::TYPE_FILETIME) {
qDebug("removing loadorder.txt");
QFile::remove(m_CurrentProfile->getLoadOrderFileName());
}
refreshESPList();
if (GameInfo::instance().getLoadOrderMechanism() == GameInfo::TYPE_FILETIME) {
// the load order should have been retrieved from file time, now save it to our own format
savePluginList();
}
m_FinishedRun(binary.absoluteFilePath(), processExitCode);
}
}
}
HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary, const QString &arguments, const QString &profileName,
const QDir ¤tDirectory, const QString &steamAppID)
{
prepareStart();
if (!binary.exists()) {
reportError(tr("Executable \"%1\" not found").arg(binary.absoluteFilePath()));
return INVALID_HANDLE_VALUE;
}
if (!steamAppID.isEmpty()) {
::SetEnvironmentVariableW(L"SteamAPPId", ToWString(steamAppID).c_str());
} else {
::SetEnvironmentVariableW(L"SteamAPPId", ToWString(m_Settings.getSteamAppID()).c_str());
}
if ((GameInfo::instance().requiresSteam())
&& (m_Settings.getLoadMechanism() == LoadMechanism::LOAD_MODORGANIZER)) {
if (!testForSteam()) {
QWidget *window = qApp->activeWindow();
if ((window != nullptr) && (!window->isVisible())) {
window = nullptr;
}
if (QuestionBoxMemory::query(window, "steamQuery",
tr("Start Steam?"),
tr("Steam is required to be running already to correctly start the game. "
"Should MO try to start steam now?"),
QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::Yes) {
startSteam(qApp->activeWindow());
}
}
}
while (m_DirectoryUpdate) {
::Sleep(100);
QCoreApplication::processEvents();
}
// need to make sure all data is saved before we start the application
if (m_CurrentProfile != nullptr) {
m_CurrentProfile->modlistWriter().writeImmediately(true);
}
// TODO: should also pass arguments
if (m_AboutToRun(binary.absoluteFilePath())) {
return startBinary(binary, arguments, profileName, m_Settings.logLevel(), currentDirectory, true);
} else {
qDebug("start of \"%s\" canceled by plugin", qPrintable(binary.absoluteFilePath()));
return INVALID_HANDLE_VALUE;
}
}
HANDLE OrganizerCore::startApplication(const QString &executable, const QStringList &args, const QString &cwd, const QString &profile)
{
QFileInfo binary;
QString arguments = args.join(" ");
QString currentDirectory = cwd;
QString profileName = profile;
if (profile.length() == 0) {
if (m_CurrentProfile != nullptr) {
profileName = m_CurrentProfile->name();
} else {
throw MyException(tr("No profile set"));
}
}
QString steamAppID;
if (executable.contains('\\') || executable.contains('/')) {
// file path
binary = QFileInfo(executable);
if (binary.isRelative()) {
// relative path, should be relative to game directory
binary = QFileInfo(QDir::fromNativeSeparators(ToQString(GameInfo::instance().getGameDirectory())) + "/" + executable);
}
if (cwd.length() == 0) {
currentDirectory = binary.absolutePath();
}
try {
const Executable &exe = m_ExecutablesList.findByBinary(binary);
steamAppID = exe.m_SteamAppID;
} catch (const std::runtime_error&) {
// nop
}
} else {
// only a file name, search executables list
try {
const Executable &exe = m_ExecutablesList.find(executable);
steamAppID = exe.m_SteamAppID;
if (arguments == "") {
arguments = exe.m_Arguments;
}
binary = exe.m_BinaryInfo;
if (cwd.length() == 0) {
currentDirectory = exe.m_WorkingDirectory;
}
} catch (const std::runtime_error&) {
qWarning("\"%s\" not set up as executable", executable.toUtf8().constData());
binary = QFileInfo(executable);
}
}
return spawnBinaryDirect(binary, arguments, profileName, currentDirectory, steamAppID);
}
bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode)
{
if (m_UserInterface != nullptr) {
m_UserInterface->lock();
ON_BLOCK_EXIT([&] () { m_UserInterface->unlock(); });
}
DWORD retLen;
JOBOBJECT_BASIC_PROCESS_ID_LIST info;
bool isJobHandle = true;
ULONG lastProcessID = ULONG_MAX;
HANDLE processHandle = handle;
DWORD res = ::MsgWaitForMultipleObjects(1, &handle, false, 500, QS_KEY | QS_MOUSE);
while ((res != WAIT_FAILED)
&& (res != WAIT_OBJECT_0)
&& ((m_UserInterface == nullptr) || !m_UserInterface->unlockClicked())) {
if (isJobHandle) {
if (::QueryInformationJobObject(handle, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) {
if (info.NumberOfProcessIdsInList == 0) {
// fake signaled state
res = WAIT_OBJECT_0;
break;
} else {
// this is indeed a job handle. Figure out one of the process handles as well.
if (lastProcessID != info.ProcessIdList[0]) {
lastProcessID = info.ProcessIdList[0];
if (processHandle != handle) {
::CloseHandle(processHandle);
}
processHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, lastProcessID);
}
}
} else {
// the info-object I passed only provides space for 1 process id. but since this code only cares about whether there
// is more than one that's good enough. ERROR_MORE_DATA simply signals there are at least two processes running.
// any other error probably means the handle is a regular process handle, probably caused by running MO in a job without
// the right to break out.
if (::GetLastError() != ERROR_MORE_DATA) {
isJobHandle = false;
}
}
}
// keep processing events so the app doesn't appear dead
QCoreApplication::processEvents();
res = ::MsgWaitForMultipleObjects(1, &handle, false, 500, QS_KEY | QS_MOUSE);
}
if (exitCode != nullptr) {
::GetExitCodeProcess(processHandle, exitCode);
}
::CloseHandle(processHandle);
return res == WAIT_OBJECT_0;
}
bool OrganizerCore::onAboutToRun(const std::function<bool (const QString &)> &func)
{
auto conn = m_AboutToRun.connect(func);
return conn.connected();
}
bool OrganizerCore::onFinishedRun(const std::function<void (const QString &, unsigned int)> &func)
{
auto conn = m_FinishedRun.connect(func);
return conn.connected();
}
bool OrganizerCore::onModInstalled(const std::function<void (const QString &)> &func)
{
auto conn = m_ModInstalled.connect(func);
return conn.connected();
}
void OrganizerCore::refreshModList(bool saveChanges)
{
// don't lose changes!
if (saveChanges) {
m_CurrentProfile->modlistWriter().writeImmediately(true);
}
ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, m_Settings.displayForeign());
m_CurrentProfile->refreshModStatus();
m_ModList.notifyChange(-1);
refreshDirectoryStructure();
}
void OrganizerCore::refreshESPList()
{
if (m_DirectoryUpdate) {
// don't mess up the esp list if we're currently updating the directory structure
m_PostRefreshTasks.append([this] () { this->refreshESPList(); });
return;
}
m_CurrentProfile->modlistWriter().write();
// clear list
try {
m_PluginList.refresh(m_CurrentProfile->name(),
*m_DirectoryStructure,
m_CurrentProfile->getPluginsFileName(),
m_CurrentProfile->getLoadOrderFileName(),
m_CurrentProfile->getLockedOrderFileName());
} catch (const std::exception &e) {
reportError(tr("Failed to refresh list of esps: %1").arg(e.what()));
}
}
void OrganizerCore::refreshBSAList()
{
DataArchives *archives = m_GamePlugin->feature<DataArchives>();
if (archives != nullptr) {
m_ArchivesInit = false;
// default archives are the ones enabled outside MO. if the list can't be found (which might
// happen if ini files are missing) use hard-coded defaults (preferrably the same the game would use)
m_DefaultArchives = archives->archives(m_CurrentProfile);
if (m_DefaultArchives.length() == 0) {
m_DefaultArchives = archives->vanillaArchives();
}
m_ActiveArchives.clear();
auto iter = enabledArchives();
m_ActiveArchives = toStringList(iter.begin(), iter.end());
if (m_ActiveArchives.isEmpty()) {
m_ActiveArchives = m_DefaultArchives;
}
if (m_UserInterface != nullptr) {
m_UserInterface->updateBSAList(m_DefaultArchives, m_ActiveArchives);
}
m_ArchivesInit = true;
}
}
void OrganizerCore::refreshLists()
{
if ((m_CurrentProfile != nullptr) && m_DirectoryStructure->isPopulated()) {
refreshESPList();
refreshBSAList();
} // no point in refreshing lists if no files have been added to the directory tree
}
void OrganizerCore::updateModActiveState(int index, bool active)
{
ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
QDir dir(modInfo->absolutePath());
for (const QString &esm : dir.entryList(QStringList() << "*.esm", QDir::Files)) {
m_PluginList.enableESP(esm, active);
}
int enabled = 0;
QStringList esps = dir.entryList(QStringList() << "*.esp", QDir::Files);
for (const QString &esp : esps) {
const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp));
if (file.get() == nullptr) {
qWarning("failed to activate %s", qPrintable(esp));
continue;
}
if (active != m_PluginList.isEnabled(esp)
&& file->getAlternatives().empty()) {
m_PluginList.enableESP(esp, active);
++enabled;
}
}
if (active && (enabled > 1)) {
MessageDialog::showMessage(tr("Multiple esps activated, please check that they don't conflict."), qApp->activeWindow());
}
m_PluginList.refreshLoadOrder();
// immediately save affected lists
m_PluginListsWriter.writeImmediately(false);
}
void OrganizerCore::updateModInDirectoryStructure(unsigned int index, ModInfo::Ptr modInfo)
{
// add files of the bsa to the directory structure
m_DirectoryRefresher.addModFilesToStructure(m_DirectoryStructure
, modInfo->name()
, m_CurrentProfile->getModPriority(index)
, modInfo->absolutePath()
, modInfo->stealFiles()
);
DirectoryRefresher::cleanStructure(m_DirectoryStructure);
// need to refresh plugin list now so we can activate esps
refreshESPList();
// activate all esps of the specified mod so the bsas get activated along with it
updateModActiveState(index, true);
// now we need to refresh the bsa list and save it so there is no confusion about what archives are avaiable and active
refreshBSAList();
if (m_UserInterface != nullptr) {
m_UserInterface->archivesWriter().write();
}
std::vector<QString> archives = enabledArchives();
m_DirectoryRefresher.setMods(m_CurrentProfile->getActiveMods(),
std::set<QString>(archives.begin(), archives.end()));
// finally also add files from bsas to the directory structure
m_DirectoryRefresher.addModBSAToStructure(m_DirectoryStructure
, modInfo->name()
, m_CurrentProfile->getModPriority(index)
, modInfo->absolutePath()
, modInfo->archives()
);
}
void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply)
{
if (m_PluginContainer != nullptr) {
for (IPluginModPage *modPage : m_PluginContainer->plugins<MOBase::IPluginModPage>()) {
ModRepositoryFileInfo *fileInfo = new ModRepositoryFileInfo();
if (modPage->handlesDownload(url, reply->url(), *fileInfo)) {
fileInfo->repository = modPage->name();
m_DownloadManager.addDownload(reply, fileInfo);
return;
}
}
}
// no mod found that could handle the download. Is it a nexus mod?
if (url.host() == "www.nexusmods.com") {
int modID = 0;
int fileID = 0;
QRegExp modExp("mods/(\\d+)");
if (modExp.indexIn(url.toString()) != -1) {
modID = modExp.cap(1).toInt();
}
QRegExp fileExp("fid=(\\d+)");
if (fileExp.indexIn(reply->url().toString()) != -1) {
fileID = fileExp.cap(1).toInt();
}
m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo(modID, fileID));
} else {
if (QMessageBox::question(qApp->activeWindow(), tr("Download?"),
tr("A download has been started but no installed page plugin recognizes it.\n"
"If you download anyway no information (i.e. version) will be associated with the download.\n"
"Continue?"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo());
}
}
}
ModListSortProxy *OrganizerCore::createModListProxyModel()
{
ModListSortProxy *result = new ModListSortProxy(m_CurrentProfile, this);
result->setSourceModel(&m_ModList);
return result;
}
PluginListSortProxy *OrganizerCore::createPluginListProxyModel()
{
PluginListSortProxy *result = new PluginListSortProxy(this);
result->setSourceModel(&m_PluginList);
return result;
}
IPluginGame *OrganizerCore::managedGame() const
{
return m_GamePlugin;
}
std::vector<QString> OrganizerCore::enabledArchives()
{
std::vector<QString> result;
QFile archiveFile(m_CurrentProfile->getArchivesFileName());
if (archiveFile.open(QIODevice::ReadOnly)) {
while (!archiveFile.atEnd()) {
result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed());
}
archiveFile.close();
}
return result;
}
void OrganizerCore::refreshDirectoryStructure()
{
if (!m_DirectoryUpdate) {
m_CurrentProfile->modlistWriter().writeImmediately(true);
m_DirectoryUpdate = true;
std::vector<std::tuple<QString, QString, int> > activeModList = m_CurrentProfile->getActiveMods();
auto archives = enabledArchives();
m_DirectoryRefresher.setMods(activeModList,
std::set<QString>(archives.begin(), archives.end()));
QTimer::singleShot(0, &m_DirectoryRefresher, SLOT(refresh()));
}
}
void OrganizerCore::directory_refreshed()
{
DirectoryEntry *newStructure = m_DirectoryRefresher.getDirectoryStructure();
Q_ASSERT(newStructure != m_DirectoryStructure);
if (newStructure != nullptr) {
std::swap(m_DirectoryStructure, newStructure);
delete newStructure;
} else {
// TODO: don't know why this happens, this slot seems to get called twice with only one emit
return;
}
m_DirectoryUpdate = false;
if (m_CurrentProfile != nullptr) {
refreshLists();
}
for (int i = 0; i < m_ModList.rowCount(); ++i) {
ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
modInfo->clearCaches();
}
for (auto task : m_PostRefreshTasks) {
task();
}
}
void OrganizerCore::profileRefresh()
{
// have to refresh mods twice (again in refreshModList), otherwise the refresh isn't complete. Not sure why
ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, m_Settings.displayForeign());
m_CurrentProfile->refreshModStatus();
refreshModList();
}
void OrganizerCore::modStatusChanged(unsigned int index)
{
try {
ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
if (m_CurrentProfile->modEnabled(index)) {
updateModInDirectoryStructure(index, modInfo);
} else {
updateModActiveState(index, false);
refreshESPList();
if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) {
FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(modInfo->name()));
origin.enable(false);
}
if (m_UserInterface != nullptr) {
m_UserInterface->archivesWriter().write();
}
}
modInfo->clearCaches();
for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) {
ModInfo::Ptr modInfo = ModInfo::getByIndex(i);
int priority = m_CurrentProfile->getModPriority(i);
if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) {
// priorities in the directory structure are one higher because data is 0
m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())).setPriority(priority + 1);
}
}
m_DirectoryStructure->getFileRegister()->sortOrigins();
refreshLists();
} catch (const std::exception& e) {
reportError(tr("failed to update mod list: %1").arg(e.what()));
}
}
void OrganizerCore::loginSuccessful(bool necessary)
{
if (necessary) {
MessageDialog::showMessage(tr("login successful"), qApp->activeWindow());
}
foreach (QString url, m_PendingDownloads) {
downloadRequestedNXM(url);
}
m_PendingDownloads.clear();
for (auto task : m_PostLoginTasks) {
task();
}
m_PostLoginTasks.clear();
NexusInterface::instance()->loginCompleted();
}
void OrganizerCore::loginSuccessfulUpdate(bool necessary)
{
if (necessary) {
MessageDialog::showMessage(tr("login successful"), qApp->activeWindow());
}
m_Updater.startUpdate();
}
void OrganizerCore::loginFailed(const QString &message)
{
if (QMessageBox::question(qApp->activeWindow(), tr("Login failed"), tr("Login failed, try again?")) == QMessageBox::Yes) {
if (nexusLogin(true)) {
return;
}
}
if (!m_PendingDownloads.isEmpty()) {
MessageDialog::showMessage(tr("login failed: %1. Download will not be associated with an account").arg(message), qApp->activeWindow());
for (QString url : m_PendingDownloads) {
downloadRequestedNXM(url);
}
m_PendingDownloads.clear();
} else {
MessageDialog::showMessage(tr("login failed: %1").arg(message), qApp->activeWindow());
m_PostLoginTasks.clear();
}
NexusInterface::instance()->loginCompleted();
}
void OrganizerCore::loginFailedUpdate(const QString &message)
{
MessageDialog::showMessage(tr("login failed: %1. You need to log-in with Nexus to update MO.").arg(message), qApp->activeWindow());
}
void OrganizerCore::syncOverwrite()
{
unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool {
std::vector<ModInfo::EFlag> flags = mod->getFlags();
return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end(); });
ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex);
SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure, qApp->activeWindow());
if (syncDialog.exec() == QDialog::Accepted) {
syncDialog.apply(QDir::fromNativeSeparators(m_Settings.getModDirectory()));
modInfo->testValid();
refreshDirectoryStructure();
}
}
std::vector<unsigned int> OrganizerCore::activeProblems() const
{
std::vector<unsigned int> problems;
if (m_PluginList.enabledCount() > 255) {
problems.push_back(PROBLEM_TOOMANYPLUGINS);
}
return problems;
}
QString OrganizerCore::shortDescription(unsigned int key) const
{
switch (key) {
case PROBLEM_TOOMANYPLUGINS: {
return tr("Too many esps and esms enabled");
} break;
default: {
return tr("Description missing");
} break;
}
}
QString OrganizerCore::fullDescription(unsigned int key) const
{
switch (key) {
case PROBLEM_TOOMANYPLUGINS: {
return tr("The game doesn't allow more than 255 active plugins (including the official ones) to be loaded. You have to disable some unused plugins or "
"merge some plugins into one. You can find a guide here: <a href=\"http://wiki.step-project.com/Guide:Merging_Plugins\">http://wiki.step-project.com/Guide:Merging_Plugins</a>");
} break;
default: {
return tr("Description missing");
} break;
}
}
bool OrganizerCore::hasGuidedFix(unsigned int) const
{
return false;
}
void OrganizerCore::startGuidedFix(unsigned int) const
{
}
bool OrganizerCore::saveCurrentLists()
{
if (m_DirectoryUpdate) {
qWarning("not saving lists during directory update");
return false;
}
try {
savePluginList();
if (m_UserInterface != nullptr) {
m_UserInterface->archivesWriter().write();
}
} catch (const std::exception &e) {
reportError(tr("failed to save load order: %1").arg(e.what()));
}
return true;
}
void OrganizerCore::savePluginList()
{
if (m_DirectoryUpdate) {
// delay save till after directory update
m_PostRefreshTasks.append([&] () { this->savePluginList(); });
return;
}
m_PluginList.saveTo(m_CurrentProfile->getPluginsFileName(),
m_CurrentProfile->getLoadOrderFileName(),
m_CurrentProfile->getLockedOrderFileName(),
m_CurrentProfile->getDeleterFileName(),
m_Settings.hideUncheckedPlugins());
m_PluginList.saveLoadOrder(*m_DirectoryStructure);
}
void OrganizerCore::prepareStart() {
if (m_CurrentProfile == nullptr) {
return;
}
m_CurrentProfile->modlistWriter().write();
m_CurrentProfile->createTweakedIniFile();
saveCurrentLists();
m_Settings.setupLoadMechanism();
storeSettings();
}
std::vector<std::pair<QString, QString>> OrganizerCore::fileMapping()
{
IPluginGame *game = qApp->property("managed_game").value<IPluginGame*>();
return fileMapping(game->dataDirectory().absolutePath(),
directoryStructure(),
directoryStructure());
}
std::vector<std::pair<QString, QString>> OrganizerCore::fileMapping(
const QString &dataPath,
const DirectoryEntry *base,
const DirectoryEntry *directoryEntry)
{
std::vector<std::pair<QString, QString>> result;
for (FileEntry::Ptr current : directoryEntry->getFiles()) {
bool isArchive = false;
int origin = current->getOrigin(isArchive);
if (isArchive || (origin == 0)) {
continue;
}
QString fileName = ToQString(current->getRelativePath());
QString source = ToQString(base->getOriginByID(origin).getPath()) + fileName;
QString target = QDir::toNativeSeparators(dataPath) + fileName;
result.push_back(std::make_pair(source, target));
}
// recurse into subdirectories
std::vector<DirectoryEntry*>::const_iterator current, end;
directoryEntry->getSubDirectories(current, end);
for (; current != end; ++current) {
std::vector<std::pair<QString, QString>> subRes = fileMapping(dataPath, base, *current);
result.insert(result.end(), subRes.begin(), subRes.end());
}
return result;
}
| [
"fr00gyl@gmail.com"
] | fr00gyl@gmail.com |
beeca12c7a0b550ce926b3ba13310e516f6a34bd | 058641627a8f32e691be01ae01560e05badf5db9 | /symbian/kernel/src/SimRequest.cpp | 5941663f3b32e0291be0d6ceca1f16d2422d39f6 | [] | no_license | migrsoft/nbk | 7ae29bd44ec6d92ee0065953885056cef04a27b1 | 30eedbbddddd605a70ca1210b8467820bbbd6efd | refs/heads/master | 2023-03-21T14:23:05.626831 | 2021-03-10T07:29:32 | 2021-03-10T07:29:32 | 346,268,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,756 | cpp | /*
============================================================================
Name : SimRequest.cpp
Author : Yulun Wu
Version : 1.0
Copyright : Baidu MIC
Description : CSimRequest implementation
============================================================================
*/
#include "SimRequest.h"
#include "ResourceManager.h"
#include <coemain.h>
#include <bautils.h>
#include "../../../stdc/tools/str.h"
#define BUFFER_SIZE 32768
CSimRequest::CSimRequest(TInt aType) : CActive(EPriorityStandard)
{
iType = aType;
iCompressed = EFalse;
iFileOpen = EFalse;
iMime = NEMIME_UNKNOWN;
iBuf = NULL;
}
CSimRequest* CSimRequest::NewLC(TInt aType)
{
CSimRequest* self = new (ELeave) CSimRequest(aType);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CSimRequest* CSimRequest::NewL(TInt aType)
{
CSimRequest* self = CSimRequest::NewLC(aType);
CleanupStack::Pop(); // self;
return self;
}
void CSimRequest::ConstructL()
{
User::LeaveIfError(iTimer.CreateLocal());
CActiveScheduler::Add(this);
}
CSimRequest::~CSimRequest()
{
Cancel();
iTimer.Close();
if (iFileOpen) {
iFile.Close();
}
if (iBuffer) {
delete iBuffer;
iBuffer = NULL;
}
if (iUrl) {
delete iUrl;
iUrl = NULL;
}
if (iBuf)
NBK_free(iBuf);
}
void CSimRequest::DoCancel()
{
iTimer.Cancel();
}
void CSimRequest::StartL()
{
Cancel();
iStage = EUninitialized;
iTimer.After(iStatus, 5);
SetActive();
}
void CSimRequest::RC_Cancel()
{
DoCancel();
}
void CSimRequest::RunL()
{
TBool stop = EFalse;
if (iStage == EUninitialized) {
iStage = EInitialized;
if (iType == EHistoryCache) {
stop = CheckFile();
}
else if (iType == EFileCache) {
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqHeader);
}
else if (iType == ESimNoCacheError) {
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqNoCache);
stop = ETrue;
}
else if (iType == ESimApError) {
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqError);
stop = ETrue;
}
else
stop = ETrue;
}
else if (iStage != EError) {
if (iType == EHistoryCache)
stop = ReadData();
else if (iType == EFileCache)
stop = ReadCacheData();
else
stop = ETrue;
}
if (stop) {
iStage = EError;
}
else {
iTimer.After(iStatus, 5);
SetActive();
}
}
TInt CSimRequest::RunError(TInt aError)
{
return aError;
}
// 检测临时缓存目录中是否存在请求的资源
TBool CSimRequest::CheckFile()
{
CResourceManager* manager = CResourceManager::GetPtr();
RFs& rfs = CCoeEnv::Static()->FsSession();
iByteRead = 0;
if (iFileOpen) {
iFile.Close();
iFileOpen = EFalse;
}
int len = manager->GetCachePath().Length();
HBufC* name = HBufC::New(len + 64);
name->Des().Zero();
switch (iRequest->type) {
// 主文档请求,包含主页面或云浏览页面数据包
case NEREQT_MAINDOC:
{
TPtr p = name->Des();
TPtr path = manager->GetCachePath();
// 主文档URI数据文件
p.Format(KCacheUriFormat, &path, iRequest->pageId);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
int size;
iFile.Size(size);
if (iUrl)
delete iUrl;
iUrl = HBufC8::New(size);
TPtr8 p = iUrl->Des();
iFile.Read(p, size);
iFile.Close();
}
}
// gzip压缩的主文档
p.Format(KCacheDocFormat, &path, iRequest->pageId);
p.Append(KGzipSuffix);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
iFileOpen = ETrue;
iCompressed = ETrue;
}
break;
}
// 未压缩的主文档
p.Format(KCacheDocFormat, &path, iRequest->pageId);
p.Append(KHtmlSuffix);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
iFileOpen = ETrue;
}
break;
}
// wap.wmlc
p.Format(KCacheDocFormat, &path, iRequest->pageId);
p.Append(KWbxmlSuffix);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
iFileOpen = ETrue;
iMime = NEMIME_DOC_WMLC;
}
break;
}
break;
}
// 单张图片请求
case NEREQT_IMAGE:
{
TPtrC8 url;
TBuf8<32> md5str;
TBuf<32> md5strU;
url.Set((TUint8*)iRequest->url, nbk_strlen(iRequest->url));
CResourceManager::GetMsgDigestByMd5L(md5str, url);
md5strU.Copy(md5str);
// 图片以URI的MD5值命名的文件存储路径
TPtr p = name->Des();
TPtr path = manager->GetCachePath();
p.Format(KCachePathFormat, &path, iRequest->pageId);
p.Append(md5strU);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
iFileOpen = ETrue;
}
}
break;
}
// CSS
case NEREQT_CSS:
{
TPtrC8 url;
TBuf8<32> md5str;
TBuf<32> md5strU;
url.Set((TUint8*)iRequest->url, nbk_strlen(iRequest->url));
CResourceManager::GetMsgDigestByMd5L(md5str, url);
md5strU.Copy(md5str);
TPtr p = name->Des();
TPtr path = manager->GetCachePath();
// 压缩
p.Format(KCachePathFormat, &path, iRequest->pageId);
p.Append(md5strU);
p.Append(KCszSuffix);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
iFileOpen = ETrue;
iMime = NEMIME_DOC_CSS;
iCompressed = ETrue;
}
}
// 非压缩
p.Format(KCachePathFormat, &path, iRequest->pageId);
p.Append(md5strU);
p.Append(KCssSuffix);
if (BaflUtils::FileExists(rfs, p)) {
if (iFile.Open(rfs, p, EFileRead) == KErrNone) {
iFileOpen = ETrue;
iMime = NEMIME_DOC_CSS;
}
}
break;
}
} // switch
delete name;
if (iFileOpen) {
iFile.Size(iSize);
if (iBuffer == NULL)
iBuffer = HBufC8::New(BUFFER_SIZE);
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqHeader);
return EFalse;
}
else {
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqError);
return ETrue;
}
}
TBool CSimRequest::ReadData()
{
if (iFileOpen) {
TPtr8 p = iBuffer->Des();
if (iFile.Read(p, BUFFER_SIZE) == KErrNone) {
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqData);
iByteRead += p.Length();
if (iByteRead >= iSize) {
iFile.Close();
iFileOpen = EFalse;
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqComplete);
}
else
return EFalse;
}
}
return ETrue;
}
TBool CSimRequest::ReadCacheData()
{
if (iBuf == NULL) {
iBuf = (char*)NBK_malloc(BUFFER_SIZE);
iByteRead = 0;
}
iRead = cacheMgr_getData(iCacheMgr, iCacheId, iBuf, BUFFER_SIZE, iByteRead);
iByteRead += iRead;
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqData);
if (iByteRead >= iSize) {
iObserver->OnSimRequestData(MSimRequestObserver::ESimReqComplete);
return ETrue;
}
return EFalse;
}
TBool CSimRequest::GetNextDataPart(TPtrC8& aDataPart)
{
if (iBuf)
aDataPart.Set((TUint8*)iBuf, iRead);
else
aDataPart.Set(iBuffer->Des());
return (iByteRead >= iSize) ? EFalse : ETrue;
}
void CSimRequest::ReleaseData()
{
if (iBuffer)
iBuffer->Des().Zero();
}
| [
"yulun2013@outlook.com"
] | yulun2013@outlook.com |
c98d2f22f4434cebc8d40beaa9f07e6407474dba | 48c78b8111787c175a1a0481d211ddac38385ae9 | /src/core/FBPComponent.h | f001a2f74c6a9fbba5febbcacafad9a203017665 | [] | no_license | Qt-Widgets/qcircuit | 9b37feeee8f2daf61e432a2bbe251bba54fc0b9e | 7bfceafbba7872890e0310e41300c70c801384ec | refs/heads/master | 2021-05-27T14:11:42.766528 | 2014-08-29T10:26:26 | 2014-08-29T10:26:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,515 | h | /*
* File: FBPComponent.h
* Author: acailly
*
* Created on 13 février 2014, 18:17
*/
#ifndef FBPCOMPONENT_H
#define FBPCOMPONENT_H
#include <QtCore/QFuture>
#include <QtCore/QQueue>
#include <QtCore/QVariant>
class FBPInputPort;
class FBPOutputPort;
class FBPComponentListener;
class FBPComponent : public QObject {
Q_OBJECT
public:
enum State
{
NOT_STARTED,
ACTIVATED,
FINISHED
};
public:
FBPComponent(QObject* parent = NULL);
virtual ~FBPComponent();
FBPInputPort* addInputPort(QString name);
FBPOutputPort* addOutputPort(QString name);
FBPInputPort* getInputPort(QString name);
FBPOutputPort* getOutputPort(QString name);
bool isSelfStarting();
void setSelfStarting(bool value);
bool isActive();
bool isFinished();
void wait();
void activate();
void addListener(FBPComponentListener* listener);
void removeListener(FBPComponentListener* listener);
protected:
virtual void execute()=0;
bool receive(QString name, QVariant& outData);
int received(QString name);
void send(QString name, QVariant value);
void close(QString name);
private:
void execute0();
QMap<QString, FBPInputPort*> inputPorts;
QMap<QString, FBPOutputPort*> outputPorts;
bool selfStarting;
QFuture<void> future;
State state;
QSet<FBPComponentListener*> listeners;
};
#endif /* FBPCOMPONENT_H */
| [
"acailly@itlink.fr"
] | acailly@itlink.fr |
b23bd17bb8e3874f911452cc2afe746baff0419e | 30ec2372ac36d40f4557c5f39cb606452e6e6bf5 | /StarVMC/geant3/geant321/mmass.inc | 3ad06c9ed8e8c56e6091d6e7380c635f392e9a99 | [] | no_license | yfisyak/star-sw | fe77d1f6f246bfa200a0781a0335ede7e3f0ce77 | 449bba9cba3305baacbd7f18f7b3a51c61b81e61 | refs/heads/main | 2023-07-12T01:15:45.728968 | 2021-08-04T22:59:16 | 2021-08-04T22:59:16 | 382,115,093 | 2 | 0 | null | 2021-07-01T17:54:02 | 2021-07-01T17:54:01 | null | UTF-8 | C++ | false | false | 531 | inc | *
* $Id: mmass.inc,v 1.1.1.3 2009/02/18 20:33:07 fisyak Exp $
*
* $Log: mmass.inc,v $
* Revision 1.1.1.3 2009/02/18 20:33:07 fisyak
* *** empty log message ***
*
* Revision 1.1.1.1 2002/06/16 15:18:38 hristov
* Separate distribution of Geant3
*
* Revision 1.1.1.1 1999/05/18 15:55:16 fca
* AliRoot sources
*
* Revision 1.1.1.1 1995/10/24 10:20:45 cernlib
* Geant
*
*
#ifndef CERNLIB_GEANT321_MMASS_INC
#define CERNLIB_GEANT321_MMASS_INC
*
*
* mmass.inc
*
COMMON/MMASS/ZN,ZP,ZD,ZT,ZHE3,ZA,AN,AP,AD,AT,AHE3,AA
#endif
| [
"fisyak@rcas6005.rcf.bnl.gov"
] | fisyak@rcas6005.rcf.bnl.gov |
295cdc5f8e03f5692c59cc131f64cb2a95697a8b | d0eb64e4aabebdc2fac7a3284e363bf82639e18e | /sketches/vlqp/enemies.cpp | 659e7826ff3bc2ad621b9f5769cdf69eea7fa888 | [] | no_license | dspig/arduboy-for-pc | a07ebe6814b19780cc94ea419bf0a99fdc1a2d15 | a4ac47bb22da367e373232589f0c516f1300d3ba | refs/heads/master | 2021-06-15T22:03:36.157382 | 2016-04-12T18:57:25 | 2016-04-12T18:57:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,982 | cpp | #include "enemies.h"
#include "player.h"
#include "pickup.h"
// globals ///////////////////////////////////////////////////////////////////
Enemy zombies[ZOMBIE_MAX];
// method implementations ////////////////////////////////////////////////////
// setZombie
// sets the position of a zombie, and enables that instance
void setZombie(Enemy& obj, int x, int y)
{
obj.frame = 0;
obj.active = true;
obj.direction = ENEMY_FACING_WEST;
obj.x = x;
obj.y = y;
obj.health = 2;
obj.flashTime = 0;
}
// spawnZombie
// adds a zombie in a random place in the map
// returns true if success, false if failure
bool spawnZombie()
{
int x = random(16, LEVEL_WIDTH-ZOMBIE_WIDTH-16);
int y = random(16, LEVEL_HEIGHT-ZOMBIE_HEIGHT-16);
if((x < coolGirl.x - WIDTH) || (x > coolGirl.x + WIDTH) || (y < coolGirl.y - HEIGHT) || (y > coolGirl.y + HEIGHT))
{
return addZombie(x, y);
}
return false;
}
// addZombie
// searches the zombies list for an empty slot, adds one if available
// returns true if successful, false otherwise
bool addZombie(int x, int y)
{
byte id;
for(id=0; id<ZOMBIE_MAX; id++)
{
if(!zombies[id].active)
{
setZombie(zombies[id], x, y);
return true;
break;
}
}
return false;
}
// updateZombie
// updates the zombie according to game rules
// zombies are "removed" (set inactive) when health reaches zero
void updateZombie(Enemy& obj)
{
char vx = 0;
char vy = 0;
if (arduboy.everyXFrames(ZOMBIE_STEP_DELAY))
{
///////////
// input //
///////////
// chase player
if(obj.x < coolGirl.x) vx = ZOMBIE_SPEED;
if(obj.x > coolGirl.x) vx = -ZOMBIE_SPEED;
if(obj.y < coolGirl.y) vy = ZOMBIE_SPEED;
if(obj.y > coolGirl.y) vy = -ZOMBIE_SPEED;
// if out of bounds, delete this
if((obj.x < 0) || (obj.y < 0) || (obj.x >= LEVEL_WIDTH) || (obj.y >= LEVEL_HEIGHT))
{
obj.active = false;
return;
}
// update orientation
if(vx < 0)
obj.direction = ENEMY_FACING_WEST;
else if(vx > 0)
obj.direction = ENEMY_FACING_EAST;
////////////////////////
// horizontal physics //
////////////////////////
// update position
obj.x += vx;
// collide with other zombies
zombieCollide(obj.x, obj.y, true, vx, ZOMBIE_WIDTH, ZOMBIE_HEIGHT);
// collide with player
if(zombieCollision(obj, coolGirl.x, coolGirl.y, PLAYER_WIDTH, PLAYER_HEIGHT))
{
if(vx > 0)
obj.x = coolGirl.x - ZOMBIE_WIDTH;
else if(vx < 0)
obj.x = coolGirl.x + PLAYER_WIDTH;
playerHealthOffset(coolGirl, -1);
vx = 0;
}
// collide with walls
mapCollide(obj.x, obj.y, true, vx, ZOMBIE_WIDTH, ZOMBIE_HEIGHT);
//////////////////////
// vertical physics //
//////////////////////
// update position
obj.y += vy;
// collide with other zombies
zombieCollide(obj.x, obj.y, false, vy, ZOMBIE_WIDTH, ZOMBIE_HEIGHT);
// collide with player
if(zombieCollision(obj, coolGirl.x, coolGirl.y, PLAYER_WIDTH, PLAYER_HEIGHT))
{
if(vy > 0)
obj.y = coolGirl.y - ZOMBIE_HEIGHT;
else if(vy < 0)
obj.y = coolGirl.y + PLAYER_HEIGHT;
playerHealthOffset(coolGirl, -1);
vy = 0;
}
// collide with walls
mapCollide(obj.x, obj.y, false, vy, ZOMBIE_WIDTH, ZOMBIE_HEIGHT);
///////////////
// animation //
///////////////
if(vx || vy)
{
// Advance animation frame
if (arduboy.everyXFrames(ZOMBIE_FRAME_SKIP)) obj.frame++;
// Just 4 frames
if (obj.frame >= ZOMBIE_FRAME_COUNT ) obj.frame = 0;
}
else
{
obj.frame = 0;
}
}
if(obj.health == 0)
{
obj.active = false;
}
}
// updateZombies
// updates every active zombie in the list
void updateZombies()
{
byte i;
for(i=0; i<ZOMBIE_MAX; i++)
{
if(!zombies[i].active) continue;
updateZombie(zombies[i]);
}
}
/*
void drawZombieBlips()
{
short drawX, drawY;
byte id;
for(id=0; id<ZOMBIE_MAX; id++)
{
if(!zombies[id].active) continue;
drawX = zombies[id].x - mapPositionX;
drawY = zombies[id].y - mapPositionY;
byte drawColor = (arduboy.frameCount % 16) < 8;
if(drawX < 0 && drawX > -WIDTH/2)
{
arduboy.drawPixel(1, drawY + ZOMBIE_HEIGHT/2, drawColor);
arduboy.drawPixel(1, drawY + ZOMBIE_HEIGHT/2+1, drawColor);
arduboy.drawPixel(2, drawY + ZOMBIE_HEIGHT/2, drawColor);
arduboy.drawPixel(2, drawY + ZOMBIE_HEIGHT/2+1, drawColor);
}
else if(drawX > WIDTH && drawX < WIDTH/2+WIDTH)
{
arduboy.drawPixel(WIDTH-1, drawY + ZOMBIE_HEIGHT/2, drawColor);
arduboy.drawPixel(WIDTH-1, drawY + ZOMBIE_HEIGHT/2+1, drawColor);
arduboy.drawPixel(WIDTH-2, drawY + ZOMBIE_HEIGHT/2, drawColor);
arduboy.drawPixel(WIDTH-2, drawY + ZOMBIE_HEIGHT/2+1, drawColor);
}
else if(drawY < 0 && drawY > -HEIGHT/2)
{
arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2, 1, drawColor);
arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2+1, 1, drawColor);
arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2, 2, drawColor);
arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2+1, 2, drawColor);
}
else if(drawY > HEIGHT && drawY < HEIGHT/2+HEIGHT)
{
arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2, HEIGHT-1, drawColor);
arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2+1, HEIGHT-1, drawColor);
arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2, HEIGHT-2, drawColor);
arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2+1, HEIGHT-2, drawColor);
}
}
}
*/
// drawZombie
// draws a single zombie
void drawZombie(Enemy& obj)
{
short drawX, drawY;
if(obj.active)
{
if(obj.flashTime > 0)
{
obj.flashTime--;
}
if((obj.flashTime % 4) < 2)
{
drawX = obj.x - mapPositionX;
drawY = obj.y - mapPositionY;
sprites.drawPlusMask(drawX, drawY, zombie_plus_mask, obj.frame + 8*obj.direction);
}
}
else if(obj.flashTime > 0)
{
obj.flashTime--;
arduboy.drawCircle(obj.x - mapPositionX + ZOMBIE_WIDTH/2, obj.y - mapPositionY + ZOMBIE_HEIGHT/2, 12 - obj.flashTime*2, 1);
}
}
// drawZombies
// draws every active zombie in the zombie list
void drawZombies()
{
byte id;
// Draw all the zombies!
for (id=0; id<ZOMBIE_MAX; id++)
{
drawZombie(zombies[id]);
}
}
// zombieHealthOffset
// takes a value to be added to zombie health
// kills the zombie if health goes below zero
bool zombieHealthOffset(Enemy& obj, char amount)
{
obj.health += amount;
// killed
if(obj.health <= 0)
{
arduboy.tunes.tone(220, 20);
obj.flashTime = ZOMBIE_FLASH_TIME;
obj.active = false;
rollingScore += 100;
addPickup(obj.x + 4, obj.y + 4);
}
else if(amount < 0)
{
obj.flashTime = ZOMBIE_FLASH_TIME;
arduboy.tunes.tone(640, 20);
}
}
// zombieCollision
// takes zombie id, collision box to test against
// returns true if collision boxes intersect
bool zombieCollision(Enemy& obj, int x, int y, char w, char h)
{
return
( obj.active ) &&
( obj.x < x+w ) &&
( obj.x + ZOMBIE_WIDTH > x ) &&
( obj.y < y+h ) &&
( obj.y + ZOMBIE_HEIGHT > y );
}
// clearZombies
// clears the entire list of zombies
void clearZombies()
{
byte id;
for(id=0; id<ZOMBIE_MAX; id++)
{
zombies[id].active = false;
}
}
void zombieCollide(int &x, int &y, bool horizontal, char &vel, char w, char h)
{
byte id;
for(id=0; id<ZOMBIE_MAX; id++)
{
if(zombieCollision(zombies[id], x, y, w, h))
{
if(x == zombies[id].x && y == zombies[id].y) continue;
if(horizontal)
{
if(vel > 0)
x = zombies[id].x - w;
else if(vel < 0)
x = zombies[id].x + ZOMBIE_WIDTH;
}
else
{
if(vel > 0)
y = zombies[id].y - h;
else if(vel < 0)
y = zombies[id].y + ZOMBIE_HEIGHT;
}
vel = 0;
}
}
}
| [
"info@JO3RI.be"
] | info@JO3RI.be |
06dae261ded5f872dcdc5f5959a3db6e2439607b | 6fcfe3a7263f365dddc5c4653f3a50e02adfd1ec | /1. C vs C++/function_call_puzzle_in_c++.cpp | bcaf3a6841c2d458219d3efb1d495c0d186cda69 | [] | no_license | Gurkamal2323/Data-Structures-and-Algorithms | dcfe84003458d16c358bb5b7d28d7d7b90391754 | 2aa353d19989108a66f10ae991b51db5f1e651a2 | refs/heads/master | 2021-01-10T23:54:51.221471 | 2016-11-19T14:23:44 | 2016-11-19T14:23:44 | 70,786,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | #include<iostream>
using namespace std;
void func()
{
/*definition*/
}
int main()
{
func();
func(2);
return 0;
}
| [
"gurkamal2323@gmail.com"
] | gurkamal2323@gmail.com |
d3bc9b612d441642fa63c7850da9b818b8d6bda7 | b11b140ef2fbb3e3e2d0eb53fdbe4c8943ad5ebb | /NorthMultiUnivTrain/week2_codeheaven/G/g.cpp | 40d422a15c3ca0b062eb85af1f00e78c75a6dd51 | [] | no_license | jer22/OI | ea953208ab43542c51eada3c62ef529a6c14588e | 545c2424f277a6626b0f22fb666edd8c37e7328b | refs/heads/master | 2021-04-18T22:57:05.678732 | 2017-11-02T15:40:34 | 2017-11-02T15:40:34 | 27,431,322 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,465 | cpp | #include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
bool pri[1000005];
int p[1000005], num = 0, tot = 0;
int fa[MAXN], pos[1000005];
int minfac[1000005];
int fin(int p) {
if (p == fa[p]) return p;
return fa[p] = fin(fa[p]);
}
void un(int a, int b) {
fa[fin(a)] = fin(b);
}
void init() {
for (int i = 2; i <= 1000000; i++) {
if (!pri[i]) {
minfac[i] = i;
p[++num] = i;
pos[i] = num;
}
for (int j = 1; j <= num; j++) {
if(i * p[j] > 1000000) break;
pri[i * p[j]] = 1;
minfac[p[j] * i] = p[j];
}
}
// for (int i = 2; i <= 1000000; i++) {
// int x = i;
// while (x > 1) {
// int t = minfac[x];
// fac[i].push_back(t);
// while (!(x % t)) x /= t;
// }
// }
}
bool vis[MAXN], vv[MAXN];
int main() {
freopen("g.in", "r", stdin);
// freopen("out", "w", stdout);
init();
int T, n;
scanf("%d", &T);
for (int cas = 1; cas <= T; cas++) {
scanf("%d", &n);
for (int i = 1; i <= num; i++) {
vis[i] = vv[i] = 0;
fa[i] = i;
}
int ans = 0;
int x;
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
if (x == 1) ans++;
int pre = 0;
while (x > 1) {
int t = minfac[x];
vis[pos[t]] = 1;
if (pre) {
un(pre, pos[t]);
}
pre = pos[t];
while (!(x % t)) x /= t;
}
}
for (int i = 1; i <= num; i++) {
if (!vis[i]) continue;
int p = fin(i);
if (!vv[p]) {
ans++;
vv[p] = 1;
}
}
printf("Case %d: %d\n", cas, ans);
}
return 0;
}
| [
"shijieyywd@gmail.com"
] | shijieyywd@gmail.com |
78e7d13d8763b94ce9fcc7bb85f987c4c94c0225 | 732cfb5872b378252168e34601faf5d0f4d23b12 | /Source/Gdk/Graphics/Shader/ShaderManager.cpp | 01b81e44847d9762d75b5d425ac7930f2e51bdfe | [] | no_license | jnonline/gdk | d6d069541d3381817c58cb47511be92f403c954d | 8f02e10465fd2cba0af9e19f431322333d55c301 | refs/heads/master | 2016-09-06T01:02:53.443856 | 2012-02-20T06:14:03 | 2012-02-20T06:14:03 | 35,491,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,034 | cpp | /*
* Copyright (c) 2011, Raincity Games LLC
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
#include "BasePCH.h"
#include "ShaderManager.h"
using namespace Gdk;
// Static Instantiations
ShaderManager* ShaderManager::singleton = NULL;
// *****************************************************************
/// @brief
/// Constructor
// *****************************************************************
ShaderManager::ShaderManager()
{
}
// *****************************************************************
/// @brief
/// Destructor
// *****************************************************************
ShaderManager::~ShaderManager()
{
}
// *****************************************************************
/// @brief
/// Creates an Shader resource from the given Gdk Shader asset
/// @param name
/// Name of the Gdk Shader asset. This will also be the resource name.
/// @param async
/// If true, the asset will be loaded by a background thread. (Default = false)
/// @param height
/// The priority for an asyncronous load. Higher priority items are processed first.
// *****************************************************************
Shader* ShaderManager::FromAsset(const char *name, bool async, int asyncPriority)
{
return (Shader*) singleton->LoadUtility(name, async, asyncPriority, &ShaderManager::PerformLoadFromAsset);
}
// *****************************************************************
/// @brief
/// Gets a new Shader instance for the base ResourceManager.
/// @remarks
/// GDK Internal use only
// *****************************************************************
Resource* ShaderManager::OnCreateNewResourceInstance()
{
return new Shader();
}
// *****************************************************************
void ShaderManager::PerformLoadFromAsset(Resource* resource)
{
// Get the Shader*
Shader* shader = (Shader*)resource;
// Load the Shader from it's corresponding asset
shader->LoadFromAsset();
} | [
"justin@raincitygames.com@84234807-5fa8-7533-bdbf-dec7f933a0b8"
] | justin@raincitygames.com@84234807-5fa8-7533-bdbf-dec7f933a0b8 |
f9a2df98d620732395bf150a1d2fa2a6da8aaafc | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chrome/browser/safe_browsing/cloud_content_scanning/file_source_request_unittest.cc | 5e2ff081c325c28f713e8d476c594e647e764b16 | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 16,509 | cc | // Copyright (c) 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/cloud_content_scanning/file_source_request.h"
#include "base/bind_helpers.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/test/bind_test_util.h"
#include "base/test/task_environment.h"
#include "chrome/browser/enterprise/connectors/common.h"
#include "chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.h"
#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace safe_browsing {
namespace {
enterprise_connectors::AnalysisSettings settings(bool block_unsupported_types) {
enterprise_connectors::AnalysisSettings settings;
settings.block_unsupported_file_types = block_unsupported_types;
return settings;
}
// Helpers to cast base::DoNothing, otherwise FileSourceRequest's ctor calls
// would be ambiguous. This hack should be removed once only
// ContentAnalysisResponse is supported.
BinaryUploadService::ContentAnalysisCallback DoNothingConnector() {
return base::DoNothing();
}
BinaryUploadService::Callback DoNothingLegacy() {
return base::DoNothing();
}
} // namespace
class FileSourceRequestTest : public testing::TestWithParam<bool> {
public:
FileSourceRequestTest() = default;
bool use_legacy_proto() const { return GetParam(); }
std::unique_ptr<FileSourceRequest> MakeRequest(bool block_unsupported_types,
base::FilePath path,
base::FilePath file_name) {
if (use_legacy_proto()) {
return std::make_unique<FileSourceRequest>(
settings(block_unsupported_types), path, file_name,
DoNothingLegacy());
} else {
return std::make_unique<FileSourceRequest>(
settings(block_unsupported_types), path, file_name,
DoNothingConnector());
}
}
void GetResultsForFileContents(const std::string& file_contents,
BinaryUploadService::Result* out_result,
BinaryUploadService::Request::Data* out_data) {
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.doc");
base::WriteFile(file_path, file_contents.data(), file_contents.size());
auto request = MakeRequest(/*block_unsupported_types=*/false, file_path,
file_path.BaseName());
bool called = false;
base::RunLoop run_loop;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called, &out_result, &out_data](
BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
called = true;
run_loop.Quit();
*out_result = result;
*out_data = data;
}));
run_loop.Run();
EXPECT_TRUE(called);
}
private:
};
INSTANTIATE_TEST_SUITE_P(, FileSourceRequestTest, testing::Bool());
TEST_P(FileSourceRequestTest, InvalidFiles) {
base::test::TaskEnvironment task_environment;
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
{
// Non-existent files should return UNKNOWN and have no information set.
base::FilePath path = temp_dir.GetPath().AppendASCII("not_a_real.doc");
auto request =
MakeRequest(/*block_unsupported_types=*/false, path, path.BaseName());
bool called = false;
base::RunLoop run_loop;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called](BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
called = true;
run_loop.Quit();
EXPECT_EQ(result, BinaryUploadService::Result::UNKNOWN);
EXPECT_EQ(data.size, 0u);
EXPECT_TRUE(data.contents.empty());
EXPECT_TRUE(data.hash.empty());
}));
run_loop.Run();
EXPECT_TRUE(called);
}
{
// Directories should not be used as paths passed to GetFileSHA256Blocking,
// so they should return UNKNOWN and have no information set.
base::FilePath path = temp_dir.GetPath();
auto request =
MakeRequest(/*block_unsupported_types=*/false, path, path.BaseName());
bool called = false;
base::RunLoop run_loop;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called](BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
called = true;
run_loop.Quit();
EXPECT_EQ(result, BinaryUploadService::Result::UNKNOWN);
EXPECT_EQ(data.size, 0u);
EXPECT_TRUE(data.contents.empty());
EXPECT_TRUE(data.hash.empty());
}));
run_loop.Run();
EXPECT_TRUE(called);
}
}
TEST_P(FileSourceRequestTest, NormalFiles) {
base::test::TaskEnvironment task_environment;
BinaryUploadService::Result result;
BinaryUploadService::Request::Data data;
std::string normal_contents = "Normal file contents";
GetResultsForFileContents(normal_contents, &result, &data);
EXPECT_EQ(result, BinaryUploadService::Result::SUCCESS);
EXPECT_EQ(data.size, normal_contents.size());
EXPECT_EQ(data.contents, normal_contents);
// printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B");
std::string long_contents =
std::string(BinaryUploadService::kMaxUploadSizeBytes, 'a');
GetResultsForFileContents(long_contents, &result, &data);
EXPECT_EQ(result, BinaryUploadService::Result::SUCCESS);
EXPECT_EQ(data.size, long_contents.size());
EXPECT_EQ(data.contents, long_contents);
// printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"4F0E9C6A1A9A90F35B884D0F0E7343459C21060EEFEC6C0F2FA9DC1118DBE5BE");
}
TEST_P(FileSourceRequestTest, LargeFiles) {
base::test::TaskEnvironment task_environment;
BinaryUploadService::Result result;
BinaryUploadService::Request::Data data;
std::string large_file_contents(BinaryUploadService::kMaxUploadSizeBytes + 1,
'a');
GetResultsForFileContents(large_file_contents, &result, &data);
EXPECT_EQ(result, BinaryUploadService::Result::FILE_TOO_LARGE);
EXPECT_EQ(data.size, large_file_contents.size());
EXPECT_TRUE(data.contents.empty());
// python3 -c "print('a' * (50 * 1024 * 1024 + 1), end='')" | sha256sum | tr
// '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"9EB56DB30C49E131459FE735BA6B9D38327376224EC8D5A1233F43A5B4A25942");
std::string very_large_file_contents(
2 * BinaryUploadService::kMaxUploadSizeBytes, 'a');
GetResultsForFileContents(very_large_file_contents, &result, &data);
EXPECT_EQ(result, BinaryUploadService::Result::FILE_TOO_LARGE);
EXPECT_EQ(data.size, very_large_file_contents.size());
EXPECT_TRUE(data.contents.empty());
// python3 -c "print('a' * (100 * 1024 * 1024), end='')" | sha256sum | tr
// '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"CEE41E98D0A6AD65CC0EC77A2BA50BF26D64DC9007F7F1C7D7DF68B8B71291A6");
}
TEST_P(FileSourceRequestTest, PopulatesDigest) {
base::test::TaskEnvironment task_environment;
std::string file_contents = "Normal file contents";
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath file_path = temp_dir.GetPath().AppendASCII("foo.doc");
// Create the file.
base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
file.WriteAtCurrentPos(file_contents.data(), file_contents.size());
auto request = MakeRequest(/*block_unsupported_types=*/false, file_path,
file_path.BaseName());
base::RunLoop run_loop;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop](BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
run_loop.Quit();
}));
run_loop.Run();
// printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]'
EXPECT_EQ(request->digest(),
"29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B");
}
TEST_P(FileSourceRequestTest, PopulatesFilename) {
base::test::TaskEnvironment task_environment;
std::string file_contents = "contents";
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath file_path = temp_dir.GetPath().AppendASCII("foo.doc");
// Create the file.
base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
file.WriteAtCurrentPos(file_contents.data(), file_contents.size());
auto request = MakeRequest(/*block_unsupported_types=*/false, file_path,
file_path.BaseName());
base::RunLoop run_loop;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop](BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
run_loop.Quit();
}));
run_loop.Run();
EXPECT_EQ(request->filename(), "foo.doc");
}
TEST_P(FileSourceRequestTest, CachesResults) {
base::test::TaskEnvironment task_environment;
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
std::string normal_contents = "Normal file contents";
base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.doc");
base::WriteFile(file_path, normal_contents.data(), normal_contents.size());
BinaryUploadService::Result async_result;
BinaryUploadService::Request::Data async_data;
auto request = MakeRequest(/*block_unsupported_types=*/false, file_path,
file_path.BaseName());
bool called = false;
base::RunLoop run_loop;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called, &async_result, &async_data](
BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
called = true;
run_loop.Quit();
async_result = result;
async_data = data;
}));
run_loop.Run();
ASSERT_TRUE(called);
BinaryUploadService::Result sync_result;
BinaryUploadService::Request::Data sync_data;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called, &sync_result, &sync_data](
BinaryUploadService::Result result,
const BinaryUploadService::Request::Data& data) {
called = true;
run_loop.Quit();
sync_result = result;
sync_data = data;
}));
EXPECT_EQ(sync_result, async_result);
EXPECT_EQ(sync_data.contents, async_data.contents);
EXPECT_EQ(sync_data.size, async_data.size);
EXPECT_EQ(sync_data.hash, async_data.hash);
}
TEST_P(FileSourceRequestTest, Encrypted) {
content::BrowserTaskEnvironment browser_task_environment;
content::InProcessUtilityThreadHelper in_process_utility_thread_helper;
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
base::FilePath test_zip;
EXPECT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_zip));
test_zip = test_zip.AppendASCII("safe_browsing")
.AppendASCII("download_protection")
.AppendASCII("encrypted.zip");
auto request = MakeRequest(/*block_unsupported_types=*/false, test_zip,
test_zip.BaseName());
bool called = false;
base::RunLoop run_loop;
BinaryUploadService::Result result;
BinaryUploadService::Request::Data data;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called, &result, &data](
BinaryUploadService::Result tmp_result,
const BinaryUploadService::Request::Data& tmp_data) {
called = true;
run_loop.Quit();
result = tmp_result;
data = tmp_data;
}));
run_loop.Run();
ASSERT_TRUE(called);
EXPECT_EQ(result, BinaryUploadService::Result::FILE_ENCRYPTED);
// du chrome/test/data/safe_browsing/download_protection -b
EXPECT_EQ(data.size, 20015u);
// sha256sum < chrome/test/data/safe_browsing/download_protection/\
// encrypted.zip | tr '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"701FCEA8B2112FFAB257A8A8DFD3382ABCF047689AB028D42903E3B3AA488D9A");
EXPECT_EQ(request->digest(), data.hash);
}
TEST_P(FileSourceRequestTest, UnsupportedFileTypeBlock) {
base::test::TaskEnvironment task_environment;
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
std::string normal_contents = "Normal file contents";
base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.xyz");
base::WriteFile(file_path, normal_contents.data(), normal_contents.size());
auto request = MakeRequest(/*block_unsupported_types=*/true, file_path,
file_path.BaseName());
if (request->use_legacy_proto()) {
request->set_request_dlp_scan(DlpDeepScanningClientRequest());
request->set_request_malware_scan(MalwareDeepScanningClientRequest());
} else {
request->add_tag("dlp");
request->add_tag("malware");
}
bool called = false;
base::RunLoop run_loop;
BinaryUploadService::Result result;
BinaryUploadService::Request::Data data;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called, &result, &data](
BinaryUploadService::Result tmp_result,
const BinaryUploadService::Request::Data& tmp_data) {
called = true;
run_loop.Quit();
result = tmp_result;
data = tmp_data;
}));
run_loop.Run();
ASSERT_TRUE(called);
EXPECT_EQ(result,
BinaryUploadService::Result::DLP_SCAN_UNSUPPORTED_FILE_TYPE);
EXPECT_EQ(data.contents, normal_contents);
EXPECT_EQ(data.size, normal_contents.size());
// printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B");
EXPECT_EQ(request->digest(), data.hash);
}
TEST_P(FileSourceRequestTest, UnsupportedFileTypeNoBlock) {
base::test::TaskEnvironment task_environment;
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
std::string normal_contents = "Normal file contents";
base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.xyz");
base::WriteFile(file_path, normal_contents.data(), normal_contents.size());
auto request = MakeRequest(/*block_unsupported_types=*/false, file_path,
file_path.BaseName());
if (request->use_legacy_proto()) {
request->set_request_dlp_scan(DlpDeepScanningClientRequest());
request->set_request_malware_scan(MalwareDeepScanningClientRequest());
} else {
request->add_tag("dlp");
request->add_tag("malware");
}
bool called = false;
base::RunLoop run_loop;
BinaryUploadService::Result result;
BinaryUploadService::Request::Data data;
request->GetRequestData(base::BindLambdaForTesting(
[&run_loop, &called, &result, &data](
BinaryUploadService::Result tmp_result,
const BinaryUploadService::Request::Data& tmp_data) {
called = true;
run_loop.Quit();
result = tmp_result;
data = tmp_data;
}));
run_loop.Run();
ASSERT_TRUE(called);
// The dlp request should have been removed since the type is unsupported.
if (request->use_legacy_proto()) {
EXPECT_FALSE(request->deep_scanning_request().has_dlp_scan_request());
} else {
for (const std::string& tag : request->content_analysis_request().tags())
EXPECT_NE("dlp", tag);
}
EXPECT_EQ(result, BinaryUploadService::Result::SUCCESS);
EXPECT_EQ(data.contents, normal_contents);
EXPECT_EQ(data.size, normal_contents.size());
// printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]'
EXPECT_EQ(data.hash,
"29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B");
EXPECT_EQ(request->digest(), data.hash);
}
} // namespace safe_browsing
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
37456a66ddca6d5b53a1009c6c1c424911679795 | f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d | /SDK/PVR_DatasmithContent_classes.hpp | c097e0a94725264ac3f6e98b5d2f2bb523fb6be9 | [] | no_license | hinnie123/PavlovVRSDK | 9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b | 503f8d9a6770046cc23f935f2df1f1dede4022a8 | refs/heads/master | 2020-03-31T05:30:40.125042 | 2020-01-28T20:16:11 | 2020-01-28T20:16:11 | 151,949,019 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 22,670 | hpp | #pragma once
// PavlovVR (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class DatasmithContent.DatasmithObjectTemplate
// 0x0000 (0x0028 - 0x0028)
class UDatasmithObjectTemplate : public UObject
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithObjectTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithActorTemplate
// 0x00A0 (0x00C8 - 0x0028)
class UDatasmithActorTemplate : public UDatasmithObjectTemplate
{
public:
unsigned char UnknownData00[0x50]; // 0x0028(0x0050) UNKNOWN PROPERTY: SetProperty DatasmithContent.DatasmithActorTemplate.Layers
unsigned char UnknownData01[0x50]; // 0x0078(0x0050) UNKNOWN PROPERTY: SetProperty DatasmithContent.DatasmithActorTemplate.Tags
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithActorTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithAreaLightActor
// 0x0020 (0x0348 - 0x0328)
class ADatasmithAreaLightActor : public AActor
{
public:
EDatasmithAreaLightActorShape LightShape; // 0x0328(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0329(0x0003) MISSED OFFSET
struct FVector2D Dimensions; // 0x032C(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
struct FLinearColor Color; // 0x0334(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float Intensity; // 0x0344(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAreaLightActor");
return ptr;
}
};
// Class DatasmithContent.DatasmithAreaLightActorTemplate
// 0x0028 (0x0050 - 0x0028)
class UDatasmithAreaLightActorTemplate : public UDatasmithObjectTemplate
{
public:
EDatasmithAreaLightActorShape LightShape; // 0x0028(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET
struct FVector2D Dimensions; // 0x002C(0x0008) (ZeroConstructor, IsPlainOldData)
struct FLinearColor Color; // 0x0034(0x0010) (ZeroConstructor, IsPlainOldData)
float Intensity; // 0x0044(0x0004) (ZeroConstructor, IsPlainOldData)
unsigned char bHidden : 1; // 0x0048(0x0001)
unsigned char UnknownData01[0x7]; // 0x0049(0x0007) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAreaLightActorTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithAssetImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithAssetImportData : public UAssetImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAssetImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithStaticMeshImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithStaticMeshImportData : public UDatasmithAssetImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithStaticMeshCADImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithStaticMeshCADImportData : public UDatasmithStaticMeshImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshCADImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithSceneImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithSceneImportData : public UAssetImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSceneImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithCADImportSceneData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithCADImportSceneData : public UDatasmithSceneImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithCADImportSceneData");
return ptr;
}
};
// Class DatasmithContent.DatasmithMDLSceneImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithMDLSceneImportData : public UDatasmithSceneImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithMDLSceneImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithDeltaGenAssetImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithDeltaGenAssetImportData : public UDatasmithAssetImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithDeltaGenAssetImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithDeltaGenSceneImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithDeltaGenSceneImportData : public UDatasmithSceneImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithDeltaGenSceneImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithVREDAssetImportData
// 0x0008 (0x0030 - 0x0028)
class UDatasmithVREDAssetImportData : public UDatasmithAssetImportData
{
public:
unsigned char UnknownData00[0x8]; // 0x0028(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithVREDAssetImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithVREDSceneImportData
// 0x0000 (0x0028 - 0x0028)
class UDatasmithVREDSceneImportData : public UDatasmithSceneImportData
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithVREDSceneImportData");
return ptr;
}
};
// Class DatasmithContent.DatasmithAssetUserData
// 0x0050 (0x0078 - 0x0028)
class UDatasmithAssetUserData : public UAssetUserData
{
public:
TMap<struct FName, struct FString> MetaData; // 0x0028(0x0050) (Edit, BlueprintVisible, ZeroConstructor, EditConst)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAssetUserData");
return ptr;
}
};
// Class DatasmithContent.DatasmithCineCameraComponentTemplate
// 0x0068 (0x0090 - 0x0028)
class UDatasmithCineCameraComponentTemplate : public UDatasmithObjectTemplate
{
public:
struct FDatasmithCameraFilmbackSettingsTemplate FilmbackSettings; // 0x0028(0x0008) (ZeroConstructor, IsPlainOldData)
struct FDatasmithCameraLensSettingsTemplate LensSettings; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData)
struct FDatasmithCameraFocusSettingsTemplate FocusSettings; // 0x0034(0x0008) (ZeroConstructor, IsPlainOldData)
float CurrentFocalLength; // 0x003C(0x0004) (ZeroConstructor, IsPlainOldData)
float CurrentAperture; // 0x0040(0x0004) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0xC]; // 0x0044(0x000C) MISSED OFFSET
struct FDatasmithPostProcessSettingsTemplate PostProcessSettings; // 0x0050(0x0040)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithCineCameraComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithContentBlueprintLibrary
// 0x0000 (0x0028 - 0x0028)
class UDatasmithContentBlueprintLibrary : public UBlueprintFunctionLibrary
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithContentBlueprintLibrary");
return ptr;
}
struct FString STATIC_GetDatasmithUserDataValueForKey(class UObject* Object, const struct FName& Key);
void STATIC_GetDatasmithUserDataKeysAndValuesForValue(class UObject* Object, const struct FString& StringToMatch, TArray<struct FName>* OutKeys, TArray<struct FString>* OutValues);
class UDatasmithAssetUserData* STATIC_GetDatasmithUserData(class UObject* Object);
};
// Class DatasmithContent.DatasmithImportOptions
// 0x0060 (0x0088 - 0x0028)
class UDatasmithImportOptions : public UObject
{
public:
EDatasmithImportSearchPackagePolicy SearchPackagePolicy; // 0x0028(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportAssetConflictPolicy MaterialConflictPolicy; // 0x0029(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportAssetConflictPolicy TextureConflictPolicy; // 0x002A(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportActorPolicy StaticMeshActorImportPolicy; // 0x002B(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportActorPolicy LightImportPolicy; // 0x002C(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportActorPolicy CameraImportPolicy; // 0x002D(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportActorPolicy OtherActorImportPolicy; // 0x002E(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
EDatasmithImportMaterialQuality MaterialQuality; // 0x002F(0x0001) (ZeroConstructor, Transient, IsPlainOldData)
unsigned char UnknownData00[0x8]; // 0x0030(0x0008) MISSED OFFSET
struct FDatasmithImportBaseOptions BaseOptions; // 0x0038(0x0018) (Edit, BlueprintVisible, Config)
struct FDatasmithTessellationOptions TessellationOptions; // 0x0050(0x000C) (Edit, BlueprintVisible, Config)
struct FDatasmithReimportOptions ReimportOptions; // 0x005C(0x0002) (Edit, BlueprintVisible, Config)
unsigned char UnknownData01[0x2A]; // 0x005E(0x002A) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithImportOptions");
return ptr;
}
};
// Class DatasmithContent.DatasmithLandscapeTemplate
// 0x0010 (0x0038 - 0x0028)
class UDatasmithLandscapeTemplate : public UDatasmithObjectTemplate
{
public:
class UMaterialInterface* LandscapeMaterial; // 0x0028(0x0008) (ZeroConstructor, IsPlainOldData)
int StaticLightingLOD; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x0034(0x0004) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithLandscapeTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithLightComponentTemplate
// 0x0038 (0x0060 - 0x0028)
class UDatasmithLightComponentTemplate : public UDatasmithObjectTemplate
{
public:
unsigned char bVisible : 1; // 0x0028(0x0001)
unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET
unsigned char CastShadows : 1; // 0x002C(0x0001)
unsigned char bUseTemperature : 1; // 0x002C(0x0001)
unsigned char bUseIESBrightness : 1; // 0x002C(0x0001)
unsigned char UnknownData01[0x3]; // 0x002D(0x0003) MISSED OFFSET
float Intensity; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData)
float Temperature; // 0x0034(0x0004) (ZeroConstructor, IsPlainOldData)
float IESBrightnessScale; // 0x0038(0x0004) (ZeroConstructor, IsPlainOldData)
struct FLinearColor LightColor; // 0x003C(0x0010) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData02[0x4]; // 0x004C(0x0004) MISSED OFFSET
class UMaterialInterface* LightFunctionMaterial; // 0x0050(0x0008) (ZeroConstructor, IsPlainOldData)
class UTextureLightProfile* IESTexture; // 0x0058(0x0008) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithLightComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithPointLightComponentTemplate
// 0x0010 (0x0038 - 0x0028)
class UDatasmithPointLightComponentTemplate : public UDatasmithObjectTemplate
{
public:
ELightUnits IntensityUnits; // 0x0028(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET
float SourceRadius; // 0x002C(0x0004) (ZeroConstructor, IsPlainOldData)
float SourceLength; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData)
float AttenuationRadius; // 0x0034(0x0004) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithPointLightComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithScene
// 0x0000 (0x0028 - 0x0028)
class UDatasmithScene : public UObject
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithScene");
return ptr;
}
};
// Class DatasmithContent.DatasmithSceneActor
// 0x0058 (0x0380 - 0x0328)
class ADatasmithSceneActor : public AActor
{
public:
class UDatasmithScene* Scene; // 0x0328(0x0008) (Edit, ZeroConstructor, EditConst, IsPlainOldData)
unsigned char UnknownData00[0x50]; // 0x0330(0x0050) UNKNOWN PROPERTY: MapProperty DatasmithContent.DatasmithSceneActor.RelatedActors
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSceneActor");
return ptr;
}
};
// Class DatasmithContent.DatasmithSceneComponentTemplate
// 0x00B8 (0x00E0 - 0x0028)
class UDatasmithSceneComponentTemplate : public UDatasmithObjectTemplate
{
public:
unsigned char UnknownData00[0x8]; // 0x0028(0x0008) MISSED OFFSET
struct FTransform RelativeTransform; // 0x0030(0x0030) (IsPlainOldData)
TEnumAsByte<EComponentMobility> Mobility; // 0x0060(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData01[0x7]; // 0x0061(0x0007) MISSED OFFSET
unsigned char UnknownData02[0x28]; // 0x0061(0x0028) UNKNOWN PROPERTY: SoftObjectProperty DatasmithContent.DatasmithSceneComponentTemplate.AttachParent
unsigned char UnknownData03[0x50]; // 0x0090(0x0050) UNKNOWN PROPERTY: SetProperty DatasmithContent.DatasmithSceneComponentTemplate.Tags
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSceneComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithSkyLightComponentTemplate
// 0x0010 (0x0038 - 0x0028)
class UDatasmithSkyLightComponentTemplate : public UDatasmithObjectTemplate
{
public:
TEnumAsByte<ESkyLightSourceType> SourceType; // 0x0028(0x0001) (ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET
int CubemapResolution; // 0x002C(0x0004) (ZeroConstructor, IsPlainOldData)
class UTextureCube* Cubemap; // 0x0030(0x0008) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSkyLightComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithSpotLightComponentTemplate
// 0x0008 (0x0030 - 0x0028)
class UDatasmithSpotLightComponentTemplate : public UDatasmithObjectTemplate
{
public:
float InnerConeAngle; // 0x0028(0x0004) (ZeroConstructor, IsPlainOldData)
float OuterConeAngle; // 0x002C(0x0004) (ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSpotLightComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithStaticMeshComponentTemplate
// 0x0020 (0x0100 - 0x00E0)
class UDatasmithStaticMeshComponentTemplate : public UDatasmithSceneComponentTemplate
{
public:
class UStaticMesh* StaticMesh; // 0x00E0(0x0008) (ZeroConstructor, IsPlainOldData)
TArray<class UMaterialInterface*> OverrideMaterials; // 0x00E8(0x0010) (ZeroConstructor)
unsigned char UnknownData00[0x8]; // 0x00F8(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshComponentTemplate");
return ptr;
}
};
// Class DatasmithContent.DatasmithStaticMeshTemplate
// 0x0078 (0x00A0 - 0x0028)
class UDatasmithStaticMeshTemplate : public UDatasmithObjectTemplate
{
public:
struct FDatasmithMeshSectionInfoMapTemplate SectionInfoMap; // 0x0028(0x0050) (Edit, EditConst)
int LightMapCoordinateIndex; // 0x0078(0x0004) (Edit, ZeroConstructor, EditConst, IsPlainOldData)
int LightMapResolution; // 0x007C(0x0004) (Edit, ZeroConstructor, EditConst, IsPlainOldData)
TArray<struct FDatasmithMeshBuildSettingsTemplate> BuildSettings; // 0x0080(0x0010) (Edit, ZeroConstructor, EditConst)
TArray<struct FDatasmithStaticMaterialTemplate> StaticMaterials; // 0x0090(0x0010) (Edit, ZeroConstructor, EditConst)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshTemplate");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
31f9d57023e4d1b176c49ed6335064aabfb3470d | 0b3aad9b8519368712217328f5909d1f944f466b | /Map.h | 01c5660c631092a5dab8d4be82043d5d998d064e | [] | no_license | CCA-Programs/RPG.txt | 729e4aa938ba6e969348bfb340bcd3181fc37df1 | 5a0d0c0d94182944c085833d15770cc4c97b37bc | refs/heads/master | 2020-12-24T10:54:55.878903 | 2016-11-11T19:12:31 | 2016-11-11T19:12:31 | 73,122,562 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,034 | h | #ifndef MAP_H
#define MAP_H
#include<vector>
using namespace std;
//Last modified by Todd Selwitz
//This header file defines the map that the character traverses.
//The vector holds the positions, and the enumerator determines what is on that square.
//EMPTY means that that square is not walkable, has no traps.
//OK means that the square is walkable and has no traps
//WALL implies the square is not walkable (different from EMPTY?)
//DOOR represents a link to another level or another part of the same level
//WATER could be used for fishing, healing, etc. (undetermined for now)
//LAVA steadily causes damage over time.
//TRAP has a one-time hazard (could be level dependent)
//ENEMY starts an "enemy" event
enum FLOOR_STATE {EMPTY, OK, WALL, DOOR, WATER, LAVA, TRAP, ENEMY} //Types of floor tiles ("OK" means
//the tile is walkable and has no traps
class Map{
private:
vector <vector<int> > map; //holds all positions on the map.
int character_pos; //holds the character location
};
#endif
| [
"selwitz.todd@gmail.com"
] | selwitz.todd@gmail.com |
2ee0f7f4ad35a3f3a107ca8dc4096efce85bc1a4 | ec2d8729d794cd682d17b5b6cf6d74c729ca2ca1 | /server/PlayerInfo.h | 10231437c7cb44739db064f539c77bb37f8b9576 | [
"MIT"
] | permissive | Jekmant/sampvoice | 640bea3aa94adf545e0027b5a49d0a02109109a4 | 13cab77a740d456e3ca6109c24563344312271fd | refs/heads/master | 2022-11-28T15:00:12.033481 | 2020-08-11T18:25:34 | 2020-08-11T18:25:34 | 286,818,282 | 2 | 0 | null | 2020-08-11T18:23:31 | 2020-08-11T18:23:30 | null | UTF-8 | C++ | false | false | 707 | h | /*
This is a SampVoice project file
Developer: CyberMor <cyber.mor.2020@gmail.ru>
See more here https://github.com/CyberMor/sampvoice
Copyright (c) Daniel (CyberMor) 2020 All rights reserved
*/
#pragma once
#include <set>
#include <atomic>
#include <cstdint>
#include "Stream.h"
struct PlayerInfo {
const uint8_t pluginVersion = NULL;
const bool microStatus = false;
std::atomic_bool muteStatus = { false };
std::atomic_bool recordStatus = { false };
std::set<Stream*> listenerStreams;
std::set<Stream*> speakerStreams;
std::set<uint8_t> keys;
PlayerInfo(
const uint8_t pluginVersion,
const bool microStatus
) :
pluginVersion(pluginVersion),
microStatus(microStatus)
{}
};
| [
"cyber.mor.2020@gmail.com"
] | cyber.mor.2020@gmail.com |
75f1512e11e75cceabcce7800a11c78f727297b6 | f4e17640afef6d1b4d4a85f583a90e37f705dbd5 | /B2G/gecko/content/xslt/src/xpath/nsXPathNamespace.h | ef27f3924096f71a7b8d6703eba9bfb7eeb14262 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | wilebeast/FireFox-OS | d370362916f0c5a5408fa08285dbf4779f8b5eb3 | 43067f28711d78c429a1d6d58c77130f6899135f | refs/heads/master | 2016-09-05T22:06:54.838558 | 2013-09-03T13:49:21 | 2013-09-03T13:49:21 | 12,572,236 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 968 | h | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef nsXPathNamespace_h__
#define nsXPathNamespace_h__
#include "nsIDOMXPathNamespace.h"
/* d0a75e07-b5e7-11d5-a7f2-df109fb8a1fc */
#define TRANSFORMIIX_XPATH_NAMESPACE_CID \
{ 0xd0a75e07, 0xb5e7, 0x11d5, { 0xa7, 0xf2, 0xdf, 0x10, 0x9f, 0xb8, 0xa1, 0xfc } }
#define TRANSFORMIIX_XPATH_NAMESPACE_CONTRACTID \
"@mozilla.org/transformiix/xpath-namespace;1"
/**
* A class for representing XPath namespace nodes in the DOM.
*/
class nsXPathNamespace : public nsIDOMXPathNamespace
{
public:
// nsISupports interface
NS_DECL_ISUPPORTS
// nsIDOMNode interface
NS_DECL_NSIDOMNODE
// nsIDOMXPathNamespace interface
NS_DECL_NSIDOMXPATHNAMESPACE
};
#endif
| [
"info@hadrons.me"
] | info@hadrons.me |
2ce777b89e1823ff0e88ebc2f7df46328471a6ff | 4bebe4f1116f59c3ad8075580ab03a4e2c1a561e | /code_caffe-rc3_fvmtl_ccelc/include/caffe/layers/sigmoid_cross_entropyNeg_loss_layer.hpp | f53b8b23df54d10c95fe63961dff7b000ceff2c9 | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause"
] | permissive | markatopoulou/fvmtl-ccelc | 2f74d68e3fee9bd516fce24604da5044acebde6c | 4c6e0ac2e4c0cc6181f0836151a871bbff257ddb | refs/heads/master | 2020-03-20T05:25:08.515265 | 2018-06-13T13:17:44 | 2018-06-13T13:17:44 | 137,213,724 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,670 | hpp | #ifndef CAFFE_SIGMOID_CROSS_ENTROPYNEG_LOSS_LAYER_HPP_
#define CAFFE_SIGMOID_CROSS_ENTROPYNEG_LOSS_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/layers/loss_layer.hpp"
#include "caffe/layers/sigmoidNeg_layer.hpp"
namespace caffe {
/**
* @brief Computes the cross-entropy (logistic) loss @f$
* E = \frac{-1}{n} \sum\limits_{n=1}^N \left[
* p_n \log \hat{p}_n +
* (1 - p_n) \log(1 - \hat{p}_n)
* \right]
* @f$, often used for predicting targets interpreted as probabilities.
*
* This layer is implemented rather than separate
* SigmoidLayer + CrossEntropyLayer
* as its gradient computation is more numerically stable.
* At test time, this layer can be replaced simply by a SigmoidLayer.
*
* @param bottom input Blob vector (length 2)
* -# @f$ (N \times C \times H \times W) @f$
* the scores @f$ x \in [-\infty, +\infty]@f$,
* which this layer maps to probability predictions
* @f$ \hat{p}_n = \sigma(x_n) \in [0, 1] @f$
* using the sigmoid function @f$ \sigma(.) @f$ (see SigmoidLayer).
* -# @f$ (N \times C \times H \times W) @f$
* the targets @f$ y \in [0, 1] @f$
* @param top output Blob vector (length 1)
* -# @f$ (1 \times 1 \times 1 \times 1) @f$
* the computed cross-entropy loss: @f$
* E = \frac{-1}{n} \sum\limits_{n=1}^N \left[
* p_n \log \hat{p}_n + (1 - p_n) \log(1 - \hat{p}_n)
* \right]
* @f$
*/
template <typename Dtype>
class SigmoidCrossEntropyNegLossLayer : public LossLayer<Dtype> {
public:
explicit SigmoidCrossEntropyNegLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param),
sigmoid_layer_(new SigmoidNegLayer<Dtype>(param)),
sigmoid_output_(new Blob<Dtype>()) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "SigmoidCrossEntropyNegLoss"; }
protected:
/// @copydoc SigmoidCrossEntropyNegLossLayer
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
/**
* @brief Computes the sigmoid cross-entropy loss error gradient w.r.t. the
* predictions.
*
* Gradients cannot be computed with respect to the target inputs (bottom[1]),
* so this method ignores bottom[1] and requires !propagate_down[1], crashing
* if propagate_down[1] is set.
*
* @param top output Blob vector (length 1), providing the error gradient with
* respect to the outputs
* -# @f$ (1 \times 1 \times 1 \times 1) @f$
* This Blob's diff will simply contain the loss_weight* @f$ \lambda @f$,
* as @f$ \lambda @f$ is the coefficient of this layer's output
* @f$\ell_i@f$ in the overall Net loss
* @f$ E = \lambda_i \ell_i + \mbox{other loss terms}@f$; hence
* @f$ \frac{\partial E}{\partial \ell_i} = \lambda_i @f$.
* (*Assuming that this top Blob is not used as a bottom (input) by any
* other layer of the Net.)
* @param propagate_down see Layer::Backward.
* propagate_down[1] must be false as gradient computation with respect
* to the targets is not implemented.
* @param bottom input Blob vector (length 2)
* -# @f$ (N \times C \times H \times W) @f$
* the predictions @f$x@f$; Backward computes diff
* @f$ \frac{\partial E}{\partial x} =
* \frac{1}{n} \sum\limits_{n=1}^N (\hat{p}_n - p_n)
* @f$
* -# @f$ (N \times 1 \times 1 \times 1) @f$
* the labels -- ignored as we can't compute their error gradients
*/
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
//virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
// const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
/// The internal SigmoidLayer used to map predictions to probabilities.
shared_ptr<SigmoidNegLayer<Dtype> > sigmoid_layer_;
/// sigmoid_output stores the output of the SigmoidLayer.
shared_ptr<Blob<Dtype> > sigmoid_output_;
/// bottom vector holder to call the underlying SigmoidLayer::Forward
vector<Blob<Dtype>*> sigmoid_bottom_vec_;
/// top vector holder to call the underlying SigmoidLayer::Forward
vector<Blob<Dtype>*> sigmoid_top_vec_;
};
} // namespace caffe
#endif // CAFFE_SIGMOID_CROSS_ENTROPYNEG_LOSS_LAYER_HPP_
| [
"markatopoulou@iti.gr"
] | markatopoulou@iti.gr |
67192cb9533fab6d2210b70d28c843fcf0bd2ae0 | 2df690d1f8a617e016f00911fe9aa8d4e83949a3 | /dsp/rrc_compute.cpp | e840c75077ae1ad6cf00a24191599945d477532a | [
"MIT"
] | permissive | kb3gtn/kb3gtn_sdr | 60aeb83696261c857ebe05b7c590f4e5b1053f1f | 384c2ea7c778cd0ddbf355a705a19cbf08725d4e | refs/heads/master | 2020-04-09T16:42:54.435094 | 2018-12-17T00:43:13 | 2018-12-17T00:43:13 | 160,460,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,009 | cpp | #include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
std::vector<double> computeRRC(double sps, double a, double d);
int main() {
cout << "computing RRC response for:\n";
double sps = 4;
cout << " samples/symbol => " << sps << "\n";
double a = 0.35;
cout << " rolloff (a) => " << a << "\n";
double d = 4;
cout << " duration (d) => " << -1.0*d << "-> +" << d << "\n";
std::vector<double> coeff = computeRRC( sps, a, d );
std::cout << "Number of Taps computed: " << coeff.size() << "\n";
std::cout << "Coefficents calculated:\n";
for (auto &c: coeff)
std::cout << c << ", ";
std::cout << "\n";
return 0;
}
std::vector<double> computeRRC(double sps, double a, double d) {
double tap_count = ( sps*2.0*d )+1.0;
std::vector<double> p(tap_count);
std::fill(p.begin(), p.end(), 0.0);
std::vector<double>::iterator cp = p.begin(); // current tap iterator.
for ( double t=-1*d; t <= d+(1.0/sps); t=t+(1.0/sps) ) {
if ( t == 0 ) {
std::cout << "(debug) t=0 case hit..\n";
*cp = (1-a)+4.0*a/M_PI; // OK
} else {
if ( ( t == 1.0/(4.0*a)) || (t == -1.0/(4.0*a)) ) {
std::cout << "(debug) t=1/(4*a) case hit..\n";
*cp = a/std::sqrt(2)*((1.0+2.0/M_PI)*std::sin(M_PI/(4.0*a))+(1.0-2.0/M_PI)*std::cos(M_PI/(4.0*a)));
} else {
// matlab: (sin(pi*-4*(1-a))+4*a*-4*cos(pi*-4*(1+a)))/(pi*-4*(1-(4*a*-4)^2))
*cp =(sin(M_PI*t*(1-a))+4*a*t*cos(M_PI*t*(1+a)))/(M_PI*t*(1-pow(4*a*t,2)));
}
}
cp++; // next tap.
}
// Normalize unit energy
// get squared sum
double ss=0;
for ( auto &t: p)
ss = ss + (t*t);
// compute the normalization value (nv)
double nv = std::sqrt(ss);
// apply normalization value to all taps
for ( auto &t: p )
t = t / nv;
// return taps computed
return p;
}
| [
"kb3gtn@gmail.com"
] | kb3gtn@gmail.com |
fb0f072c07e65e0d314c26a12ec33f2762a1da6e | f2cba86a7fad90570e2020bb12a7f51729aa6afa | /include/ITransaction.h | 58ffa159ca016c2249adcb678fcdc167285f6edd | [] | no_license | emergebtc/TavosBTC | 7ddcc01c2c5b1811785120d0e4c9d31b7b813e04 | f1bf530b9be008452ff7259fbbb3dbff8ba1da18 | refs/heads/master | 2016-09-15T21:13:02.156429 | 2015-08-01T08:21:06 | 2015-08-01T08:21:06 | 39,250,551 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,791 | h | // Copyright (c) 2011-2015 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <array>
#include <cstdint>
#include <vector>
namespace CryptoNote {
typedef std::array<uint8_t, 32> PublicKey;
typedef std::array<uint8_t, 32> SecretKey;
typedef std::array<uint8_t, 32> KeyImage;
typedef std::array<uint8_t, 32> Hash;
typedef std::vector<uint8_t> Blob;
struct AccountAddress {
PublicKey spendPublicKey;
PublicKey viewPublicKey;
};
struct AccountKeys {
AccountAddress address;
SecretKey spendSecretKey;
SecretKey viewSecretKey;
};
struct KeyPair {
PublicKey publicKey;
SecretKey secretKey;
};
namespace TransactionTypes {
enum class InputType : uint8_t { Invalid, Key, Multisignature, Generating };
enum class OutputType : uint8_t { Invalid, Key, Multisignature };
struct InputKey {
uint64_t amount;
std::vector<uint64_t> keyOffsets;
KeyImage keyImage; // double spending protection
};
struct InputMultisignature {
uint64_t amount;
uint32_t signatures;
uint64_t outputIndex;
};
struct OutputKey {
uint64_t amount;
PublicKey key;
};
struct OutputMultisignature {
uint64_t amount;
std::vector<PublicKey> keys;
uint32_t requiredSignatures;
};
struct GlobalOutput {
PublicKey targetKey;
uint64_t outputIndex;
};
typedef std::vector<GlobalOutput> GlobalOutputsContainer;
struct OutputKeyInfo {
PublicKey transactionPublicKey;
size_t transactionIndex;
size_t outputInTransaction;
};
struct InputKeyInfo {
uint64_t amount;
GlobalOutputsContainer outputs;
OutputKeyInfo realOutput;
};
}
//
// ITransactionReader
//
class ITransactionReader {
public:
virtual ~ITransactionReader() { }
virtual Hash getTransactionHash() const = 0;
virtual Hash getTransactionPrefixHash() const = 0;
virtual PublicKey getTransactionPublicKey() const = 0;
virtual uint64_t getUnlockTime() const = 0;
// extra
virtual bool getPaymentId(Hash& paymentId) const = 0;
virtual bool getExtraNonce(std::string& nonce) const = 0;
// inputs
virtual size_t getInputCount() const = 0;
virtual uint64_t getInputTotalAmount() const = 0;
virtual TransactionTypes::InputType getInputType(size_t index) const = 0;
virtual void getInput(size_t index, TransactionTypes::InputKey& input) const = 0;
virtual void getInput(size_t index, TransactionTypes::InputMultisignature& input) const = 0;
// outputs
virtual size_t getOutputCount() const = 0;
virtual uint64_t getOutputTotalAmount() const = 0;
virtual TransactionTypes::OutputType getOutputType(size_t index) const = 0;
virtual void getOutput(size_t index, TransactionTypes::OutputKey& output) const = 0;
virtual void getOutput(size_t index, TransactionTypes::OutputMultisignature& output) const = 0;
// signatures
virtual size_t getRequiredSignaturesCount(size_t inputIndex) const = 0;
virtual bool findOutputsToAccount(const AccountAddress& addr, const SecretKey& viewSecretKey, std::vector<uint32_t>& outs, uint64_t& outputAmount) const = 0;
// various checks
virtual bool validateInputs() const = 0;
virtual bool validateOutputs() const = 0;
virtual bool validateSignatures() const = 0;
// serialized transaction
virtual Blob getTransactionData() const = 0;
};
//
// ITransactionWriter
//
class ITransactionWriter {
public:
virtual ~ITransactionWriter() { }
// transaction parameters
virtual void setUnlockTime(uint64_t unlockTime) = 0;
// extra
virtual void setPaymentId(const Hash& paymentId) = 0;
virtual void setExtraNonce(const std::string& nonce) = 0;
// Inputs/Outputs
virtual size_t addInput(const TransactionTypes::InputKey& input) = 0;
virtual size_t addInput(const AccountKeys& senderKeys, const TransactionTypes::InputKeyInfo& info, KeyPair& ephKeys) = 0;
virtual size_t addInput(const TransactionTypes::InputMultisignature& input) = 0;
virtual size_t addOutput(uint64_t amount, const AccountAddress& to) = 0;
virtual size_t addOutput(uint64_t amount, const std::vector<AccountAddress>& to, uint32_t requiredSignatures) = 0;
// transaction info
virtual bool getTransactionSecretKey(SecretKey& key) const = 0;
virtual void setTransactionSecretKey(const SecretKey& key) = 0;
// signing
virtual void signInputKey(size_t input, const TransactionTypes::InputKeyInfo& info, const KeyPair& ephKeys) = 0;
virtual void signInputMultisignature(size_t input, const PublicKey& sourceTransactionKey, size_t outputIndex, const AccountKeys& accountKeys) = 0;
};
class ITransaction :
public ITransactionReader,
public ITransactionWriter {
public:
virtual ~ITransaction() { }
};
}
| [
"smallstratos@hotmail.com"
] | smallstratos@hotmail.com |
a729705b8f52d4018319078d29777673ee5f801f | ca780c75c1e7339ee2cc8802b18c48cf70f10172 | /re2c/src/dfa/cfg/freeze.cc | 926089d306f59173f533e85e3997add86ae5ae2c | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] | permissive | gkantsidis/re2c | b8f793c727dc4cb96ef12d862e687afdeb9fc3b3 | 8a82ee027744a3a21ae45c70ace0d5076cf591a8 | refs/heads/master | 2021-05-04T13:25:42.903156 | 2018-02-06T14:34:06 | 2018-02-06T14:34:06 | 120,313,604 | 1 | 0 | null | 2018-02-05T14:12:48 | 2018-02-05T14:12:48 | null | UTF-8 | C++ | false | false | 1,297 | cc | #include <stddef.h>
#include <vector>
#include "src/dfa/dfa.h"
#include "src/dfa/tcmd.h"
namespace re2c
{
/* note [tag freezing]
*
* Comparison of tag commands should be very fast (constant time):
* many optimizations rely on this (like tunnelling, hoisting and
* especially Moore's minimization, which compares whole classes
* of tagged transition at once). So we bring each command to some
* 'normal form' and insert it into common index.
*
* After that commands can be addressed and compared by index.
* They also become immutable, because different commands may
* share representation in memory.
*/
void freeze_tags(dfa_t &dfa)
{
tcpool_t &pool = dfa.tcpool;
const size_t
nstate = dfa.states.size(),
nsym = dfa.nchars;
dfa.tcid0 = pool.insert(dfa.tcmd0);
dfa.tcmd0 = NULL;
for (size_t i = 0; i < nstate; ++i) {
dfa_state_t *s = dfa.states[i];
tcmd_t **cmd = s->tcmd,
**const fin = cmd + nsym,
**const fall = fin + 1;
tcid_t *id = s->tcid = new tcid_t[nsym + 2];
// transition commands
for(; cmd < fin; ++cmd) {
*id++ = pool.insert(*cmd);
}
// final epsilon-transition command
*id++ = pool.insert(*fin);
// fallback epsilon-transition command
*id++ = pool.insert(*fall);
delete[] s->tcmd;
s->tcmd = NULL;
}
}
} // namespace re2c
| [
"skvadrik@gmail.com"
] | skvadrik@gmail.com |
6fa32a1000fbffccded27efe35f782658020387b | c1eacf630af8b23852845f27d6509b4b0d5eea1b | /DataStruct/AAAAA19_0522KMP.cpp | b26a21768bed32c827009ddbb1b8eed07da72d3b | [] | no_license | GISjingjie/DataStruct | 59f2408a44cdcde9b6307847267be9b7d07388f7 | 9bed92b9a19b09dd51479f73460b31a6b8dee464 | refs/heads/master | 2021-07-12T16:23:31.641629 | 2020-06-15T08:59:43 | 2020-06-15T08:59:43 | 146,618,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,244 | cpp | #include <stdio.h>
#include <Stdlib.h>
void PreFix(char pattern[],int prefix[],int lenP)
{
prefix[0]=0;
int len=0;
int i=1;
while(i<=lenP)
{
if(pattern[i]==pattern[len])
{
len++;
prefix[i]=len;
i++;
}else
{
if(len>0)
{
len=prefix[len-1];
}else
{
prefix[i]=len;
i++;
}
}
}
}
void SortPreFix(int prefix[],int len)
{
for(int i=len;i>0;i--)
{
prefix[i]=prefix[i-1];
}
prefix[0]=0;
}
int KMP(char string[],char pattern[],int prefix[],int strlen,int lenP)
{
int j=0;
int ret=-1;
for(int i=0;i<strlen&&pattern[j]!='\0';)
{
if(string[i]==pattern[j])
{
i++;
j++;
ret=i;
if(j==lenP)
{
ret-=lenP;
return ret;
}
}else if(string[i]!=pattern[j]&&j==0)
{
j=prefix[j];
i++;
}else
{
j=prefix[j];
}
}
return -1;
}
int main()
{
char Pattern[]="BCABCA";
int lenP=sizeof(Pattern)/sizeof(Pattern[0])-1;
printf("LEP:%d\n",lenP);
int prefix[lenP];
PreFix(Pattern,prefix,lenP);
SortPreFix(prefix,lenP);
for(int i=0;i<lenP;i++)
{
printf("%d\n",prefix[i]);
}
char String[]="ABCBCABACBCABCAAB";
int StrLen=sizeof(String)/sizeof(String[0])-1;
int position=KMP(String,Pattern,prefix,StrLen,lenP);
printf("Position:%d\n",position);
}
| [
"479309982@qq.com"
] | 479309982@qq.com |
045bba8865b28a03fc13eec6073dcd016095db9f | 3cd4cc83515c335728b7c16e7610f25dd8e087fe | /examples/Examples/Chap05/5.3_ImageResliceExample2.cpp | bbb429a1daa733dfd34c92b01c4c6f23f397fc06 | [] | no_license | liuyaoxinneo/VTK | a223cf1f05639299ce6afae23c19d2989d55578b | 90dc403896aef1ba828e413950e4ffe3ab041eb6 | refs/heads/master | 2021-05-08T08:02:22.252992 | 2017-10-15T13:55:37 | 2017-10-15T13:55:37 | 106,976,917 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 5,889 | cpp | /**********************************************************************
文件名: 5.3_ImageResliceExample2.cpp
Copyright (c) 张晓东, 罗火灵. All rights reserved.
更多信息请访问:
http://www.vtkchina.org (VTK中国)
http://blog.csdn.net/www_doling_net (东灵工作室)
**********************************************************************/
#include <vtkSmartPointer.h>
#include <vtkImageReader2.h>
#include <vtkMatrix4x4.h>
#include <vtkImageReslice.h>
#include <vtkLookupTable.h>
#include <vtkImageMapToColors.h>
#include <vtkImageActor.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkInteractorStyleImage.h>
#include <vtkCommand.h>
#include <vtkImageData.h>
#include <vtkMetaImageReader.h>
#include <vtkImageCast.h>
class vtkImageInteractionCallback : public vtkCommand
{
public:
static vtkImageInteractionCallback *New()
{
return new vtkImageInteractionCallback;
}
vtkImageInteractionCallback()
{
this->Slicing = 0;
this->ImageReslice = 0;
this->Interactor = 0;
}
void SetImageReslice(vtkImageReslice *reslice)
{
this->ImageReslice = reslice;
}
vtkImageReslice *GetImageReslice()
{
return this->ImageReslice;
}
void SetInteractor(vtkRenderWindowInteractor *interactor)
{
this->Interactor = interactor;
}
vtkRenderWindowInteractor *GetInteractor()
{
return this->Interactor;
}
virtual void Execute(vtkObject *, unsigned long event, void *)
{
vtkRenderWindowInteractor *interactor = this->GetInteractor();
int lastPos[2];
interactor->GetLastEventPosition(lastPos);
int currPos[2];
interactor->GetEventPosition(currPos);
if (event == vtkCommand::LeftButtonPressEvent)
{
this->Slicing = 1;
}
else if (event == vtkCommand::LeftButtonReleaseEvent)
{
this->Slicing = 0;
}
else if (event == vtkCommand::MouseMoveEvent)
{
if (this->Slicing)
{
vtkImageReslice *reslice = this->ImageReslice;
// Increment slice position by deltaY of mouse
int deltaY = lastPos[1] - currPos[1];
reslice->Update();
double sliceSpacing = reslice->GetOutput()->GetSpacing()[2];
vtkMatrix4x4 *matrix = reslice->GetResliceAxes();
// move the center point that we are slicing through
double point[4];
double center[4];
point[0] = 0.0;
point[1] = 0.0;
point[2] = sliceSpacing * deltaY;
point[3] = 1.0;
matrix->MultiplyPoint(point, center);
matrix->SetElement(0, 3, center[0]);
matrix->SetElement(1, 3, center[1]);
matrix->SetElement(2, 3, center[2]);
//printf("%f %f %f\n", center[0], center[1], center[2]);
interactor->Render();
}
else
{
vtkInteractorStyle *style = vtkInteractorStyle::SafeDownCast(
interactor->GetInteractorStyle());
if (style)
{
style->OnMouseMove();
}
}
}
}
private:
int Slicing;
vtkImageReslice *ImageReslice;
vtkRenderWindowInteractor *Interactor;
};
int main()
{
vtkSmartPointer<vtkMetaImageReader> reader =
vtkSmartPointer<vtkMetaImageReader>::New();
reader->SetFileName ( "..\\data\\brain.mhd" );
reader->Update();
int extent[6];
double spacing[3];
double origin[3];
reader->GetOutput()->GetExtent(extent);
reader->GetOutput()->GetSpacing(spacing);
reader->GetOutput()->GetOrigin(origin);
double center[3];
center[0] = origin[0] + spacing[0] * 0.5 * (extent[0] + extent[1]);
center[1] = origin[1] + spacing[1] * 0.5 * (extent[2] + extent[3]);
center[2] = origin[2] + spacing[2] * 0.5 * (extent[4] + extent[5]);
static double axialElements[16] = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
vtkSmartPointer<vtkMatrix4x4> resliceAxes =
vtkSmartPointer<vtkMatrix4x4>::New();
resliceAxes->DeepCopy(axialElements);
resliceAxes->SetElement(0, 3, center[0]);
resliceAxes->SetElement(1, 3, center[1]);
resliceAxes->SetElement(2, 3, center[2]);
vtkSmartPointer<vtkImageReslice> reslice =
vtkSmartPointer<vtkImageReslice>::New();
reslice->SetInputConnection(reader->GetOutputPort());
reslice->SetOutputDimensionality(2);
reslice->SetResliceAxes(resliceAxes);
reslice->SetInterpolationModeToLinear();
vtkSmartPointer<vtkLookupTable> colorTable =
vtkSmartPointer<vtkLookupTable>::New();
colorTable->SetRange(0, 1000);
colorTable->SetValueRange(0.0, 1.0);
colorTable->SetSaturationRange(0.0, 0.0);
colorTable->SetRampToLinear();
colorTable->Build();
vtkSmartPointer<vtkImageMapToColors> colorMap =
vtkSmartPointer<vtkImageMapToColors>::New();
colorMap->SetLookupTable(colorTable);
colorMap->SetInputConnection(reslice->GetOutputPort());
vtkSmartPointer<vtkImageActor> imgActor =
vtkSmartPointer<vtkImageActor>::New();
imgActor->SetInput(colorMap->GetOutput());
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
renderer->AddActor(imgActor);
renderer->SetBackground(.4, .5, .6);
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->SetSize(500, 500);
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkInteractorStyleImage> imagestyle =
vtkSmartPointer<vtkInteractorStyleImage>::New();
renderWindowInteractor->SetInteractorStyle(imagestyle);
renderWindowInteractor->SetRenderWindow(renderWindow);
renderWindowInteractor->Initialize();
vtkSmartPointer<vtkImageInteractionCallback> callback =
vtkSmartPointer<vtkImageInteractionCallback>::New();
callback->SetImageReslice(reslice);
callback->SetInteractor(renderWindowInteractor);
imagestyle->AddObserver(vtkCommand::MouseMoveEvent, callback);
imagestyle->AddObserver(vtkCommand::LeftButtonPressEvent, callback);
imagestyle->AddObserver(vtkCommand::LeftButtonReleaseEvent, callback);
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| [
"neo19941120@hotmail.com"
] | neo19941120@hotmail.com |
d8a61c2f740b53e2f194d9823b866319d330ca43 | fd472b2dcd3b28477f61574c6d41dabf1993d6df | /src/gc/main_debug3.cc | 990cc94643354565649427221c64c5e84c60d1c8 | [] | no_license | SimonHPedersen/gbvm | 566db9b53e7a2c3c50e5d050351729302438b6b7 | 2d5041b9373b41724110afb89f0be5d1b6c19f48 | refs/heads/master | 2016-09-06T02:33:26.023454 | 2014-02-26T18:19:07 | 2014-02-26T18:19:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,778 | cc | //$Id: main_debug3.cc,v 1.3 2000/12/06 14:50:13 ilsoe Exp $
#include <stdlib.h>
#include <stdio.h>
#include <iostream.h>
#include "garbage_collector.hpp"
class Test_t {
public:
void *operator new(size_t size, void *freePointer) {
return freePointer;
}
Test_t() {
}
void *a;
void *b;
void *c;
void *d;
void *e;
void *f;
void *g;
};
int main(int argc, char** argv) {
DB_ENABLE(gc_gc);
DB_ENABLE(gc_mg);
DB_ENABLE(gc_mg_heapdump);
DB_ENABLE(gc_remset_dump);
DB_ENABLE(gc_car);
DB_ENABLE(gc_car_delete);
DB_ENABLE(gc_vmo);
DB_ENABLE(gc_vmo_dump_refs);
//DB_ENABLE(gc_vmo_mro_verb);
DB_ENABLE(gc_trn);
DB_ENABLE(gc_objd);
DB_ENABLE(gc_glob_setvmr);
ObjectDescriptor_t *objDes = new ObjectDescriptor_t(300,0);
//objDes->print();
objDes->setReferenceAt(0);
objDes->setReferenceAt(1);
objDes->setReferenceAt(2);
objDes->setReferenceAt(3);
objDes->setReferenceAt(4);
objDes->setReferenceAt(5);
objDes->setReferenceAt(6);
//objDes->print();
// test 1 BYTES_IN_CAR should be 1024, 2 cars in train
VMObject_t *o0 = garbageCollector->addRootObject(objDes);
Test_t *t0 = new (o0->getDataPtr())Test_t();
VMObject_t *o1 = garbageCollector->addNewObject(objDes);
Test_t *t1 = new (o1->getDataPtr())Test_t();
VMObject_t *o2 = garbageCollector->addNewObject(objDes);
Test_t *t2 = new (o2->getDataPtr())Test_t();
VMObject_t *o3 = garbageCollector->addNewObject(objDes);
Test_t *t3 = new (o3->getDataPtr())Test_t();
VMObject_t *o4 = garbageCollector->addNewObject(objDes);
Test_t *t4 = new (o4->getDataPtr())Test_t();
VMObject_t *o5 = garbageCollector->addNewObject(objDes);
Test_t *t5 = new (o5->getDataPtr())Test_t();
VMObject_t *o6 = garbageCollector->addNewObject(objDes);
Test_t *t6 = new (o6->getDataPtr())Test_t();
VMObject_t *o7 = garbageCollector->addNewObject(objDes);
Test_t *t7 = new (o7->getDataPtr())Test_t();
VMObject_t *o8 = garbageCollector->addNewObject(objDes);
Test_t *t8 = new (o8->getDataPtr())Test_t();
/* creating popular object */
VMObject_t *o_n;
Test_t *t_n;
for(int i = 0; i < 100; i++) {
o_n = garbageCollector->addNewObject(objDes);
t_n = new (o_n->getDataPtr()) Test_t();
setVMReference(t_n, &(t_n->a), t1);
}
setVMReference(t0, &(t0->a), t5);
setVMReference(t1, &(t1->a), t2);
setVMReference(t2, &(t2->a), t3);
setVMReference(t3, &(t3->a), t4);
setVMReference(t4, &(t4->a), t3);
setVMReference(t5, &(t5->a), t1);
setVMReference(t5, &(t5->b), t6);
setVMReference(t7, &(t7->a), t8);
setVMReference(t8, &(t8->a), t7);
/*
setVMReference(t0, &(t0->b), t1);
setVMReference(t0, &(t0->c), t1);
setVMReference(t0, &(t0->d), t1);
setVMReference(t0, &(t0->e), t1);
setVMReference(t0, &(t0->f), t1);
setVMReference(t0, &(t0->g), t1);
setVMReference(t2, &(t2->b), t1);
setVMReference(t2, &(t2->c), t1);
setVMReference(t2, &(t2->d), t1);
setVMReference(t2, &(t2->e), t1);
setVMReference(t2, &(t2->f), t1);
setVMReference(t2, &(t2->g), t1);
setVMReference(t3, &(t3->b), t1);
setVMReference(t3, &(t3->c), t1);
setVMReference(t3, &(t3->d), t1);
setVMReference(t3, &(t3->e), t1);
setVMReference(t3, &(t3->f), t1);
setVMReference(t3, &(t3->g), t1);
setVMReference(t4, &(t4->b), t1);
setVMReference(t4, &(t4->c), t1);
setVMReference(t4, &(t4->d), t1);
setVMReference(t4, &(t4->e), t1);
setVMReference(t4, &(t4->f), t1);
setVMReference(t4, &(t4->g), t1);
setVMReference(t5, &(t5->c), t1);
setVMReference(t5, &(t5->d), t1);
setVMReference(t5, &(t5->e), t1);
setVMReference(t5, &(t5->f), t1);
setVMReference(t5, &(t5->g), t1);
*/
while(1) {
garbageCollector->garbageCollect();
}
}
| [
"shp@trifork.com"
] | shp@trifork.com |
c27f59de03510ad17d140860da30230b8b27b6eb | 1495647af9e5941772ab7d383b4cf78cdb0fb77f | /Graph/Home/adjacency_matrix.cpp | 0b9ea70df2b8595ecb16f8d89543555a07c2ece1 | [] | no_license | Imran4424/Data-Structure | aa7e33b567406dd9bf25be7cc35d72f0cee761a9 | 9b6b8e5367849e133aa437040946794db63399b1 | refs/heads/master | 2022-04-07T12:47:23.894934 | 2022-02-10T16:13:12 | 2022-02-10T16:13:12 | 124,618,740 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,988 | cpp | #include <iostream>
#include <iomanip>
using namespace std; /// adjacency matrix of fig 8.3 of example 8.3
int main()
{
int n,i,j,sum,k;
cout<<"Number of nodes"<<endl;
cin>>n;
int mat[n][n],mat2[n][n],mat3[n][n],mat4[n][n],B[n][n];
cout<<"Input your adjacency matrix"<<endl;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cin>>mat[i][j];
}
}
cout<<endl<<"mat:"<<endl<<endl;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout<<setw(2)<<mat[i][j]<<" ";
}
cout<<endl;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
sum = 0;
for(k=0;k<n;k++){
sum += mat[i][k]*mat[k][j];
}
mat2[i][j] = sum;
}
}
cout<<endl<<"mat2:"<<endl<<endl;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout<<setw(2)<<mat2[i][j]<<" ";
}
cout<<endl;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
sum = 0;
for(k=0;k<n;k++){
sum += mat2[i][k]*mat[k][j];
}
mat3[i][j] = sum;
}
}
cout<<endl<<"mat3:"<<endl<<endl;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout<<setw(2)<<mat3[i][j]<<" ";
}
cout<<endl;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
sum = 0;
for(k=0;k<n;k++){
sum += mat3[i][k]*mat[k][j];
}
mat4[i][j] = sum;
}
}
cout<<endl<<"mat4:"<<endl<<endl;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout<<setw(2)<<mat4[i][j]<<" ";
}
cout<<endl;
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
B[i][j] = (mat[i][j]+ mat2[i][j]+ mat3[i][j]+ mat4[i][j]);
}
}
cout<<endl<<"B:"<<endl<<endl;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout<<setw(2)<<B[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| [
"akashganga.programming.534363@gmail.com"
] | akashganga.programming.534363@gmail.com |
2941abc0c960bb70b6bf1533aaa04676862b6e26 | eafc52e8480fbc2021e2480235b14843b6682b10 | /src/main.cpp | 9bdd64dbbeffd03559a03c88e168844ef9a5dcda | [
"MIT"
] | permissive | grand151/esp32-laser-show | 22e0a19354ccc6423b129c1910c9ffe2731b73d4 | 0aa26b065101aa4ef93a5ba2202d0c6c1671cb44 | refs/heads/main | 2023-06-26T09:21:55.779652 | 2021-07-26T12:16:31 | 2021-07-26T12:16:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,532 | cpp | #include <stdio.h>
#include <string.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_spiffs.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <arpa/inet.h>
#include <vector>
#include "ILDAFile.h"
#include "SPIRenderer.h"
static const char *TAG = "main";
extern "C"
{
void app_main(void);
}
static const char *files[] = {
"/spiffs/Xwing.ild.gz",
"/spiffs/LemmTumble.ild.gz",
"/spiffs/Vader.ild.gz",
"/spiffs/Enterprise2.ild.gz"};
static const int num_files = 4;
void app_main()
{
vTaskDelay(2000 / portTICK_PERIOD_MS);
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = false};
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK)
{
if (ret == ESP_FAIL)
{
ESP_LOGE(TAG, "Failed to mount or format filesystem");
}
else if (ret == ESP_ERR_NOT_FOUND)
{
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
}
else
{
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
}
return;
}
// read all the files in
std::vector<ILDAFile *> ilda_files;
for (int i = 0; i < num_files; i++)
{
ILDAFile *ilda = new ILDAFile();
ilda->read(files[i]);
ilda_files.push_back(ilda);
}
esp_vfs_spiffs_unregister(NULL);
SPIRenderer *renderer = new SPIRenderer(ilda_files);
renderer->start();
// run forever
while (true)
{
vTaskDelay(600000 / portTICK_PERIOD_MS);
}
} | [
"chris@cmgresearch.com"
] | chris@cmgresearch.com |
d596890675d163c7936c035c101cb118842b1bf6 | 6b5191c8f1fb9f2cbc6b6431a0df9406da27e5b0 | /Multiples of 3 and 5.cpp | ce67c1687c5d1ea7e381ade57979835803b05fae | [] | no_license | shashank10721/competitive-Programming | 81620e498e44507a1c14e3de981f1f106471d425 | 2b7ef4612bab2052e1a5ae8b0206eea41eab1961 | refs/heads/master | 2021-06-07T02:00:25.716164 | 2021-05-20T16:44:36 | 2021-05-20T16:44:36 | 150,933,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | # competitive-Programming
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[1000],b[1000],c[1000],s1=0,s2=0,s3=0,sum;
for(int i=1;i<1000;i++)
{
a[i]=3*i;
b[i]=5*i;
c[i]=15*i;
}
for(int i=1;i<1000;i++)
{
if(a[i]<1000)
s1=s1+a[i];
if(b[i]<1000)
s2=s2+b[i];
if(c[i]<1000)
s3=s3+c[i];
}
cout<<(s1+s2-s3);
return 0;
}
| [
"noreply@github.com"
] | shashank10721.noreply@github.com |
235083df26040e887b2f2a4c2a617a0f97422532 | 515a26637797286e20d1bc79defedbfc52914dd2 | /threads/threadFunctor/thread.hpp | 4f437f7eb06cdf7169df3e3b4d7319db25708eea | [] | no_license | ofirvarsano/CPP | 40d3997567f8a4d62983bace3cb3f9c4260e7d6d | 4c795e616279e8d1001b78179cba886417986f72 | refs/heads/main | 2023-05-26T08:17:03.616629 | 2021-06-09T11:59:55 | 2021-06-09T11:59:55 | 375,332,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | hpp | #ifndef THREAD_H
#define THREAD_H
#include <pthread.h>
namespace advcpp {
class Runnable {
public:
virtual ~Runnable() { }
//virtual void operator()() const = 0;
virtual void Do() const = 0;
};
class Uncopyable {
protected:
Uncopyable() {};
private:
Uncopyable(Uncopyable const&); // no copy
};
class Thread : private Uncopyable {
public:
//typedef void* (*actFunc)(void*);
explicit Thread(Runnable& a_func);
~Thread();
void Join();
void Detach();
void Cancel();
bool operator==(const Thread& a_other) const;
bool operator!=(const Thread& a_other) const;
public:
static void SleepMicroSeconds(unsigned long a_microSeconds);
static void Yield();
private:
Thread(const Thread&); // no copy
Thread& operator=(const Thread&); // no copy
private:
bool m_joinable;
pthread_t m_thread;
private:
static void* Start(void*);
};
} //advcpp
#endif // THREAD_H
| [
"noreply@github.com"
] | ofirvarsano.noreply@github.com |
9b5443d214f9a24ea42537f461c19f84a2ad54d6 | b8be56136362dc4cf3c51136285f38815ff6ab4b | /sketch_oct15b/sketch_oct15b.ino | afc6d60e0f3f1fb50597520d203e83f64021a425 | [] | no_license | ivanferrier/ECE-196 | 3910fb0c313a0374fe4bd60e4f37f46ceea6cb97 | f9c30bf20ebe6025b3efa09d5d341ad5a2324ec9 | refs/heads/master | 2020-04-11T05:26:22.896109 | 2018-12-12T21:49:07 | 2018-12-12T21:49:07 | 161,549,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 100 | ino | #include <Blnk.h>
Blnk blnk(13);
void setup()
{
}
void loop()
{
blnk.start();
delay(3000);
}
| [
"i_ferrier@aol.com"
] | i_ferrier@aol.com |
b223ffeb28765d7c2cc2a3b372731d8abbfacfdb | 03151cea816f33416b5cbb6356d875bf9ccf732a | /oled.cpp | d20faccfa3d7829c3918936704c9fec49a9064a4 | [] | no_license | HybridAir/pndt_v1 | f59e720d76d92625bdecfc0d640c05e57a06d22e | 371e976acfa1b1267b7de502f85859be3c4be572 | refs/heads/master | 2021-03-12T22:46:34.769004 | 2014-12-13T14:46:03 | 2014-12-13T14:46:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,261 | cpp | //handles the main hardware display related operations
#include "oled.h"
extern settings set;
extern menus menu;
extern io inout;
//extern rtcTime time;
extern Adafruit_SSD1306 display;
extern pages page;
extern pageBatt batt;
//function that is called all the time in main to update the display
//"page" functionality
//page/mode selection menu
//scrolling text announcement page, home screen clock data thing, battery/charge, settings, games, power warnings
//Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
oled::oled() {
display.setTextSize(4);
display.setTextColor(WHITE);
display.setTextWrap(false);
}
void oled::begin() {
display.begin(SSD1306_SWITCHCAPVCC); //turn the display on
display.display(); //show the splash screen
//prepare the startup timer
unsigned long previousMillis = millis();
unsigned long currentMillis = 0;
while(currentMillis < previousMillis + 2000) { //while we're waiting for 1 second to elapse
currentMillis = millis(); //keep checking the time
//stabilize the temperature and battery levels so they're correct
inout.processTmp(true);
inout.processBatt(true);
//also give the user some time to view the splash screen
}
display.clearDisplay();
batt.powerCheck(); //need to check the battery and display any priority warnings
}
void oled::dispMon() {
//there's going to be stuff in here okay
//first line is always going to clear the display
//next lines are going to go through each page to see what needs displaying
//each page will add it's stuff if necessary
//after that there will be some other "functions" that might need displaying
//includes the button bar and probably battery warnings
//last line is a display.display
display.clearDisplay();
batt.powerCheck();
if(set.getMenu()) { //check if the menu needs to be displayed
menu.doMain(); //do the main menu page
}
else {
page.doPage(); //the menu isn't open, resume normal operation
}
display.display();
}
void oled::drawBtnBar(char left, String center, char right) {
display.drawFastHLine(0, 55, SSD1306_LCDWIDTH, WHITE); //draw the separator line
display.setTextSize(1);
//left
display.fillTriangle(8, 56, 16, 56, 8, 64, WHITE); //left side designy stuff
display.fillRect(0, 56, 8, 8, WHITE);
display.setTextColor(BLACK); //print out the left indicator character, and "bold" it
display.setCursor(2, 56);
display.print(left);
display.setCursor(3, 56);
display.print(left);
//center
display.setTextColor(WHITE);
centerText(57, 1, center);
//right
display.fillTriangle(112, 56, 120, 56, 120, 64, WHITE); //right side designy stuff
display.fillRect(120, 56, 8, 8, WHITE);
display.setTextColor(BLACK); //print out the right indicator character, and "bold" it
display.setCursor(121, 56);
display.print(right);
display.setCursor(120, 56);
display.print(right);
}
void oled::centerText(byte y, byte size, String in) {
byte textSize = (in.length() * 6) * size; //24px 4 chars
//byte out = (SSD1306_LCDWIDTH - textSize)/2;
display.setTextSize(size);
display.setCursor((SSD1306_LCDWIDTH - textSize)/2, y);
display.print(in);
}
void oled::showTitle(String in) {
display.setTextColor(WHITE);
centerText(0, 1, in);
display.drawFastHLine(0, 8, SSD1306_LCDWIDTH, WHITE);
}
byte oled::extractD0(byte input) { //extracts the digit in the tens place
return input / 10;
}
byte oled::extractD1(byte input) { //extracts the digit in the ones place
return input - (extractD0(input) * 10);
}
| [
"s.tratton.blake@gmail.com"
] | s.tratton.blake@gmail.com |
197b2cbc0737392f5f59ad0f359d26278aa81bc4 | 7e68c3e0e86d1a1327026d189a613297b769c411 | /Lib/Include/CompactKeyType.h | 91cd060dd9b7d9869bb64201c2751f0a08374246 | [] | no_license | staticlibs/Big-Numbers | bc08092e36c7c640dcf43d863448cd066abaebed | adbfa38cc2e3b8ef706a3ac8bbd3e398f741baf3 | refs/heads/master | 2023-03-16T20:25:08.699789 | 2020-12-20T20:50:25 | 2020-12-20T20:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,347 | h | #pragma once
template <typename T> class CompactKeyType {
private:
T m_value;
public:
CompactKeyType() {
}
inline CompactKeyType(T value) : m_value(value) {
}
#pragma warning( push )
#pragma warning(disable:4311 4302)
inline ULONG hashCode() const {
if(sizeof(m_value) > sizeof(ULONG)) {
ULONG result = 0;
const ULONG *start = (ULONG*)&m_value;
const ULONG *end = start + sizeof(m_value) / sizeof(ULONG);
for(const ULONG *p = start; p < end;) {
result ^= *(p++);
}
return result;
} else {
return (ULONG)m_value;
}
}
#pragma warning( pop )
inline bool operator==(const CompactKeyType &k) const {
return m_value == k.m_value;
}
operator T() const {
return m_value;
}
};
class Packer;
template<typename T> Packer &operator<<(Packer &p, const CompactKeyType<T> &v) {
p << (T)v;
return p;
}
template<typename T> Packer &operator>>(Packer &p, CompactKeyType<T> &v) {
T tmp;
p >> tmp;
v = tmp;
return p;
}
class CompactStrKeyType {
private:
const TCHAR *m_value;
public:
CompactStrKeyType() : m_value(EMPTYSTRING) {
}
inline CompactStrKeyType(const TCHAR *value) : m_value(value) {
}
#pragma warning( push )
#pragma warning(disable:4311 4302)
inline ULONG hashCode() const {
return strHash(m_value);
}
#pragma warning( pop )
inline bool operator==(const CompactStrKeyType &k) const {
return _tcscmp(m_value,k.m_value) == 0;
}
operator const TCHAR*() const {
return m_value;
}
};
class CompactStrIKeyType {
private:
const TCHAR *m_value;
public:
CompactStrIKeyType() : m_value(EMPTYSTRING) {
}
inline CompactStrIKeyType(const TCHAR *value) : m_value(value) {
}
#pragma warning( push )
#pragma warning(disable:4311 4302)
inline ULONG hashCode() const {
return striHash(m_value);
}
#pragma warning( pop )
inline bool operator==(const CompactStrIKeyType &k) const {
return _tcsicmp(m_value,k.m_value) == 0;
}
operator const TCHAR*() const {
return m_value;
}
};
typedef CompactKeyType<short > CompactShortKeyType;
typedef CompactKeyType<USHORT> CompactUShortKeyType;
typedef CompactKeyType<int > CompactIntKeyType;
typedef CompactKeyType<UINT > CompactUIntKeyType;
typedef CompactKeyType<float > CompactFloatKeyType;
typedef CompactKeyType<double> CompactDoubleKeyType;
| [
"jesper.gr.mikkelsen@gmail.com"
] | jesper.gr.mikkelsen@gmail.com |
6dad87338185450c4791d52c823c2b7bdf2e2b79 | 479f17b25cd610e9dfbbd70d09007c8a57202708 | /PFACTORS.cpp | 38cf62d796cf27dc46b95feb7cf0232c999f2cc3 | [] | no_license | Luckymaster/HARD-SPOJ | e70823e9cb19f0a3dfa132bb70156b5f4357942c | c17bad75ec940b43488c4e7ad7b43f315925c4a0 | refs/heads/master | 2021-09-18T14:51:33.845970 | 2021-08-25T12:41:32 | 2021-08-25T12:41:32 | 161,028,667 | 9 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 12,138 | cpp | #include <bits/stdc++.h>
#define LL long long
using namespace std;
//https://sites.math.rutgers.edu/~zeilberg/essays683/renault.html
vector<LL>prime;
vector<bool>isPrimes(10005,1);
vector<int>pp[1000001];
int fibk[]={1,3,8,6,20,24,16,12,24,60,10,24,28,48,40,24,36,24 ,18 ,60 ,16 ,30 ,48 ,24 ,100 ,84 ,72 ,48 ,
14 ,120 ,30 ,48 ,40 ,36 ,80 ,24 ,76,18 ,56 ,60 ,40 ,48 ,88 ,30 ,120 ,48 ,32 ,24 ,112 ,300 ,72 ,84 ,108,
72,20 ,48 ,72 ,42 ,58 ,120 ,60, 30 ,48 ,96, 140 ,120, 136, 36, 48 ,240 ,70 ,24 ,148 ,228, 200 ,18, 80, 168,
78 ,120,216,120,168,48,180,264,56,60,44,120,112,48,120,96,180,48,196,336,120,300,50,72,208,84,80,108,72,72,
108,60,152,48,76,72,240,42,168,174,144,120,110,60,40,30,500,48,256,192,88,420,130,120,144,408,360,36,276,48
,46 ,240 ,32, 210 ,140 ,24, 140 ,444 ,112 ,228,148,600,50,36,72,240 ,60,168,316,78,216,240,48,216,328,120,
40,168,336,48,364,180,72,264,348,168,400,120,232,132,178,120,90,336,120,48,380, 20,180,96,144,180,190,96,
388 ,588, 280 ,336 ,396 ,120 ,22 ,300 ,136 ,150 ,112 ,72 ,40, 624 ,48 ,168 ,90, 240 ,42,108,280,72,440,72,
240,108,296,60,252,456,448,48,600,228,456,72,114,240,80,84,52,168,160,174,312,144,238,120,240 ,330,648,
60,560 ,120 ,252 ,60 ,168 ,1500 ,250 ,48 ,240, 768 ,360 ,384 ,516, 264 ,304 ,420 ,168 ,390 ,176, 120,
540 ,144 ,88, 408, 268 ,360 ,270 ,72 ,112 ,276 ,100 ,48 ,556, 138 ,120 ,240 ,56, 96 ,568, 210 ,360
,420, 80, 48 ,612 ,420, 392 ,444 ,588, 336, 580 ,228,360,444,336,600,176,150,200,72,60,72,88,240,208,
60,310,168,628,948,240, 8,636,216,70,480,72,48,36,216,700,984,216,120,32 ,120,110,168,456 ,336 ,680 ,
48 ,676,1092 ,152,180 ,30 ,72 ,784 ,264 ,240 ,348 ,232 ,168 ,174, 1200 ,504 ,240 ,236, 696 ,140 ,132 ,
144, 534 ,358, 120, 342 ,90 ,440 ,336 ,740, 120 ,736 ,48, 120,1140,432,120,748,180,1000,96,28,144,378,
180,256,570,768,192,80,1164,264,588,388,840, 144,336,520,396,780,120,796,66,144,600,200,408,420,150,
1080 ,336 ,380, 72,408 ,120,552 ,624 ,464,48, 840 ,336 ,184, 90 ,418 ,240 ,84 ,42, 96 ,108 ,900 ,840,
240 ,72 ,280 ,1320 ,430 ,72 ,868 ,240, 280 ,108 ,144 ,888 ,438 ,60, 336 ,252 ,888 ,456 ,220 ,1344 ,296,
96, 448, 600 ,40 ,228,200,456,560,72,916,114,72,240,46 ,240,928,168,120,156,936,168,272,480,632,348,440,
312,900,144,216,714,478,240,532,240,48,330,980 ,648,976 ,60 ,328 ,1680 ,490 ,120,252, 252, 120 ,120 ,
560 ,168 ,498, 1500, 336,750,1008,48,100,240,728,768,254,360,592,768,72,516,1040,264,160,912,696,420,26
,168 ,1048,390 ,400,528 ,180 ,120 ,1104,540 ,696, 144, 280,264 ,360 ,408,712 ,804, 560,360, 90 ,270, 360
,144 ,540 ,336, 1096 ,276 ,120 ,300 ,126 ,48 ,624 ,1668 ,760 ,138,124,120,616,240,360,168,376,96,380,1704
,432,420,568,360,570,420,760,240,1200,96, 1156,612,776,420,336,1176,540,444,840,588, 1176,336 ,90,1740,
792, 456,1188,360,720, 444 ,88, 336, 598 ,600, 600 ,528 ,408 ,150 ,220 ,600 ,1216, 144 ,112, 60 ,224 ,
72, 1228 ,264 ,40, 240, 1236 ,624, 206 ,60 ,144 ,930, 176 ,168 ,2500, 1884 ,360 ,948 ,684, 240, 630,
156, 168, 636, 1280, 216, 112 ,210, 840, 960, 640, 72, 1288, 48 ,440, 36, 1296, 216, 290, 2100, 240,
984 ,1308, 216 ,260,120,888,96,658,120,220,330,504, 168,720,456,336,336,448,2040 ,60,48,1348,2028,1800,
1092,452,456,784,180,456,30,1368,72 ,1380 ,2352,456, 264 ,756,240,138,348,240,696 ,460, 168, 360 ,174
,104 ,1200 ,700 ,504 ,684 ,480, 160, 708, 400 ,696, 118 ,420 ,312, 132, 240 ,144, 140 ,534, 952, 1074
,718, 120, 208 ,342 ,240 ,90 ,700, 1320, 1456, 336, 1944 ,2220 ,792, 120 ,1468 ,2208, 560, 48 ,680
,120, 738,1140,504, 432,496,120,740,2244,168,180,144,3000,750,96,1000,84,100 ,144,1516,378,240,180,
380,768,432,570,360,768,812,384 ,192 ,240 ,1032, 1164,1548,264,300,588,304, 1164 ,360 ,840 ,70 ,144
,504 ,336 ,1580 ,1560 ,1576 ,396 ,176 ,780,304,120,420,2388,1080,66,228, 144 ,288 ,1200,264 ,600,740
,408,240, 420,536 ,300,202, 1080 ,270,336,1080,1140, 1640,72,792,408,336, 120 ,820, 552, 1648 ,624 ,200, 1392,1656, 48, 276 ,840, 1112 ,672 ,1008, 552 ,1680,90 ,360 ,1254 ,838, 240 ,406, 84 ,56 ,42 ,1820 ,96 ,880 ,216 ,568, 900 ,912, 840 ,1708 ,240 ,360 ,72 ,1716, 840 ,78 ,1320 ,80, 1290 ,1728 ,144 ,1740, 2604 ,1224 ,240 ,390 ,840, 952 ,108, 1176 ,144 ,2000, 888, 1756, 438 ,1176, 120 ,176, 336, 1768, 252 ,1160, 888 ,1776, 456 ,256 ,660,1080,1344,288,888,1780,192,336,1344,210,600,108,120,176,228,180,600,1816,456,600,1680,70,72,840 ,2748,120,114,1040,72,102,240,88,138,140,240,1900,2784,624,336,928,120,1008,156,1240,936,180,168, 1876, 816 ,1256, 480, 470 ,1896 ,240, 696 ,720 ,1320 ,1896 ,312, 1036, 900 ,1272 ,144 ,212 ,216 ,380 ,714 ,280 ,1434 ,1104 ,480, 930 ,1596 ,72 ,240 ,1940 ,48, 176, 660, 72 ,2940, 970 ,648 ,368 ,2928 ,1400, 120, 652, 984 ,220, 1680 ,216 ,1470 ,1968 ,120 ,1980 ,252 ,32 ,252, 528,120 ,198 ,240 ,440 ,1680 ,220 ,168, 1996 ,498, 1368 ,1500,560,336,1044,750,680,1008,108,48,126,300,1352,240,2028,2184,560,768,456,762,1018,360,510,1776,120,1536,200,72,1092,516,784,3120,206,264,2068,480,240,912,180,696,1038,840,232,78,592,168,180,3144,696,780,262,1200,1050,528,1512,180,420,240,400,1104,472,540,530,696,2128,144,280,840,980,264,356,360,144,408,532,2136,2200,804,1432,1680,168,360,96,90,1368,270,240,360,128,288,1320,540,1090,336,2188,3288,1480,276,732,120,1264,300,736,126,96,48,1260,624,360,1668,554,2280,50,276,432,372,2240,120,2236,1848,1496,240,522,360,2248,168,3000,1128,336,96,1128,1140,56,1704,1040,432,2280,840,1512,1704,1224,360,656,570,768,420,1140,2280,1140,240,768,1200,230,192,2308,3468,80,612,308,2328,180,420,792,336,2328,1176,260,540,776,888,336,840,1170,588,144,1176,800,336,360,90,1560,1740,1180,792,1456,912,1560,1188,2376,360,280,720,1592,444,2388,264,2380,336,144,1794,540,600,1200,600,200,528,240,408,1260,300,840,660,1392,600,2428,3648,3240,288,812,336,432,60,760,672,816,72,2800,3684,408,264,614,120,410,240,552,1236,1260,624,2476,618,464,60,1332,144,380,930,840,528,616,336,624,7500,552,1884,1424,360,500,948,1672,684,1258,240,196,630,168,312,240,168,720,636,288,3840,120,216,1224,336,1800,210,852,840,426,1920,240,1920,2568,72,2580,3864,840,48,322,1320,430,36,1720,1296,1520,216,2596,870,1736,2100,1300,240,2608,984,840,1308,872,216,720,780,144,240,700,888,880,96,1752,1974,1318,120,1320,660,1008,330,2700,504,2656,168,888,720,1210,456,1320,336,440,336,1520,1344,1456,2040,888,60,468,96,1340,4044,448,2028,630,1800,1552,1092,40,1356,540,456,1392,2352,600,360,680,456,224,30,560,1368,2736,72,2812,1380,1832,2352,2748,456,500,528,216,756,1584,240,460,138,184,348,2780,240,1332,696,928,1380,504,168,176,360,120,174,1280,312,1398,1200,936,2100,240,504,280,684,272,960,704,480,504,708,1896,1200,2840,696,756,354,440,420,112,312,2848,264,1800,240,168,144,1428,420,216,1068,2868,2856,80,1074,1912,2154,1438,240,130,624,1064,342,3060,240,2896,180,48,2100,1450,1320,2908,4368,1960,336,480,1944,1458,2220,976,792,720,120,2940,4404,984,2208,532,1680,490,96,1960,2040,2900,120,336,738,504,1140,1480,504,424,432,360,1488,2976,120,1488,2220,560,2244,2988,168,1680,180,1992,144,1498,3000,234,750,336,96,880,3000,1380,84,1008,300,302,144,396,4548,200,378,760,240,1680,360,2184,1140,1016,768,300,432,1016,1140,230,360,1530,768,592,2436,440,768,756,192,216,240,816,1032,3088,1164,1040,1548,1008,264,774,300,160,1176,1036,912,620,1164,696,360,1558,840,448,210,104,144,3140,504,3136,336,1048,4740,1570,1560,1540,4728,1200,396,504,528,526,780,360,912,3168,120,3180,420,1104,2388,912,1080,1672,132,2088,228,140,144,68,288,280,2400,160,264,912,600,360,2220,3216,408,1608,240,2136,420,3228,1608,180,600,560,606,1618,1080,810,270,360,336,3500,1080,3256,1140,360,4920,208,144,1680,792,1080,408,3276,336,740,120,1096,2460,540,552,160,4944,360,624,1764,600,1792,1392,504,1656,220,48,3316,276,624,840,50,3336,3328,1344,2280,1008,3336,552,834,1680,248,180,1904,360,3400,1254,616,2514,1776,240,1640,1218,360,84,3380,168,240,84,376,5460,396,96,3388,2640,760,432,3396,1704,566,900,1296,912,1820,840,60,5124,568,240,854,360,406,72,2280,1716,3920,840,900,78,2280,1320,430,240,3448,1290,1200,1728,1580,288,1008,1740,2312,2604,1156,1224,1160,240,2328,390,608,840,870,2856,336,216,1740,1176,3496,144,1080,6000,1872,888,3508,5268,2520,438,2000,1176,1758,240,1176,528,440,336,1180,5304,360,252,420,3480,240,888,792,1776,700,456,3556,768,2376,660,1932,1080,3568,1344,720,288,3576,888,894,5340,264,384,1640,336,3580,1344,2392,210,2064,600,1800,108,600,120,3420,528,644,456,1224,180,1810,600,2128,5448,440,456,624,600,72,1680,1216,210,1216,144,3700,840,336,2748,870,120,1830,228,224,3120,3680,72,1680,102,2456,240,176,264,1764,138,120,420,3696,240,3784,5700,2472,2784,108,624,2160,672,824,2784,1820,120,930,1008,432,156,3740,3720,3736,936,176,180,374,168,3748,5628,5000,816,1252,3768,1878,480,360,1410,1072,1896,140,240,1368,1392,1888,720,60,1320,2520,1896,3780,312,2160,3108,168,900,1900,1272,1740,144,1280,636,3816,216,336,1140,112,1428,1276,840,3840,1434,2520,1104,450,960,684,930,640,1596,400,72,160,240,1288,5820,1930,48,3868,528,1320,1320,1036,72,2224,2940,1296,2910,952,648,1940,1104,1160,2928,1948,4200,390,240,240,1956,720,984,1872,660,2616,1680,2052,216,700,1470,520,1968,112,120,890,1980,2664,252,1316,96,3900,252,2632,528,
1978,120,1136,198,440,480,3980,1320,3976,1680,504,660,90,168,3988,5988,720,498,3996,1368,666,3000};
LL GCD (int a,int b) { return __gcd(a,b);}
LL LCM(LL a, LL b) {
return (a /GCD(a,b))*(LL)b;
}
LL get_pisano_period(LL m) {
LL a = 0, b = 1, c = a + b;
for (LL i = 0; i < m * m; i++) {
c = (a + b) % m;
a = b;
b = c;
if (a == 0 && b == 1) return i + 1;
}
}
void genPrimes(){
for(int i=2;i*i<=10000;i++){
if(isPrimes[i]){
for(int j=i;i*j<=10000;j++) isPrimes[i*j] = 0;
}
}
prime.push_back(2);
for(int i=3;i<=10000;i+=2)if(isPrimes[i])prime.push_back(i);
}
LL mulmod(LL a, LL b, LL mod) {
LL res = (a * ((long double) b / (long double) mod));
res = a * b - res * mod;
if (res >= mod) res -= mod;
if (res < 0) res += mod;
return res;
}
LL a,b;
LL fibb(LL n, LL MM){
if(n==0){
a=0;b=1;
return a;
}
else{
a=fibb(n>>1,MM);
LL c = mulmod(a , (b+b - a+MM) , MM);
LL d = mulmod(b,b,MM) + mulmod(a,a,MM);
if(d>=MM)d-=MM;
if(n&1){
a=d;
b=c+d;
return a;
}
else{
a=c;
b=d;
return a;
}
}
}
map<int,int> getFactors(int n){
map<int,int> factors;
for(LL i=0;prime[i]*prime[i]<=n;i++){
int ck = 0;
if(n%prime[i]==0){
while(n%prime[i]==0){
ck+=1;
n/=prime[i];
}
factors[prime[i]] = ck;
}
}
if(n > 1)factors[n] = 1;
return factors;
}
LL findPeriod(int M) {
LL p = 0, cnt = 3;
if (M <= 2000){
cnt=fibk[M-1];
} else {
if (M % 5 == 1 || M % 5 == 4)
cnt = M - 1;
else
cnt = (M + 1) * 2;
}
map<int,int> :: iterator it;
map<int,int> factors = getFactors(cnt);
LL fn, fn1;
for (it=factors.begin();it!=factors.end();it++)
{
for (int j = 1; j <= it->second; j++)
{
fibb(cnt / it->first, M); fn=a, fn1=b;;
if (fn != 0LL || fn1 != 1LL)
break;
else
cnt = cnt / it->first;
}
}
return cnt;
}
int findPisano(int M) {
int period = -1;
for (int i = 0; prime[i] * prime[i] <= M; i++) {
int cp = 1;
if (M % prime[i] == 0) {
while (M %prime[i] == 0) {
cp *= prime[i];
M /= prime[i];
}
if (period == -1) period = findPeriod(prime[i]) * (cp/prime[i]);
else period = LCM(period, findPeriod(prime[i]) * (cp/prime[i]));
}
}
if (M > 1) {
if (period == -1) period = findPeriod(M);
else period = LCM(period, findPeriod(M));
}
return period;
}
void genPisano(){
pp[1].push_back(1);
for(int i=2;i<100001;i++){
pp[findPisano(i)].push_back(i);
}
}
vector<int> getDivisors(int n){
vector<int> fact;
for(int i=1;i*i<=n;i++){
if(n%i==0){
fact.push_back(i);
if(i!=n/i){
fact.push_back(n/i);
}
}
}
return fact;
}
int main() {
genPrimes();
genPisano();
int t,n;
cin >> t;
while(t--){
cin >> n;
vector<int>ans = getDivisors(n);
sort(ans.begin(),ans.end());
int res = 0;
for(int i=0;i<ans.size();i++) {
if(ans[i] > 1000000) continue;
for(int j=0;j<pp[ans[i]].size();j++){
if(pp[ans[i]][j] <= 100000){
res+=1;
}
}
}
cout << res <<endl;
}
return 0;
}
| [
"noreply@github.com"
] | Luckymaster.noreply@github.com |
cfd5a4f665f3f306c3ee608e9d5188c271012ddc | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Editor/GraphEditor/Public/SNameComboBox.h | 5af17b83389331c84c88779ead4971042f15b6f0 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 2,959 | h | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
#include "Styling/SlateColor.h"
#include "Layout/Margin.h"
#include "Widgets/SWidget.h"
#include "Widgets/SCompoundWidget.h"
#include "Framework/SlateDelegates.h"
#include "Widgets/Input/SComboBox.h"
//#include "UnrealString.h"
/**
* A combo box that shows FName content.
*/
class SNameComboBox : public SCompoundWidget
{
public:
DECLARE_DELEGATE_RetVal_OneParam(FString, FGetNameComboLabel, TSharedPtr<FName>);
typedef TSlateDelegates< TSharedPtr<FName> >::FOnSelectionChanged FOnNameSelectionChanged;
SLATE_BEGIN_ARGS( SNameComboBox )
: _ColorAndOpacity( FSlateColor::UseForeground() )
, _ContentPadding(FMargin(4.0, 2.0))
, _OnGetNameLabelForItem()
{}
/** Selection of FNames to pick from */
SLATE_ARGUMENT( TArray< TSharedPtr<FName> >*, OptionsSource )
/** Text color and opacity */
SLATE_ATTRIBUTE( FSlateColor, ColorAndOpacity )
/** Visual padding of the button content for the combobox */
SLATE_ATTRIBUTE( FMargin, ContentPadding )
/** Called when the FName is chosen. */
SLATE_EVENT( FOnNameSelectionChanged, OnSelectionChanged)
/** Called when the combo box is opened */
SLATE_EVENT( FOnComboBoxOpening, OnComboBoxOpening )
/** Called when combo box needs to establish selected item */
SLATE_ARGUMENT( TSharedPtr<FName>, InitiallySelectedItem )
/** [Optional] Called to get the label for the currently selected item */
SLATE_EVENT( FGetNameComboLabel, OnGetNameLabelForItem )
SLATE_END_ARGS()
void Construct( const FArguments& InArgs );
/** Called to create a widget for each FName */
TSharedRef<SWidget> MakeItemWidget( TSharedPtr<FName> StringItem );
void SetSelectedItem (TSharedPtr<FName> NewSelection);
/** Returns the currently selected FName */
TSharedPtr<FName> GetSelectedItem()
{
return SelectedItem;
}
/** Request to reload the name options in the combobox from the OptionsSource attribute */
void RefreshOptions();
/** Clears the selected item in the name combo */
void ClearSelection();
private:
TSharedPtr<FName> OnGetSelection() const {return SelectedItem;}
/** Called when selection changes in the combo pop-up */
void OnSelectionChanged(TSharedPtr<FName> Selection, ESelectInfo::Type SelectInfo);
/** Helper method to get the text for a given item in the combo box */
FText GetSelectedNameLabel() const;
FText GetItemNameLabel(TSharedPtr<FName> StringItem) const;
private:
/** Called to get the text label for an item */
FGetNameComboLabel GetTextLabelForItem;
/** The FName item selected */
TSharedPtr<FName> SelectedItem;
/** Array of shared pointers to FNames so combo widget can work on them */
TArray< TSharedPtr<FName> > Names;
/** The combo box */
TSharedPtr< SComboBox< TSharedPtr<FName> > > NameCombo;
/** Forwarding Delegate */
FOnNameSelectionChanged SelectionChanged;
};
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
464c0b3d0ffc084dd5eb20711edb392538de7339 | fd8fdf41880f3f67f8e6413c297b5144097b50ad | /trunk/src/cgi/notice_cgi/cgi_notice_notify_get.cpp | 343d873e7828f3ad88b611d60883500a33d7468d | [] | no_license | liuxuanhai/CGI_Web | c67d4db6a3a4de3714babbd31f095d2285545aac | 273343bb06a170ac3086d633435e7bcaaa81e8c5 | refs/heads/master | 2020-03-18T12:27:40.035442 | 2016-09-28T11:18:26 | 2016-09-28T11:18:26 | 134,727,689 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,356 | cpp | #include "notice_server_cgi.h"
#include "proto_io_tcp_client.h"
class CgiNoticeNotifyGet: public NoticeServerCgi
{
public:
CgiNoticeNotifyGet() :
NoticeServerCgi(0, "config.ini", "logger.properties")
{
}
bool InnerProcess()
{
uint64_t iPaAppidMd5 = strtoul(((string)GetInput().GetValue("pa_appid_md5")).c_str(),NULL,10);
uint64_t iOpenidMd5 = strtoul(((string)GetInput().GetValue("openid_md5")).c_str(),NULL,10);
ZERO_INT_RETURN(iPaAppidMd5);
ZERO_INT_RETURN(iOpenidMd5);
::common::protoio::ProtoIOTcpClient client(m_notice_server_ip, m_notice_server_port);
std::string strErrMsg = "";
::hoosho::msg::Msg stRequest;
::hoosho::msg::Msg stResponse;
::hoosho::msg::MsgHead* header = stRequest.mutable_head();
uint32_t iSeq = 1;
header->set_seq(iSeq);
header->set_cmd(hoosho::msg::QUERY_NOTICE_NOTIFY_REQ);
::hoosho::noticenotify::QueryNoticeNotifyReq* req = stRequest.mutable_notice_notify_query_req();
req->set_pa_appid_md5(iPaAppidMd5);
req->set_openid_md5(iOpenidMd5);
if (client.io(stRequest, stResponse, strErrMsg) < 0)
{
LOG4CPLUS_DEBUG(logger, "failed, strErrMsg=" << strErrMsg << std::endl;);
return -1;
}
std::ostringstream oss;
if (stResponse.head().cmd() == hoosho::msg::QUERY_NOTICE_NOTIFY_RES && stResponse.head().seq() == iSeq)
{
if (stResponse.head().result() == hoosho::msg::E_OK)
{
LOG4CPLUS_DEBUG(logger, "succe!!\n"<<stResponse.Utf8DebugString() << std::endl);
uint32_t stauts =stResponse.notice_notify_query_res().status();
GetAnyValue()["status"]=stauts;
DoReply(CGI_RET_CODE_OK);
}
else if (stResponse.head().result() == hoosho::msg::E_SERVER_INNER_ERROR)
{
LOG4CPLUS_DEBUG(logger, "error!! result= 1" << std::endl);
LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl);
DoReply(CGI_RET_CODE_SERVER_BUSY);
}
else
{
LOG4CPLUS_DEBUG(logger, "error!! result no 1 or 0" << std::endl);
LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl);
DoReply(CGI_RET_CODE_SERVER_BUSY);
}
}
else
{
LOG4CPLUS_DEBUG(logger, "error!! what 7 package?" << std::endl);
LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl);
DoReply(CGI_RET_CODE_SERVER_BUSY);
}
return true;
}
};
int main()
{
CgiNoticeNotifyGet cgi;
if (!cgi.Run())
{
return -1;
}
return 0;
}
| [
"penghuijun6738@163.com"
] | penghuijun6738@163.com |
179ad58d76af742208e0b39680351d420eb97fab | 67e0f28469124358d518dacff4cef3dd1956450e | /OneWaySurvivor/SourceFolder/Source/Sound/Base/Sound_Base_3D.cpp | 431a8cef7bf369d24c1989bbd64cde532d70eb94 | [] | no_license | FUKUDA87/OneWaySurvivor | 4593e669c032a357f248380c2b355eb794173f22 | 056f9dd621bc00d75fd95178c0b4b63db1ddf74c | refs/heads/master | 2020-11-27T17:43:11.055535 | 2020-07-20T09:55:18 | 2020-07-20T09:55:18 | 229,548,351 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,240 | cpp | #include "Sound_Base_3D.h"
extern LPDIRECTSOUND3DLISTENER8 lpSListener;
C_Sound_Base_3D::C_Sound_Base_3D(const S_SOUND_DATA * Data, std::string FileName)
{
M_Sound_Data = *Data;
Init_Sound(&M_Sound_Data.Sound_CategoryNo, &M_Sound_Data.Sound_No, FileName);
}
bool C_Sound_Base_3D::Update(const S_CAMERA_POS * CamPos, const bool * Flg,const int *Volume)
{
if (DeleteFlg > 1)return false;
DWORD SFlg;
soundCol.Sound3D->SetPosition(M_Sound_Data.Pos.x, M_Sound_Data.Pos.y, M_Sound_Data.Pos.z, DS3D_IMMEDIATE);//音源の位置
lpSListener->SetPosition(CamPos->Pos.x, CamPos->Pos.y, CamPos->Pos.z, DS3D_IMMEDIATE);//リスナーの位置
//リスナーが見ている方向計算
D3DXVECTOR3 Vec;
Vec = CamPos->Look - CamPos->Pos;
D3DXVec3Normalize(&Vec, &Vec);
lpSListener->SetOrientation(Vec.x, Vec.y, Vec.z, CamPos->Head.x, CamPos->Head.y, CamPos->Head.z, DS3D_IMMEDIATE);//リスナーが見ている方向とリスナーの頭の方向
soundCol.Sound->GetStatus(&SFlg);
if (M_MoveFlg != 2) {
if ((SFlg&DSBSTATUS_PLAYING) == 0) {
Loop_Mode();
if ((*Flg == true) || (Loop_Mode_Flg == true)) {
soundCol.Sound->Play(0, 0, 0);
M_MoveFlg = 1;
}
}
}
soundCol.Sound->SetVolume(*Volume);
return true;
}
| [
"kd1290926@st.kobedenshi.ac.jp"
] | kd1290926@st.kobedenshi.ac.jp |
42faa582bcb17db69b2c7560bac4f01060f9b042 | b2dedee28c3aa96fac1d9f31bf55c724ffde442d | /Sparky_core/src/utils/ImageLoad.h | ad6344e32d7e52a676b216258a4c66a10feed0c4 | [] | no_license | Arrekusu/Sparky | fd7834e73fe566316a580d1f3444df47439af63d | dcaf589415da8d44664710ab4322b721bdf9fd00 | refs/heads/master | 2021-07-08T01:56:42.358799 | 2017-10-05T06:36:43 | 2017-10-05T06:36:43 | 104,973,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | h | #pragma once
#include <FreeImage.h>
#include <string>
namespace sparky { namespace graphics{
static BYTE* load_image(const char* filename, GLsizei* width, GLsizei* height)
{
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
FIBITMAP *dib = nullptr;
BYTE* bits = nullptr;
fif = FreeImage_GetFileType(filename, 0);
if (fif == FIF_UNKNOWN)
fif = FreeImage_GetFIFFromFilename(filename);
if (fif == FIF_UNKNOWN)
return nullptr;
if (FreeImage_FIFSupportsReading(fif))
dib = FreeImage_Load(fif, filename);
if (!dib)
return nullptr;
BYTE* pixels = FreeImage_GetBits(dib);
*width = FreeImage_GetWidth(dib);
*height = FreeImage_GetHeight(dib);
int bpp = FreeImage_GetBPP(dib);
int size = *width * *height * (bpp / 8);
BYTE* result = new BYTE[size];
memcpy(result, pixels, size);
return result;
}
} }
| [
"arrekusu.a@gmail.com"
] | arrekusu.a@gmail.com |
9414deb06b716abe05fdfc392db6585d8d4895c4 | 5c5ba0cbdc972b56a3ac7664f68a74fe382c645a | /uri/8 - Computer Geometry/1991/Main.cpp | 1ec2e7228f457d353a29d3518af879ff10d881d0 | [] | no_license | humbertodias/challenges | 91e090b70ed65269ff94f0b8d4096526d3545ba3 | b832d55491b4d5c840b0bb25b931aef8f04f5784 | refs/heads/master | 2020-04-05T14:03:38.384606 | 2019-01-29T12:28:13 | 2019-01-29T12:28:13 | 94,749,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,433 | cpp | #include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
#include <vector>
#include <queue>
#include <list>
#include <stack>
#include <map>
#include <sstream>
#include <climits>
#include <set>
// #include <unordered_map>
#define ll long long
#define ull unsigned long long
#define PII pair<int,int>
#define PDD pair<double,double>
#define FT first
#define SD second
#define REP(i,j,k) for(int (i)=(j);(i)<(k);++(i))
#define PB push_back
#define PI acos(-1)
#define DB(x) cerr << #x << " = " << x << endl;
#define _ << ", " <<
#define MP make_pair
#define EPS 1e-9
#define INF 0x3f3f3f3f
#define IOFAST() ios_base::sync_with_stdio(0);cin.tie(0)
#define FILL(x,v) memset(x,v,sizeof(x))
// #define umap unordered_map
using namespace std;
template <class _T> inline string tostr(const _T& a){ ostringstream os(""); os<<a;return os.str(); }
const int MAXN = 2000;
double cen[2][MAXN];
double rad[2][MAXN];
bool nor[2][MAXN];
int sz[2];
char str[10];
int main(){
double A;
while( cin >> A ){
if( A < 0) break;
REP(i,0,2){
scanf("%d%s", &sz[i], str);
int rdsum = 0;
bool north = (str[0] == 'N');
REP(j,0,sz[i]){
int a; scanf("%d", &a);
rdsum += a;
cen[i][j] = rdsum;
rad[i][j] = a;
nor[i][j] = north;
north = !north;
rdsum += a;
}
}
double mid, lo = 0, hi = A;
while( fabs( hi - lo ) > EPS){
mid = (lo+hi)/2;
//DB( mid );
bool touch = false;
int i = 0, j = 0;
while( i < sz[0] || j < sz[1]){
double distrad = sqrt( pow( cen[0][i] - cen[1][j], 2) + pow(mid,2));
if( !nor[0][i] && nor[1][j] ){
if( distrad < rad[0][i] + rad[1][j] ){ //TODO EPS
touch = true;
goto leave;
}
} else if( nor[0][i] && !nor[1][j] ){
if( mid < EPS ){
touch = true;
goto leave;
}
} else {
double c1 , c2 , r1, r2;
if( nor[0][i] && nor[1][j]){
c1 = cen[0][i]; c2 = cen[1][j]; r1 = rad[0][i]; r2 = rad[1][j];
} else {
c1 = cen[1][j]; c2 = cen[0][i]; r1 = rad[1][j]; r2 = rad[0][i];
}
double distleft = sqrt(pow( (c1+r1) - c2, 2) + pow(mid,2));
double distright = sqrt(pow( (c1-r1) - c2, 2) + pow(mid,2));
if( distleft < r2 || distright < r2 ){
touch = true;
goto leave;
}
}
if( i < sz[0] && j < sz[1] &&
fabs( (cen[0][i] + rad[0][i]) - (cen[1][j] + rad[1][j]) ) < 1e-5){
i++, j++;
} else if( cen[0][i] + rad[0][i] > cen[1][j] + rad[1][j] && j + 1 < sz[1]) { j++;
} else {
i++;
}
}
leave :
if( touch ) lo = mid;
else hi = mid;
}
printf("%.2lf\n", (A - mid));
}
return 0;
} | [
"humberto.dias@techne.com.br"
] | humberto.dias@techne.com.br |
93e3d6a63428afeca35f07c19eea2d060f406584 | c74ab075ac54317a46f345fb0fbbbda1cf26abf8 | /B_Zero_Array.cpp | 1472b13a4c1d5611eab25989edbcb0e9abe03a6d | [] | no_license | friendlyNeighbourhoodFool/code | 8e54b9bf540603ceb09fec61bd518e0e282f1c84 | 7ffbc6eec746e9ed9a36550660cbdea48f0372f6 | refs/heads/main | 2023-06-27T08:27:37.508708 | 2021-07-20T17:31:50 | 2021-07-20T17:31:50 | 375,769,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,248 | cpp | /*
'Cause I love the adrenaline in my veins
*/
#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
//using namespace __gnu_pbds;
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> pbds;
#define endl '\n'
#define fast \
ios_base::sync_with_stdio(0); \
cin.tie(0); \
cout.tie(0);
#define rep(i, j, n) for (int i = j; i < n; i++)
#define pre(i, j, n) for (int i = j; i >= n; i--)
#define debug(a...) \
cout << #a << ": "; \
for (auto it : a) \
cout << it << " "; \
cout << endl;
#define deb(a) cout << #a << " " << a << endl;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const string no = "NO", yes = "YES";
const ll inf = 1e18;
const int mod = 1e9 + 7;
const ld pi = acosl(-1.0);
bool isPrime[100005];
ll fact[100005];
bool sbs(const pair<ll, ll> &a, const pair<ll, ll> b) { return a.second > b.second; }
//comparator fxn in stl sort should return false if swap is to be done
//return a.first<b.first if first ke according increasing in comparator
void seive()
{
memset(isPrime, true, sizeof(isPrime));
isPrime[1] = false;
isPrime[2] = true;
for (int i = 2; i * i <= 100005; i++)
{
for (int j = i * i; j <= 100005; j += i)
{
isPrime[j] = false;
}
}
}
void factorial()
{
fact[0] = fact[1] = 1;
for (int i = 2; i < 100005; i++)
fact[i] = (fact[i - 1] % mod * i % mod) % mod;
}
ll factor[200001];
void factorise_sieve()
{
int maxN = 200001;
for (int i = 1; i <= maxN; i++)
factor[i] = i;
for (int i = 2; i <= maxN; i += 2)
factor[i] = 2;
for (int i = 3; i * i <= maxN; i++)
{
if (factor[i] == i)
{
for (int j = i * i; j < maxN + 1; j += i)
if (factor[j] == j)
factor[j] = i;
}
}
}
long long power(long long x, int y, int p)
{
long long res = 1;
x = x % p;
while (y > 0)
{
if (y & 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
long long modInverse(long long n, int p)
{
return power(n, p - 2, p);
}
long long nCrModPFermat(long long n, int r, int p)
{
if (n < r)
return 0;
if (r == 0)
return 1;
long long fac[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = (fac[i - 1] * i) % p;
return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;
}
ll n;
vector<ll> a;
int main()
{
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
fast;
cin >> n;
ll sum = 0;
rep(i, 0, n)
{
ll t;
cin >> t;
sum+=t;
a.push_back(t);
}
sort(a.begin(),a.end());
if(a[n-1]<=sum-a[n-1]&&sum%2==0)cout<<yes<<endl;
else cout<<no<<endl;
} | [
"noreply@github.com"
] | friendlyNeighbourhoodFool.noreply@github.com |
1834fa3c43ac6d660ba393bcd391f3efcd062e7f | dccf5f6339baba548a83a7d390b63e285c9f0581 | /chrome/browser/resource_coordinator/tab_manager_stats_collector.cc | b086923148926e355b335b91d440573e35c072dd | [
"BSD-3-Clause"
] | permissive | Trailblazer01010111/chromium | 83843c9e45abb74a1a23df7302c1b274e460aee2 | 3fd9a73f1e93ce041a4580c20e30903ab090e95c | refs/heads/master | 2022-12-06T22:58:46.158304 | 2018-05-12T09:55:21 | 2018-05-12T09:55:21 | 133,138,333 | 1 | 0 | null | 2018-05-12T11:07:57 | 2018-05-12T11:07:56 | null | UTF-8 | C++ | false | false | 18,673 | 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 "chrome/browser/resource_coordinator/tab_manager_stats_collector.h"
#include <cstdint>
#include <memory>
#include <unordered_set>
#include <utility>
#include "base/atomic_sequence_num.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_macros.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/resource_coordinator/resource_coordinator_web_contents_observer.h"
#include "chrome/browser/resource_coordinator/tab_manager_web_contents_data.h"
#include "chrome/browser/resource_coordinator/time.h"
#include "chrome/browser/sessions/session_restore.h"
#include "components/metrics/system_memory_stats_recorder.h"
#include "content/public/browser/swap_metrics_driver.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/metrics/public/cpp/ukm_recorder.h"
namespace resource_coordinator {
namespace {
const char* kSessionTypeName[] = {"SessionRestore", "BackgroundTabOpening"};
constexpr int kSamplingOdds = 10;
// Only report a subset of this metric as the volume is too high.
bool ShouldReportExpectedTaskQueueingDurationToUKM(
size_t background_tab_loading_count,
size_t background_tab_pending_count) {
size_t tab_count =
background_tab_loading_count + background_tab_pending_count;
DCHECK_GE(tab_count, 1u);
// We always collect this metric when we have 2 or more backgrounded loading
// or pending tabs (|tab_count|). And we sample the rest, i.e. when there is
// one tab loading in the background and no tabs pending, which is the less
// interesting majority. In this way, we cap the volume while keeping all
// interesting data.
if (tab_count > 1)
return true;
if (base::RandUint64() % kSamplingOdds == 0)
return true;
return false;
}
ukm::SourceId GetUkmSourceId(content::WebContents* contents) {
ResourceCoordinatorWebContentsObserver* observer =
ResourceCoordinatorWebContentsObserver::FromWebContents(contents);
if (!observer)
return ukm::kInvalidSourceId;
return observer->ukm_source_id();
}
} // namespace
void TabManagerStatsCollector::BackgroundTabCountStats::Reset() {
tab_count = 0u;
tab_paused_count = 0u;
tab_load_auto_started_count = 0u;
tab_load_user_initiated_count = 0u;
}
class TabManagerStatsCollector::SwapMetricsDelegate
: public content::SwapMetricsDriver::Delegate {
public:
explicit SwapMetricsDelegate(
TabManagerStatsCollector* tab_manager_stats_collector,
SessionType type)
: tab_manager_stats_collector_(tab_manager_stats_collector),
session_type_(type) {}
~SwapMetricsDelegate() override = default;
void OnSwapInCount(uint64_t count, base::TimeDelta interval) override {
tab_manager_stats_collector_->RecordSwapMetrics(
session_type_, "SwapInPerSecond", count, interval);
}
void OnSwapOutCount(uint64_t count, base::TimeDelta interval) override {
tab_manager_stats_collector_->RecordSwapMetrics(
session_type_, "SwapOutPerSecond", count, interval);
}
void OnDecompressedPageCount(uint64_t count,
base::TimeDelta interval) override {
tab_manager_stats_collector_->RecordSwapMetrics(
session_type_, "DecompressedPagesPerSecond", count, interval);
}
void OnCompressedPageCount(uint64_t count,
base::TimeDelta interval) override {
tab_manager_stats_collector_->RecordSwapMetrics(
session_type_, "CompressedPagesPerSecond", count, interval);
}
void OnUpdateMetricsFailed() override {
tab_manager_stats_collector_->OnUpdateSwapMetricsFailed();
}
private:
TabManagerStatsCollector* tab_manager_stats_collector_;
const SessionType session_type_;
};
TabManagerStatsCollector::TabManagerStatsCollector() {
SessionRestore::AddObserver(this);
}
TabManagerStatsCollector::~TabManagerStatsCollector() {
SessionRestore::RemoveObserver(this);
}
void TabManagerStatsCollector::RecordWillDiscardUrgently(int num_alive_tabs) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::TimeTicks discard_time = NowTicks();
UMA_HISTOGRAM_COUNTS_100("Discarding.Urgent.NumAliveTabs", num_alive_tabs);
if (last_urgent_discard_time_.is_null()) {
UMA_HISTOGRAM_CUSTOM_TIMES(
"Discarding.Urgent.TimeSinceStartup", discard_time - start_time_,
base::TimeDelta::FromSeconds(1), base::TimeDelta::FromDays(1), 50);
} else {
UMA_HISTOGRAM_CUSTOM_TIMES("Discarding.Urgent.TimeSinceLastUrgent",
discard_time - last_urgent_discard_time_,
base::TimeDelta::FromMilliseconds(100),
base::TimeDelta::FromDays(1), 50);
}
// TODO(fdoray): Remove this #if when RecordMemoryStats is implemented for all
// platforms.
#if defined(OS_WIN) || defined(OS_CHROMEOS)
// Record system memory usage at the time of the discard.
metrics::RecordMemoryStats(metrics::RECORD_MEMORY_STATS_TAB_DISCARDED);
#endif
last_urgent_discard_time_ = discard_time;
}
void TabManagerStatsCollector::RecordSwitchToTab(
content::WebContents* old_contents,
content::WebContents* new_contents) {
if (!is_session_restore_loading_tabs_ &&
!is_in_background_tab_opening_session_) {
return;
}
if (IsInOverlappedSession())
return;
auto* new_data = TabManager::WebContentsData::FromWebContents(new_contents);
DCHECK(new_data);
if (is_session_restore_loading_tabs_) {
UMA_HISTOGRAM_ENUMERATION(kHistogramSessionRestoreSwitchToTab,
new_data->tab_loading_state(),
TAB_LOADING_STATE_MAX);
}
if (is_in_background_tab_opening_session_) {
UMA_HISTOGRAM_ENUMERATION(kHistogramBackgroundTabOpeningSwitchToTab,
new_data->tab_loading_state(),
TAB_LOADING_STATE_MAX);
}
if (old_contents)
foreground_contents_switched_to_times_.erase(old_contents);
DCHECK(
!base::ContainsKey(foreground_contents_switched_to_times_, new_contents));
if (new_data->tab_loading_state() != TAB_IS_LOADED) {
foreground_contents_switched_to_times_.insert(
std::make_pair(new_contents, NowTicks()));
}
}
void TabManagerStatsCollector::RecordExpectedTaskQueueingDuration(
content::WebContents* contents,
base::TimeDelta queueing_time) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// TODO(fdoray): Consider not recording this for occluded tabs.
if (contents->GetVisibility() == content::Visibility::HIDDEN)
return;
if (IsInOverlappedSession())
return;
ukm::SourceId ukm_source_id = GetUkmSourceId(contents);
if (is_session_restore_loading_tabs_) {
UMA_HISTOGRAM_TIMES(
kHistogramSessionRestoreForegroundTabExpectedTaskQueueingDuration,
queueing_time);
size_t restored_tab_count =
g_browser_process->GetTabManager()->restored_tab_count();
if (ukm_source_id != ukm::kInvalidSourceId && restored_tab_count > 1) {
ukm::builders::
TabManager_SessionRestore_ForegroundTab_ExpectedTaskQueueingDurationInfo(
ukm_source_id)
.SetExpectedTaskQueueingDuration(queueing_time.InMilliseconds())
.SetSequenceId(sequence_++)
.SetSessionRestoreSessionId(session_id_)
.SetSessionRestoreTabCount(restored_tab_count)
.SetSystemTabCount(
g_browser_process->GetTabManager()->GetTabCount())
.Record(ukm::UkmRecorder::Get());
}
}
if (is_in_background_tab_opening_session_) {
UMA_HISTOGRAM_TIMES(
kHistogramBackgroundTabOpeningForegroundTabExpectedTaskQueueingDuration,
queueing_time);
size_t background_tab_loading_count =
g_browser_process->GetTabManager()->GetBackgroundTabLoadingCount();
size_t background_tab_pending_count =
g_browser_process->GetTabManager()->GetBackgroundTabPendingCount();
if (ukm_source_id != ukm::kInvalidSourceId &&
ShouldReportExpectedTaskQueueingDurationToUKM(
background_tab_loading_count, background_tab_pending_count)) {
ukm::builders::
TabManager_BackgroundTabOpening_ForegroundTab_ExpectedTaskQueueingDurationInfo(
ukm_source_id)
.SetBackgroundTabLoadingCount(background_tab_loading_count)
.SetBackgroundTabOpeningSessionId(session_id_)
.SetBackgroundTabPendingCount(background_tab_pending_count)
.SetExpectedTaskQueueingDuration(queueing_time.InMilliseconds())
.SetSequenceId(sequence_++)
.SetSystemTabCount(
g_browser_process->GetTabManager()->GetTabCount())
.Record(ukm::UkmRecorder::Get());
}
}
}
void TabManagerStatsCollector::RecordBackgroundTabCount() {
DCHECK(is_in_background_tab_opening_session_);
if (!is_overlapping_background_tab_opening_) {
UMA_HISTOGRAM_COUNTS_100(kHistogramBackgroundTabOpeningTabCount,
background_tab_count_stats_.tab_count);
UMA_HISTOGRAM_COUNTS_100(kHistogramBackgroundTabOpeningTabPausedCount,
background_tab_count_stats_.tab_paused_count);
UMA_HISTOGRAM_COUNTS_100(
kHistogramBackgroundTabOpeningTabLoadAutoStartedCount,
background_tab_count_stats_.tab_load_auto_started_count);
UMA_HISTOGRAM_COUNTS_100(
kHistogramBackgroundTabOpeningTabLoadUserInitiatedCount,
background_tab_count_stats_.tab_load_user_initiated_count);
}
}
void TabManagerStatsCollector::OnSessionRestoreStartedLoadingTabs() {
DCHECK(!is_session_restore_loading_tabs_);
UpdateSessionAndSequence();
CreateAndInitSwapMetricsDriverIfNeeded(SessionType::kSessionRestore);
is_session_restore_loading_tabs_ = true;
ClearStatsWhenInOverlappedSession();
}
void TabManagerStatsCollector::OnSessionRestoreFinishedLoadingTabs() {
DCHECK(is_session_restore_loading_tabs_);
UMA_HISTOGRAM_BOOLEAN(kHistogramSessionOverlapSessionRestore,
is_overlapping_session_restore_ ? true : false);
if (swap_metrics_driver_)
swap_metrics_driver_->UpdateMetrics();
is_session_restore_loading_tabs_ = false;
is_overlapping_session_restore_ = false;
}
void TabManagerStatsCollector::OnBackgroundTabOpeningSessionStarted() {
DCHECK(!is_in_background_tab_opening_session_);
UpdateSessionAndSequence();
background_tab_count_stats_.Reset();
CreateAndInitSwapMetricsDriverIfNeeded(SessionType::kBackgroundTabOpening);
is_in_background_tab_opening_session_ = true;
ClearStatsWhenInOverlappedSession();
}
void TabManagerStatsCollector::OnBackgroundTabOpeningSessionEnded() {
DCHECK(is_in_background_tab_opening_session_);
UMA_HISTOGRAM_BOOLEAN(kHistogramSessionOverlapBackgroundTabOpening,
is_overlapping_background_tab_opening_ ? true : false);
if (swap_metrics_driver_)
swap_metrics_driver_->UpdateMetrics();
RecordBackgroundTabCount();
is_in_background_tab_opening_session_ = false;
is_overlapping_background_tab_opening_ = false;
}
void TabManagerStatsCollector::CreateAndInitSwapMetricsDriverIfNeeded(
SessionType type) {
if (IsInOverlappedSession()) {
swap_metrics_driver_ = nullptr;
return;
}
// Always create a new instance in case there is a SessionType change because
// this is shared between SessionRestore and BackgroundTabOpening.
swap_metrics_driver_ = content::SwapMetricsDriver::Create(
base::WrapUnique<content::SwapMetricsDriver::Delegate>(
new SwapMetricsDelegate(this, type)),
base::TimeDelta::FromSeconds(0));
// The driver could still be null on a platform with no swap driver support.
if (swap_metrics_driver_)
swap_metrics_driver_->InitializeMetrics();
}
void TabManagerStatsCollector::RecordSwapMetrics(SessionType type,
const std::string& metric_name,
uint64_t count,
base::TimeDelta interval) {
base::HistogramBase* histogram = base::Histogram::FactoryGet(
"TabManager.Experimental." + std::string(kSessionTypeName[type]) + "." +
metric_name,
1, // minimum
10000, // maximum
50, // bucket_count
base::HistogramBase::kUmaTargetedHistogramFlag);
histogram->Add(static_cast<double>(count) / interval.InSecondsF());
}
void TabManagerStatsCollector::OnUpdateSwapMetricsFailed() {
swap_metrics_driver_ = nullptr;
}
void TabManagerStatsCollector::OnDidStartMainFrameNavigation(
content::WebContents* contents) {
foreground_contents_switched_to_times_.erase(contents);
}
void TabManagerStatsCollector::OnWillLoadNextBackgroundTab(bool timeout) {
UMA_HISTOGRAM_BOOLEAN(kHistogramBackgroundTabOpeningTabLoadTimeout, timeout);
}
void TabManagerStatsCollector::OnTabIsLoaded(content::WebContents* contents) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!base::ContainsKey(foreground_contents_switched_to_times_, contents))
return;
base::TimeDelta switch_load_time =
NowTicks() - foreground_contents_switched_to_times_[contents];
ukm::SourceId ukm_source_id = GetUkmSourceId(contents);
if (is_session_restore_loading_tabs_ && !IsInOverlappedSession()) {
UMA_HISTOGRAM_MEDIUM_TIMES(kHistogramSessionRestoreTabSwitchLoadTime,
switch_load_time);
if (ukm_source_id != ukm::kInvalidSourceId) {
ukm::builders::
TabManager_Experimental_SessionRestore_TabSwitchLoadStopped(
ukm_source_id)
.SetSequenceId(sequence_++)
.SetSessionRestoreSessionId(session_id_)
.SetSessionRestoreTabCount(
g_browser_process->GetTabManager()->restored_tab_count())
.SetSystemTabCount(
g_browser_process->GetTabManager()->GetTabCount())
.SetTabSwitchLoadTime(switch_load_time.InMilliseconds())
.Record(ukm::UkmRecorder::Get());
}
}
if (is_in_background_tab_opening_session_ && !IsInOverlappedSession()) {
UMA_HISTOGRAM_MEDIUM_TIMES(kHistogramBackgroundTabOpeningTabSwitchLoadTime,
switch_load_time);
if (ukm_source_id != ukm::kInvalidSourceId) {
ukm::builders::
TabManager_Experimental_BackgroundTabOpening_TabSwitchLoadStopped(
ukm_source_id)
.SetBackgroundTabLoadingCount(
g_browser_process->GetTabManager()
->GetBackgroundTabLoadingCount())
.SetBackgroundTabOpeningSessionId(session_id_)
.SetBackgroundTabPendingCount(
g_browser_process->GetTabManager()
->GetBackgroundTabPendingCount())
.SetSequenceId(sequence_++)
.SetSystemTabCount(
g_browser_process->GetTabManager()->GetTabCount())
.SetTabSwitchLoadTime(switch_load_time.InMilliseconds())
.Record(ukm::UkmRecorder::Get());
}
}
foreground_contents_switched_to_times_.erase(contents);
}
void TabManagerStatsCollector::OnWebContentsDestroyed(
content::WebContents* contents) {
foreground_contents_switched_to_times_.erase(contents);
}
bool TabManagerStatsCollector::IsInOverlappedSession() {
return is_session_restore_loading_tabs_ &&
is_in_background_tab_opening_session_;
}
void TabManagerStatsCollector::ClearStatsWhenInOverlappedSession() {
if (!IsInOverlappedSession())
return;
swap_metrics_driver_ = nullptr;
foreground_contents_switched_to_times_.clear();
background_tab_count_stats_.Reset();
is_overlapping_session_restore_ = true;
is_overlapping_background_tab_opening_ = true;
}
void TabManagerStatsCollector::UpdateSessionAndSequence() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// This function is used by both SessionRestore and BackgroundTabOpening. This
// is fine because we do not report any metric when those two overlap.
++session_id_;
sequence_ = 0;
}
// static
const char TabManagerStatsCollector::
kHistogramSessionRestoreForegroundTabExpectedTaskQueueingDuration[] =
"TabManager.SessionRestore.ForegroundTab.ExpectedTaskQueueingDuration";
// static
const char TabManagerStatsCollector::
kHistogramBackgroundTabOpeningForegroundTabExpectedTaskQueueingDuration[] =
"TabManager.BackgroundTabOpening.ForegroundTab."
"ExpectedTaskQueueingDuration";
// static
const char TabManagerStatsCollector::kHistogramSessionRestoreSwitchToTab[] =
"TabManager.SessionRestore.SwitchToTab";
// static
const char
TabManagerStatsCollector::kHistogramBackgroundTabOpeningSwitchToTab[] =
"TabManager.BackgroundTabOpening.SwitchToTab";
// static
const char
TabManagerStatsCollector::kHistogramSessionRestoreTabSwitchLoadTime[] =
"TabManager.Experimental.SessionRestore.TabSwitchLoadTime."
"UntilTabIsLoaded";
// static
const char TabManagerStatsCollector::
kHistogramBackgroundTabOpeningTabSwitchLoadTime[] =
"TabManager.Experimental.BackgroundTabOpening.TabSwitchLoadTime."
"UntilTabIsLoaded";
// static
const char TabManagerStatsCollector::kHistogramBackgroundTabOpeningTabCount[] =
"TabManager.BackgroundTabOpening.TabCount";
// static
const char
TabManagerStatsCollector::kHistogramBackgroundTabOpeningTabPausedCount[] =
"TabManager.BackgroundTabOpening.TabPausedCount";
// static
const char TabManagerStatsCollector::
kHistogramBackgroundTabOpeningTabLoadAutoStartedCount[] =
"TabManager.BackgroundTabOpening.TabLoadAutoStartedCount";
// static
const char TabManagerStatsCollector::
kHistogramBackgroundTabOpeningTabLoadUserInitiatedCount[] =
"TabManager.BackgroundTabOpening.TabLoadUserInitiatedCount";
// static
const char
TabManagerStatsCollector::kHistogramBackgroundTabOpeningTabLoadTimeout[] =
"TabManager.BackgroundTabOpening.TabLoadTimeout";
// static
const char TabManagerStatsCollector::kHistogramSessionOverlapSessionRestore[] =
"TabManager.SessionOverlap.SessionRestore";
// static
const char
TabManagerStatsCollector::kHistogramSessionOverlapBackgroundTabOpening[] =
"TabManager.SessionOverlap.BackgroundTabOpening";
} // namespace resource_coordinator
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
fd89085ed0100d3ce5b4f11df84112502ef7e7d5 | b21bcc5c2203ce4a7d5ceb9bcf0d72cf79db6abc | /leetcode/hard/candy/src/main.cpp | e06c928b0bbb02733832fd5b3635e491c19d6e98 | [] | no_license | zhaoyunfuture/study | 81ad69a4abfedb3d14efa1080a2bcf091ab2e1a8 | ebed9809c84c31ff67b988b3bb3c3289b2b818d7 | refs/heads/master | 2022-01-18T21:33:06.613463 | 2022-01-09T13:19:58 | 2022-01-09T13:19:58 | 47,873,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | #include <string.h>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int candy(vector<int>& ratings) {
int size = ratings.size();
if(size==1)
return size;
vector<int> c;
bool onlyfall = true;
for(int i=0;i<size-1;i++){
c.push_back(1);
if(ratings.at(i)<ratings.at(i+1))
onlyfall = false;
}
c.push_back(1);
if(onlyfall){
sort (ratings.begin(), ratings.end(), myobject);
}
bool flag = false;
do{
flag = false;
for(int i=0;i<size-1;i++){
if(ratings.at(i)>ratings.at(i+1)){
if(c.at(i)<=c.at(i+1)){
c.at(i) += c.at(i+1) -c.at(i) + 1;
flag = true;
}
}else if(ratings.at(i)<ratings.at(i+1)){
if(c.at(i)>=c.at(i+1)){
c.at(i+1) += c.at(i) -c.at(i+1) + 1;
flag = true;
}
}
}
}while(flag);
int out=0;
for(int i=0;i<size;i++){
out +=c.at(i);
}
return out;
}
};
int main(int argc, char* argv[])
{
return 0;
}
| [
"zyfuture@qq.com"
] | zyfuture@qq.com |
d63d86fa8a3104e787d0e4da83aaa9d517ad1c62 | 7d4977f51c74af9548fa607b518c7b5dafeba576 | /Programmers/src/49191/solution.cpp | 44447bdcd4b319e1cf5b0f8dcfa9cd8d6abf25b7 | [
"MIT"
] | permissive | lstar2397/algorithms | 7b200c7ee929ba21e0eb6432677bf234d6c8b239 | 686ea882079e26111f86b5bd5a7ab1b14ccf0fa2 | refs/heads/master | 2020-04-15T21:38:15.618585 | 2019-02-01T14:50:37 | 2019-02-01T14:50:37 | 165,040,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cpp | #include <vector>
#include <algorithm>
using namespace std;
void dfs(vector<int> graph[], int v, int e, bool visited[], int arr[][101])
{
visited[e] = true;
if (v != e)
{
arr[v][e] = 1;
arr[e][v] = 0;
}
for (size_t i = 0; i < graph[e].size(); i++)
{
int next = graph[e][i];
if (!visited[next])
dfs(graph, v, next, visited, arr);
}
}
int solution(int n, vector<vector<int>> results) {
int arr[101][101];
vector<int> graph[101];
fill(&arr[0][0], &arr[0][0] + (sizeof(arr) / sizeof(int)), -1);
for (int i = 1; i <= n; i++)
arr[i][i] = 0;
for (size_t i = 0; i < results.size(); i++)
graph[results[i][0]].push_back(results[i][1]);
for (int i = 1; i <= n; i++)
{
bool visited[101] = { false, };
dfs(graph, i, i, visited, arr);
}
int answer = n;
for (int i = 1; i <= n; i++)
{
bool flag = false;
for (int j = 1; j <= n; j++)
{
if (arr[i][j] == -1)
{
flag = true;
break;
}
}
if (flag)
answer--;
}
return answer;
} | [
"lstar2397@naver.com"
] | lstar2397@naver.com |
5e453ab330b1464279b795a125decc5e1238cd1b | ecf5f95dd74fd008f9c8d6d4d89393362a821d9c | /manos_cartesian_velocity_control/include/manos_cartesian_velocity_control/cartesian_state_controller.h | cd0826addf520e3a9f79a9a2bf4a07208017f1cb | [] | no_license | ThanasisTs/manos | 29ae0778b76e2fb4ba827dfd2f02e33b968ef3de | f8b897150a9de59ee1c4c58a347abea39b7e59b6 | refs/heads/master | 2021-09-10T03:20:23.679620 | 2020-03-12T10:55:40 | 2020-03-12T10:55:40 | 207,255,111 | 0 | 1 | null | 2019-09-09T07:55:11 | 2019-09-09T07:55:11 | null | UTF-8 | C++ | false | false | 2,172 | h | #ifndef CARTESIAN_STATE_CONTROLLER_H
#define CARTESIAN_STATE_CONTROLLER_H
#include <ros/node_handle.h>
#include <cartesian_state_msgs/PoseTwist.h>
#include <hardware_interface/joint_state_interface.h>
#include <controller_interface/controller.h>
#include <kdl/chainfksolvervel_recursive.hpp>
#include <kdl/chainfksolverpos_recursive.hpp>
#include "manos_cartesian_velocity_control/kinematic_chain_controller_base.h"
#include <realtime_tools/realtime_publisher.h>
namespace controller_interface
{
/** \brief This class implements a cartesian state publisher
* for ROS control.
*/
class CartesianStateController:
public KinematicChainControllerBase<
hardware_interface::JointStateInterface>
{
public:
CartesianStateController() {}
~CartesianStateController() {}
/** \brief The init function is called to initialize the controller from a
* non-realtime thread with a pointer to the hardware interface, itself,
* instead of a pointer to a RobotHW.
*s
* \param robot The specific hardware interface used by this controller.
*
* \param n A NodeHandle in the namespace from which the controller
* should read its configuration, and where it should set up its ROS
* interface.
*
* \returns True if initialization was successful and the controller
* is ready to be started.
*/
bool init(hardware_interface::JointStateInterface *robot, ros::NodeHandle &n);
/** \brief This is called from within the realtime thread just before the
* first call to \ref update
*
* \param time The current time
*/
void starting(const ros::Time& time);
/*!
* \brief Issues commands to the joint. Called at regular intervals
*/
void update(const ros::Time& time, const ros::Duration& period);
protected:
ros::Publisher pub_state_;
KDL::FrameVel x_dot_;
KDL::Frame x_;
boost::shared_ptr<KDL::ChainFkSolverVel> fk_vel_solver_;
boost::shared_ptr<KDL::ChainFkSolverPos> fk_pos_solver_;
boost::shared_ptr<realtime_tools::RealtimePublisher<
cartesian_state_msgs::PoseTwist> > realtime_pub_;
ros::Time last_publish_time_;
double publish_rate_;
};
} // namespace controller_interface
#endif
| [
"ThanasisTs@github.com"
] | ThanasisTs@github.com |
abcdb79140e4edbf8ee5f593c0687f9a3fd18362 | 87464fd51294f061472244148aebce14e454f2a6 | /DataStructures/Graph/Graph_AdjList.cpp | bdbaabe339429e31702b3a801382605407916a33 | [] | no_license | msk4862/DS-Algo | 6fb348e4ae0f685f58b89f619ce4edc6690c3817 | 10e41a8ce1879fceee6f064c81192aa3e981d8d4 | refs/heads/master | 2021-08-02T23:31:44.813569 | 2021-07-24T11:18:51 | 2021-07-24T11:18:51 | 199,693,163 | 4 | 3 | null | 2020-10-07T19:28:55 | 2019-07-30T16:56:48 | C++ | UTF-8 | C++ | false | false | 886 | cpp | #include<bits/stdc++.h>
using namespace std;
/*
Graph data structure
using Adjacency list
*/
class Graph {
public:
int V;
unordered_map<int, list<int>> l;
/*
If vecrtices are numeric values from 1 to N
we can use simply use array of list i.e. list<int> *l;
*/
Graph(int V) {
this->V = V;
// l = new list<int>[V];
}
// assuming biderectional edges
void addEdge(int v1, int v2) {
l[v1].push_back(v2);
l[v2].push_back(v1);
}
void printAdjacencyList() {
for (auto e: l)
{
cout<<"Vertex "<<e.first<<"-> ";
for(auto nbr : e.second) cout<<nbr<<" ";
cout<<"\n";
}
}
};
int main() {
Graph g(4);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 1);
g.printAdjacencyList();
} | [
"shoaib.mca19.du@gmail.com"
] | shoaib.mca19.du@gmail.com |
55c7193bbf4fa47c60e7d50eabb9e565ecf8fbca | 6f11c693f13a5c9dfb0c453fab13611344e238fb | /vtorcs-RL-color/src/tools/accc/mainaccc.cpp | 6cb170b85c2116dbe7cbcacdde7ae681b8a2e9c2 | [
"MIT",
"GPL-2.0-only",
"GPL-1.0-or-later"
] | permissive | tushartk/gym_torcs | ebc0eb867a1e37d7efdceb99ba4fb582d36425ff | 32d694f209dd94924bb9454733aeb6cc5ffeca11 | refs/heads/master | 2022-04-14T01:54:43.320746 | 2020-04-14T01:15:00 | 2020-04-14T01:15:00 | 255,478,013 | 0 | 0 | MIT | 2020-04-14T01:11:31 | 2020-04-14T01:11:30 | null | UTF-8 | C++ | false | false | 9,419 | cpp | /***************************************************************************
file : accc.cpp
created : Fri Apr 18 23:10:53 CEST 2003
copyright : (C) 2003 by Christophe Guionneau
version : $Id: mainaccc.cpp,v 1.4.2.1 2008/11/09 17:50:23 berniw Exp $
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
/** @file
@author Christophe Guionneau
@version $Id: mainaccc.cpp,v 1.4.2.1 2008/11/09 17:50:23 berniw Exp $
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <cstring>
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <math.h>
#include "accc.h"
/* -g g-track-2.ac -l0 g2.ac -d3 200900 -d2 200 -d1 100 -S 200 >t */
/* +es 80 p-gt1.ac porsche-gt1.ac>t */
int distSplit=0;
char *InputFileName = NULL;
char *OutputFileName = NULL;
char * fileL0=NULL;
char * fileL1=NULL;
char * fileL2=NULL;
char * fileL3=NULL;
char * OrderString=NULL;
int d1=0;
int d2=0;
int d3=0;
int useStrip=0;
int extendedStrips=0;
int extendedEnvCoord=0;
int isobjectacar=0;
int extendedTriangles=0;
int notexturesplit=0;
int collapseObject=0;
int typeConvertion =0;
int far_dist=10000;
int normalMapping=0;
extern double smooth_angle;
void usage(void)
{
fprintf(stderr, "Ac3d Compiler $Revision: 1.4.2.1 $ \n");
fprintf(stderr, "Usage: accc [option] <inputfile> <outputfile> [dist][-order \"orderstring\"]<\n");
/*fprintf(stderr, "-strip : stripify any ac3d output models\n");*/
fprintf(stderr, "+o: ac3d to ac3d : the result file is optimized\n");
fprintf(stderr, " in using groups by zone of track\n");
fprintf(stderr, " track must be named TKMNxxx\n");
fprintf(stderr, " dist is used to determine the distance of the objects\n");
/* fprintf(stderr, "+om: ac3d to ac3d : the result is a vertex merged unique obj\n" );
fprintf(stderr, " for smooth car only\n");*/
fprintf(stderr, "-o: ac3d to obj \n");
fprintf(stderr, "+s: ac3d to ac3d with strips (used for cars) \n");
fprintf(stderr, "+es <angle_of_smooth>: ac3d to ac3d with strips (used for cars) and extended ac3d file output \n");
fprintf(stderr, " (computed normals) angle is in degrees : example : +es 80.0 clkdtm_o.ac clkdtm.ac \n");
fprintf(stderr, " the output file will also contains the secondary textcoord for the env sliding \n");
fprintf(stderr, "+et: ac3d to ac3d with triangles (used for cars) and extended ac3d file output (normals normals) \n");
fprintf(stderr, "+etn: ac3d to ac3d with triangles no split and extended ac3d file output (normals normals) \n");
fprintf(stderr, "+shad: ac3d to ac3d with triangles, create a new ac3d file used for track shading\n vertical mapping of a single texture \n");
fprintf(stderr, "<inputfile>: \n");
fprintf(stderr, "<oututfile>: \n");
fprintf(stderr, "-order \"orderstring\": only used with +es , +s and +et \n");
fprintf(stderr, " \"orderstring\" is the order of the objects during the save\n");
fprintf(stderr, " for example : \"HB;OB;OBM\" is the names of the objet separate\n");
fprintf(stderr, " by a semicolon\n");
fprintf(stderr, " for imported NFS cars the object name \"HB\" must be used instead\n");
fprintf(stderr, " of \":HB\"\n");
fprintf(stderr, "-g <outputfile>: for grouping multilayer ac3d track \n");
fprintf(stderr, " -l0 <input filename> : the base geometry\n");
fprintf(stderr, " -l1 <input filename> : the base geometry map-tiled \n");
fprintf(stderr, " -l2 <input filename> : the base geometry skids/and grass details \n");
fprintf(stderr, " -l3 <input filename> : the base geometry shadows \n");
fprintf(stderr, " -d3 <val> : the max distance of groups in tkmn\n");
fprintf(stderr, " -d2 <val> : the distance of group 2 in tkmn\n");
fprintf(stderr, " -d1 <val> : the distance of group 1 in tkmn\n");
fprintf(stderr, " -S <val> : the distance of splitting for TERRAIN* objects\n");
fprintf(stderr, " -es : for extended ac3d file format for strips\n");
fprintf(stderr, " -nts : no texture split (for debug)\n");
}
void init_args(int argc, char **argv)
{
if (argc<4)
{usage();exit(1);}
if (!strcmp(argv[1],"-o")) {
typeConvertion=_AC3DTOOBJ;
}
else if (!strcmp(argv[1],"+o")) {
typeConvertion=_AC3DTOAC3D;
}
else if (!strcmp(argv[1],"+om")) {
typeConvertion=_AC3DTOAC3DM;
}
else if (!strcmp(argv[1],"+s")) {
typeConvertion=_AC3DTOAC3DS;
}
else if (!strcmp(argv[1],"+es")) {
typeConvertion=_AC3DTOAC3DS;
isobjectacar=1;
extendedStrips=1;
extendedEnvCoord=1;
collapseObject=1;
sscanf(argv[2],"%lf",&smooth_angle);
InputFileName = strdup(argv[3]);
OutputFileName = strdup(argv[4]);
}
else if (!strcmp(argv[1],"+et")) {
typeConvertion=_AC3DTOAC3D;
extendedStrips=0;
isobjectacar=1;
extendedEnvCoord=1;
extendedTriangles=1;
collapseObject=1;
}
else if (!strcmp(argv[1],"+etn")) {
typeConvertion=_AC3DTOAC3D;
extendedStrips=0;
isobjectacar=1;
extendedEnvCoord=1;
notexturesplit=0;
collapseObject=1;
extendedTriangles=1;
}
else if (!strcmp(argv[1],"+shad")) {
typeConvertion=_AC3DTOAC3D;
extendedStrips=0;
isobjectacar=0;
notexturesplit=1;
extendedTriangles=0;
normalMapping=1;
collapseObject=1;
}
else if (!strcmp(argv[1],"-g")) {
typeConvertion=_AC3DTOAC3DGROUP;
}
else {
usage();
exit(1);
}
if (typeConvertion==_AC3DTOAC3DGROUP)
{
int i=3;
/* read other arguments */
OutputFileName = strdup(argv[2]);
for (i=3; i<argc; i++)
{
if (!strcmp(argv[i],"-es"))
{
extendedStrips=1;
continue;
}
if (!strcmp(argv[i],"-nts"))
{
notexturesplit=1;
continue;
}
if (!strcmp(argv[i],"-S"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
distSplit=atoi(argv[i]);
continue;
}
if (!strcmp(argv[i],"-l0"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
fileL0=argv[i];
continue;
}
if (!strcmp(argv[i],"-l1"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
fileL1=argv[i];
continue;
}
if (!strcmp(argv[i],"-l2"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
fileL2=argv[i];
continue;
}
if (!strcmp(argv[i],"-l3"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
fileL3=argv[i];
continue;
}
if (!strcmp(argv[i],"-d3"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
d3=atoi(argv[i]);
continue;
}
if (!strcmp(argv[i],"-d2"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
d2=atoi(argv[i]);
continue;
}
if (!strcmp(argv[i],"-d1"))
{
if (argc<=i+1){usage();exit(-1);}
i++;
d1=atoi(argv[i]);
continue;
}
}
}
else
{
if (InputFileName==NULL)
InputFileName = strdup(argv[2]);
if (OutputFileName==NULL)
OutputFileName = strdup(argv[3]);
if (argc==7)
{if (!strcmp(argv[5],"-order"))
OrderString=argv[6];
}
else
if (typeConvertion==_AC3DTOAC3D)
if (argc>=5)
if (!strcmp(argv[4],"-order"))
OrderString=argv[5];
else
far_dist=atoi(argv[4]);
}
}
/*extern void WindowsSpecInit(void);*/
void redraw ()
{}
void reshape ( int w, int h )
{}
void keyboard ( unsigned char, int, int )
{ exit ( 0 ) ;}
int
main(int argc, char **argv)
{
char *fake_argv[3] ;
fake_argv[0] = "ac3dto3ds" ;
fake_argv[1] = "converter" ;
fake_argv[2] = NULL ;
init_args(argc, argv);
extern int loadACo( char * inputFilename, char * outputFilename, int saveIn);
extern int loadAC( char * inputFilename, char * outputFilename, int saveIn);
#ifdef _3DS
extern int load3ds( char * inputFilename, char * outputFilename);
#endif
if (typeConvertion==_AC3DTO3DS)
{
loadAC( InputFileName, OutputFileName,0);
}
else if (typeConvertion==_3DSTOAC3D)
{
#ifdef _3DS
load3ds( InputFileName, OutputFileName);
#endif
}
else if (typeConvertion==_AC3DTOAC3D)
{
loadACo( InputFileName, OutputFileName,0);
}
else if (typeConvertion==_AC3DTOOBJ)
{
loadAC( InputFileName, OutputFileName,1);
}
else if (typeConvertion==_AC3DTOAC3DM)
{
loadAC( InputFileName, OutputFileName,2);
}
else if (typeConvertion==_AC3DTOAC3DS)
{
loadAC( InputFileName, OutputFileName,3);
}
else if (typeConvertion==_AC3DTOAC3DGROUP)
{
loadAndGroup( OutputFileName);
}
return 0;
}
| [
"yossy0157@gmail.com"
] | yossy0157@gmail.com |
d73a3b6ac91e621194fbd262454983e9ae8ae0ee | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/86/daea033a9686a0/main.cpp | 96bf8525753723004de8122fe71ff6795cf44c1d | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,775 | cpp | #include <map>
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <sstream>
#include <cstdarg>
enum JType {
JInt = 0,
JVoid = 1,
JString = 2,
JBool = 3
};
std::string JTypeToString(JType type)
{
switch (type)
{
case(JInt): return "I";
case(JVoid): return "V";
case(JString): return "Ljava/lang/String;";
case(JBool): return "Z";
default: return "";
}
return "";
}
template<int N>
struct JTypeList;
template<>
struct JTypeList<0>
{
void insert(std::stringstream& ss) const {}
};
template<>
struct JTypeList<1> : JTypeList<0>
{
JTypeList(JType v) : value(v) {};
JTypeList(JTypeList<0> const&, JType v)
: value(v) {}
void insert(std::stringstream& ss) const
{
ss << JTypeToString(value);
}
JType value;
};
template<int N>
struct JTypeList : JTypeList<N-1>
{
JTypeList(JTypeList<N-1> const& init, JType last)
: JTypeList<N-1>(init, init.value), value(last) {}
void insert(std::stringstream& ss) const
{
JTypeList<N-1>::insert(ss);
ss << JTypeToString(value);
}
JType value;
};
JTypeList<2> operator,(JType lhs, JType rhs)
{
return JTypeList<2>(JTypeList<1>(lhs), rhs);
}
template<int N>
JTypeList<N+1> operator,(JTypeList<N> const& l, JType next)
{
return JTypeList<N+1>(l, next);
}
static JTypeList<0> const NoArgs = {};
template<int N>
std::string MakeSig(JType returnType, JTypeList<N> const& args)
{
std::stringstream ss;
ss << "(";
args.insert(ss);
ss << ")" << JTypeToString(returnType);
return ss.str();
}
int main()
{
std::cout << MakeSig(JInt, (JString, JBool)) << std::endl;
std::cout << MakeSig(JInt, NoArgs);
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
a18a355bf6ab005814beee72a71a3767e7e015a7 | b800fcf6bc5b78a5f84c9da4c3bab74cb8693a3d | /pgm7/Grain.hpp | 45d3f92e5e23fb8d4b73e951263e25c118fc64aa | [] | no_license | billymeli/CS311 | 15f3f42259cd5df0c2cf6cd1521c21456225569f | 47f4d26963a85f42b31b45bac71bf56837ec5227 | refs/heads/master | 2021-05-09T16:11:37.693620 | 2018-05-02T01:17:39 | 2018-05-02T01:17:39 | 119,101,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,073 | hpp | /*
* Grain.h
*
* Created on: Feb 9, 2018
* Author: Joe
*/
#include <string>
#ifndef GRAIN_H_
#define GRAIN_H_
/**
* The Grain class identifies properties of a sample of grain
*/
class Grain {
public:
// Constructor default
Grain();
// Constructor allowing caller to specify sample's moisture level (%) and foreign material (%)
Grain(double moistureLevel, double foreignMaterial);
// Destructor
virtual ~Grain();
// pure virtual functions
virtual Grain* clone() const = 0;
virtual std::string getType() const = 0;
virtual int getTypeVal() const = 0;
virtual const double getAverageTestWeight() const = 0;
virtual const double getIdealMoistureLevel() const = 0;
// returns a string that represents the grain type
std::string toString() const;
// Accessor to return sample's moisture level (percent)
double getMoistureLevel() const;
// Accessor to return sample's foreign material (percent)
double getForeignMaterial() const;
protected:
// Member variables
double moistureLevel;
double foreignMaterial;
};
#endif /* GRAIN_H_ */
| [
"mstevebilly@yahoo.com"
] | mstevebilly@yahoo.com |
c1f9638ea07fcfd1c8d73e4989ef6fda3caee882 | c54d3be7040ad850a67041912f99544f64e493a3 | /Blinking_Lights.ino | 93bc091ec8bb2da25cd4effbe5bd1e7820f23cf4 | [] | no_license | kodyamani/Robot-Blinking-Lights | 1ec13b6a507aca7308cc6bbdd3902c4de0714e59 | 9b670a5d97eb889de520356c8dc204714577e3ea | refs/heads/master | 2020-03-21T18:22:35.062443 | 2018-06-27T13:50:36 | 2018-06-27T13:50:36 | 138,785,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,912 | ino | int redLED = 3;
void setup() {
pinMode(redLED,OUTPUT);
}
void loop() {
//H
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
//I
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
//Space between two words
delay(7000);
//W
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(3000);
//O
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(3000);
//R
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
//L
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
//D
digitalWrite(redLED,HIGH);
delay(3000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(1000);
digitalWrite(redLED,HIGH);
delay(1000);
digitalWrite(redLED,LOW);
delay(10000); //This is to end the sentence
}
| [
"noreply@github.com"
] | kodyamani.noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.